Merge upstream/main into trinity-dsv41; port V4.1 engram onto shared n-gram module
Merges upstream/main (eed0e44c) into trinity-dsv41 (PR #4057 + trinity LoRA warm start, adapter reload timeouts, renderers fork). Submodule pins for verifiers, prime-envs and prime-kernels follow upstream/main; renderers stays on the trinity fork. Followingb417ea31(#4293), the three n-gram files take upstream's side and DeepSeek-V4.1's engram is ported onto the shared module: - engram.py: DeepseekV41NGramHasher(NGramHasher) replaces EngramHasher. It maps tokens through the compressed token map, cuts look-back at document starts only (no EOS reset), pads with compressed_token_map[pad_token_id], takes consecutive_primes_from(engram_vocab_size, skip=24*table, count=24) as head sizes, and uses odd PCG64 multipliers seeded with 10007 * engram_layer_ids[table]. Table rows come from the config (384006168 / 384016682) and are checked to hold every bucket. DeepseekV41Engram is now only the gate (wkv, q/k weights). - modeling: DeepseekV41Model.ngram = NGramEmbeddings(hasher, {1: 0, 14: 1}, head_dim=256, non-persistent layout, deduplicating lookup). The row is hashed once and looked up outside the layers. layers[i].engram runs the gate inside the AC-wrapped compiled block. PackedContext carries cu_seqlens. - conversion: HF layers.{i}.engram.embed.weight <-> model.ngram.tables.{i}.weight. The gate keeps its HF name, so vLLM-side names are unchanged. - layers/ngram.py: NGramTable/NGramEmbeddings gain persistent_layout and deduplicate_lookup options. - ngram_lookup.py: RowShardedLookup(deduplicate=True) sends unique ids (torch.unique) and sums repeated-row grads in fp32. ngram_runtime warms up the all-to-all before training. - model.py: drops AllToAllEmbeddingParallel, the FSDP-ignored table path, the hand-applied divide factor and the dp_replicate guard. freeze_engram_tables is keyed on NGramTable. optim/__init__.py drops the "engrams." Muon rule. - transports: the fp8 row-chunk NCCL export is keyed on NGramTables that no ChunkedConvOp converts (utils.weights.get_row_chunked_tables). It handles plain, 1-D Shard(0) and multi-dim meshes (replicate or size-1 FSDP dims). filesystem.py rejects such tables by the same rule instead of hasattr(rows_per_rank). - dsv41_indexer.py: upstream moved fp8_indexer to DeepGEMM and removed _triton_fp8_indexer_kernel, so V4.1's two-level indexer now vendors that Triton kernel (KEY_ALIGNMENT 16) to keep scoring unchanged. Equivalence against the pre-merge tree (HEAD282af805): - Hashed ids are bit-identical for two synthetic configs with packed multi-document rows (incl. 1-token docs, 24 heads/table, many collisions). Primes, offsets, multipliers and pad id are identical. The real config gives identical 2x24 primes, multipliers and 384006168/384016682 rows. - The table lookup + gate matches the old DeepseekV41Engram bitwise (outputs and grads of the table, wkv, q/k and the streams), fp32 and bf16, CPU and CUDA. - A 6-layer V4.1 stack (attention/MoE stubbed), loaded from the same HF state dict, matches bitwise in its output and all 58 HF-named grads. - RowShardedLookup(deduplicate) on gloo with 2 and 3 ranks and uneven rows: outputs bitwise equal to a local lookup and to the old _AllToAllLookup. fp32 grads are bitwise equal to the old path. bf16 grads differ by about 1 bf16 ulp, because the old path accumulated into an fp32 master. - The fp8 export on gloo (plain, 1-D, replicate x shard, size-1 x shard) reassembles byte-identical to quantize_rows_ue8m0 of the full table. Untested here (no SM90 GPUs, one free GPU): multi-GPU FSDP+RowShardedLookup training, the NCCL export through PyNccl into vLLM, the vLLM RowChunkWriter, and the GPU-only test_deepseek_v41.py (skipped on SM86). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,156 @@
|
||||
name: GPU Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [labeled]
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: >-
|
||||
${{ github.workflow }}-${{
|
||||
(github.event_name == 'pull_request'
|
||||
&& github.event.pull_request.head.repo.full_name == github.repository
|
||||
&& github.event.label.name == 'gpu-ci')
|
||||
&& format('pr-{0}', github.event.pull_request.number)
|
||||
|| format('{0}-{1}', github.event_name, github.run_id) }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: Gate
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||
|| (github.event.pull_request.head.repo.full_name == github.repository
|
||||
&& github.event.label.name == 'gpu-ci')
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Remove gpu-ci label
|
||||
if: github.event_name == 'pull_request'
|
||||
continue-on-error: true
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
run: gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/labels/gpu-ci"
|
||||
|
||||
unit-gpu:
|
||||
name: Unit (GPU)
|
||||
needs: gate
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
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@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: uv run pytest tests/unit -m gpu
|
||||
|
||||
integration:
|
||||
name: Integration / ${{ matrix.name }}
|
||||
needs: gate
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
|
||||
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
|
||||
max-parallel: 5
|
||||
matrix:
|
||||
include:
|
||||
- {test: reverse_text_sft, name: Reverse Text SFT}
|
||||
- {test: reverse_text_sft_lora, name: Reverse Text SFT LoRA}
|
||||
- {test: pretrain, name: Pretrain}
|
||||
- {test: reverse_text, name: Reverse Text}
|
||||
- {test: reverse_text_rl_opd, name: Reverse Text RL OPD}
|
||||
- {test: reverse_text_rl_sft, name: Reverse Text RL SFT}
|
||||
- {test: alphabet_sort, name: Alphabet Sort}
|
||||
- {test: reverse_text_lora, name: Reverse Text LoRA}
|
||||
- {test: reverse_text_moe, name: Reverse Text MoE}
|
||||
- {test: reverse_text_modelexpress, name: Reverse Text ModelExpress}
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
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@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Install ModelExpress server
|
||||
if: matrix.test == 'reverse_text_modelexpress'
|
||||
run: |
|
||||
apt-get install -y curl make gcc
|
||||
bash scripts/install_modelexpress.sh
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ matrix.test }}-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
@@ -17,10 +17,18 @@ on:
|
||||
type: choice
|
||||
options: [all, parallel, eval]
|
||||
default: all
|
||||
eval_config:
|
||||
description: "eval: config to run, by name (e.g. gsm8k). Leave empty to run all."
|
||||
required: false
|
||||
default: ""
|
||||
eval_repeats:
|
||||
description: "eval: independent runs. Use 5 to produce a new baseline."
|
||||
description: "eval: independent runs of each config. Use 5 to produce a new baseline."
|
||||
required: false
|
||||
default: "1"
|
||||
eval_max_parallel:
|
||||
description: "eval: most eval jobs to run at once (empty: no limit). Use it to spread a baseline's runs over time."
|
||||
required: false
|
||||
default: ""
|
||||
eval_model:
|
||||
description: "eval: model id on Prime Inference (empty: the config's model)"
|
||||
required: false
|
||||
@@ -47,7 +55,6 @@ concurrency:
|
||||
|
||||
env:
|
||||
EVAL_REPEATS: ${{ inputs.eval_repeats || '1' }}
|
||||
EVAL_NAME: gsm8k
|
||||
|
||||
jobs:
|
||||
parallel:
|
||||
@@ -101,20 +108,52 @@ jobs:
|
||||
if: ${{ !inputs.suite || inputs.suite == 'all' || inputs.suite == 'eval' }}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
repeats: ${{ steps.plan.outputs.repeats }}
|
||||
configs: ${{ steps.plan.outputs.configs }}
|
||||
names: ${{ steps.plan.outputs.names }}
|
||||
matrix: ${{ steps.plan.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- id: plan
|
||||
run: echo "repeats=$(jq -nc "[range(1; $EVAL_REPEATS + 1)]")" >> "$GITHUB_OUTPUT"
|
||||
env:
|
||||
CONFIG: ${{ inputs.eval_config }}
|
||||
# Display name of each config in job names and the summary. A config not listed shows its file name.
|
||||
NAMES: '{"gsm8k": "GSM8K", "pi-terminalbench2-1": "Terminal-Bench-2.1"}'
|
||||
run: |
|
||||
configs=$(ls tests/regression/configs/eval/*.toml | xargs -n1 basename | sed 's/\.toml$//')
|
||||
if [ -n "$CONFIG" ]; then
|
||||
configs=$(echo "$configs" | grep -Fx "$CONFIG" || true)
|
||||
if [ -z "$configs" ]; then
|
||||
echo "Error: eval config '$CONFIG' not found" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
configs=$(printf '%s\n' "$configs" | jq -R . | jq -sc .)
|
||||
# One job per config and repeat. The repeat shows in the job name only when there are several.
|
||||
names=$(jq -nc --argjson configs "$configs" --argjson names "$NAMES" '
|
||||
[$configs[] as $c | {($c): ($names[$c] // $c)}] | add')
|
||||
matrix=$(jq -nc --argjson configs "$configs" --argjson names "$names" --argjson n "$EVAL_REPEATS" '[
|
||||
$configs[] as $c | range(1; $n + 1) as $r
|
||||
| {config: $c, repeat: $r, name: (if $n > 1 then "\($names[$c]) (\($r))" else $names[$c] end)}
|
||||
]')
|
||||
echo "configs=$configs" >> "$GITHUB_OUTPUT"
|
||||
echo "names=$names" >> "$GITHUB_OUTPUT"
|
||||
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
eval:
|
||||
name: ${{ strategy.job-total > 1 && format('Eval / Run ({0})', matrix.repeat) || 'Eval / Run' }}
|
||||
name: Eval / ${{ matrix.name }}
|
||||
needs: eval-plan
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
# The GitHub-hosted maximum. An agent eval caps the agent time of each rollout in its
|
||||
# config, so that it ends before this limit.
|
||||
timeout-minutes: 360
|
||||
strategy:
|
||||
fail-fast: false
|
||||
max-parallel: ${{ fromJSON(inputs.eval_max_parallel || '256') }}
|
||||
matrix:
|
||||
repeat: ${{ fromJSON(needs.eval-plan.outputs.repeats) }}
|
||||
include: ${{ fromJSON(needs.eval-plan.outputs.matrix) }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
@@ -132,34 +171,67 @@ jobs:
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-packages --locked
|
||||
# Harbor tasksets download their task files into ~/.cache/harbor. The prime-envs
|
||||
# commit pins every taskset's data, so it keys the cache.
|
||||
- name: Key the Harbor cache
|
||||
id: harbor
|
||||
run: echo "key=harbor-${{ matrix.config }}-$(git rev-parse HEAD:deps/prime-envs)" >> "$GITHUB_OUTPUT"
|
||||
- name: Cache Harbor tasks
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/harbor
|
||||
key: ${{ steps.harbor.outputs.key }}
|
||||
- name: Run eval
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
MODEL: ${{ inputs.eval_model }}
|
||||
CONFIG: ${{ matrix.config }}
|
||||
REPEAT: ${{ matrix.repeat }}
|
||||
run: |
|
||||
start=$(date +%s)
|
||||
uv run eval @ "tests/regression/configs/eval/$EVAL_NAME.toml" ${MODEL:+-m "$MODEL"} \
|
||||
--no-monitors.prime --run.name "repeat-${{ matrix.repeat }}" --output-dir outputs
|
||||
python3 tests/regression/scripts/eval.py collect "outputs/repeat-${{ matrix.repeat }}" \
|
||||
--repeat ${{ matrix.repeat }} --wall-s "$(( $(date +%s) - start ))" --out result.json
|
||||
uv run eval @ "tests/regression/configs/eval/$CONFIG.toml" ${MODEL:+-m "$MODEL"} \
|
||||
--no-monitors.prime --run.name "$CONFIG-$REPEAT" --output-dir outputs
|
||||
mkdir -p "results/$CONFIG"
|
||||
python3 tests/regression/scripts/eval.py collect "outputs/$CONFIG-$REPEAT" \
|
||||
--repeat "$REPEAT" --wall-s "$(( $(date +%s) - start ))" --out "results/$CONFIG/$REPEAT.json"
|
||||
- name: Upload result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: eval-result-${{ matrix.repeat }}
|
||||
name: eval-result-${{ matrix.config }}-${{ matrix.repeat }}
|
||||
path: |
|
||||
result.json
|
||||
outputs/repeat-${{ matrix.repeat }}/logs
|
||||
outputs/repeat-${{ matrix.repeat }}/monitors/file/metrics.jsonl
|
||||
outputs/repeat-${{ matrix.repeat }}/monitors/file/traces/stream.index.jsonl
|
||||
results
|
||||
outputs/${{ matrix.config }}-${{ matrix.repeat }}/logs
|
||||
outputs/${{ matrix.config }}-${{ matrix.repeat }}/monitors/file/metrics.jsonl
|
||||
outputs/${{ matrix.config }}-${{ matrix.repeat }}/monitors/file/traces/stream.index.jsonl
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
# Each config posts its own message when its eval ends, so a long eval does not delay
|
||||
# the others. Only nightly and manual runs of one repeat post. Runs for a new baseline
|
||||
# report in the summary only. always(), because a job that hits its timeout ends as
|
||||
# cancelled, and that eval must still report.
|
||||
- name: Post to Slack
|
||||
if: ${{ always() && github.event_name != 'pull_request' && env.EVAL_REPEATS == '1' }}
|
||||
env:
|
||||
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
|
||||
CONFIG: ${{ matrix.config }}
|
||||
NAME: ${{ matrix.name }}
|
||||
run: |
|
||||
if [ -z "$SLACK_WEBHOOK_URL" ]; then
|
||||
echo "SLACK_WEBHOOK_URL is not set. Skipped."
|
||||
exit 0
|
||||
fi
|
||||
python3 tests/regression/scripts/eval.py summarize --name "$NAME" \
|
||||
$(find results -path "results/$CONFIG/*.json" 2>/dev/null) \
|
||||
--expected 1 --baseline "tests/regression/baselines/eval/$CONFIG.json" \
|
||||
--slack slack.json > /dev/null || true
|
||||
curl -fsS -X POST -H "Content-Type: application/json" --data @slack.json "$SLACK_WEBHOOK_URL"
|
||||
|
||||
eval-summary:
|
||||
name: Eval / Summary
|
||||
needs: eval
|
||||
needs: [eval-plan, eval]
|
||||
if: ${{ !cancelled() && needs.eval.result != 'skipped' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -175,36 +247,48 @@ jobs:
|
||||
with:
|
||||
path: artifacts
|
||||
pattern: eval-result-*
|
||||
- name: Compare against baseline
|
||||
- name: Compare against baselines
|
||||
env:
|
||||
CONFIGS: ${{ needs.eval-plan.outputs.configs }}
|
||||
NAMES: ${{ needs.eval-plan.outputs.names }}
|
||||
run: |
|
||||
# A single downloaded artifact lands in artifacts/ itself, several land in subdirectories.
|
||||
status=0
|
||||
python3 tests/regression/scripts/eval.py summarize $(find artifacts -name result.json) \
|
||||
--expected "$EVAL_REPEATS" --baseline "tests/regression/baselines/eval/$EVAL_NAME.json" \
|
||||
> summary.md || status=$?
|
||||
: > summary.md
|
||||
for config in $(echo "$CONFIGS" | jq -r '.[]'); do
|
||||
name=$(echo "$NAMES" | jq -r --arg c "$config" '.[$c]')
|
||||
python3 tests/regression/scripts/eval.py summarize --name "$name" \
|
||||
$(find artifacts -path "*/results/$config/*.json") \
|
||||
--expected "$EVAL_REPEATS" --baseline "tests/regression/baselines/eval/$config.json" \
|
||||
>> summary.md || status=1
|
||||
done
|
||||
tee -a "$GITHUB_STEP_SUMMARY" < summary.md
|
||||
exit $status
|
||||
- name: Open baseline PR
|
||||
if: ${{ !cancelled() && inputs.eval_set_baseline && needs.eval.result == 'success' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
CONFIGS: ${{ needs.eval-plan.outputs.configs }}
|
||||
run: |
|
||||
configs=$(echo "$CONFIGS" | jq -r 'join(", ")')
|
||||
branch="regression/eval-baseline-${{ github.run_id }}"
|
||||
python3 tests/regression/scripts/eval.py baseline $(find artifacts -name result.json) \
|
||||
--out "tests/regression/baselines/eval/$EVAL_NAME.json" \
|
||||
--report "tests/regression/reports/eval/$EVAL_NAME.md"
|
||||
for config in $(echo "$CONFIGS" | jq -r '.[]'); do
|
||||
python3 tests/regression/scripts/eval.py baseline $(find artifacts -path "*/results/$config/*.json") \
|
||||
--out "tests/regression/baselines/eval/$config.json" \
|
||||
--report "tests/regression/reports/eval/$config.md"
|
||||
done
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git checkout -b "$branch"
|
||||
git add tests/regression/baselines/eval tests/regression/reports/eval
|
||||
git commit -m "Refresh $EVAL_NAME eval regression baseline"
|
||||
git commit -m "Refresh eval regression baselines: $configs"
|
||||
git push origin "$branch"
|
||||
{
|
||||
echo "## Summary"
|
||||
echo
|
||||
echo "- Refresh the \`$EVAL_NAME\` eval regression baseline from [this run]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)."
|
||||
echo "- Refresh the eval regression baselines of $configs from [this run]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)."
|
||||
echo
|
||||
cat summary.md
|
||||
} > body.md
|
||||
gh pr create --base main --head "$branch" --body-file body.md \
|
||||
--title "chore: refresh $EVAL_NAME eval regression baseline"
|
||||
--title "chore: refresh eval regression baselines"
|
||||
|
||||
+4
-159
@@ -82,7 +82,7 @@ jobs:
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
|
||||
@@ -123,8 +123,6 @@ jobs:
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
|
||||
integration: ${{ steps.matrix.outputs.tests }}
|
||||
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v4
|
||||
@@ -132,7 +130,7 @@ jobs:
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
filters: |
|
||||
unit:
|
||||
eval:
|
||||
- &runtime
|
||||
- '.github/workflows/tests.yml'
|
||||
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
|
||||
@@ -144,164 +142,11 @@ jobs:
|
||||
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
|
||||
- 'tests/{__init__.py,conftest.py,utils.py}'
|
||||
- 'tests/integration/{__init__.py,conftest.py}'
|
||||
- 'tests/unit/{train,inference}/**'
|
||||
- 'src/prime_rl/inference/**'
|
||||
sft:
|
||||
- *runtime
|
||||
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
|
||||
- 'src/prime_rl/dashboard/**'
|
||||
- 'tests/integration/dashboard_smoke.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
|
||||
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
|
||||
- 'src/prime_rl/monitors/**'
|
||||
- 'src/prime_rl/eval/{online,runner}.py'
|
||||
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
|
||||
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
|
||||
rl:
|
||||
- *runtime
|
||||
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
|
||||
- 'src/prime_rl/dashboard/**'
|
||||
- 'tests/integration/dashboard_smoke.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
|
||||
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
|
||||
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
|
||||
- 'src/prime_rl/eval/{online,runner}.py'
|
||||
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
|
||||
- 'tests/integration/test_alphabet_sort.py'
|
||||
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
|
||||
- 'configs/ci/integration/alphabet_sort.toml'
|
||||
eval:
|
||||
- *runtime
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_worker_pool,algorithm,monitors}.py'
|
||||
- 'src/prime_rl/{control,eval,orchestrator,monitors}/**'
|
||||
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
|
||||
- 'src/prime_rl/entrypoints/{eval,env_worker_pool}.py'
|
||||
- 'tests/integration/test_gsm8k_eval.py'
|
||||
- 'configs/ci/integration/gsm8k-eval.toml'
|
||||
- name: Build integration matrix
|
||||
id: matrix
|
||||
env:
|
||||
# Main and manual runs retain the full suite.
|
||||
RUN_ALL: ${{ github.event_name != 'pull_request' }}
|
||||
SFT: ${{ steps.filter.outputs.sft || 'false' }}
|
||||
RL: ${{ steps.filter.outputs.rl || 'false' }}
|
||||
run: |
|
||||
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
|
||||
if $all or $sft then
|
||||
{test: "reverse_text_sft", name: "Reverse Text SFT"},
|
||||
{test: "reverse_text_sft_lora", name: "Reverse Text SFT LoRA"}
|
||||
else empty end,
|
||||
if $all or $rl then
|
||||
{test: "reverse_text", name: "Reverse Text"},
|
||||
{test: "reverse_text_rl_opd", name: "Reverse Text RL OPD"},
|
||||
{test: "reverse_text_rl_sft", name: "Reverse Text RL SFT"},
|
||||
{test: "alphabet_sort", name: "Alphabet Sort"},
|
||||
{test: "reverse_text_lora", name: "Reverse Text LoRA"},
|
||||
{test: "reverse_text_moe", name: "Reverse Text MoE"}
|
||||
else empty end
|
||||
]')
|
||||
echo "tests=$tests" >> "$GITHUB_OUTPUT"
|
||||
|
||||
unit-gpu:
|
||||
name: Unit (GPU)
|
||||
needs: changes
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 45
|
||||
if: needs.changes.outputs.unit == 'true'
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
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@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: uv run pytest tests/unit -m gpu
|
||||
|
||||
integration:
|
||||
name: Integration / ${{ matrix.name }}
|
||||
needs: changes
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 60
|
||||
if: needs.changes.outputs.integration != '[]'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
|
||||
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
|
||||
max-parallel: 5
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.changes.outputs.integration) }}
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y git
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
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@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ matrix.test }}-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
integration-eval:
|
||||
name: Integration / GSM8K Eval
|
||||
|
||||
+1
-2
@@ -144,9 +144,8 @@ celerybeat.pid
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
/ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
|
||||
@@ -61,5 +61,6 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
|
||||
## GitHub
|
||||
|
||||
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
|
||||
- **GPU CI is opt-in**: pushes to a PR don't run GPU tests. The full GPU suite runs on the PR's current commit when someone applies the `gpu-ci` label. Only when the user asks, request a run with `gh pr edit <num> --add-label gpu-ci`. The workflow removes the label, so re-add it after new pushes.
|
||||
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
|
||||
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
|
||||
|
||||
@@ -225,6 +225,14 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
|
||||
# Install uv for development use
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
|
||||
# The platform installs Hub environments with `uv run --no-sync prime env install`.
|
||||
# The CLI gets its own tool venv so its dependencies stay out of prime-rl's lock;
|
||||
# `prime env install` still installs into the project venv (/app/.venv).
|
||||
ARG PRIME_CLI_VERSION=0.19.2
|
||||
RUN UV_TOOL_DIR=/opt/uv-tools UV_TOOL_BIN_DIR=/usr/local/bin \
|
||||
uv tool install --no-cache --python /usr/bin/python3.12 "prime==${PRIME_CLI_VERSION}" \
|
||||
&& prime --version
|
||||
|
||||
USER appuser
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
|
||||
@@ -33,7 +33,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
|
||||
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
|
||||
4. End-to-end post-training: SFT, RL training, and evals.
|
||||
5. Multi-node deployment with Slurm support.
|
||||
6. Multimodal support for VLMs such as Qwen3.5.
|
||||
6. Multimodal support for Qwen3.5 and Qwen3.8 VLMs, with [image RL and SFT examples](examples/extra/vlm/README.md).
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
|
||||
|
||||
@@ -46,9 +46,11 @@ The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/m
|
||||
| Family | Example IDs | MoE | EP | CP |
|
||||
|--------|-------------|-----|----|-----|
|
||||
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
|
||||
| GLM-5.3 Flash, text only (`glm5_next`) | `zai-org/GLM-5.3-Flash-BF16` | yes | ✅ | ✅ |
|
||||
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Qwen3.8 Flash Next VLM (`qwen4_exp`) | `Qwen/Qwen3.8-Flash-Next` | yes | ✅ | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Muse Glimmer, text only (`muse_glimmer`) | `meta-models/Muse-Glimmer-30B` | no | — | ✅ |
|
||||
|
||||
@@ -3,12 +3,12 @@ bf16 EP path (``TorchTokenDispatcher`` + ``BF16ExpertCompute``) for the same rou
|
||||
workload, weights, and token counts, and check the gradients agree.
|
||||
|
||||
Requires >=2 SM90+ GPUs, PyTorch >= 2.9 (CUDA symmetric memory), and the prime-mega-moe
|
||||
``deep_gemm`` wheel from Prime Intellect installed over the public one. ``NCCL_MAX_CTAS`` must be
|
||||
set to at most the SMs Mega MoE reserves for NCCL (16). ``--hidden`` must be a multiple of 256 and
|
||||
``--intermediate`` a multiple of 128.
|
||||
``deep_gemm`` wheel from Prime Intellect installed over the public one. ``NCCL_MAX_CTAS`` defaults to half
|
||||
the SMs Mega MoE reserves for NCCL (16). ``--hidden`` must be a multiple of 256 and ``--intermediate`` a
|
||||
multiple of 128.
|
||||
|
||||
Usage:
|
||||
NCCL_MAX_CTAS=16 torchrun --nproc_per_node=8 benchmarks/mega_moe/bench_mega_moe.py \
|
||||
torchrun --nproc_per_node=8 benchmarks/mega_moe/bench_mega_moe.py \
|
||||
--num-experts 128 --top-k 8 --hidden 2048 --intermediate 1024 --tokens-per-rank 2048
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,12 @@ import torch.distributed as dist
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import FusedTokenDispatcher, TorchTokenDispatcher
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute
|
||||
from prime_rl.trainer.models.layers.mega_moe import MegaMoEExpertCompute, mega_moe_available, reserve_sms_for_comm
|
||||
from prime_rl.trainer.models.layers.mega_moe import (
|
||||
MegaMoEExpertCompute,
|
||||
default_nccl_max_ctas,
|
||||
mega_moe_available,
|
||||
reserve_sms_for_comm,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
|
||||
|
||||
@@ -58,6 +63,7 @@ def main() -> None:
|
||||
args = parse_args()
|
||||
local_rank = int(os.environ["LOCAL_RANK"])
|
||||
torch.cuda.set_device(local_rank)
|
||||
default_nccl_max_ctas(16, num_concurrent=2)
|
||||
dist.init_process_group(backend="nccl", device_id=torch.device("cuda", local_rank))
|
||||
rank, world_size = dist.get_rank(), dist.get_world_size()
|
||||
group = dist.group.WORLD
|
||||
@@ -108,7 +114,7 @@ def main() -> None:
|
||||
intermediate_hidden=args.intermediate,
|
||||
group=group,
|
||||
max_tokens_per_rank=args.tokens_per_rank,
|
||||
num_sms=reserve_sms_for_comm(16),
|
||||
num_sms=reserve_sms_for_comm(16, num_concurrent=2),
|
||||
)
|
||||
mega = (FusedTokenDispatcher(), mega_compute)
|
||||
|
||||
|
||||
@@ -20,14 +20,6 @@ max_steps = 20
|
||||
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
ep = 8
|
||||
|
||||
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
|
||||
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
|
||||
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
|
||||
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
|
||||
# nodes against the same weights and conversion cache this config trains on.
|
||||
[model.moe.dispatch]
|
||||
type = "torch"
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
max_steps = 30
|
||||
|
||||
[resume]
|
||||
step = 20
|
||||
@@ -0,0 +1,23 @@
|
||||
# Qwen3-0.6B trained from scratch on Reverse-Text-SFT as token shards. The test writes the shards and passes their
|
||||
# folder as --data.paths and --val.data.paths.
|
||||
max_steps = 20
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
paths = ["set-by-the-test"]
|
||||
seq_len = 1024
|
||||
batch_size = 8
|
||||
micro_batch_size = 2
|
||||
|
||||
[val]
|
||||
interval = 10
|
||||
num_samples = 16
|
||||
|
||||
[val.data]
|
||||
paths = ["set-by-the-test"]
|
||||
seq_len = 1024
|
||||
micro_batch_size = 2
|
||||
@@ -1,6 +1,6 @@
|
||||
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
|
||||
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
|
||||
# a ten-minute budget, against Prime Inference on the default model. One env server
|
||||
# a ten-minute budget, against Prime Inference on the default model. One env worker pool
|
||||
# per source; the sources share the taskset, so each carries its own name.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-env.toml
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 548244b959...797040d29e
Vendored
+1
-1
Submodule deps/prime-kernels updated: 310196075d...b52bd9dd4f
Vendored
+1
-1
Submodule deps/verifiers updated: 9f0f03ae47...72d08a0b65
+21
-19
@@ -22,9 +22,11 @@ The trainer only runs `prime-rl`'s own model implementations, selected from the
|
||||
| Family | HF config types | EP | CP |
|
||||
|---|---|---|---|
|
||||
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
|
||||
| GLM-5.3 Flash, text only (`glm5_next`) | `zai-org/GLM-5.3-Flash-BF16` | ✅ | ✅ |
|
||||
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
|
||||
| Qwen3.8 Flash Next VLM | `Qwen/Qwen3.8-Flash-Next` | ✅ | ✅ |
|
||||
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
|
||||
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
|
||||
| Muse Glimmer (text only) | `meta-models/Muse-Glimmer-30B` | — | ✅ |
|
||||
@@ -114,25 +116,24 @@ score functions, normalization and routing weights remain FP32.
|
||||
|
||||
For models that weight expert outputs after expert computation, local and Torch EP dispatch multiply
|
||||
by FP32 routing weights and sum the contributions in FP32, then cast once to the expert output dtype.
|
||||
This also covers MXFP8 expert compute with Torch dispatch. DeepEP and MegaMoE use their own combine
|
||||
kernels and do not share this accumulation guarantee.
|
||||
This also covers MXFP8 expert compute with Torch dispatch. With DeepEP, each rank sums its experts'
|
||||
outputs for a token in FP32 and casts once, then DeepEP's combine adds these per-rank BF16 sums in FP32
|
||||
(across nodes, after summing each node's ranks in FP32 and casting to BF16). MegaMoE uses its own combine
|
||||
kernels and does not share this accumulation guarantee.
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
|
||||
|
||||
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
|
||||
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
|
||||
- **`deepep`**: DeepEP custom dispatch/combine kernels. `num_sms` (default 32) is the number of SMs its kernels take from compute. DeepEP runs one communication channel per two SMs, so more SMs move tokens faster. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "deepep"
|
||||
num_sms = 20
|
||||
token_chunk_size = 4096
|
||||
num_sms = 32
|
||||
```
|
||||
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
### Runtime Fusions
|
||||
|
||||
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
|
||||
@@ -157,36 +158,37 @@ The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim
|
||||
|
||||
The built-in VLM registry covers:
|
||||
|
||||
| Family | `model_type` | Vision attr | LM attr |
|
||||
|---|---|---|---|
|
||||
| Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` |
|
||||
| Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` |
|
||||
| Family | `model_type` |
|
||||
|---|---|
|
||||
| Qwen3.5 | `qwen3_5` |
|
||||
| Qwen3.5-MoE | `qwen3_5_moe` |
|
||||
| Qwen3.8 Flash Next | `qwen4_exp` |
|
||||
|
||||
The trainer finds the vision encoder at `model.visual` and the language model at `model.language_model`.
|
||||
|
||||
Text-only checkpoints of these families set `language_model_only: true` in `config.json` and ship no `model.visual` weights. The trainer then builds no vision encoder. vLLM does not read this field, so for `rl` also set `inference.vllm.language_model_only = true`.
|
||||
|
||||
### Enabling VLM Mode
|
||||
|
||||
Add `[model.vlm]` and bfloat16 dtypes:
|
||||
Add `[model.vlm]` to your RL or SFT config:
|
||||
|
||||
```toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
# freeze_vision_encoder = true # default; set false to fine-tune the encoder
|
||||
```
|
||||
|
||||
The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically.
|
||||
For `rl`, set `[model.vlm]` in the shared `[model]` block.
|
||||
|
||||
VLM training requires a registered custom PrimeRL implementation.
|
||||
|
||||
### Limitations
|
||||
|
||||
- **Vision encoder frozen by default.** The default LoRA targets do not match Qwen3.5 vision modules. Set `freeze_vision_encoder = false` to fine-tune the encoder; this is incompatible with LoRA because LoRA freezes all non-adapter parameters.
|
||||
- **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio.
|
||||
- **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing.
|
||||
- **Precision settings are separate.** The examples serve with `inference.vllm.dtype = "bfloat16"` while retaining `trainer.model.optimization_dtype = "float32"` and `reduce_dtype = "float32"`. VLM mode does not require BF16 optimizer state or gradient reduction.
|
||||
- **Monitor trainer–inference mismatch.** Image encoding, parallel reductions and model kernels can contribute numerical differences. Track `mismatch_kl/all/mean`, `masked_mismatch_kl/mean`, `unmasked_mismatch_kl/mean` and `is_masked/mean` alongside reward.
|
||||
- **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images.
|
||||
|
||||
## LoRA Training
|
||||
|
||||
+3
-1
@@ -181,6 +181,8 @@ Long rollouts span several weight updates, and finished rollouts can wait in the
|
||||
|
||||
`orchestrator.max_staleness` (default 8) bounds token staleness. The orchestrator masks tokens past the bound out of the loss, and drops a sample only when no token is left to train. Rollouts are never cancelled for staleness.
|
||||
|
||||
The orchestrator ships each sample's per-token staleness to the trainer. The trainer logs the mismatch KL per log2 staleness bin (`0`, `1`, `2-3`, `4-7`, …, `64+`) as `mismatch_kl_by_staleness/{bin}/{mean,std,max}`. Use these metrics to separate the drift that staleness causes from the trainer–inference numerical mismatch: bin `0` holds only the numerical mismatch.
|
||||
|
||||
## Loss
|
||||
|
||||
### Loss Components
|
||||
@@ -607,7 +609,7 @@ tok.apply_chat_template(messages, tokenize=False)
|
||||
# (the <think>R1</think> from turn 2 is gone)
|
||||
```
|
||||
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `glm-5`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
|
||||
Hand-coded renderers ship for `qwen3`, `qwen3-vl`, `qwen3.5`, `qwen3.8`, `glm-5`, `glm-4.5`, `minimax-m2`, `deepseek-v3`, `kimi-k2`, `kimi-k2.5`, `nemotron-3`, `gpt-oss`; anything else falls back to `DefaultRenderer` (a generic `apply_chat_template` wrapper). Pick one via:
|
||||
|
||||
```toml
|
||||
[orchestrator.renderer]
|
||||
|
||||
+7
-6
@@ -41,10 +41,11 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
|
||||
|
||||
| Workflow | Trigger | What runs | Where |
|
||||
|---|---|---|---|
|
||||
| [`tests.yml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/tests.yml) | CPU jobs: every PR + push to `main`. GPU jobs: relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | CPU: `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`). GPU: `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | CPU: `ubuntu-latest`. GPU: self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
|
||||
| [`regression.yml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/regression.yml) | 03:00 PST daily + manual `workflow_dispatch` (`suite` picks one suite); `eval` also on PRs that touch it | `parallel`: `tests/regression/test_parallel_invariance.py` (layouts that need more than 2 GPUs skip). `eval`: `tests/regression/configs/eval/*.toml` against Prime Inference, compared against `tests/regression/baselines/eval/` | `eval`: `ubuntu-latest`. `parallel`: `prime-rl-2xh200` |
|
||||
| [`tests.yml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/tests.yml) | CPU jobs: every PR + push to `main`. `gsm8k_eval`: relevant changes in non-draft PRs, every push to `main`, manual dispatch | CPU: `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`). Separate hosted `gsm8k_eval` job | `ubuntu-latest` |
|
||||
| [`gpu.yml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu.yml) | On a PR: applying the `gpu-ci` label (Triage or higher). Also every merge to `main` and manual dispatch | Full GPU suite: `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5` | Self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for the trigger check |
|
||||
| [`regression.yml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/regression.yml) | 03:00 PST daily + manual `workflow_dispatch` (`suite` picks one suite; `eval_config` picks one eval config); `eval` also on PRs that touch it | `parallel`: `tests/regression/test_parallel_invariance.py` (layouts that need more than 2 GPUs skip). `eval`: every `tests/regression/configs/eval/*.toml` (gsm8k, PI-TerminalBench2.1) against Prime Inference, each compared against its baseline in `tests/regression/baselines/eval/`. Nightly and manual runs post one Slack message per config through the `SLACK_WEBHOOK_URL` secret | `eval`: `ubuntu-latest`. `parallel`: `prime-rl-2xh200` |
|
||||
|
||||
The GPU jobs skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
|
||||
Pushes to a PR do not run GPU jobs. To run the GPU suite on a PR's current commit, apply the `gpu-ci` label (drafts included). The workflow removes the label when it starts, so re-apply it to run again after new pushes or to retry. A new trigger cancels the PR's queued or in-flight GPU run. Fork PRs cannot run GPU CI: a maintainer can push the branch to this repo and label that PR. A PR with merge conflicts cannot run it until the conflicts are resolved.
|
||||
|
||||
### Markers
|
||||
|
||||
@@ -142,9 +143,9 @@ In the PR that adds the new model, you also need to provide a table covering the
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
|
||||
|
||||
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` whenever `image_grid_thw` is given (the renderer owns the token→modality mapping; the trainer always passes plain `position_ids`, which the model uses for text-only rows). Keep the vision encoder at `model.model.visual` and the text model at `model.model.language_model`: FSDP, freezing, activation checkpointing, compile, the MoE runtime and NCCL weight broadcast find them there (`trainer/vlm.py`). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class. RL turns raw image refs into vision kwargs with the model class's `materialize_images(refs, processor)`; Qwen3.5 and Qwen3.8 Flash Next each define it in their `vision.py`, and a new family implements its own.
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for every batch with images.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
+4
-4
@@ -15,7 +15,7 @@ This page covers `uv run eval` — evaluating a model in one or more environment
|
||||
- [Prime](#prime)
|
||||
- [Metrics](#metrics)
|
||||
|
||||
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
|
||||
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env worker pools are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
|
||||
|
||||
## Launch
|
||||
|
||||
@@ -79,7 +79,7 @@ Per-source `group_size` and `sampling` override the top-level defaults. The top-
|
||||
|
||||
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
|
||||
|
||||
Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
Every source's env worker pool is spawned by the eval process unless the source sets `serve.address`, in which case the pool is externally managed. A pool's broker binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
|
||||
## Live Concurrency
|
||||
|
||||
@@ -118,7 +118,7 @@ Monitors receive the run's metrics and episodes through one abstraction. The fil
|
||||
|
||||
### File
|
||||
|
||||
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
|
||||
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env worker pools stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
|
||||
|
||||
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
|
||||
|
||||
@@ -130,7 +130,7 @@ Each source's epoch streams as an evaluation on the Prime platform. The launcher
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8
|
||||
```
|
||||
|
||||
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `View on Prime` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
|
||||
The monitor opens one Prime evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its Prime identity in `monitors/prime/run.json` (one entry per evaluation), and the dashboard's top bar shows a `View on Prime` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
|
||||
|
||||
## Metrics
|
||||
|
||||
|
||||
+2
-2
@@ -192,7 +192,7 @@ Both backends support the 2 most important things:
|
||||
|
||||
### Routing policies
|
||||
The policies you might want to configure are:
|
||||
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
|
||||
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Releases run with bounded concurrency; a release that waits too long for a slot, or fails, is dropped, and the router expires the session after its TTL. Failed releases are logged as a warning and counted in the cumulative `sessions/released` and `sessions/release_failed` metrics.
|
||||
|
||||
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
|
||||
|
||||
@@ -326,7 +326,7 @@ enable_router_replay = true # this will also auto-set inference.vllm.enable_retu
|
||||
enable_return_routed_experts = true
|
||||
```
|
||||
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env worker pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Router replay works with `inference.kv_cache_offload` (native and Mooncake). vLLM keeps routing rows in a local store keyed by block hash, and no connector moves them with the KV, so a loaded block has no rows on this instance. prime-rl therefore limits an offload load to the prompt tokens the client already has routing for: the blocks before `routed_experts_prompt_start`. Multi-turn rollouts keep their offload hits, because the reloaded earlier turns sit before that position. Offloaded prefixes past it (first turns, prompts shared across a group or across nodes) are recomputed. Loaded blocks then serve local GPU prefix hits like any other block, so a local hit is cut at the first loaded block that a request needs routing from (for example a first turn that hits a prefix reloaded by another rollout's later turn), and the rest is recomputed. Under P/D, decode-side loads are not limited: decode requests emit routing only from their first forward.
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"eval",
|
||||
"inference",
|
||||
"scaling",
|
||||
"model-express",
|
||||
"algorithms",
|
||||
"ipo",
|
||||
"advanced",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# ModelExpress
|
||||
|
||||
`[weight_broadcast] type = "modelexpress"` sends full FSDP weight updates from the trainer to vLLM through [ModelExpress](https://github.com/ai-dynamo/modelexpress) (MX). Inference GPUs pull their shards over RDMA (NIXL) from a host snapshot of the trainer shards, so the trainer does not run a collective with inference.
|
||||
|
||||
## Setup
|
||||
|
||||
The GPU extra pins the MX client (`modelexpress==0.8.0.dev20261022`). Build the matching server and its Redis backend once on the shared filesystem:
|
||||
|
||||
```bash
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
`uv run rl` starts a run-scoped server and Redis (logs under `logs/modelexpress/`). Multi-node SLURM jobs start them on the trainer head node. To use an existing server instead, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
|
||||
|
||||
## Config
|
||||
|
||||
```toml
|
||||
[weight_broadcast]
|
||||
type = "modelexpress"
|
||||
staging_buffer_bytes = 4294967296 # bounded staging; omit to stage the full update
|
||||
staging_buffers_count = 2 # overlap the next read with the current install
|
||||
```
|
||||
|
||||
- `staging_mode`: `COPY_TO_HOST` (default) snapshots trainer shards into host memory. `COPY_TO_DEVICE` uses extra GPU memory. `IN_PLACE` copies nothing, but requires the trainer tensors to stay unchanged and already have the transfer dtype until inference has installed them.
|
||||
- `staging_buffer_bytes` × `staging_buffers_count` bounds the extra receiver memory per inference GPU. Without it, each GPU stages a full copy of its shard, which can OOM at high `gpu_memory_utilization`.
|
||||
|
||||
## Behavior
|
||||
|
||||
- The first update is slower while MX plans the transfer; later updates reuse the plan.
|
||||
- Inference is paused only after the trainer has published the version. A failed update leaves inference paused; restart the trainer and inference together, since there is no rollback.
|
||||
- Trainer rank 0 and the orchestrator must share the broadcast directory, which holds only rendezvous markers, not weights.
|
||||
|
||||
## Limitations
|
||||
|
||||
LoRA, speculative decoding, Dynamo discovery and SFT online evals are rejected at config validation. P/D disaggregated inference is not supported, and pipeline parallelism is untested.
|
||||
+11
-7
@@ -104,20 +104,19 @@ type = "torch"
|
||||
transport = "bf16"
|
||||
```
|
||||
|
||||
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
|
||||
For DeepEP, set `type = "deepep"` and tune `num_sms` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
|
||||
|
||||
Mega MoE (`type = "mega_moe"`) fuses dispatch, the SwiGLU expert MLP, and combine into one persistent kernel per direction, overlapping the expert-parallel communication with the GEMMs. `precision` selects the expert GEMMs: `bf16` (default, SM90+), `mxfp8` (SM100), `fp8` (blockwise FP8 forward and backward, SM90), or `fp8_bwd` (BF16 forward, blockwise FP8 backward, SM90); `[trainer.model.moe.compute]` does not apply to those layers. The kernels come from prime-mega-moe, Prime Intellect's closed-source DeepGEMM fork, built as a `deep_gemm` wheel that replaces the public one (`uv pip install --no-deps <wheel>` after syncing). Without it, selecting `mega_moe` fails at startup with a message naming the missing kernels. Mega MoE needs EP > 1, nvcc 13 on `CUDA_HOME` for the runtime JIT, gated experts without biases, `hidden_size` divisible by 256 and `moe_intermediate_size` by 128.
|
||||
|
||||
The kernels are persistent grids that synchronize across ranks, so an NCCL kernel on another stream (FSDP all-gathers, gradient reductions) has to fit in the SMs they leave free, or the two deadlock. `num_reserved_sms` is how many SMs they leave free. `NCCL_MAX_CTAS` caps the CTAs (one per SM) a NCCL kernel launches, so the trainer refuses to start unless it is set to at most `num_reserved_sms`. 16 is enough for FSDP's collectives; every reserved SM is taken from the GEMMs, so match the two rather than over-reserving. The symmetric buffer is sized once at startup from `max_tokens_per_rank`, which defaults to the micro batch (`model.seq_len` for RL, `data.micro_batch_size * data.seq_len` for SFT); a smaller value is rejected at startup.
|
||||
The kernels are persistent grids that synchronize across ranks, so an NCCL kernel on another stream (FSDP all-gathers, gradient reductions) has to fit in the SMs they leave free, or the two deadlock. `num_reserved_sms` is how many SMs they leave free. `NCCL_MAX_CTAS` caps the CTAs (one per SM) a NCCL kernel launches. In the worst case each NCCL kernel uses all `NCCL_MAX_CTAS`, so at most `num_reserved_sms // NCCL_MAX_CTAS` NCCL kernels can run concurrently. FSDP overlaps an all-gather and a reduce-scatter, and HSDP (`dp_replicate > 1`) adds an all-reduce, so the trainer sets `NCCL_MAX_CTAS` to `num_reserved_sms // 2` (`// 3` under HSDP) when it is unset, and refuses to start if it is set higher than that. The default 16 reserved SMs (8 CTAs, 5 under HSDP) are enough for FSDP's collectives; every reserved SM is taken from the GEMMs, so raise `num_reserved_sms` only if NCCL needs more. The symmetric buffer is sized once at startup from `max_tokens_per_rank`, which defaults to a rank's share of the micro batch under context parallelism (`model.seq_len / model.cp` for RL, `data.micro_batch_size * data.seq_len / model.cp` for SFT); a smaller value is rejected at startup.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "mega_moe"
|
||||
precision = "bf16" # or "mxfp8" (SM100), "fp8" / "fp8_bwd" (SM90)
|
||||
num_reserved_sms = 16 # SMs left free for NCCL; NCCL_MAX_CTAS must be <= this
|
||||
num_reserved_sms = 16 # SMs left free for NCCL; NCCL_MAX_CTAS defaults to this // 2 (// 3 under HSDP)
|
||||
|
||||
[trainer.env_vars]
|
||||
NCCL_MAX_CTAS = "16"
|
||||
CUDA_HOME = "/usr/local/cuda-13.0"
|
||||
PATH = "/usr/local/cuda-13.0/bin:${PATH}"
|
||||
```
|
||||
@@ -142,7 +141,7 @@ cp = 2 # CP degree
|
||||
| `trainer.model.ac.mode = "selective"` | medium | small |
|
||||
| `trainer.model.ac_offloading` | extra | a bit more |
|
||||
|
||||
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
|
||||
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates that cannot safely replay; full AC recomputes MoE dispatch communication. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
@@ -248,7 +247,6 @@ type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
SFT multi-node:
|
||||
@@ -271,6 +269,10 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### ModelExpress weight broadcast
|
||||
|
||||
See [ModelExpress](model-express.md) for the `modelexpress` weight transport.
|
||||
|
||||
### NIXL weight broadcast
|
||||
|
||||
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
|
||||
@@ -308,7 +310,9 @@ To benchmark a parallelism config before committing a multi-day run, run a short
|
||||
uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
|
||||
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
|
||||
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
|
||||
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4 --no-monitors.prime
|
||||
```
|
||||
|
||||
With `--data.fake.generate-samples`, fake RL data packs random-length samples into each row; add `--data.fake.doc-len N` to make every sample N tokens instead (the last one cut to fill the row), e.g. two 262k-token rollouts in a 524k-token row.
|
||||
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup.
|
||||
|
||||
+158
-17
@@ -17,10 +17,12 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
- [Launch](#launch-1)
|
||||
- [SFT-Specific Knobs](#sft-specific-knobs)
|
||||
- [Important Metrics](#important-metrics-1)
|
||||
- [Pretraining](#pretraining)
|
||||
- [Checkpointing](#checkpointing)
|
||||
- [Enabling Checkpoints](#enabling-checkpoints)
|
||||
- [Resuming a Run](#resuming-a-run)
|
||||
- [Pausing a Live Run](#pausing-a-live-run)
|
||||
- [Pausing or Checkpointing a Live Run](#pausing-or-checkpointing-a-live-run)
|
||||
- [Updating the Config Live](#updating-the-config-live)
|
||||
- [Serving Checkpoints](#serving-checkpoints)
|
||||
- [Observability](#observability)
|
||||
- [Config Files](#config-files)
|
||||
@@ -38,10 +40,38 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
|---|---|---|
|
||||
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
|
||||
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
|
||||
| `uv run pretrain` | Pretraining from scratch on tokenized shards. | Launches torchrun internally; see [Pretraining](#pretraining). |
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-worker-pool` per source. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
|
||||
| `uv run env-worker-pool` | One source's worker pool replica: a broker and its env workers. | Launchers start these automatically. Use this command for standalone pools, including sources whose `serve.address` points to an externally managed pool. |
|
||||
|
||||
### Env worker pools
|
||||
|
||||
Each train/eval source has its own env configuration. Two sources can use the same taskset
|
||||
with different agents or settings. Each source can have multiple worker pool replicas:
|
||||
single-node runs start one, and multi-node RL runs start one per inference node. An explicit
|
||||
`serve.address` selects one externally managed pool instead.
|
||||
|
||||
```text
|
||||
Orchestrator
|
||||
└── Source (env configuration)
|
||||
├── Pool replica 1: PRL::EnvBroker
|
||||
│ ├── PRL::EnvWorker
|
||||
│ └── PRL::EnvWorker
|
||||
└── Pool replica 2: PRL::EnvBroker
|
||||
└── PRL::EnvWorker
|
||||
```
|
||||
|
||||
The orchestrator selects the least-loaded replica; its broker dispatches to the least-busy
|
||||
worker. Each worker loads its own Verifiers env and can execute multiple episodes concurrently.
|
||||
The orchestrator loads the dataset and sends task data with each request. Even a one-worker
|
||||
pool has a broker and a separate worker process.
|
||||
|
||||
`[serve]` configures the pool's address, static/elastic worker count and per-worker episode
|
||||
concurrency. Each broker publishes its bound address under
|
||||
`configs/attempt_N/resolved/envs/<split>/<name>.address` (or `<name>.<replica>.address` for
|
||||
multiple replicas). Broker and worker logs share the source's log file.
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -74,8 +104,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
|
||||
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
|
||||
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. The orchestrator's env servers and its [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) logs use the same level. |
|
||||
| `--monitors.wandb` (+ `--monitors.wandb.project`, `--monitors.wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
|
||||
| `--no-monitors.prime` | Stop streaming metrics and episodes to the Prime Intellect platform (Prime Lab), on by default. See [Prime](#prime). |
|
||||
|
||||
@@ -131,6 +160,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
**Stability** (trainer):
|
||||
|
||||
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
|
||||
- `mismatch_kl_by_staleness/{bin}/{mean,std,max}` — the same KL per log2 bin of token staleness (`0`, `1`, `2-3`, `4-7`, …, `64+`). Bin `0` is the numerical trainer–inference mismatch alone; the rise across bins is the policy drift that staleness adds.
|
||||
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
|
||||
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
|
||||
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
|
||||
@@ -204,9 +234,9 @@ clear_thinking = true
|
||||
|
||||
The same config selects the renderer for RL under `[orchestrator.renderer]`. The [`renderers` README](https://github.com/PrimeIntellect-ai/renderers#custom-renderers) shows the class behind this example.
|
||||
|
||||
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
|
||||
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, Qwen3.8, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5/Qwen3.8.
|
||||
|
||||
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
|
||||
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class: Qwen3.5 dense and MoE, and Qwen3.8 Flash Next (`qwen4_exp`, text and images). See the [multimodal examples](../examples/extra/vlm/README.md) for SFT and multi-node image RL configurations.
|
||||
|
||||
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
|
||||
|
||||
@@ -246,11 +276,11 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They 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).
|
||||
The launcher starts the inference server, one env worker pool per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They 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 Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env worker pools, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
@@ -296,6 +326,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
|
||||
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
|
||||
- For MoE with EP: `ep_imbalance/rank/{mean,max}` — the busiest EP rank's routes over the mean rank's (padding included) in each layer and microstep, which sets the layer's expert time. It takes the max over DP groups at each layer and microstep, then the mean and max over the step's layers and microsteps; `ep_imbalance/rank_dp_mean/{mean,max}` takes the DP mean instead.
|
||||
|
||||
**Performance:**
|
||||
|
||||
@@ -304,9 +335,65 @@ Pulled from the console log and mirrored to W&B.
|
||||
| `perf/throughput`, `perf/throughput_per_gpu` | tokens/s overall and per GPU |
|
||||
| `perf/mfu` | MFU, including attention FLOPs |
|
||||
| `perf/mfu_6dn` | MFU from the plain 6 x active params x tokens estimate (no attention FLOPs) |
|
||||
| `perf/peak_memory` | peak GPU memory (GiB) |
|
||||
| `perf/peak_memory` | peak GPU memory from all sources, max over ranks (GiB) |
|
||||
| `perf/non_torch_memory` | GPU memory outside PyTorch's caching allocator (symmetric memory such as Mega MoE's buffers, NCCL, CUDA context), max over ranks (GiB) |
|
||||
| `time/step`, `time/forward_backward`, `time/save_ckpt` | step breakdown |
|
||||
|
||||
## Pretraining
|
||||
|
||||
`uv run pretrain` trains a model from scratch on tokenized text. It shares the trainer, launcher, checkpointing and monitoring with `uv run sft`. What differs is the data, and that the weights start from the model's own init: `model.name` only supplies the architecture, and a resumed run loads its weights from the checkpoint. The from-scratch init is tested on dense models. The defaults are SFT's, except `optim.lr = 1e-3` and a 10-step linear learning-rate warmup.
|
||||
|
||||
**Tokenize first.** prime-rl does not tokenize; it reads the output of [datatrove](https://github.com/huggingface/datatrove)'s `DocumentTokenizer`: `*.ds` token files, each with its `.ds.index` (document ends) and `.ds.metadata`. datatrove is a separate install (`pip install datatrove`), not a prime-rl dependency. Set `eos_token` to the tokenizer's end-of-text token, which is not always its EOS: for Qwen it is `<|endoftext|>`, not `<|im_end|>`. datatrove adds no separator by default and prime-rl adds none either, so without one the documents run together and the model never learns to stop. The trainer warns at startup when shards look like they have no separator.
|
||||
|
||||
```python
|
||||
# Run with datatrove installed. Tokenize held-out documents into another folder for validation.
|
||||
from datatrove.executor import LocalPipelineExecutor
|
||||
from datatrove.pipeline.readers import ParquetReader
|
||||
from datatrove.pipeline.tokens import DocumentTokenizer
|
||||
|
||||
LocalPipelineExecutor(
|
||||
pipeline=[
|
||||
ParquetReader("hf://datasets/HuggingFaceFW/fineweb-edu/sample/10BT"),
|
||||
DocumentTokenizer(
|
||||
output_folder="data/fineweb-edu",
|
||||
tokenizer_name_or_path="Qwen/Qwen3-0.6B",
|
||||
eos_token="<|endoftext|>",
|
||||
),
|
||||
],
|
||||
tasks=16,
|
||||
).run()
|
||||
```
|
||||
|
||||
**Configure.** Only `data.paths` is required:
|
||||
|
||||
```toml
|
||||
max_steps = 1000
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B" # only the architecture is read
|
||||
|
||||
[data]
|
||||
paths = ["data/fineweb-edu"]
|
||||
seq_len = 2048
|
||||
batch_size = 256
|
||||
|
||||
[val] # optional
|
||||
interval = 100
|
||||
num_samples = 512 # windows per validation; leave out to read the held-out shards once
|
||||
|
||||
[val.data]
|
||||
paths = ["data/fineweb-edu-val"]
|
||||
seq_len = 2048
|
||||
```
|
||||
|
||||
All files in `data.paths` (in folder order, then file name order) form one token pool. Each epoch reads every `seq_len` window of the pool once, in a new random order and from a new random offset drawn from `data.seed`. Attention and positions restart at every document; `data.document_masking = false` makes a window one sequence. A resumed run reads exactly the windows an uninterrupted run would, also on another number of GPUs, as long as `data.num_workers` stays the same.
|
||||
|
||||
**Launch.**
|
||||
|
||||
```bash
|
||||
uv run pretrain @ pretrain.toml
|
||||
```
|
||||
|
||||
## Checkpointing
|
||||
|
||||
Checkpointing is split across processes because the orchestrator and trainer can be on different machines and on different steps at any given time. Inference is stateless.
|
||||
@@ -347,7 +434,25 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Pausing a Live Run
|
||||
#### What a resume restores
|
||||
|
||||
- The curriculum of each train source, and the live config (see [Updating the Config Live](#updating-the-config-live)).
|
||||
- The open train groups: groups that were drawn but not shipped at the checkpoint. The checkpoint saves no partial groups, so a resume re-runs each one whole, before it draws new tasks. A re-run group goes through the curriculum again, with its new rollouts. A group that finished without training (for example, rejected by the curriculum) does not re-run.
|
||||
- A resume drops the open groups of a removed source or task. It also drops those of a streaming taskset, which cannot find a task by key.
|
||||
|
||||
#### Changing sources on resume
|
||||
|
||||
A resume can add, remove or change train and eval sources.
|
||||
|
||||
- Sources match by name (`name`, else the env id). Renaming a source counts as removing it and adding a new one. A source that you add on resume uses the launch config.
|
||||
- Tasks match by `Task.key`. The default key hashes the task data without the generated row index (`idx`), so adding, removing or moving rows keeps the state of the other tasks. A change to a task's other data, including a config-level `system_prompt`, makes it a new task. Identical rows need distinct `TaskData.id` values or a custom `Task.key` to keep their state separate.
|
||||
- A new train source starts with a fresh curriculum. The checkpointed curriculum of a removed train source is dropped.
|
||||
- When a source's taskset gains or loses tasks, `StandardSampler` keeps the sampling counts of the remaining tasks. New tasks start at the lowest remaining count, so they join the current pass. `DifficultyPoolSampler` drops the rewards of removed tasks, and new tasks start unseen.
|
||||
- A streaming taskset resumes at the same offset into the stream, so a changed stream does not resume at the same task.
|
||||
- A changed sampler type starts the sampler fresh. Admission gates match by name: a new gate starts fresh, and the state of a removed gate is dropped.
|
||||
- Eval sources hold no checkpointed state. A new eval source first runs at the next step that is a multiple of its interval.
|
||||
|
||||
### Pausing or Checkpointing a Live Run
|
||||
|
||||
With `--trainer.control` and `--orchestrator.control` (SFT: `--control`), the trainer serves a small control API on port 8040 and the orchestrator on 8041. Each saves only its own state, so a pause asks the trainer first: it accepts the pause at its next step N, trains N, saves it and stops. The orchestrator is then asked to pause at N and saves its state as of shipping N, which it can always do because a paused trainer never requests N + 1. A pause is `committed` on each once that component saved N, and the run continues with `--resume`:
|
||||
|
||||
@@ -355,15 +460,51 @@ With `--trainer.control` and `--orchestrator.control` (SFT: `--control`), the tr
|
||||
uv run rl @ rl.toml --ckpt --trainer.control --orchestrator.control --run.name my-run
|
||||
|
||||
curl -X POST localhost:8040/v1/actions -H 'content-type: application/json' -d '{"type": "pause"}'
|
||||
# {"id": "3f2a...", "type": "pause", "state": "pending", "step": null}
|
||||
# {"id": "3f2a...", "type": "pause", "state": "pending", "step": null, "changes": null}
|
||||
curl localhost:8040/v1/actions/3f2a...
|
||||
# {"id": "3f2a...", "type": "pause", "state": "accepted", "step": 12}
|
||||
# {"id": "3f2a...", "type": "pause", "state": "accepted", "step": 12, "changes": null}
|
||||
curl -X POST localhost:8041/v1/actions -H 'content-type: application/json' -d '{"type": "pause", "step": 12}'
|
||||
# {"id": "9c41...", "type": "pause", "state": "pending", "step": 12}
|
||||
# {"id": "9c41...", "type": "pause", "state": "pending", "step": 12, "changes": null}
|
||||
```
|
||||
|
||||
Once paused, both keep serving the API until the run is stopped, so its owner can read the committed step first.
|
||||
|
||||
A `checkpoint` action takes the same two calls and saves step N without stopping the run. Since the trainer keeps going, the orchestrator has to receive its request before the trainer finishes N and requests N + 1; a later request gets a 409 because the orchestrator no longer has the state of N:
|
||||
|
||||
```bash
|
||||
curl -X POST localhost:8040/v1/actions -H 'content-type: application/json' -d '{"type": "checkpoint"}'
|
||||
curl -X POST localhost:8041/v1/actions -H 'content-type: application/json' -d '{"type": "checkpoint", "step": 12}'
|
||||
```
|
||||
|
||||
### Updating the Config Live
|
||||
|
||||
With `--orchestrator.control`, you can also resubmit the full orchestrator config while the run is going. Read the current config, edit it, and submit it back as an `update_config` action:
|
||||
|
||||
```bash
|
||||
curl localhost:8041/v1/config > current.json
|
||||
# {"revision": 0, "step": 41, "config": {...}}
|
||||
jq '{type: "update_config", config: (.config | .max_staleness = 4 | .train.source[0].sampling.temperature = 0.8)}' current.json > update.json
|
||||
curl -X POST localhost:8041/v1/actions -H 'content-type: application/json' -d @update.json
|
||||
# {"id": "7b0e...", "type": "update_config", "state": "pending", "step": null, "changes": [{"path": "train.source[0].sampling.temperature", "old": 1.0, "new": 0.8}, {"path": "max_staleness", "old": 8, "new": 4}]}
|
||||
curl localhost:8041/v1/actions/7b0e...
|
||||
# {"id": "7b0e...", "type": "update_config", "state": "applied", "step": 43, "changes": [...]}
|
||||
```
|
||||
|
||||
The orchestrator validates the config and compares it with the running one when you submit it. A rejected update returns 422 with the changed fields that are frozen in `frozen`, and any validation `errors`. It returns 409 if another update is queued or the run is pausing. The update applies after the orchestrator ships its next step: rollouts dispatched from then on use the new config, while running rollouts, and groups that already started, keep their old settings. Nothing is cancelled. Each applied update bumps the config revision, is logged, and is written to `configs/attempt_<n>/resolved/updates/rev_<k>.json`. Checkpoints record the live config, so `--resume` continues with the updates that were in effect at the checkpoint. The rule is per field: if the launch config still has the value the checkpointed run was launched with, the live value is restored; if you changed the field in the launch config, your value wins. The orchestrator logs the restored fields and writes them to `updates/rev_<k>.json` of the new attempt.
|
||||
|
||||
Only these fields are live; every other field is frozen:
|
||||
|
||||
| Field | Effect |
|
||||
|---|---|
|
||||
| `batch_size`, `max_staleness` | The next batch uses the new size, and queued samples are checked against the new staleness bound. |
|
||||
| `concurrency.min_inflight`, `concurrency.max_inflight` | Moves the adaptive concurrency band. A lower limit cancels nothing; new rollouts wait until enough finish. A target set through the concurrency API stays in place. `concurrency.initial_inflight` only seeds the startup cap, so it may change (e.g. to stay below a lower `max_inflight`) without effect. |
|
||||
| `train.source[*].ratio` | Changes the env mix weights. |
|
||||
| `train.source[*].sampling` | Changes a source's `temperature`, `max_completion_tokens` and `extra_body`. `top_p`, `top_k` and `logprobs` are frozen: they decide sampling replay and top-logprob streams at launch. Set sampling per source: the group-level `train.sampling` is only a default for the sources and is frozen. |
|
||||
| `eval.source[*].interval` | Changes eval cadence from the next policy update. |
|
||||
| `train.source[*].algo.length_penalty` | Changes a GRPO source's length penalty: its weights, its type, or turning it on (a config) or off (`null`). It applies to every group scored from the next step on, including groups already running, since a group is scored when its last rollout finishes. Set it per source: the group-level `train.algo` is only a default for the sources and is frozen. |
|
||||
|
||||
Frozen fields include the model, tokenizer, renderer, transports, monitors, logging, checkpointing, output directory, padding and the trainer topology, which are fixed at launch. `seq_len` and `max_steps` are frozen because the trainer depends on them. Group sizes, algorithms (except the length penalty), curricula, eval sampling and task selection are frozen, as are adding, removing, renaming or reordering sources and turning eval on or off. In the config, a live field is annotated with `Annotated[T, Live()]` (from `prime_rl.configs.diff`); every other field is frozen.
|
||||
|
||||
### Exporting Checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
|
||||
@@ -403,10 +544,10 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node inference stdout (multi-node only)
|
||||
│ └── router.log # the single global router (multi-node only)
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
└── envs/{train,eval}/<env_name>.log # source's worker pool (broker + worker processes)
|
||||
```
|
||||
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
@@ -459,7 +600,7 @@ Name the Prime run in TOML:
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
|
||||
The process that supervises the launch registers the run before the components start, and every component logs to it. That is the `rl` or `sft` launcher, also inside a single-node SLURM job, or the run owner that wraps a multi-node SLURM job's step. The run's id is also the run identity (`PRL_RUN_ID`) and the W&B run id. On `rl` the orchestrator uploads the episodes and its metrics, and the trainer uploads its per-step metrics. A trainer started without the `rl` launcher needs `--no-monitors.prime`. On `sft` the run carries the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and the trainer's per-step metrics and validation losses. Online evals log to the same run, like an `rl` run's: the online-eval process uploads its eval metrics and every eval episode. The components only flush their uploads; the process that registered the run finishes it once every component exited. A launch that fails marks the run failed, and so does a SLURM job that SLURM cancels or stops at its time limit.
|
||||
|
||||
The platform run needs `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. Like the W&B monitor, a run without a key, or one whose registration fails (no team, a team outside the allowlist), fails at launch: authenticate, select a team with `prime switch`, or pass `--no-monitors.prime`. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
|
||||
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ Walk-throughs for the core environments (baseline eval → optional SFT warmup
|
||||
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
|
||||
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
|
||||
- [`vlm/`](extra/vlm/README.md) — Qwen3.5 / Qwen3.8 multi-node image RL and dense + MoE LoRA SFT
|
||||
|
||||
## Related config folders
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# GLM-5.3 Flash SWE RL on SWE-rebench-V2 (20-turn cap) at 128K context:
|
||||
# 2 trainer nodes + 4 vLLM replicas (TP 8, one node each), H200.
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-5.3-flash/swe.toml
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 131072
|
||||
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
|
||||
clean = true
|
||||
|
||||
[run]
|
||||
name = "glm53-flash-swe"
|
||||
|
||||
[ckpt]
|
||||
interval = 10
|
||||
keep_last = 1
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-Flash-BF16"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "glm53-flash"
|
||||
name = "swe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 12000
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
# Trainer nodes peak near 3 TB host RAM with AdamW offloaded; the orchestrator's 128K rollout buffer tips them over.
|
||||
orchestrator_on_inference = true
|
||||
|
||||
[slurm]
|
||||
job_name = "glm53-flash-swe"
|
||||
partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
# vLLM sizes this hybrid model's pages at 640 tokens; DeepGEMM's k-pool indexer on SM90 needs a multiple of 256.
|
||||
block_size = 768
|
||||
# Higher values OOM on the first weight update while receiving an MoE layer.
|
||||
gpu_memory_utilization = 0.75
|
||||
# vLLM's KDA decode kernel puts num_seqs * 64 on a grid axis capped at 65535.
|
||||
max_num_seqs = 512
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
|
||||
[trainer.ckpt]
|
||||
# Weights only: AdamW state would make each checkpoint ~4.5 TB instead of ~0.65 TB.
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.model]
|
||||
ep = 8
|
||||
# Keeps 16K tokens per GPU at 128K context.
|
||||
cp = 8
|
||||
offload = "full"
|
||||
# Host RAM sits at ~99% with AdamW state offloaded; activation offloading tipped a trainer node into a stall.
|
||||
ac_offloading = "None"
|
||||
|
||||
[trainer.model.ac]
|
||||
mode = "full"
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
# GLM-5.3 Flash's text template is GLM-5.3's.
|
||||
name = "glm-5.3"
|
||||
clear_thinking = false
|
||||
|
||||
[orchestrator.train.sampling.extra_body.chat_template_kwargs]
|
||||
clear_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swerebench"
|
||||
env.taskset.id = "swerebench-v2"
|
||||
env.taskset.dataset_name = "PrimeIntellect/SWE-rebench-V2-Filtered-Verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.max_turns = 20
|
||||
# Fail rollouts stuck on a dead sandbox stream instead of letting them hold in-flight slots forever.
|
||||
env.timeout.episode = 7200
|
||||
env.agent.runtime.labels = ["glm53-flash", "swe"]
|
||||
@@ -27,7 +27,7 @@ prime login # or: prime config set-api-key <your-key>
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
|
||||
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses in the env workers.
|
||||
|
||||
## Setup
|
||||
|
||||
|
||||
@@ -1,22 +1,39 @@
|
||||
# VLM SFT
|
||||
# Vision-language training
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
RL and SFT examples for the custom [PrimeRL VLM implementations](../../../docs/advanced.md#multimodal-training).
|
||||
|
||||
## Image RL
|
||||
|
||||
| Config | Model | Batch / group | CP |
|
||||
|---|---|---|---|
|
||||
| [`rl-qwen3.5.toml`](rl-qwen3.5.toml) | `Qwen/Qwen3.5-122B-A10B` | 336 / 16 | 4 |
|
||||
| [`rl-qwen3.8.toml`](rl-qwen3.8.toml) | `Qwen/Qwen3.8-Flash-Next` | 256 / 16 | 8 |
|
||||
|
||||
Both target **4 trainer + 4 inference nodes**, each with 8× H200 GPUs.
|
||||
|
||||
The examples use `primeintellect/color-codeword` with separate training and evaluation task slices. Replace it with your multimodal environment and compatible harness, and update run/W&B names and the shared output path. Install environments with `uv sync --all-extras --all-packages` and export any credentials they require.
|
||||
|
||||
After [setup](../../../README.md#setup), validate from a shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/extra/vlm/rl-qwen3.8.toml --dry-run
|
||||
```
|
||||
|
||||
Remove `--dry-run` to submit; swap in `rl-qwen3.5.toml` for Qwen3.5. See [Scaling](../../../docs/scaling.md) for Slurm configuration and [Training](../../../docs/training.md) for monitoring and resume.
|
||||
|
||||
## SFT
|
||||
|
||||
Both configs use LoRA with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | sanity-scale, 20 steps |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, EP8) | one 8-GPU node |
|
||||
|
||||
## Run it
|
||||
|
||||
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
|
||||
Set `data.name` to your [multimodal chat dataset](../../../docs/training.md#dataset-format), then:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/extra/vlm/sft.toml
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
|
||||
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
|
||||
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
|
||||
Keep `micro_batch_size = 1` for VLM SFT and the MoE config's EP degree aligned with its GPU count. See [Training](../../../docs/training.md) for checkpoint export.
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# Qwen3.5 image RL: 4 trainer + 4 inference nodes, each with 8 H200 GPUs.
|
||||
# Customize the environment IDs, W&B names and shared paths before launching.
|
||||
seq_len = 237568
|
||||
max_steps = 200
|
||||
output_dir = "/shared/outputs"
|
||||
|
||||
[run]
|
||||
name = "your-run-name"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-122B-A10B"
|
||||
|
||||
[model.vlm]
|
||||
freeze_vision_encoder = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
gpus_per_node = 8
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
orchestrator_on_inference = true
|
||||
|
||||
[slurm]
|
||||
time = "7-00:00:00"
|
||||
job_name = "your-run-name"
|
||||
|
||||
[ckpt]
|
||||
interval = 10
|
||||
keep_last = 1
|
||||
keep_interval = 200
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 7200
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 7200
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
cp = 4
|
||||
ep = 8
|
||||
attn = "flash_attention_3"
|
||||
offload = "optimizer"
|
||||
optimization_dtype = "float32"
|
||||
reduce_dtype = "float32"
|
||||
freeze_moe_router = false
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
mode = "full"
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
lr = 1e-6
|
||||
mu = 0.95
|
||||
betas1 = 0.9
|
||||
betas2 = 0.95
|
||||
weight_decay = 0.01
|
||||
max_norm = 1.0
|
||||
|
||||
[trainer.scheduler]
|
||||
type = "constant"
|
||||
|
||||
[trainer.log]
|
||||
level = "info"
|
||||
|
||||
[monitors.wandb]
|
||||
entity = "your-wandb-entity"
|
||||
project = "your-wandb-project"
|
||||
name = "your-run-name"
|
||||
|
||||
[monitors.file]
|
||||
path = "metrics.jsonl"
|
||||
compress = true
|
||||
float_decimals = 6
|
||||
|
||||
[inference]
|
||||
enable_fp32_lm_head = true
|
||||
enable_fp32_router_logits = true
|
||||
|
||||
[inference.vllm]
|
||||
seed = 0
|
||||
dtype = "bfloat16"
|
||||
max_model_len = 237568
|
||||
max_num_seqs = 256
|
||||
max_num_batched_tokens = 8192
|
||||
tensor_parallel_size = 4
|
||||
data_parallel_size = 2
|
||||
enable_expert_parallel = true
|
||||
all2all_backend = "allgather_reducescatter"
|
||||
gpu_memory_utilization = 0.85
|
||||
mm_encoder_tp_mode = "data"
|
||||
mm_processor_cache_gb = 128
|
||||
mm_processor_cache_type = "lru"
|
||||
mamba_cache_dtype = "float32"
|
||||
enable_prefix_caching = true
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "qwen3_coder"
|
||||
reasoning_parser = "None"
|
||||
safetensors_load_strategy = "prefetch"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
[inference.router]
|
||||
type = "vllm-router"
|
||||
policy = "sticky_least_loaded"
|
||||
|
||||
[inference.env_vars]
|
||||
VLLM_ENGINE_READY_TIMEOUT_S = "7200"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 336
|
||||
max_staleness = 8
|
||||
|
||||
# Adaptive episode cap: starts at 96 and grows or backs off with engine pressure.
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 96
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.5"
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
|
||||
# Cycle through the task catalog in a seeded shuffled order.
|
||||
[orchestrator.train.select]
|
||||
shuffle = true
|
||||
seed = 0
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
top_p = 1.0
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[orchestrator.train.sampling.extra_body]
|
||||
min_p = 0.0
|
||||
top_k = -1
|
||||
return_token_ids = true
|
||||
|
||||
[trainer.loss]
|
||||
type = "ipo"
|
||||
eps = 0.3
|
||||
adv_tau = 1.0
|
||||
max_importance_ratio = 10000.0
|
||||
|
||||
# Replace color-codeword with your multimodal environment and compatible harness.
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
select.include.idx = ["0:1024"]
|
||||
env.taskset.id = "primeintellect/color-codeword@0.1.0"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.harness.compaction.summarize_at_tokens = 184320
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
group_size = 2
|
||||
skip_first_step = false
|
||||
retrigger_on_resume = true
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
temperature = 1.0
|
||||
top_p = 1.0
|
||||
max_tokens = 16384
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "color-codeword-eval"
|
||||
select.include.idx = ["1024:1152"]
|
||||
env.taskset.id = "primeintellect/color-codeword@0.1.0"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.harness.compaction.summarize_at_tokens = 184320
|
||||
@@ -0,0 +1,187 @@
|
||||
# Qwen3.8 image RL: 4 trainer + 4 inference nodes, each with 8 H200 GPUs.
|
||||
# Customize the environment IDs, W&B names and shared paths before launching.
|
||||
seq_len = 237568
|
||||
max_steps = 200
|
||||
output_dir = "/shared/outputs"
|
||||
|
||||
[run]
|
||||
name = "your-run-name"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.8-Flash-Next"
|
||||
|
||||
[model.vlm]
|
||||
freeze_vision_encoder = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
gpus_per_node = 8
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
orchestrator_on_inference = true
|
||||
|
||||
[slurm]
|
||||
time = "7-00:00:00"
|
||||
job_name = "your-run-name"
|
||||
|
||||
[ckpt]
|
||||
interval = 10
|
||||
keep_last = 1
|
||||
keep_interval = 200
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 7200
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 7200
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
cp = 8
|
||||
ep = 8
|
||||
attn = "flash_attention_3"
|
||||
offload = "optimizer"
|
||||
optimization_dtype = "float32"
|
||||
reduce_dtype = "float32"
|
||||
freeze_moe_router = false
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
mode = "full"
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
lr = 1e-6
|
||||
mu = 0.95
|
||||
betas1 = 0.9
|
||||
betas2 = 0.95
|
||||
weight_decay = 0.01
|
||||
max_norm = 1.0
|
||||
|
||||
[trainer.scheduler]
|
||||
type = "constant"
|
||||
|
||||
[trainer.log]
|
||||
level = "info"
|
||||
|
||||
[monitors.wandb]
|
||||
entity = "your-wandb-entity"
|
||||
project = "your-wandb-project"
|
||||
name = "your-run-name"
|
||||
|
||||
[monitors.file]
|
||||
path = "metrics.jsonl"
|
||||
compress = true
|
||||
float_decimals = 6
|
||||
|
||||
[inference]
|
||||
enable_fp32_lm_head = true
|
||||
enable_fp32_router_logits = true
|
||||
|
||||
[inference.vllm]
|
||||
seed = 0
|
||||
dtype = "bfloat16"
|
||||
max_model_len = 237568
|
||||
max_num_seqs = 256
|
||||
max_num_batched_tokens = 8192
|
||||
tensor_parallel_size = 4
|
||||
data_parallel_size = 2
|
||||
enable_expert_parallel = true
|
||||
all2all_backend = "allgather_reducescatter"
|
||||
gpu_memory_utilization = 0.85
|
||||
mm_encoder_tp_mode = "data"
|
||||
mm_processor_cache_gb = 128
|
||||
mm_processor_cache_type = "lru"
|
||||
mamba_cache_dtype = "float32"
|
||||
enable_prefix_caching = true
|
||||
enable_auto_tool_choice = true
|
||||
tool_call_parser = "qwen3_coder"
|
||||
reasoning_parser = "qwen3"
|
||||
safetensors_load_strategy = "prefetch"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
[inference.vllm.engram_config]
|
||||
cpu_offload = true
|
||||
|
||||
[inference.router]
|
||||
type = "vllm-router"
|
||||
policy = "sticky_least_loaded"
|
||||
|
||||
[inference.env_vars]
|
||||
VLLM_ENGINE_READY_TIMEOUT_S = "7200"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
max_staleness = 8
|
||||
|
||||
# Adaptive episode cap: starts at 96 and grows or backs off with engine pressure.
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 96
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.8"
|
||||
enable_thinking = true
|
||||
preserve_thinking = true
|
||||
reasoning_effort = "xhigh"
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
|
||||
# Cycle through the task catalog in a seeded shuffled order.
|
||||
[orchestrator.train.select]
|
||||
shuffle = true
|
||||
seed = 0
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
top_p = 1.0
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[orchestrator.train.sampling.extra_body]
|
||||
min_p = 0.0
|
||||
top_k = -1
|
||||
return_token_ids = true
|
||||
|
||||
[trainer.loss]
|
||||
type = "ipo"
|
||||
eps = 0.3
|
||||
adv_tau = 1.0
|
||||
max_importance_ratio = 10000.0
|
||||
|
||||
# Replace color-codeword with your multimodal environment and compatible harness.
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
select.include.idx = ["0:1024"]
|
||||
env.taskset.id = "primeintellect/color-codeword@0.1.0"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.harness.compaction.summarize_at_tokens = 184320
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
group_size = 2
|
||||
skip_first_step = false
|
||||
retrigger_on_resume = true
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
temperature = 1.0
|
||||
top_p = 1.0
|
||||
max_tokens = 16384
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "color-codeword-eval"
|
||||
select.include.idx = ["1024:1152"]
|
||||
env.taskset.id = "primeintellect/color-codeword@0.1.0"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.harness.compaction.summarize_at_tokens = 184320
|
||||
@@ -12,8 +12,6 @@ ep = 8 # keep in sync with deployment.num_train_gpus
|
||||
name = "auto"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
freeze_vision_encoder = true
|
||||
|
||||
[model.lora]
|
||||
|
||||
@@ -11,8 +11,6 @@ reduce_dtype = "bfloat16"
|
||||
name = "auto"
|
||||
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
freeze_vision_encoder = true
|
||||
|
||||
[model.lora]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
|
||||
|
||||
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
|
||||
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-worker-pool schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -21,6 +21,6 @@ from prime_rl.configs.rl import RLConfig
|
||||
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
|
||||
```
|
||||
|
||||
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
|
||||
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_worker_pool`).
|
||||
|
||||
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.2.dev158",
|
||||
"verifiers>=0.4.1",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -40,6 +40,7 @@ import verifiers.v1 as vf
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.diff import Live
|
||||
from prime_rl.configs.shared import VLLMClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -209,8 +210,8 @@ class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Length penalty subtracted from each reward before the GRPO baseline: a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max. ``linear`` uses trace token counts; opt-in ``linear-subagent`` discounts semantic subagent tokens. None disables it."""
|
||||
length_penalty: Annotated[LengthPenaltyConfig | None, Live()] = None
|
||||
"""Length penalty subtracted from each reward before the GRPO baseline: a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max. ``linear`` uses trace token counts; opt-in ``linear-subagent`` discounts semantic subagent tokens. None disables it. The only live field of an algorithm: a config update may change it, or turn it on or off, while the run is going."""
|
||||
|
||||
@field_validator("length_penalty", mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Compare two configs for a live update: what changed, and which changes are frozen.
|
||||
|
||||
A field is frozen unless it is ``Annotated`` with ``Live()``. A live field changes freely
|
||||
with everything below it, including swapping its value for None or for another config
|
||||
class. An unmarked sub-config is compared field by field, and so is an unmarked list of
|
||||
sub-configs of the same length, by position: live fields below them stay live. Any other
|
||||
change to an unmarked field is frozen. A sub-config annotated with ``Frozen()`` is frozen
|
||||
with everything below it, live fields included."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic.fields import FieldInfo
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Live:
|
||||
"""``Annotated`` marker for a field that may change while a run is going."""
|
||||
|
||||
live: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Frozen:
|
||||
"""``Annotated`` marker for a sub-config whose fields stay frozen, live ones included:
|
||||
e.g. a default that only seeds other fields when the config loads."""
|
||||
|
||||
live: bool = False
|
||||
|
||||
|
||||
def _live(info: FieldInfo, live: bool | None) -> bool | None:
|
||||
"""Whether a field below a field whose state is ``live`` is live: True, False, or
|
||||
None while no marker has decided it."""
|
||||
if live is not None:
|
||||
return live
|
||||
for metadata in info.metadata:
|
||||
marked = getattr(metadata, "live", None)
|
||||
if marked is not None:
|
||||
return marked
|
||||
return None
|
||||
|
||||
|
||||
class ConfigChange(BaseModel):
|
||||
path: str
|
||||
"""Dotted path with list indices: ``train.source[0].sampling.temperature``."""
|
||||
old: Any
|
||||
new: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConfigDiff:
|
||||
changes: list[ConfigChange] = field(default_factory=list)
|
||||
frozen: list[str] = field(default_factory=list)
|
||||
"""Paths of frozen fields the new config changes."""
|
||||
|
||||
|
||||
def diff_config(old: BaseModel, new: BaseModel) -> ConfigDiff:
|
||||
diff = ConfigDiff()
|
||||
_diff_value(old, new, "", diff)
|
||||
return diff
|
||||
|
||||
|
||||
def _diff_value(old: Any, new: Any, path: str, diff: ConfigDiff, live: bool | None = None) -> None:
|
||||
"""``live``: True at or below a LIVE field, False at or below a FROZEN one."""
|
||||
if old == new:
|
||||
return
|
||||
if isinstance(old, BaseModel) and type(old) is type(new):
|
||||
for name, info in type(old).model_fields.items():
|
||||
field_path = f"{path}.{name}" if path else name
|
||||
_diff_value(getattr(old, name), getattr(new, name), field_path, diff, _live(info, live))
|
||||
return
|
||||
if (
|
||||
isinstance(old, list)
|
||||
and isinstance(new, list)
|
||||
and len(old) == len(new)
|
||||
and any(isinstance(item, BaseModel) for item in old + new)
|
||||
):
|
||||
# Lists of configs (e.g. sources) compare by position; their identifying fields are frozen.
|
||||
for index, (old_item, new_item) in enumerate(zip(old, new)):
|
||||
_diff_value(old_item, new_item, f"{path}[{index}]", diff, live)
|
||||
return
|
||||
if live:
|
||||
diff.changes.append(ConfigChange(path=path, old=to_jsonable_python(old), new=to_jsonable_python(new)))
|
||||
else:
|
||||
diff.frozen.append(path)
|
||||
|
||||
|
||||
def frozen_raw_changes(
|
||||
model: BaseModel, dumped: dict, raw: dict, path: str = "", live: bool | None = None
|
||||
) -> list[str]:
|
||||
"""Paths of frozen fields that ``raw`` (a submitted config dict) changes from ``dumped``
|
||||
(``model`` dumped to JSON). Unlike ``diff_config``, this needs no validated new config,
|
||||
so it still reports frozen changes that also make the new config invalid."""
|
||||
changes = []
|
||||
for name, info in type(model).model_fields.items():
|
||||
field_live = _live(info, live)
|
||||
if name not in raw or raw[name] == dumped[name] or field_live:
|
||||
continue
|
||||
field_path = f"{path}.{name}" if path else name
|
||||
value, raw_value = getattr(model, name), raw[name]
|
||||
if isinstance(value, BaseModel) and isinstance(raw_value, dict):
|
||||
changes += frozen_raw_changes(value, dumped[name], raw_value, field_path, field_live)
|
||||
elif isinstance(value, list) and isinstance(raw_value, list) and len(value) == len(raw_value):
|
||||
for index, item in enumerate(value):
|
||||
item_path = f"{field_path}[{index}]"
|
||||
if isinstance(item, BaseModel) and isinstance(raw_value[index], dict):
|
||||
changes += frozen_raw_changes(item, dumped[name][index], raw_value[index], item_path, field_live)
|
||||
elif raw_value[index] != dumped[name][index]:
|
||||
changes.append(item_path)
|
||||
else:
|
||||
changes.append(field_path)
|
||||
return changes
|
||||
|
||||
|
||||
def merge_resumed_config(base: Any, applied: Any, launch: Any) -> Any:
|
||||
"""Merge dumped configs on resume: ``base`` is what the checkpointed run was launched
|
||||
with, ``applied`` what was live at the checkpoint, ``launch`` what this run is launched
|
||||
with. A value the launch config left as it was in ``base`` resumes from ``applied``; any
|
||||
value the launch config changed wins. Sources match by name, so a source that the
|
||||
launch config adds is used as launched."""
|
||||
if launch == base:
|
||||
return applied
|
||||
if isinstance(launch, dict) and isinstance(base, dict) and isinstance(applied, dict):
|
||||
return {
|
||||
key: merge_resumed_config(base.get(key, _MISSING), applied.get(key, value), value)
|
||||
for key, value in launch.items()
|
||||
}
|
||||
if isinstance(launch, list) and isinstance(base, list) and isinstance(applied, list) and len(base) == len(applied):
|
||||
keys = [_source_key(item) for item in base]
|
||||
if None not in keys:
|
||||
# Sources merge by identity, not position, so a source added, removed or moved on
|
||||
# resume never takes the live values of another source.
|
||||
resumed = dict(zip(keys, zip(base, applied)))
|
||||
return [
|
||||
merge_resumed_config(*resumed[key], item) if (key := _source_key(item)) in resumed else item
|
||||
for item in launch
|
||||
]
|
||||
if len(launch) == len(base):
|
||||
return [merge_resumed_config(*values) for values in zip(base, applied, launch)]
|
||||
return launch
|
||||
|
||||
|
||||
def _source_key(item: Any) -> str | None:
|
||||
"""The identity of a dumped source config: its `resolved_name` (its name, else its env
|
||||
id), the key `TrainSource` restores curricula by. None for anything that is not a source."""
|
||||
if not isinstance(item, dict) or "name" not in item or not isinstance(item.get("env"), dict):
|
||||
return None
|
||||
if item["name"]:
|
||||
return item["name"]
|
||||
env = item["env"]
|
||||
taskset = env.get("taskset")
|
||||
taskset_id = taskset.get("id") if isinstance(taskset, dict) else None
|
||||
# As `vf.EnvConfig.env_id`.
|
||||
if taskset_id and env.get("id"):
|
||||
return f"{env['id']}+{taskset_id}"
|
||||
return taskset_id or env.get("id")
|
||||
|
||||
|
||||
_MISSING = object()
|
||||
@@ -1,45 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
|
||||
The launchers write one of these per train/eval source they manage, with
|
||||
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
address_file: Path | None = None
|
||||
"""Publish the bound address to this file once serving. Set by the launchers for the
|
||||
servers they spawn, so the address never has to be agreed on up front (``serve.address``
|
||||
unset binds an OS-assigned port)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
"""Narrow ``env`` to the selected env's config class."""
|
||||
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
return self.env.env_id or ""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
if not self.env_id:
|
||||
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
|
||||
return self
|
||||
@@ -0,0 +1,84 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class StaticPoolConfig(BaseConfig):
|
||||
"""Fixed env worker pool: pre-spawn `num_workers` workers up front."""
|
||||
|
||||
type: Literal["static"] = "static"
|
||||
num_workers: int = Field(4, ge=1)
|
||||
"""Worker processes to pre-spawn."""
|
||||
|
||||
|
||||
class ElasticPoolConfig(BaseConfig):
|
||||
"""Elastic env worker pool: start at one worker and scale up on demand."""
|
||||
|
||||
type: Literal["elastic"] = "elastic"
|
||||
max_workers: int | None = Field(None, ge=1)
|
||||
"""Upper bound on workers (None = unbounded)."""
|
||||
multiplex: int = Field(128, ge=1)
|
||||
"""Episodes per worker for the scale-up trigger: add a worker once in-flight episodes
|
||||
reach 90% of `workers * multiplex`."""
|
||||
|
||||
|
||||
# Discriminated on `type` so the CLI selects with `--serve.pool.type static|elastic`.
|
||||
PoolConfig = Annotated[StaticPoolConfig | ElasticPoolConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class ServeConfig(BaseConfig):
|
||||
"""The `[serve]` block: the worker pool, the ZMQ address, and each worker's
|
||||
episode bound."""
|
||||
|
||||
pool: PoolConfig = Field(default_factory=ElasticPoolConfig)
|
||||
"""Worker-pool sizing. `elastic` (default) starts at one worker and scales up on
|
||||
demand; `static` pre-spawns a fixed `num_workers`."""
|
||||
address: str | None = None
|
||||
"""ZMQ address the pool's broker binds (and clients connect to). None binds an
|
||||
OS-assigned loopback port and publishes it through the pool's address file."""
|
||||
max_concurrent: int | None = Field(None, ge=1)
|
||||
"""Episodes in flight per worker (None = unbounded). How many agent runs one episode
|
||||
carries is the env's own (`--env.max-concurrent-agents`, one at a time by default)."""
|
||||
|
||||
|
||||
class EnvWorkerPoolConfig(BaseConfig):
|
||||
"""``uv run env-worker-pool``: one source's env and its broker/worker pool replica.
|
||||
Launchers write one config per managed train/eval source. Each replica's broker
|
||||
publishes its bound address to ``address_file``; its workers execute episodes."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: ServeConfig = ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
address_file: Path | None = None
|
||||
"""Publish the bound address to this file once serving. Set by the launchers for the
|
||||
pools they spawn, so the address never has to be agreed on up front (``serve.address``
|
||||
unset binds an OS-assigned port)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
"""Narrow ``env`` to the selected env's config class."""
|
||||
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
return self.env.env_id or ""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
if not self.env_id:
|
||||
raise ValueError('no env configured — set env = { taskset = { id = "<id>" } }')
|
||||
return self
|
||||
@@ -4,7 +4,7 @@ from pathlib import Path
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
@@ -49,7 +49,7 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
"""Where each eval source's env worker pool lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
|
||||
is an externally managed server; None means the launcher spawns the server and the
|
||||
eval learns its address from the file it publishes."""
|
||||
@@ -63,7 +63,7 @@ class EvalResumeConfig(BaseConfig):
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
pool, then exit. Every source's env worker pool is spawned by the eval process unless
|
||||
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
|
||||
``prime login``) with the concurrency pinned at 128."""
|
||||
|
||||
@@ -108,7 +108,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
@property
|
||||
@@ -172,14 +172,9 @@ class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).
|
||||
|
||||
``EvalMonitorsConfig``, not the base ``MonitorsConfig``: the launcher
|
||||
converts the trainer's ``[monitors.prime]`` into a
|
||||
``PrimeEvalMonitorConfig`` for the online-eval process, and the base
|
||||
type would drop (or forbid) the prime block at the eval.json
|
||||
dump/re-parse boundary."""
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``): the
|
||||
trainer's, so the process logs to the trainer's W&B and Prime runs."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
|
||||
@@ -186,7 +186,7 @@ class VllmConfig(BaseConfig):
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem", "nixl"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem", "nixl", "modelexpress"] = "filesystem"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
|
||||
@@ -247,6 +247,12 @@ class MooncakeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
device_name: str = ""
|
||||
"""RDMA device name(s) for the store (empty = auto-detect)."""
|
||||
|
||||
lease_ttl_s: float = Field(60.0, gt=0)
|
||||
"""How long the master protects a newly written or read KV object from eviction (``-default_kv_lease_ttl``).
|
||||
It must outlast the P/D handoff (decode reads what prefill wrote; 5 s expired objects under load), but a lease
|
||||
longer than the time the pool takes to fill blocks eviction: puts then fail and the store stops caching. Under
|
||||
P/D the larger of the two roles' values applies, since one master serves both."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
# Addresses/sizes/tiers are realized by the per-node store launch in the sbatch
|
||||
# template (MOONCAKE_CONFIG_PATH JSON); blocks are keyed by model + parallel rank +
|
||||
|
||||
@@ -43,14 +43,9 @@ class FileMonitorConfig(BaseConfig):
|
||||
not the records, so this only trades record size against overlay precision."""
|
||||
|
||||
|
||||
class PrimeTrainMonitorConfig(BaseConfig):
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class PrimeEvalMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Evaluation name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
"""Run or evaluation name shown on Prime. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class MonitorsConfig(BaseConfig):
|
||||
@@ -60,14 +55,7 @@ class MonitorsConfig(BaseConfig):
|
||||
file: FileMonitorConfig | None = FileMonitorConfig()
|
||||
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
|
||||
|
||||
|
||||
class TrainMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeTrainMonitorConfig | None = PrimeTrainMonitorConfig()
|
||||
"""Log metrics and episodes to the Prime Intellect platform. On by default and
|
||||
needs a Prime API key; disable with ``--no-monitors.prime``."""
|
||||
|
||||
|
||||
class EvalMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeEvalMonitorConfig | None = PrimeEvalMonitorConfig()
|
||||
"""Upload every eval source's epoch as an evaluation on the Prime Intellect platform. On by
|
||||
default and needs a Prime API key; disable with ``--no-monitors.prime``."""
|
||||
prime: PrimeMonitorConfig | None = PrimeMonitorConfig()
|
||||
"""Log metrics and episodes to the Prime Intellect platform: a training run's processes
|
||||
log to one platform run, and a standalone eval uploads each source's epoch as an
|
||||
evaluation. On by default and needs a Prime API key; disable with ``--no-monitors.prime``."""
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias, get_args
|
||||
|
||||
@@ -12,7 +13,9 @@ from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
GRPOAlgoConfig,
|
||||
)
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.diff import Frozen, Live
|
||||
from prime_rl.configs.env_worker_pool import ServeConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ControlConfig,
|
||||
@@ -37,7 +40,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
temperature: Annotated[float, Live()] = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
top_p: float = Field(1.0, gt=0, le=1.0)
|
||||
@@ -50,7 +53,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
a default top-k is injected when only top-p truncates so sampling masks stay
|
||||
bounded — see docs/inference.md (Sampling Replay)."""
|
||||
|
||||
max_completion_tokens: int | None = None
|
||||
max_completion_tokens: Annotated[int | None, Live()] = None
|
||||
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
|
||||
|
||||
logprobs: int | None = Field(None, ge=1)
|
||||
@@ -58,7 +61,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
# Strictly speaking, extra_body is not a sampling parameter, but it is the
|
||||
# easiest way to pass arbitrary extra parameters to the server via verifiers
|
||||
extra_body: dict[str, Any] = {}
|
||||
extra_body: Annotated[dict[str, Any], Live()] = {}
|
||||
"""Extra body forwarded with each request to the inference server."""
|
||||
|
||||
def truncates_distribution(self) -> bool:
|
||||
@@ -93,8 +96,11 @@ class EnvConfig(BaseConfig):
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
serve: ServeConfig = ServeConfig()
|
||||
"""How this source's env worker pool is hosted. Each replica has a broker endpoint
|
||||
and workers running the source's env configuration. An unset ``address`` lets the
|
||||
launcher start the pool and discover its bound address. Setting ``address`` selects
|
||||
one externally managed pool; the launcher neither writes its config nor starts it."""
|
||||
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
@@ -230,7 +236,7 @@ class TrainSourceConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
ratio: Annotated[float, Live()] = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
@@ -241,7 +247,7 @@ class TrainSourceConfig(EnvConfig):
|
||||
"""Training algorithm for this env: sampling plus the per-token training signal
|
||||
(credit assignment and loss routing, fused — its ``type`` names the algorithm).
|
||||
Setting only some params keeps the group's algorithm; a different ``type`` is
|
||||
this env's own algorithm."""
|
||||
this env's own algorithm. Frozen except its live fields (the GRPO ``length_penalty``)."""
|
||||
|
||||
curriculum: CurriculumConfig | None = None
|
||||
"""User-authored task sampler and admission gates. The default cycles
|
||||
@@ -290,7 +296,7 @@ class EvalSourceConfig(EnvConfig):
|
||||
class OnlineEvalSourceConfig(EvalSourceConfig):
|
||||
"""An eval source of a training run: evaluated on a step interval."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
interval: Annotated[int, Live()] = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate this env."""
|
||||
|
||||
|
||||
@@ -341,7 +347,7 @@ class TrainConfig(SourceGroupConfig):
|
||||
source: list[TrainSourceConfig] = Field(default_factory=list)
|
||||
"""Training sources."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
sampling: Annotated[TrainSamplingConfig, Frozen()] = TrainSamplingConfig()
|
||||
"""Sampling that every training source inherits."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
@@ -351,7 +357,7 @@ class TrainConfig(SourceGroupConfig):
|
||||
"""Rollouts generated per example that every training source inherits unless it
|
||||
sets its own. ``batch_size`` must be divisible by every source's group size."""
|
||||
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
algo: Annotated[AlgoConfig, Frozen()] = GRPOAlgoConfig()
|
||||
"""Training algorithm that every training source inherits. Defaults to ``grpo``."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -440,13 +446,13 @@ class ConcurrencyConfig(BaseConfig):
|
||||
in-flight episode cap from engine KV pressure; these fields only bound and
|
||||
seed it."""
|
||||
|
||||
initial_inflight: int | None = Field(None, ge=1)
|
||||
initial_inflight: Annotated[int | None, Live()] = 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)
|
||||
min_inflight: Annotated[int, Live()] = 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)
|
||||
max_inflight: Annotated[int | None, Live()] = 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")
|
||||
@@ -498,7 +504,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
@@ -519,13 +525,20 @@ class OrchestratorConfig(BaseConfig):
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
env_worker_pool_replicas: int | None = Field(None, ge=1)
|
||||
"""Replicas of each launcher-managed env worker pool, each publishing its address to
|
||||
``<name>.<replica>.address``; the orchestrator spreads each source's episodes over them,
|
||||
least loaded first. None means one pool publishing to ``<name>.address``. Set by the
|
||||
``rl`` launcher: multi-node runs start one replica per inference node, so pool
|
||||
memory spreads over all of them."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
dispatch_per_minute: int | None = Field(None, ge=1)
|
||||
"""Rate limit on episode dispatch, shared by train and eval: at most this many episodes start per minute. Each episode counts once, so a group of ``group_size`` episodes counts ``group_size`` times. Recommended for sandbox-backed environments to pace provisioning during autoscaling. None disables it."""
|
||||
|
||||
batch_size: int = Field(128, ge=1)
|
||||
batch_size: Annotated[int, Live()] = Field(128, ge=1)
|
||||
"""Samples to train on per step."""
|
||||
|
||||
constant_trainer_batch_size: bool = True
|
||||
@@ -552,15 +565,15 @@ class OrchestratorConfig(BaseConfig):
|
||||
max_steps: int | None = None
|
||||
"""Maximum training steps. If None, runs indefinitely."""
|
||||
|
||||
max_staleness: int = Field(8, ge=0)
|
||||
max_staleness: Annotated[int, Live()] = Field(8, ge=0)
|
||||
"""Maximum token staleness: the version a batch trains on (v{step-1}) minus the policy version that sampled the token, queue time included. Engines label each sampled token with the policy step (vLLM ``weight_versions``); unlabelled tokens (Dynamo engines) count as old as their episode's dispatch version. Older tokens are masked out of every loss component; the rest of the sample still trains with its own advantage and inference logprobs. A sample is dropped only when nothing is left to train. Rollouts are never cancelled for staleness. Higher values yield better throughput at the cost of noisier, more off-policy updates."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
control: OrchestratorControlConfig | None = None
|
||||
"""Serve the orchestrator's control API (pause at a step the trainer accepted). If None, it
|
||||
takes no control requests."""
|
||||
"""Serve the orchestrator's control API (pause or checkpoint at a step the trainer
|
||||
accepted, update the config live). If None, it takes no control requests."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
@@ -607,10 +620,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
Owned here: every truncating config gets a top-k bound (bounds the sampling
|
||||
masks); opd/opsd is rejected (full-vocab prefill refs would mix
|
||||
normalizations). Frozen-source envs sample externally and are exempt."""
|
||||
policy_samplings = [env.sampling for env in self.train.source if env.algo.sampling.source == "policy"] or (
|
||||
[self.train.sampling] if not self.train.source else []
|
||||
)
|
||||
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
|
||||
truncating = [sampling for sampling in self.policy_samplings if sampling.truncates_distribution()]
|
||||
if not truncating:
|
||||
return self
|
||||
|
||||
@@ -636,8 +646,13 @@ class OrchestratorConfig(BaseConfig):
|
||||
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
|
||||
stacklevel=2,
|
||||
)
|
||||
for sampling in unbounded:
|
||||
sampling.top_k = TRAIN_TOP_K_DEFAULT
|
||||
self.update_policy_samplings(
|
||||
lambda sampling: (
|
||||
sampling.model_copy(update={"top_k": TRAIN_TOP_K_DEFAULT})
|
||||
if sampling.truncates_distribution() and sampling.top_k is None
|
||||
else sampling
|
||||
)
|
||||
)
|
||||
|
||||
algos = [env.algo for env in self.train.source] or [self.train.algo]
|
||||
if any(algo.type in ("opd", "opsd") for algo in algos):
|
||||
@@ -649,6 +664,23 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@property
|
||||
def policy_samplings(self) -> list[TrainSamplingConfig]:
|
||||
"""Sampling of each train source that samples from the policy, else the group's when
|
||||
there are no sources."""
|
||||
if not self.train.source:
|
||||
return [self.train.sampling]
|
||||
return [env.sampling for env in self.train.source if env.algo.sampling.source == "policy"]
|
||||
|
||||
def update_policy_samplings(self, update: Callable[[TrainSamplingConfig], TrainSamplingConfig]) -> None:
|
||||
"""Replace each of ``policy_samplings`` with ``update(sampling)``. The group's sampling is
|
||||
a frozen field, so its config is copied rather than assigned."""
|
||||
if not self.train.source:
|
||||
self.train = self.train.model_copy(update={"sampling": update(self.train.sampling)})
|
||||
for env in self.train.source:
|
||||
if env.algo.sampling.source == "policy":
|
||||
env.sampling = update(env.sampling)
|
||||
|
||||
@property
|
||||
def any_policy_sourced(self) -> bool:
|
||||
"""True when at least one train env samples rollouts from the live policy."""
|
||||
@@ -740,7 +772,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
@property
|
||||
def env_sources(self) -> list[tuple[str, EnvConfig]]:
|
||||
"""Every ``(split, source)`` this run pulls from, train first then eval — the
|
||||
order that fixes each source's deterministic env-server port."""
|
||||
order used by the launcher to write per-source pool configs."""
|
||||
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
|
||||
if self.eval is not None:
|
||||
sources += [("eval", source) for source in self.eval.source]
|
||||
@@ -748,8 +780,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
|
||||
source's own ``serve.address`` when set (an externally managed server), else None —
|
||||
the launcher spawns the server, which binds an OS-assigned port and publishes it
|
||||
"""Where each source's env worker pool lives, keyed by ``(split, resolved_name)``: the
|
||||
source's own ``serve.address`` when set (an externally managed pool), else None —
|
||||
the launcher starts the pool, whose broker binds an OS-assigned port and publishes it
|
||||
to the source's address file for the orchestrator to pick up."""
|
||||
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.configs.supervised import BaseDataConfig, BaseValConfig, SupervisedTrainerConfig
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
ConstantSchedulerConfig,
|
||||
CosineSchedulerConfig,
|
||||
LinearSchedulerConfig,
|
||||
MuonConfig,
|
||||
SignSGDConfig,
|
||||
)
|
||||
|
||||
|
||||
class DatatroveDataConfig(BaseDataConfig):
|
||||
"""Tokenized shards written by datatrove's ``DocumentTokenizer``, read as one token pool and cut into samples of
|
||||
``seq_len`` tokens."""
|
||||
|
||||
type: Literal["datatrove"] = "datatrove"
|
||||
|
||||
paths: list[Path] = Field(min_length=1)
|
||||
"""Folders of datatrove tokenized shards: ``*.ds`` token files, each with its ``.ds.index`` and ``.ds.metadata``.
|
||||
The files of all folders (in folder order, then file name order) are read as one token pool."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed for the sample order: each epoch reads every ``seq_len`` window of the pool once, in a new random order
|
||||
and from a new random offset."""
|
||||
|
||||
document_masking: bool = True
|
||||
"""Attention and positions restart at every document. If False, a sample is one sequence: attention spans the
|
||||
whole sample and positions run over it."""
|
||||
|
||||
|
||||
class PretrainValConfig(BaseValConfig):
|
||||
data: DatatroveDataConfig
|
||||
"""Held-out shard folders."""
|
||||
|
||||
num_samples: int | None = Field(None, ge=1)
|
||||
"""Windows per validation, the same ones every time. If None, one full pass over the held-out pool."""
|
||||
|
||||
|
||||
class PretrainAdamWConfig(AdamWConfig):
|
||||
lr: float = Field(1e-3, ge=0)
|
||||
"""Peak learning rate. Defaults to PyTorch's AdamW default."""
|
||||
|
||||
|
||||
class PretrainMuonConfig(MuonConfig):
|
||||
lr: float = Field(1e-3, ge=0)
|
||||
"""Peak learning rate. Defaults to 1e-3, as for AdamW."""
|
||||
|
||||
|
||||
PretrainOptimizerConfig: TypeAlias = Annotated[
|
||||
PretrainAdamWConfig | PretrainMuonConfig | SignSGDConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class PretrainLinearSchedulerConfig(LinearSchedulerConfig):
|
||||
decay_steps: int = Field(0, ge=0)
|
||||
"""Steps to decay the learning rate during the final portion of training. Defaults to 0: a decay needs
|
||||
``max_steps``."""
|
||||
|
||||
|
||||
PretrainSchedulerConfig: TypeAlias = Annotated[
|
||||
ConstantSchedulerConfig | PretrainLinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class PretrainConfig(SupervisedTrainerConfig):
|
||||
"""Pretraining: next-token loss on tokenized shards, with the weights initialized from scratch unless resuming."""
|
||||
|
||||
init_from_scratch = True
|
||||
|
||||
data: DatatroveDataConfig
|
||||
|
||||
val: PretrainValConfig | None = None
|
||||
"""Validation on held-out shards. If None, no validation runs."""
|
||||
|
||||
optim: PretrainOptimizerConfig = PretrainAdamWConfig()
|
||||
|
||||
scheduler: PretrainSchedulerConfig = PretrainLinearSchedulerConfig()
|
||||
"""Learning rate schedule. Defaults to a linear warmup over 10 steps, then constant: from a random init, Adam's
|
||||
first updates at the full learning rate are unstable."""
|
||||
@@ -1,16 +1,17 @@
|
||||
import math
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
from typing import Annotated, Any, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig, TrainSamplingConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseMultiNodeDeploymentConfig,
|
||||
BaseSingleNodeDeploymentConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
@@ -22,9 +23,9 @@ from prime_rl.configs.shared import (
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
MXFP8Config,
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
rl_micro_batch_multiple,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
@@ -78,8 +79,8 @@ class SharedMonitorsConfig(BaseConfig):
|
||||
file: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
|
||||
prime: PrimeTrainMonitorConfig | None = None
|
||||
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
"""Shared Prime platform monitor. Propagated to trainer and orchestrator, which log to one Prime run."""
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
@@ -104,20 +105,7 @@ class SharedModelConfig(BaseConfig):
|
||||
"""VLM configuration. Set this to enable vision-language model support."""
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_train_gpus: int = 1
|
||||
"""GPUs allocated to the trainer."""
|
||||
|
||||
num_infer_gpus: int = 1
|
||||
"""GPUs allocated to inference."""
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
total = self.num_train_gpus + self.num_infer_gpus
|
||||
@@ -129,21 +117,13 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig):
|
||||
num_infer_nodes: int | None = Field(None, ge=0)
|
||||
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@@ -208,7 +188,7 @@ class RLConfig(BaseConfig):
|
||||
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
|
||||
|
||||
monitors: SharedMonitorsConfig = SharedMonitorsConfig()
|
||||
"""Shared monitor configs (``monitors.wandb``, ``monitors.file``). Propagated to trainer and orchestrator; ``[orchestrator.monitors.prime]`` configures the platform monitor."""
|
||||
"""Shared monitor configs (``monitors.wandb``, ``monitors.file``, ``monitors.prime``). Propagated to trainer and orchestrator."""
|
||||
|
||||
model: SharedModelConfig | None = None
|
||||
"""Shared model config. If None, falls back to the sub-config model settings."""
|
||||
@@ -324,7 +304,8 @@ class RLConfig(BaseConfig):
|
||||
f"({run_dir}). Under the rl entrypoint, sub-config output directories are derived from "
|
||||
"output_dir / run.name — set those instead."
|
||||
)
|
||||
sub.output_dir = run_dir
|
||||
self.trainer.output_dir = run_dir
|
||||
self.orchestrator = self.orchestrator.model_copy(update={"output_dir": run_dir})
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -341,7 +322,7 @@ class RLConfig(BaseConfig):
|
||||
for wandb in (self.monitors.wandb, self.trainer.monitors.wandb, self.orchestrator.monitors.wandb):
|
||||
if wandb is not None and wandb.name is None:
|
||||
wandb.name = self.run.name
|
||||
for prime in (self.monitors.prime, self.orchestrator.monitors.prime):
|
||||
for prime in (self.monitors.prime, self.trainer.monitors.prime, self.orchestrator.monitors.prime):
|
||||
if prime is not None and prime.name is None:
|
||||
prime.name = self.run.name
|
||||
return self
|
||||
@@ -361,6 +342,16 @@ class RLConfig(BaseConfig):
|
||||
|
||||
# The orchestrator queries the inference server it is paired with; without one, it
|
||||
# must match the trainer whose weights the external server receives.
|
||||
# The components log to one run per monitor, so a monitor is on in all or none.
|
||||
for name in ("wandb", "file", "prime"):
|
||||
require_equal(
|
||||
f"monitors.{name}",
|
||||
{
|
||||
f"{component}.monitors.{name}": getattr(config.monitors, name) is not None
|
||||
for component, config in (("trainer", trainer), ("orchestrator", orchestrator))
|
||||
},
|
||||
)
|
||||
|
||||
if inference is not None:
|
||||
require_equal(
|
||||
"deployment.gpus_per_node",
|
||||
@@ -442,8 +433,20 @@ class RLConfig(BaseConfig):
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
if self.weight_broadcast.type == "modelexpress":
|
||||
dynamo = self.orchestrator.model.client.dynamo
|
||||
if dynamo is not None and dynamo.enabled:
|
||||
raise ValueError(
|
||||
"modelexpress requires static inference admin endpoints; Dynamo discovery is not supported."
|
||||
)
|
||||
if self.inference is not None:
|
||||
extra = self.inference.vllm.model_extra or {}
|
||||
if extra.get("speculative_config") is not None:
|
||||
raise ValueError("modelexpress does not support speculative decoding.")
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
|
||||
self.orchestrator = self.orchestrator.model_copy(
|
||||
update={"weight_broadcast": self.weight_broadcast.model_copy()}
|
||||
)
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
return self
|
||||
@@ -538,13 +541,11 @@ class RLConfig(BaseConfig):
|
||||
loss = self.trainer.loss
|
||||
if loss.type != "icepop" or not loss.score_centering:
|
||||
return self
|
||||
samplings = [
|
||||
env.sampling for env in self.orchestrator.train.source if env.algo.sampling.source == "policy"
|
||||
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
|
||||
if not samplings:
|
||||
if not self.orchestrator.policy_samplings:
|
||||
raise ValueError("Score centering requires a policy-sampled training source")
|
||||
requested = []
|
||||
for sampling in samplings:
|
||||
|
||||
def request_logprobs(sampling: TrainSamplingConfig) -> TrainSamplingConfig:
|
||||
if sampling.temperature <= 0:
|
||||
raise ValueError("Score centering requires stochastic sampling (temperature > 0)")
|
||||
k = sampling.top_k if sampling.truncates_distribution() else loss.score_centering_topk
|
||||
@@ -552,8 +553,10 @@ class RLConfig(BaseConfig):
|
||||
raise ValueError("Truncated score centering requires a bounded top_k")
|
||||
if sampling.logprobs is not None and sampling.logprobs < k:
|
||||
raise ValueError(f"Score centering needs sampling.logprobs >= {k}")
|
||||
sampling.logprobs = max(sampling.logprobs or 0, k)
|
||||
requested.append(sampling.logprobs + 2)
|
||||
requested.append(max(sampling.logprobs or 0, k) + 2)
|
||||
return sampling.model_copy(update={"logprobs": max(sampling.logprobs or 0, k)})
|
||||
|
||||
self.orchestrator.update_policy_samplings(request_logprobs)
|
||||
if self.inference is not None:
|
||||
if getattr(self.inference.vllm, "logprobs_mode", "processed_logprobs") != "processed_logprobs":
|
||||
raise ValueError("Score centering requires inference.vllm.logprobs_mode = 'processed_logprobs'")
|
||||
@@ -606,17 +609,14 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
self.orchestrator.pad_to_multiple_of = self.trainer.model.cp
|
||||
if isinstance(self.trainer.model.quantization, MXFP8Config):
|
||||
# MXFP8 linears quantize grad_output in 32-token blocks, per CP rank.
|
||||
self.orchestrator.pad_to_multiple_of = math.lcm(
|
||||
self.orchestrator.pad_to_multiple_of, self.trainer.model.cp * 32
|
||||
)
|
||||
pad_to_multiple_of = rl_micro_batch_multiple(self.trainer.model)
|
||||
num_train_workers = self.orchestrator.num_train_workers
|
||||
env_worker_pool_replicas = self.orchestrator.env_worker_pool_replicas
|
||||
if self.deployment.type == "single_node": # single-node
|
||||
# set num_train_workers to the number of data replicas
|
||||
non_data_parallel_size = self.trainer.model.cp
|
||||
if self.deployment.num_train_gpus > 1:
|
||||
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
|
||||
num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
|
||||
|
||||
# fill up inference capacity with dp ranks
|
||||
if self.inference is not None:
|
||||
@@ -639,19 +639,9 @@ class RLConfig(BaseConfig):
|
||||
self.orchestrator.weight_broadcast.inference_world_size = world_size
|
||||
|
||||
elif self.deployment.type == "multi_node": # multi-node
|
||||
self.orchestrator.num_train_workers = (
|
||||
self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
|
||||
)
|
||||
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
|
||||
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.trainer.model.dp_replicate = (
|
||||
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
|
||||
)
|
||||
num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node // self.trainer.model.cp
|
||||
if self.deployment.total_infer_nodes > 0:
|
||||
env_worker_pool_replicas = self.deployment.total_infer_nodes
|
||||
|
||||
if (
|
||||
self.inference is not None
|
||||
@@ -705,7 +695,7 @@ class RLConfig(BaseConfig):
|
||||
if self.inference.vllm.api_server_count == 1 and dp_per_node > 1:
|
||||
self.inference.vllm.api_server_count = dp_per_node
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl", "modelexpress"):
|
||||
# Every allocated inference GPU is an in-memory transfer worker.
|
||||
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
|
||||
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
|
||||
@@ -714,13 +704,20 @@ class RLConfig(BaseConfig):
|
||||
# factor count twice and wait for ranks that never connect. Matches
|
||||
# the disaggregated path below.
|
||||
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl", "modelexpress")
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl", "modelexpress")
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_workers
|
||||
|
||||
self.orchestrator = self.orchestrator.model_copy(
|
||||
update={
|
||||
"pad_to_multiple_of": pad_to_multiple_of,
|
||||
"num_train_workers": num_train_workers,
|
||||
"env_worker_pool_replicas": env_worker_pool_replicas,
|
||||
}
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -748,11 +745,13 @@ class RLConfig(BaseConfig):
|
||||
role_order = ["prefill"] * (infer_deploy.num_prefill_nodes * stride) + ["decode"] * (
|
||||
infer_deploy.num_decode_nodes * stride
|
||||
)
|
||||
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
|
||||
self.orchestrator = self.orchestrator.model_copy(
|
||||
update={"inference_metrics_roles": role_order * self.deployment.num_infer_replicas}
|
||||
)
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl", "modelexpress"):
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl", "modelexpress")
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl", "modelexpress")
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
|
||||
return self
|
||||
|
||||
@@ -1,54 +1,11 @@
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
FileSystemWeightBroadcastConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import BaseTrainerConfig, mega_moe_max_tokens_per_rank
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseConfig):
|
||||
batch_size: int = Field(128, ge=1)
|
||||
"""Global batch size."""
|
||||
|
||||
seq_len: int = Field(128, ge=1)
|
||||
"""Sequence length."""
|
||||
|
||||
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=1)
|
||||
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
|
||||
|
||||
pad_to_seq_len: bool = False
|
||||
"""Pad every packed row to ``seq_len * micro_batch_size`` instead of to a multiple of ``model.cp``. Rows then have
|
||||
one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...)
|
||||
at the cost of extra padding."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.micro_batch_size != 0:
|
||||
raise ValueError("Batch size must be divisible by micro batch size")
|
||||
if self.batch_size < self.micro_batch_size:
|
||||
raise ValueError("Batch size must be greater than or equal to micro batch size")
|
||||
return self
|
||||
from prime_rl.configs.supervised import BaseDataConfig, BaseValConfig, SupervisedTrainerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FakeDataConfig(BaseDataConfig):
|
||||
@@ -155,64 +112,14 @@ class SFTDataConfig(BaseDataConfig):
|
||||
return self
|
||||
|
||||
|
||||
class SFTValConfig(BaseConfig):
|
||||
interval: int = Field(50, ge=1)
|
||||
"""Run validation every N training steps."""
|
||||
|
||||
eval_on_start: bool = False
|
||||
"""Run validation before the first training step."""
|
||||
|
||||
class SFTValConfig(BaseValConfig):
|
||||
data: SFTDataConfig
|
||||
|
||||
|
||||
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_train_gpus: int = 1
|
||||
"""GPUs allocated to the trainer."""
|
||||
|
||||
num_infer_gpus: int = Field(1, validation_alias=AliasChoices("num_infer_gpus", "num_eval_gpus"))
|
||||
"""GPUs allocated to inference for online evals (alias: ``num_eval_gpus``). Only used when an ``[inference]`` block is configured."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
if self.num_train_gpus > self.gpus_per_node:
|
||||
raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: int = Field(2, ge=1)
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
|
||||
one SLURM allocation with the trainer nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
|
||||
SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class SFTConfig(BaseTrainerConfig):
|
||||
auto_freeze_moe_router = False
|
||||
# Standard L2 regularization for supervised training.
|
||||
auto_weight_decay = 0.01
|
||||
|
||||
class SFTConfig(SupervisedTrainerConfig):
|
||||
renderer: RendererConfig = AutoRendererConfig()
|
||||
"""Renderer config. Defaults to auto-selecting from the tokenizer model name."""
|
||||
|
||||
@@ -221,236 +128,6 @@ class SFTConfig(BaseTrainerConfig):
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: SFTOnlineEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server for online evals. If None (with ``eval`` set), the launcher
|
||||
does not start a server and evals connect to ``eval.client.base_url``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
|
||||
LoRA and external inference use filesystem broadcast."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
|
||||
|
||||
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
default the run directory, W&B run name and platform run name to it when not
|
||||
set explicitly."""
|
||||
if self.run.name is None:
|
||||
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
|
||||
model = self.model.name.split("/")[-1]
|
||||
parts = [part for part in (dataset, model) if part]
|
||||
self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
|
||||
self.monitors.wandb.name = self.run.name
|
||||
if self.monitors.prime is not None and self.monitors.prime.name is None:
|
||||
self.monitors.prime.name = self.run.name
|
||||
return self
|
||||
|
||||
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def normalize_deployment(cls, data):
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
|
||||
for key in ("num_train_gpus", "num_infer_gpus"):
|
||||
deployment.pop(key, None)
|
||||
return data
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def propagate_model_to_inference(cls, data):
|
||||
"""Fill ``inference.vllm.model`` from ``model.name`` before InferenceConfig
|
||||
construction, so its parser auto-resolution sees the right model name."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
inference = data.get("inference")
|
||||
model = data.get("model")
|
||||
name = model.get("name") if isinstance(model, dict) else None
|
||||
if isinstance(inference, dict) and name:
|
||||
vllm = inference.setdefault("vllm", {})
|
||||
if isinstance(vllm, dict):
|
||||
vllm.setdefault("model", name)
|
||||
return data
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node" and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_online_eval(self):
|
||||
"""Wire online evals and the trainer-to-inference weight transport."""
|
||||
if self.eval is None:
|
||||
if self.inference is not None:
|
||||
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
|
||||
return self
|
||||
|
||||
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
|
||||
if self.model.lora is not None:
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if self.weight_broadcast is None:
|
||||
if self.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
if self.weight_broadcast.type == "nixl":
|
||||
raise ValueError("NIXL weight broadcast is not supported for SFT online evals.")
|
||||
if self.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
# env servers, and evals process.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - dedicated nodes in the "
|
||||
"SFT allocation run the inference pool and evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the launcher starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the SFT SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the SFT sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
warnings.warn(
|
||||
"Online evals are configured without an [inference] block - the launcher will not "
|
||||
f"start an inference server. Make sure one is running at eval.client.base_url "
|
||||
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
|
||||
"otherwise the online-eval 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,
|
||||
)
|
||||
return self
|
||||
|
||||
total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus
|
||||
if total_gpus > self.deployment.gpus_per_node:
|
||||
raise ValueError(
|
||||
f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + "
|
||||
f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node "
|
||||
f"({self.deployment.gpus_per_node})."
|
||||
)
|
||||
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
|
||||
# Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment).
|
||||
num_infer_gpus = self.deployment.num_infer_gpus
|
||||
vllm = self.inference.vllm
|
||||
if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size:
|
||||
if num_infer_gpus % vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})."
|
||||
)
|
||||
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
|
||||
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
if "base_url" not in client.model_fields_set:
|
||||
client.base_url = f"http://{host}:{self.inference.server.port}/v1"
|
||||
elif urlparse(client.base_url).port != self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match "
|
||||
f"inference.server.port ({self.inference.server.port})."
|
||||
)
|
||||
if self.inference.router is not None and "admin_base_url" not in client.model_fields_set:
|
||||
# Admin ops (pause/update_weights/resume) must bypass the router and hit
|
||||
# the engine directly.
|
||||
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_typed_renderer(self):
|
||||
"""Require a typed renderer whenever SFT renders real samples."""
|
||||
@@ -473,71 +150,12 @@ class SFTConfig(BaseTrainerConfig):
|
||||
"typed renderer only when its template is verified to match."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_seq_len(self):
|
||||
if self.model.cp > 1:
|
||||
if self.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Sequence length must be divisible by CP degree")
|
||||
if self.val is not None and self.val.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Validation sequence length must be divisible by CP degree")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_mega_moe_max_tokens_per_rank(self):
|
||||
dispatch = self.model.moe.dispatch
|
||||
if dispatch.type == "mega_moe":
|
||||
data_configs = [self.data] + ([self.val.data] if self.val is not None else [])
|
||||
dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank(
|
||||
dispatch.max_tokens_per_rank, max(data.micro_batch_size * data.seq_len for data in data_configs)
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_micro_batch_size(self):
|
||||
if self.model.cp > 1:
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("Micro batch size must be 1 when CP is enabled")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_vlm_constraints(self):
|
||||
if self.model.vlm is None:
|
||||
return self
|
||||
if self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16":
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.")
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.deployment.nodes_per_fsdp_group is not None:
|
||||
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
|
||||
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.job_name is None:
|
||||
self.slurm.job_name = self.run.name
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
return self
|
||||
|
||||
@@ -80,13 +80,54 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
class ModelExpressWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["modelexpress"] = "modelexpress"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
staging_mode: Literal["COPY_TO_HOST", "COPY_TO_DEVICE", "IN_PLACE"] = "COPY_TO_HOST"
|
||||
"""Trainer storage policy passed to ModelExpress."""
|
||||
|
||||
staging_buffer_bytes: int | None = Field(None, gt=0)
|
||||
"""Receiver staging capacity per buffer. None stages a complete update."""
|
||||
|
||||
staging_buffers_count: int = Field(1, ge=1)
|
||||
"""Number of receiver buffers. Two overlap the next read with installation."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
FileSystemWeightBroadcastConfig
|
||||
| NCCLWeightBroadcastConfig
|
||||
| NIXLWeightBroadcastConfig
|
||||
| ModelExpressWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class BaseSingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_train_gpus: int = 1
|
||||
"""GPUs allocated to the trainer."""
|
||||
|
||||
num_infer_gpus: int = 1
|
||||
"""GPUs allocated to inference. ``sft`` uses them only for online evals with an ``[inference]`` block."""
|
||||
|
||||
|
||||
class BaseMultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: int = Field(ge=1)
|
||||
"""Training nodes."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
|
||||
@@ -159,7 +200,7 @@ class SlurmConfig(BaseConfig):
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
launch_modelexpress: bool = True
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
"""Start a job-scoped ModelExpress server for NIXL and ModelExpress weight broadcasts on multi-node jobs."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Maximum seconds a multi-node RL job that hit a non-zero exit waits for an in-flight trainer checkpoint to finish before tearing down. Without an in-flight checkpoint (or without ``[ckpt]``) it tears down immediately. Set to 0 to never wait."""
|
||||
@@ -193,12 +234,6 @@ ServerType = Literal["vllm", "openai"]
|
||||
|
||||
|
||||
class VLMConfig(BaseConfig):
|
||||
vision_encoder_attr: str
|
||||
"""Dotted attribute path to the vision encoder module (e.g. ``model.visual``)."""
|
||||
|
||||
language_model_attr: str
|
||||
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
|
||||
|
||||
freeze_vision_encoder: bool = True
|
||||
"""Freeze the vision encoder parameters during training."""
|
||||
|
||||
@@ -210,9 +245,6 @@ class BaseModelConfig(BaseConfig):
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code when initializing the tokenizer."""
|
||||
|
||||
vlm: "VLMConfig | None" = None
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
|
||||
class DynamoConfig(BaseConfig):
|
||||
enabled: bool = True
|
||||
@@ -249,10 +281,8 @@ class PolicyClientConfig(VLLMClientConfig):
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
vf_level: str = Field(default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"))
|
||||
"""Log level for the verifiers package. Defaults to ``$PRIME_VF_LOG_LEVEL`` if set, else ``info``."""
|
||||
"""Log level for the process and the verifiers library it runs, env worker pools included.
|
||||
Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
json_logging: bool = False
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
import uuid
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, ClassVar, TypeAlias
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseMultiNodeDeploymentConfig,
|
||||
BaseSingleNodeDeploymentConfig,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import BaseTrainerConfig, mega_moe_max_tokens_per_rank
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseConfig):
|
||||
batch_size: int = Field(128, ge=1)
|
||||
"""Global batch size."""
|
||||
|
||||
seq_len: int = Field(128, ge=1)
|
||||
"""Sequence length."""
|
||||
|
||||
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=1)
|
||||
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
|
||||
|
||||
pad_to_seq_len: bool = False
|
||||
"""Pad every packed row to ``seq_len * micro_batch_size`` instead of to a multiple of ``model.cp``. Rows then have
|
||||
one static shape, which avoids recompilation on dynamic sequence lengths (torch.compile, DeepGEMM JIT kernels, ...)
|
||||
at the cost of extra padding."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
if self.batch_size % self.micro_batch_size != 0:
|
||||
raise ValueError("Batch size must be divisible by micro batch size")
|
||||
if self.batch_size < self.micro_batch_size:
|
||||
raise ValueError("Batch size must be greater than or equal to micro batch size")
|
||||
return self
|
||||
|
||||
|
||||
class BaseValConfig(BaseConfig):
|
||||
interval: int = Field(50, ge=1)
|
||||
"""Run validation every N training steps."""
|
||||
|
||||
eval_on_start: bool = False
|
||||
"""Run validation before the first training step."""
|
||||
|
||||
data: BaseDataConfig
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseSingleNodeDeploymentConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
if self.num_train_gpus > self.gpus_per_node:
|
||||
raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
|
||||
return self
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseMultiNodeDeploymentConfig):
|
||||
num_infer_nodes: int = Field(0, ge=0)
|
||||
"""Inference nodes for online evals. These nodes share one SLURM allocation with the
|
||||
trainer nodes."""
|
||||
|
||||
|
||||
SupervisedDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class SupervisedTrainerConfig(BaseTrainerConfig):
|
||||
"""SFT and pretraining: next-token loss on a fixed dataset, as opposed to RL."""
|
||||
|
||||
auto_freeze_moe_router = False
|
||||
# Standard L2 regularization for supervised training.
|
||||
auto_weight_decay = 0.01
|
||||
# Initialize the weights from scratch instead of loading them from ``model.name``, unless resuming.
|
||||
init_from_scratch: ClassVar[bool] = False
|
||||
|
||||
data: BaseDataConfig
|
||||
|
||||
val: BaseValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: SFTOnlineEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server for online evals. If None (with ``eval`` set), the launcher
|
||||
does not start a server and evals connect to ``eval.client.base_url``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
|
||||
LoRA and external inference use filesystem broadcast."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
default the run directory, W&B run name and platform run name to it when not
|
||||
set explicitly."""
|
||||
if self.run.name is None:
|
||||
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
|
||||
model = self.model.name.split("/")[-1]
|
||||
parts = [part for part in (dataset, model) if part]
|
||||
self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
|
||||
self.monitors.wandb.name = self.run.name
|
||||
if self.monitors.prime is not None and self.monitors.prime.name is None:
|
||||
self.monitors.prime.name = self.run.name
|
||||
return self
|
||||
|
||||
deployment: SupervisedDeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def propagate_model_to_inference(cls, data):
|
||||
"""Fill ``inference.vllm.model`` from ``model.name`` before InferenceConfig
|
||||
construction, so its parser auto-resolution sees the right model name."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
inference = data.get("inference")
|
||||
model = data.get("model")
|
||||
name = model.get("name") if isinstance(model, dict) else None
|
||||
if isinstance(inference, dict) and name:
|
||||
vllm = inference.setdefault("vllm", {})
|
||||
if isinstance(vllm, dict):
|
||||
vllm.setdefault("model", name)
|
||||
return data
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node" and self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_online_eval(self):
|
||||
"""Wire online evals and the trainer-to-inference weight transport."""
|
||||
if self.eval is None:
|
||||
if self.inference is not None:
|
||||
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
|
||||
return self
|
||||
|
||||
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
|
||||
if self.model.lora is not None:
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.model.lora.rank
|
||||
else:
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
if self.weight_broadcast is None:
|
||||
if self.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
if self.weight_broadcast.type in ("nixl", "modelexpress"):
|
||||
raise ValueError("NIXL and ModelExpress weight broadcast are not supported for SFT online evals.")
|
||||
if self.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
# env worker pools, and evals process.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - dedicated nodes in the "
|
||||
"SFT allocation run the inference pool and evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the launcher starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the SFT SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the SFT sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
warnings.warn(
|
||||
"Online evals are configured without an [inference] block - the launcher will not "
|
||||
f"start an inference server. Make sure one is running at eval.client.base_url "
|
||||
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
|
||||
"otherwise the online-eval 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,
|
||||
)
|
||||
return self
|
||||
|
||||
total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus
|
||||
if total_gpus > self.deployment.gpus_per_node:
|
||||
raise ValueError(
|
||||
f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + "
|
||||
f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node "
|
||||
f"({self.deployment.gpus_per_node})."
|
||||
)
|
||||
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
raise ValueError(
|
||||
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
|
||||
f"({self.model.name}). Remove inference.vllm.model to inherit it."
|
||||
)
|
||||
|
||||
# Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment).
|
||||
num_infer_gpus = self.deployment.num_infer_gpus
|
||||
vllm = self.inference.vllm
|
||||
if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size:
|
||||
if num_infer_gpus % vllm.tensor_parallel_size != 0:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by "
|
||||
f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})."
|
||||
)
|
||||
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
|
||||
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
if "base_url" not in client.model_fields_set:
|
||||
client.base_url = f"http://{host}:{self.inference.server.port}/v1"
|
||||
elif urlparse(client.base_url).port != self.inference.server.port:
|
||||
raise ValueError(
|
||||
f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match "
|
||||
f"inference.server.port ({self.inference.server.port})."
|
||||
)
|
||||
if self.inference.router is not None and "admin_base_url" not in client.model_fields_set:
|
||||
# Admin ops (pause/update_weights/resume) must bypass the router and hit
|
||||
# the engine directly.
|
||||
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_seq_len(self):
|
||||
if self.model.cp > 1:
|
||||
if self.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Sequence length must be divisible by CP degree")
|
||||
if self.val is not None and self.val.data.seq_len % self.model.cp != 0:
|
||||
raise ValueError("Validation sequence length must be divisible by CP degree")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_mega_moe_max_tokens_per_rank(self):
|
||||
dispatch = self.model.moe.dispatch
|
||||
if dispatch.type == "mega_moe":
|
||||
data_configs = [self.data] + ([self.val.data] if self.val is not None else [])
|
||||
dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank(
|
||||
dispatch.max_tokens_per_rank,
|
||||
max(data.micro_batch_size * data.seq_len for data in data_configs),
|
||||
self.model.cp,
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp_micro_batch_size(self):
|
||||
if self.model.cp > 1:
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("Micro batch size must be 1 when CP is enabled")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
raise ValueError("Validation micro batch size must be 1 when CP is enabled")
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.job_name is None:
|
||||
self.slurm.job_name = self.run.name
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
return self
|
||||
@@ -16,6 +16,7 @@ from prime_rl.configs.shared import (
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
VLMConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
@@ -213,12 +214,9 @@ class DeepEPMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with DeepEP."""
|
||||
|
||||
type: Literal["deepep"] = "deepep"
|
||||
num_sms: int = Field(20, ge=1)
|
||||
num_sms: int = Field(32, ge=1)
|
||||
"""SMs allocated to DeepEP communication kernels."""
|
||||
|
||||
token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Optional chunk size used to pipeline dispatch with local expert compute."""
|
||||
|
||||
|
||||
class MegaMoeMoEDispatchConfig(BaseConfig):
|
||||
type: Literal["mega_moe"] = "mega_moe"
|
||||
@@ -227,22 +225,36 @@ class MegaMoeMoEDispatchConfig(BaseConfig):
|
||||
in blockwise FP8 (SM90). ``fp8_bwd``: BF16 forward, blockwise FP8 backward (SM90)."""
|
||||
|
||||
max_tokens_per_rank: int | None = Field(None, ge=1)
|
||||
"""Tokens per rank per MoE call that the symmetric buffer is sized for. Defaults to the micro batch
|
||||
(``model.seq_len`` for RL, ``data.micro_batch_size * data.seq_len`` for SFT) and cannot be smaller."""
|
||||
"""Tokens per rank per MoE call that the symmetric buffer is sized for. Defaults to the rank's share of the
|
||||
micro batch under context parallelism (``model.seq_len / model.cp`` for RL,
|
||||
``data.micro_batch_size * data.seq_len / model.cp`` for SFT) and cannot be smaller."""
|
||||
|
||||
num_reserved_sms: int = Field(16, ge=1)
|
||||
"""SMs left free for concurrent NCCL kernels. ``NCCL_MAX_CTAS`` must be set to at most this value."""
|
||||
num_reserved_sms: int = Field(16, ge=2)
|
||||
"""SMs left free for concurrent NCCL kernels. In the worst case each NCCL kernel uses all ``NCCL_MAX_CTAS``, so
|
||||
at most ``num_reserved_sms // NCCL_MAX_CTAS`` NCCL kernels can run concurrently. FSDP overlaps an all-gather and
|
||||
a reduce-scatter, and HSDP (``dp_replicate > 1``) adds an all-reduce, so the trainer sets ``NCCL_MAX_CTAS`` to
|
||||
this value divided by 2 (3 under HSDP) when it is unset and requires it to be at most that."""
|
||||
|
||||
|
||||
def mega_moe_max_tokens_per_rank(max_tokens_per_rank: int | None, micro_batch_tokens: int) -> int:
|
||||
def rl_micro_batch_multiple(model: "ModelConfig") -> int:
|
||||
"""RL micro batches are padded to a multiple of this: one shard per CP rank, and MXFP8 linears quantize
|
||||
grad_output in 32-token blocks per CP rank."""
|
||||
if isinstance(model.quantization, MXFP8Config):
|
||||
return model.cp * 32
|
||||
return model.cp
|
||||
|
||||
|
||||
def mega_moe_max_tokens_per_rank(max_tokens_per_rank: int | None, micro_batch_tokens: int, cp: int) -> int:
|
||||
"""A rank with more tokens than its buffer fails alone while its peers wait in the kernel, so the
|
||||
buffer must hold the full micro batch."""
|
||||
buffer must hold the rank's full share of the micro batch. Context parallelism splits every micro
|
||||
batch evenly over the ``cp`` ranks, so that share is ``micro_batch_tokens / cp``."""
|
||||
rank_tokens = -(-micro_batch_tokens // cp)
|
||||
if max_tokens_per_rank is None:
|
||||
return micro_batch_tokens
|
||||
if max_tokens_per_rank < micro_batch_tokens:
|
||||
return rank_tokens
|
||||
if max_tokens_per_rank < rank_tokens:
|
||||
raise ValueError(
|
||||
f"model.moe.dispatch.max_tokens_per_rank ({max_tokens_per_rank}) must be at least the micro batch "
|
||||
f"({micro_batch_tokens} tokens)."
|
||||
f"model.moe.dispatch.max_tokens_per_rank ({max_tokens_per_rank}) must be at least the tokens a rank "
|
||||
f"holds per micro batch ({micro_batch_tokens} tokens over cp={cp}: {rank_tokens})."
|
||||
)
|
||||
return max_tokens_per_rank
|
||||
|
||||
@@ -261,6 +273,9 @@ class MoERuntimeConfig(BaseConfig):
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
vlm: VLMConfig | None = None
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
|
||||
@@ -321,7 +336,7 @@ class ModelConfig(BaseModelConfig):
|
||||
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
|
||||
|
||||
freeze_engram_tables: bool = False
|
||||
"""Freeze DeepSeek-V4.1's engram n-gram tables (~98B parameters each), so they carry no gradient or optimizer state and are stored in bf16. Their projections and gates still train. A no-op on other models."""
|
||||
"""Freeze the model's hashed n-gram tables (`NGramTable`s: DeepSeek-V4.1's engram tables, ~98B parameters each, or Qwen3.8-Flash-Next's), so they carry no gradient or optimizer state and are stored in bf16. Their projections and gates still train. A no-op on models without n-gram tables."""
|
||||
|
||||
lora: LoRAConfig | None = None
|
||||
"""LoRA configuration. If None, LoRA is disabled."""
|
||||
@@ -352,12 +367,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
compute = self.moe.compute
|
||||
dispatch = self.moe.dispatch
|
||||
if isinstance(dispatch, DeepEPMoEDispatchConfig):
|
||||
if isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
|
||||
elif isinstance(dispatch, MegaMoeMoEDispatchConfig):
|
||||
pass # Compute is fused into dispatch; `model.moe.compute` is ignored for these layers.
|
||||
elif dispatch.transport == "mxfp8":
|
||||
if isinstance(dispatch, TorchMoEDispatchConfig) and dispatch.transport == "mxfp8":
|
||||
if not isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
|
||||
return self
|
||||
@@ -563,6 +573,15 @@ class FakeDataLoaderConfig(BaseConfig):
|
||||
generate_samples: bool = False
|
||||
"""Generate separate samples and pack them into a single micro-batch instead of using random tensors."""
|
||||
|
||||
doc_len: int | None = Field(None, ge=1)
|
||||
"""Length of each generated sample, the last one cut to fill the micro batch. If None, lengths are random up to a micro batch's length / 8. Requires generate_samples."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def doc_len_requires_generate_samples(self):
|
||||
if self.doc_len is not None and not self.generate_samples:
|
||||
raise ValueError("data.fake.doc_len requires data.fake.generate_samples")
|
||||
return self
|
||||
|
||||
|
||||
class DataLoaderConfig(BaseConfig):
|
||||
fake: FakeDataLoaderConfig | None = None
|
||||
@@ -573,7 +592,8 @@ class DataLoaderConfig(BaseConfig):
|
||||
|
||||
|
||||
class BaseTrainerConfig(BaseConfig):
|
||||
"""Fields and validators shared by the RL trainer (``TrainerConfig``) and SFT (``SFTConfig``)."""
|
||||
"""Fields and validators shared by the RL trainer (``TrainerConfig``) and the SFT and pretraining trainer
|
||||
(``SupervisedTrainerConfig``)."""
|
||||
|
||||
auto_freeze_moe_router: ClassVar[bool]
|
||||
auto_weight_decay: ClassVar[float]
|
||||
@@ -612,8 +632,8 @@ class BaseTrainerConfig(BaseConfig):
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
control: ControlConfig | None = None
|
||||
"""Serve the run control API on the master rank (pause the run after the next
|
||||
step). If None, the run takes no control requests."""
|
||||
"""Serve the run control API on the master rank (pause or checkpoint the run
|
||||
after the next step). If None, the run takes no control requests."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
@@ -626,17 +646,6 @@ class BaseTrainerConfig(BaseConfig):
|
||||
self.optim.weight_decay = self.auto_weight_decay
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
stacklevel=1,
|
||||
)
|
||||
self.optim.max_norm = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
@@ -709,7 +718,7 @@ class TrainerConfig(BaseTrainerConfig):
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
@@ -719,7 +728,7 @@ class TrainerConfig(BaseTrainerConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl", "modelexpress"):
|
||||
raise ValueError(
|
||||
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
|
||||
"PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from."
|
||||
@@ -728,10 +737,13 @@ class TrainerConfig(BaseTrainerConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_mega_moe_max_tokens_per_rank(self):
|
||||
"""RL micro batches are one packed sequence of ``model.seq_len`` tokens."""
|
||||
"""RL micro batches are one packed sequence of up to ``model.seq_len`` tokens, padded to
|
||||
``rl_micro_batch_multiple`` and split over the CP ranks."""
|
||||
dispatch = self.model.moe.dispatch
|
||||
if dispatch.type == "mega_moe":
|
||||
multiple = rl_micro_batch_multiple(self.model)
|
||||
micro_batch_tokens = -(-self.model.seq_len // multiple) * multiple
|
||||
dispatch.max_tokens_per_rank = mega_moe_max_tokens_per_rank(
|
||||
dispatch.max_tokens_per_rank, self.model.seq_len
|
||||
dispatch.max_tokens_per_rank, micro_batch_tokens, self.model.cp
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -15,7 +15,7 @@ def default_output_dir() -> Path:
|
||||
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
|
||||
|
||||
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | dict[str, Any] | None = None) -> dict:
|
||||
"""Dump a resolved config for a machine-written JSON artifact.
|
||||
|
||||
Resolved configs are written as JSON, not TOML: JSON keeps nulls, so explicit None
|
||||
|
||||
@@ -67,11 +67,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"inference.vllm.model",
|
||||
"orchestrator.model.name",
|
||||
)
|
||||
propagate(
|
||||
"model.vlm",
|
||||
"trainer.model.vlm",
|
||||
"orchestrator.model.vlm",
|
||||
)
|
||||
propagate("model.vlm", "trainer.model.vlm")
|
||||
|
||||
# [log]
|
||||
propagate("log.level", "trainer.log.level", "orchestrator.log.level", "inference.log.level")
|
||||
@@ -103,9 +99,8 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
|
||||
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
|
||||
|
||||
# [monitors.prime] leaf → orchestrator only (the RL trainer has no platform
|
||||
# integration; the SFT trainer does, but it parses SFTConfig directly).
|
||||
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
|
||||
# [monitors.prime] leaf.
|
||||
propagate("monitors.prime.name", "trainer.monitors.prime.name", "orchestrator.monitors.prime.name")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
@@ -170,7 +165,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"ckpt": ("trainer", "orchestrator"),
|
||||
"monitors.wandb": ("trainer", "orchestrator"),
|
||||
"monitors.file": ("trainer", "orchestrator"),
|
||||
"monitors.prime": ("orchestrator",),
|
||||
"monitors.prime": ("trainer", "orchestrator"),
|
||||
}
|
||||
for key, targets in presence_targets.items():
|
||||
value = get(key)
|
||||
|
||||
+23
-29
@@ -12,12 +12,13 @@ dependencies = [
|
||||
"jaxtyping>=0.3.2",
|
||||
"loguru>=0.7.3",
|
||||
"numpy>=2.2.6",
|
||||
"sympy>=1.13.3",
|
||||
"transformers==5.19.0",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.8.0",
|
||||
"prime-runs[train]>=0.1.4",
|
||||
"prime-runs[train]>=0.1.6",
|
||||
"pyzmq>=27.1.0",
|
||||
"msgpack>=1.1.2",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
@@ -28,8 +29,8 @@ dependencies = [
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.4.0",
|
||||
"renderers[multimodal]>=0.1.12",
|
||||
"verifiers[harbor]>=0.4.1",
|
||||
"renderers[multimodal]>=0.2.0",
|
||||
"pybase64>=1.4.2",
|
||||
"msgspec>=0.18",
|
||||
"fastapi>=0.115",
|
||||
@@ -39,11 +40,12 @@ dependencies = [
|
||||
[project.scripts]
|
||||
rl = "prime_rl.entrypoints.rl:main"
|
||||
sft = "prime_rl.entrypoints.sft:main"
|
||||
pretrain = "prime_rl.entrypoints.pretrain:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
eval = "prime_rl.entrypoints.eval:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
env-worker-pool = "prime_rl.entrypoints.env_worker_pool:main"
|
||||
dashboard = "prime_rl.entrypoints.dashboard:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
@@ -65,16 +67,17 @@ gpu = [
|
||||
# DSA sparse MLA forward for the default `model.dsa_backend = "cudnn_flashmla"` (sm_90a + sm_100f).
|
||||
# FlashMLA is not on PyPI and only an x86_64 wheel is published.
|
||||
"flash-mla ; sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"deep-select ; sys_platform == 'linux'",
|
||||
"flash-linear-attention>=0.6.0 ; sys_platform == 'linux'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.18.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
# Precompiled FlashInfer kernels for vLLM's flashinfer-python pin. Without them every fresh node
|
||||
# downloads the trtllm-gen cubins and JIT-builds its modules into its node-local cache at startup.
|
||||
"flashinfer-cubin==0.7.0.post1 ; sys_platform == 'linux'",
|
||||
"flashinfer-jit-cache==0.7.0.post1+cu130 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.8.0.dev20261022 ; sys_platform == 'linux'",
|
||||
]
|
||||
dashboard = [
|
||||
"fastapi>=0.115",
|
||||
@@ -189,22 +192,6 @@ exclude = [
|
||||
"deps/prime-envs/environments/tool_use/apex_agents",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
|
||||
# this capped to the validated protobuf major.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "modelexpress"
|
||||
version = "0.3.0"
|
||||
requires-dist = [
|
||||
"grpcio>=1.66.2",
|
||||
"huggingface_hub>=0.20.0",
|
||||
"nixl",
|
||||
"numpy>=1.24.0",
|
||||
"protobuf>=5.27.0,<7.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
# Mirror the upstream Pydantic compatibility correction until the next release.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "ai-dynamo-runtime"
|
||||
@@ -232,6 +219,8 @@ requires-dist = [
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# The pinned MX nightly must be available without the rolling release cooldown.
|
||||
modelexpress = false
|
||||
# verifiers pins harbor==0.24.0, published inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-10-08T00:00:00Z"
|
||||
@@ -249,12 +238,10 @@ flash_attn_3 = false
|
||||
# fast-track so first-party releases can land same-day. Only packages that
|
||||
# appear in `uv tree` need to be listed; the resolver ignores entries for
|
||||
# packages it never sees.
|
||||
prime = false
|
||||
prime-runs = false
|
||||
prime-traces = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
verifiers = false
|
||||
renderers = false
|
||||
prime-pydantic-config = false
|
||||
@@ -267,6 +254,7 @@ nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
flash-mla = false
|
||||
deep-select = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
@@ -288,8 +276,8 @@ sonic-moe = { git = "https://github.com/S1ro1/sonic-moe", rev = "0bf06ac" }
|
||||
quack-kernels = { git = "https://github.com/S1ro1/quack", rev = "f62009f" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.3/vllm_router-0.2.3-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.3/vllm_router-0.2.3-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.4/vllm_router-0.2.4-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.4/vllm_router-0.2.4-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.32.0/vllm-0.32.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -304,8 +292,12 @@ deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-3101960/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-3101960/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-b52bd9d/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-b52bd9d/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-select = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-b52bd9d/deep_select-1.0.0+bfa4507.20261026.121630-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-b52bd9d/deep_select-1.0.0+bfa4507.20261026.121543-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
# FlashMLA nv_dev @ b7643bd built against torch 2.13.0+cu130 (see the release notes for the recipe).
|
||||
flash-mla = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
@@ -366,10 +358,12 @@ select = ["F", "I"]
|
||||
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
|
||||
# forward references and reports as syntax errors / undefined names.
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"src/prime_rl/trainer/data.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/distributed/ngram_lookup.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/models/layers/ngram.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-first-party = ["prime_rl"]
|
||||
|
||||
@@ -137,6 +137,9 @@ main() {
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
|
||||
log_info "Installing the prime CLI..."
|
||||
uv tool install prime
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
|
||||
|
||||
Executable → Regular
+35
-13
@@ -7,7 +7,9 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
MODELEXPRESS_REPOSITORY="https://github.com/ai-dynamo/modelexpress.git"
|
||||
MODELEXPRESS_REF="v0.3.0"
|
||||
# Must match the modelexpress client rev pinned in pyproject.toml.
|
||||
MODELEXPRESS_REF="446feecd33dafec3f5e8c7becab4d72894bb9640"
|
||||
PROTOC_VERSION="29.3"
|
||||
REDIS_VERSION="7.4.2"
|
||||
REDIS_SHA256="4ddebbf09061cbb589011786febdb34f29767dd7f89dbe712d2b68e808af6a1f"
|
||||
|
||||
@@ -16,29 +18,49 @@ if [[ $# -gt 0 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BIN_DIR="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
MX_DIR="$PROJECT_DIR/third_party/modelexpress"
|
||||
BIN_DIR="$MX_DIR/bin"
|
||||
mkdir -p "$BIN_DIR"
|
||||
|
||||
if [[ -x "$BIN_DIR/modelexpress-server" ]] \
|
||||
&& "$BIN_DIR/modelexpress-server" --version 2>/dev/null | grep -q "${MODELEXPRESS_REF#v}"; then
|
||||
if [[ -x "$BIN_DIR/modelexpress-server" ]] && [[ "$(cat "$BIN_DIR/modelexpress-server.ref" 2>/dev/null)" == "$MODELEXPRESS_REF" ]]; then
|
||||
echo "modelexpress-server $MODELEXPRESS_REF already installed at $BIN_DIR"
|
||||
else
|
||||
command -v cargo >/dev/null || {
|
||||
echo "cargo not found; install Rust 1.90 or newer before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
command -v protoc >/dev/null || {
|
||||
echo "protoc not found; install Protocol Buffers before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
BUILD_DIR=$(mktemp -d)
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT
|
||||
git clone --depth 1 --branch "$MODELEXPRESS_REF" "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
|
||||
# Bootstrap a job-local Rust toolchain and protoc when the host has none.
|
||||
if ! command -v cargo >/dev/null; then
|
||||
export RUSTUP_HOME="$MX_DIR/rustup" CARGO_HOME="$MX_DIR/cargo"
|
||||
if [[ ! -x "$CARGO_HOME/bin/cargo" ]]; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --no-modify-path
|
||||
fi
|
||||
export PATH="$CARGO_HOME/bin:$PATH"
|
||||
fi
|
||||
if ! command -v protoc >/dev/null; then
|
||||
PROTOC_DIR="$MX_DIR/protoc"
|
||||
if [[ ! -x "$PROTOC_DIR/bin/protoc" ]]; then
|
||||
case "$(uname -m)" in
|
||||
x86_64) PROTOC_ARCH="x86_64" ;;
|
||||
aarch64) PROTOC_ARCH="aarch_64" ;;
|
||||
*) echo "Unsupported architecture $(uname -m)" >&2; exit 1 ;;
|
||||
esac
|
||||
curl --fail --location --silent --show-error \
|
||||
--output "$BUILD_DIR/protoc.zip" \
|
||||
"https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-${PROTOC_ARCH}.zip"
|
||||
mkdir -p "$PROTOC_DIR"
|
||||
python3 -c "import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])" "$BUILD_DIR/protoc.zip" "$PROTOC_DIR"
|
||||
chmod +x "$PROTOC_DIR/bin/protoc"
|
||||
fi
|
||||
export PATH="$PROTOC_DIR/bin:$PATH" PROTOC="$PROTOC_DIR/bin/protoc"
|
||||
fi
|
||||
git clone --quiet "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
|
||||
(
|
||||
cd "$BUILD_DIR/modelexpress"
|
||||
git fetch --quiet origin "$MODELEXPRESS_REF"
|
||||
git checkout --quiet "$MODELEXPRESS_REF"
|
||||
cargo build --release --bin modelexpress-server
|
||||
)
|
||||
cp "$BUILD_DIR/modelexpress/target/release/modelexpress-server" "$BIN_DIR/"
|
||||
echo "$MODELEXPRESS_REF" > "$BIN_DIR/modelexpress-server.ref"
|
||||
fi
|
||||
|
||||
if [[ -x "$BIN_DIR/redis-server" ]] \
|
||||
|
||||
@@ -5,7 +5,7 @@ description: How the prime-rl config system works — TOML files, CLI overrides,
|
||||
|
||||
# Configs
|
||||
|
||||
prime-rl uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — a Pydantic-based TOML + CLI config system (no tyro). Every entrypoint accepts TOML files via `@` and CLI overrides.
|
||||
prime-rl uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — a Pydantic-based TOML + CLI config system (no tyro). Its local entrypoints accept TOML files via `@` and CLI overrides. Model Factory dispatch uses `prime train run CONFIG.toml` with training settings in the TOML; see [model-factory](../model-factory/SKILL.md).
|
||||
|
||||
## Loading and composition
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint,
|
||||
|
||||
# Eval
|
||||
|
||||
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
|
||||
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env worker pool per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
|
||||
|
||||
## Start an eval
|
||||
|
||||
@@ -25,7 +25,7 @@ uv run eval @ eval.toml --no-monitors.prime # keep the r
|
||||
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
|
||||
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
|
||||
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
|
||||
- Env worker pools: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
|
||||
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
|
||||
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
|
||||
@@ -91,7 +91,7 @@ Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t out
|
||||
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
|
||||
├── logs/latest/
|
||||
│ ├── eval.log # the eval process
|
||||
│ └── envs/eval/{name}.log # one log per env server
|
||||
│ └── envs/eval/{name}.log # one log per env worker pool
|
||||
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
|
||||
```
|
||||
|
||||
@@ -106,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
|
||||
|
||||
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, or score cut-off runs as 0 with `env.agent.scoring.skip_on_truncated` / `skip_on_timeout` (`env.agent.max_turn_tokens` caps each response and stops the run once one hits it, even in harnesses like RLM that continue past a capped turn), `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
|
||||
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env worker pools are children of the eval process and exit with it.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
---
|
||||
name: model-factory
|
||||
description: Launch and monitor prime-rl runs on Model Factory with prime train, and retrieve their traces. Use for requests such as "run this on model factory", including custom code revisions, private datasets, credentials, and team setup. Explicit local or SLURM jobs use start-run.
|
||||
---
|
||||
|
||||
# Model Factory
|
||||
|
||||
Use `prime train run CONFIG.toml` for managed training. `prime train CONFIG.toml`
|
||||
is the same command. The platform provisions and launches the components. Pass a
|
||||
single TOML filename directly; `@`, local `uv run rl` / `uv run sft`, and arbitrary
|
||||
dotted training flags belong to the local entrypoints. Put training overrides in
|
||||
the TOML. An explicit request to submit a SLURM job on a Model Factory cluster
|
||||
still uses the [start-run skill](../training/start-run/SKILL.md).
|
||||
|
||||
All local paths below are relative to the selected prime-rl checkout. Discover
|
||||
the user's checkout, credentials, team, and available CLI; do not assume a home
|
||||
directory, secret-file location, organization, GPU type, or previous run.
|
||||
|
||||
## CLI, authentication, and team
|
||||
|
||||
```bash
|
||||
command -v prime
|
||||
prime --version
|
||||
prime train run --help
|
||||
```
|
||||
|
||||
Install a missing CLI with `uv tool install prime`; update an existing tool with
|
||||
`uv tool upgrade prime` when a required feature needs it. Check which executable
|
||||
the shell resolves: a project environment can shadow the tool installation.
|
||||
|
||||
Authenticate with `prime login`, an existing exported `PRIME_API_KEY`, or the
|
||||
secure prompt from `prime config set-api-key`. For automation, load the key from
|
||||
the user's chosen secret store into the process environment. Do not put its value
|
||||
in command arguments, TOML, Git, or chat. A file on disk is not automatically
|
||||
exported. The [CLI config implementation](https://github.com/PrimeIntellect-ai/prime/blob/main/packages/prime/src/prime_cli/core/config.py)
|
||||
gives `PRIME_API_KEY` and nonempty `PRIME_TEAM_ID` precedence over saved settings.
|
||||
|
||||
For an API-key workflow, after loading the key securely:
|
||||
|
||||
```bash
|
||||
: "${PRIME_API_KEY:?Load a Prime API key for the launching account}"
|
||||
export PRIME_API_KEY
|
||||
```
|
||||
|
||||
Inspect the effective account configuration and available teams:
|
||||
|
||||
```bash
|
||||
prime config view --plain
|
||||
prime teams list --plain -o json
|
||||
```
|
||||
|
||||
`config view` masks the API key. Reuse the account/team the user selected; if the
|
||||
intended owner is ambiguous, resolve it before launching billable work. Set the
|
||||
chosen team ID from that list with `prime config set-team-id "$TEAM_ID"`, or use
|
||||
`export PRIME_TEAM_ID="$TEAM_ID"` for the current process. An exported team ID
|
||||
overrides `set-team-id`. To intentionally use a personal account, unset
|
||||
`PRIME_TEAM_ID` and use `prime config remove-team-id`. Team choice also scopes
|
||||
volumes and run access. See [CLI configuration](https://docs.primeintellect.ai/cli-reference/config-cli)
|
||||
and [teams](https://docs.primeintellect.ai/cli-reference/teams).
|
||||
|
||||
The launching credential and the remote run credential have different roles:
|
||||
the platform supplies a run-scoped `PRIME_API_KEY` to the Model Factory job. Do not
|
||||
include the launching key in `-e` or `--env-file`. Read
|
||||
[data and secrets](references/data-and-secrets.md) before forwarding credentials
|
||||
or using private Hugging Face data.
|
||||
|
||||
## Choose the source and a checked-in example
|
||||
|
||||
For custom training code, branches, commits, dependencies, or environments, read
|
||||
[custom code](references/custom-code.md) first. Select the runtime revision before
|
||||
adapting or validating its config.
|
||||
|
||||
Start from an existing example in that revision, copying it to a task-specific
|
||||
TOML if edits are needed. Do not use personal debug configs or prior experiment
|
||||
artifacts as the default recipe.
|
||||
|
||||
| Task | Starting point |
|
||||
| --- | --- |
|
||||
| Small RL run | [examples/basic/reverse-text/rl.toml](../../examples/basic/reverse-text/rl.toml) |
|
||||
| SFT | [examples/basic/reverse-text/sft.toml](../../examples/basic/reverse-text/sft.toml) |
|
||||
| Larger model or environment | Select a matching checked-in TOML under [examples/advanced](../../examples/advanced) |
|
||||
|
||||
```bash
|
||||
prime train models --plain -o json
|
||||
prime train gpus --plain -o json
|
||||
```
|
||||
|
||||
Use the exact model ID and GPU type available for the selected account/team.
|
||||
The [Model Factory RL docs](https://docs.primeintellect.ai/hosted-training/hosted-rl)
|
||||
describe uncached HF downloads on on-demand capacity, while reserved clusters
|
||||
require cached weights or weights on a volume. Check the actual dispatch path; an
|
||||
`HF_TOKEN` grants repository access, not cluster capacity or model-cache access.
|
||||
|
||||
Adapt the example to the requested experiment:
|
||||
|
||||
- Remove SLURM configuration and machine-local `output_dir` / `run.dir` paths.
|
||||
Put prompts and other required assets in the launched source or a supported
|
||||
volume. A path in TOML does not upload the file.
|
||||
- Set `[deployment]` explicitly, including trainer and inference GPU counts.
|
||||
Check TP/DP/EP/CP and context length against the model, hardware, and schema.
|
||||
Preserve `optimization_dtype` and `reduce_dtype` unless explicitly requested.
|
||||
- Use the revision's `[run]` and `[monitors.wandb]` schema for names and logging;
|
||||
consult the [configs skill](../configs/SKILL.md) for config structure. The
|
||||
selected revision's schema takes precedence over snippets from another build.
|
||||
- Keep RL train/eval sources separate under `orchestrator.train.source` and
|
||||
`orchestrator.eval.source`. Dataset arguments belong to the selected taskset's
|
||||
config under `env.taskset`; inspect its supported fields before setting them.
|
||||
- SFT uses `[data]` and needs real data staged on a volume. The checked-in SFT
|
||||
example also enables online eval; check CLI and cluster support before using
|
||||
it. See [data and secrets](references/data-and-secrets.md) for both paths.
|
||||
- Keep `[ckpt]` and attach a named volume when checkpoints must persist. Choose
|
||||
its size for the dataset, model, and retained checkpoints; see
|
||||
[volume sizing](https://docs.primeintellect.ai/hosted-training/volume-capacity).
|
||||
|
||||
## Validate and dispatch
|
||||
|
||||
If `prime train validate --help` is available, use that command with the same
|
||||
`--ref` / `--image-tag` and `--sft` selection as the intended launch. It is a
|
||||
validation command, not a GPU run. Otherwise, validate from the matching checkout
|
||||
and its installed environment (`CONFIG_PATH` names the prepared TOML):
|
||||
|
||||
```bash
|
||||
uv run --no-sync python - "$CONFIG_PATH" <<'PY'
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
|
||||
data = tomllib.loads(Path(sys.argv[1]).read_text())
|
||||
schema = SFTConfig if "data" in data and not {"trainer", "orchestrator"} & data.keys() else RLConfig
|
||||
schema.model_validate(data)
|
||||
print("Config valid")
|
||||
PY
|
||||
```
|
||||
|
||||
Keep dispatch metadata (`--ref`, image, GPU, volume) in CLI flags so this fallback
|
||||
receives only native prime-rl fields. Validation checks the config, not remote
|
||||
imports, private dataset access, capacity, or feature entitlements. For custom
|
||||
code, verify that the validator actually imports the selected revision's schema.
|
||||
|
||||
Summarize the prepared config, source/image, owner, GPU allocation, and expected
|
||||
run length before dispatch. Carry out an already authorized launch; ask only for
|
||||
unresolved choices or credentials that affect it. For an initial smoke run, use
|
||||
a small step budget unless the user specified otherwise.
|
||||
|
||||
```bash
|
||||
prime train run "$CONFIG_PATH" \
|
||||
--gpu-type "$GPU_TYPE" --volume "$VOLUME_NAME" \
|
||||
-e WANDB_API_KEY -e HF_TOKEN --yes --plain -o json
|
||||
```
|
||||
|
||||
Include only the flags and exported secrets that the run needs. Add
|
||||
`--ref "$CODE_REF"` for authorized custom source access, and `--sft` for SFT.
|
||||
`--yes` skips the CLI prompt for the launch the user requested. Save the returned
|
||||
`.run.runId`, config, source SHA, image selection, team, volume, and reported
|
||||
placement/rate. Share the dashboard URL returned by the CLI.
|
||||
|
||||
## Monitor and finish
|
||||
|
||||
```bash
|
||||
prime train get "$RUN_ID" --plain -o json
|
||||
prime train components "$RUN_ID" --plain
|
||||
prime train logs "$RUN_ID" --plain --tail 100
|
||||
prime train logs "$RUN_ID" -c trainer --plain --since 5m --tail 500
|
||||
prime train logs "$RUN_ID" -c inference --plain --since 5m --tail 500
|
||||
prime train metrics "$RUN_ID" --plain --limit 10
|
||||
prime train progress "$RUN_ID" --plain
|
||||
```
|
||||
|
||||
For environment logs, use `--env` with a name returned by `components`. Follow
|
||||
with `-f` or filter with `--search` / `--level ERROR` when needed. Confirm completed
|
||||
training steps and inspect rollout/eval infrastructure errors; `RUNNING` alone
|
||||
does not establish progress. Export needed component logs while pods still exist.
|
||||
|
||||
Uploaded traces persist separately from pods and can be retrieved after the run
|
||||
ends. For rollout inspection or trace downloads, read
|
||||
[retrieving traces](references/traces.md): list by run ID with `prime traces list`,
|
||||
then save raw documents with `prime traces get --raw --dest`. Listing summaries
|
||||
alone does not download the traces. The reference covers whole-run pagination,
|
||||
per-step episodes, separate eval run IDs, and missing-upload checks.
|
||||
|
||||
Queued and image-pull states can be normal. After an ambiguous dispatch timeout,
|
||||
check `prime train list` for the submitted run before retrying; do not create
|
||||
duplicates. Deterministic config, import, credential, or sandbox setup errors
|
||||
need a fix before another launch. Respect the user's run budget and stop conditions.
|
||||
|
||||
When asked to stop, or when an already agreed stop condition is reached:
|
||||
|
||||
```bash
|
||||
prime train stop "$RUN_ID" --force --plain
|
||||
prime train get "$RUN_ID" --plain -o json
|
||||
```
|
||||
|
||||
Verify terminal state, wait for volume sync, and retrieve requested checkpoints
|
||||
with `prime volumes get`. Report the run ID/link, actual completed steps, outcome,
|
||||
and checkpoint/trace artifact locations. Follow-up runs need to remain within the
|
||||
user's request.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Custom code, branches, and commits
|
||||
|
||||
Read this when the run must use code other than the managed build. The
|
||||
[public dispatch API](https://docs.primeintellect.ai/api-reference/training/create-dedicated-run)
|
||||
defines `sourceRef`: a branch, tag, or commit in **PrimeIntellect-ai/prime-rl**.
|
||||
The service resolves it to a commit, validates against that schema, and overlays
|
||||
the source on the image at pod startup.
|
||||
|
||||
## Access and revision selection
|
||||
|
||||
`prime train run CONFIG.toml --ref REF` is restricted: the run must belong to a
|
||||
team with source-ref access enabled by Prime, and the deployment must support
|
||||
source overlays. The CLI hides `--ref` from ordinary help in some releases;
|
||||
absence from help does not prove it is unsupported. Check the
|
||||
[CLI implementation](https://github.com/PrimeIntellect-ai/prime/blob/main/packages/prime/src/prime_cli/commands/rl.py)
|
||||
or installed command definition when needed. A 403 is an access issue; do not
|
||||
silently remove `--ref` and launch different code.
|
||||
|
||||
For a custom branch or commit:
|
||||
|
||||
1. Inspect the selected checkout's remote, branch, working tree, and submodule
|
||||
revisions. Identify the exact changes the user intends to run.
|
||||
2. Commit and push those changes to the canonical repository within the user's
|
||||
authorization. Confirm the remote URL before pushing; a fork named `origin`
|
||||
is not the canonical repo. Local edits, a local branch, and commits available
|
||||
only in a private fork are not uploaded by `prime train`.
|
||||
3. Verify the branch exists remotely and resolve the full commit SHA. Prefer
|
||||
that SHA for reproducibility. A branch or tag is also accepted, but record
|
||||
the resolved SHA; the CLI's `sourceRef` echo may be the input branch name.
|
||||
4. Validate the TOML using that commit's config schema and record any required
|
||||
image build. Launch with `--ref` and verify the startup log's
|
||||
`source overlay at <SHA>` matches. The entrypoint also exports
|
||||
`PRIME_RL_SOURCE_COMMIT` inside the container.
|
||||
|
||||
After selecting `CANONICAL_REMOTE` and `BRANCH`, a typical publication check is:
|
||||
|
||||
```bash
|
||||
git remote get-url "$CANONICAL_REMOTE"
|
||||
git push "$CANONICAL_REMOTE" "HEAD:refs/heads/$BRANCH"
|
||||
CODE_REF=$(git rev-parse HEAD)
|
||||
git ls-remote "$CANONICAL_REMOTE" "refs/heads/$BRANCH"
|
||||
```
|
||||
|
||||
Compare the remote SHA with `CODE_REF`, then include it in the prepared launch:
|
||||
|
||||
```bash
|
||||
prime train run "$CONFIG_PATH" --ref "$CODE_REF" \
|
||||
--gpu-type "$GPU_TYPE" --yes --plain -o json
|
||||
```
|
||||
|
||||
Carry over the volume and secret flags required by the main workflow. If supported,
|
||||
`--pr NUMBER` selects the head of an unmerged PR in the canonical repo; it is
|
||||
mutually exclusive with `--ref`, has the same access restrictions, and does not
|
||||
support fork PRs. Do not guess that a GitHub URL or a fork's branch is a valid ref.
|
||||
|
||||
If the required code is private, preserve that visibility. Do not publish it to
|
||||
the canonical public repo just to make `--ref` work. Explain the limitation and
|
||||
resolve a supported private delivery mechanism with the user/Prime before launch.
|
||||
|
||||
## Code and dependency delivery
|
||||
|
||||
`--image-tag TAG` chooses a build from the platform's prime-rl image repository;
|
||||
`--ref` chooses the source overlaid on that build. An image tag is not an arbitrary
|
||||
Docker image URI. Check the bootstrap baked into the selected image. This repo's
|
||||
[entrypoint](../../../scripts/docker-entrypoint.sh) fetches the source and pinned
|
||||
public submodules, then runs a locked workspace sync into the container's
|
||||
environment. Commit dependency changes and the updated `uv.lock` together.
|
||||
Heavy package pins (including torch, vLLM, and prime-kernels) must match the image:
|
||||
the entrypoint rejects drift instead of rebuilding those wheels. Changes to
|
||||
these pins, CUDA kernels, or system packages need a compatible image build.
|
||||
|
||||
For custom tasksets, harnesses, scorers, and tools, check that their package and
|
||||
registration are available in the remote runtime. Include source/assets and
|
||||
dependency declarations in the launched revision, or use a supported published
|
||||
environment/image delivery path. A local editable install or `prime env install`
|
||||
does not install a package in Model Factory pods. A Hub ID also needs to be accessible
|
||||
to the run's owner; use a published version compatible with the chosen runtime.
|
||||
|
||||
For a Hub delivery path, publish the package/version with `prime env push` from
|
||||
its package directory and explicitly preserve its intended visibility. For
|
||||
example, `prime env push --team "$TEAM_SLUG" --visibility PRIVATE --plain`
|
||||
uploads a private team environment; `--team` here takes the team slug, whereas
|
||||
CLI account setup uses the team ID. This requires authorization to publish that
|
||||
package. Include dependencies in the package metadata; local `tool.uv.sources`
|
||||
alone is not wheel dependency metadata. See
|
||||
[environment publishing](https://docs.primeintellect.ai/tutorials-environments/create).
|
||||
|
||||
If code lives in a submodule, push its commit to an accessible remote and commit
|
||||
the parent gitlink too. Verify how the Model Factory source overlay fetches submodules
|
||||
and installs environment packages. Do not assume a dirty local submodule or a
|
||||
private Git dependency is readable by the service. Never embed Git credentials
|
||||
in dependency URLs.
|
||||
|
||||
For files read at runtime, verify their location in the container or attached
|
||||
volume. Relative paths resolve in the remote process's working directory. Local
|
||||
absolute paths, shell environment changes, and untracked prompt files do not
|
||||
travel with the submitted TOML.
|
||||
@@ -0,0 +1,119 @@
|
||||
# Private datasets and secrets
|
||||
|
||||
## Local credentials and remote credentials
|
||||
|
||||
Load secrets from the user's chosen environment or secret manager. Check presence
|
||||
without printing values. For example, once the required credentials are loaded:
|
||||
|
||||
```bash
|
||||
: "${HF_TOKEN:?Load an HF token with access to the requested repository}"
|
||||
export HF_TOKEN
|
||||
prime train run "$CONFIG_PATH" -e HF_TOKEN --yes --plain -o json
|
||||
```
|
||||
|
||||
`-e KEY` reads the exported value; exporting alone does not forward it to Model Factory
|
||||
pods. `--env-file "$MODEL_FACTORY_ENV_FILE"` is an alternative for a file containing
|
||||
only intended remote secrets. Do not forward a general-purpose `.env` wholesale.
|
||||
Avoid inline `KEY=secret` arguments and shell tracing. Keep secret files outside
|
||||
version control with restrictive permissions. Configured local Prime/HF login
|
||||
state is not automatically copied to the remote job.
|
||||
|
||||
| Credential | Purpose |
|
||||
| --- | --- |
|
||||
| Local `PRIME_API_KEY` | Authenticates CLI/API requests; keep on the launching side. |
|
||||
| Local `PRIME_TEAM_ID` | Selects the run/volume owner; configure before dispatch. |
|
||||
| Remote `PRIME_API_KEY` | Generated and injected by the platform for the run; do not override with a personal key. |
|
||||
| `HF_TOKEN` | Pass with `-e HF_TOKEN` when remote model/dataset downloads require HF access. |
|
||||
| `WANDB_API_KEY` | Pass with `-e WANDB_API_KEY` when W&B monitoring is requested. |
|
||||
| Environment-specific keys | Forward only required names when the CLI and backend support them. |
|
||||
|
||||
### Check secret-forwarding support
|
||||
|
||||
The [Model Factory RL docs](https://docs.primeintellect.ai/hosted-training/hosted-rl#launching-a-run)
|
||||
describe arbitrary secrets reaching trainer, inference, orchestrator, and
|
||||
env-worker-pool processes. However, the CLI 0.14.0 implementation and public CLI source
|
||||
checked on 2026-10-23 still restrict dedicated runs to `WANDB_API_KEY` and
|
||||
`HF_TOKEN`. Check the installed version and
|
||||
[secret collection code](https://github.com/PrimeIntellect-ai/prime/blob/main/packages/prime/src/prime_cli/commands/rl.py)
|
||||
before relying on a third-party key. Upgrade to a release with the required
|
||||
support if available; otherwise report the blocker. Do not omit a required key,
|
||||
rename it as an unrelated credential, or put it in the config to bypass rejection.
|
||||
|
||||
`PRIME_API_KEY` is reserved by the service. The run's token is supplied by the
|
||||
platform, including for Prime services such as sandbox creation. Secrets projected
|
||||
into a training/env-worker-pool process do not automatically enter a child sandbox:
|
||||
if sandbox code itself needs a key, configure that runtime's supported secret
|
||||
injection. See [sandbox secrets](https://docs.primeintellect.ai/sandboxes/secrets).
|
||||
|
||||
## Private Hugging Face datasets for RL
|
||||
|
||||
Use an HF token with read access to the requested repository, including any gated
|
||||
dataset approval. Set the dataset ID, subset, split, and revision only through
|
||||
fields the selected taskset supports. A metric source `name` is not a dataset
|
||||
selector. Inspect the taskset config and loader if the mapping is unclear.
|
||||
|
||||
Verify access with the same token before reserving GPUs, without displaying
|
||||
private samples. Pass `-e HF_TOKEN` to the Model Factory launch and ensure the loader uses
|
||||
it. If the taskset downloads in a sandbox rather than the env worker pool, deliver the
|
||||
credential there explicitly. Custom loaders/scorers must be installed remotely;
|
||||
see [custom code](custom-code.md).
|
||||
|
||||
Alternatively, stage data on a volume and set the taskset's supported local-path
|
||||
field to its remote mount path. Verify that the process reading it actually has
|
||||
the mount; a training volume is not automatically mounted in rollout sandboxes.
|
||||
|
||||
## Private Hugging Face datasets for SFT
|
||||
|
||||
Start from [examples/basic/reverse-text/sft.toml](../../../examples/basic/reverse-text/sft.toml)
|
||||
in the selected revision. Model Factory SFT requires real datasets on a named volume;
|
||||
`HF_TOKEN` alone does not turn a Hub ID in `[data].name` into a volume dataset.
|
||||
Use HF `load_dataset`-readable Parquet/JSON with `messages` or
|
||||
`prompt`/`completion` columns, not a `save_to_disk` directory.
|
||||
|
||||
Choose `DATASET_ID`, `DATASET_REVISION`, `DATASET_DIR` (an isolated local staging
|
||||
directory), `VOLUME_NAME`, and `VOLUME_SIZE` for this task. With `HF_TOKEN` already
|
||||
exported, download and upload through the public CLI paths:
|
||||
|
||||
```bash
|
||||
uv run --no-sync hf download "$DATASET_ID" --repo-type dataset \
|
||||
--revision "$DATASET_REVISION" --local-dir "$DATASET_DIR"
|
||||
prime volumes create "$VOLUME_NAME" --size "$VOLUME_SIZE"
|
||||
prime volumes put "$VOLUME_NAME" "$DATASET_DIR/" datasets/training-data
|
||||
```
|
||||
|
||||
Reuse an existing appropriate volume instead of recreating it. These commands
|
||||
upload dataset files, not the HF credential. Check the staging directory contains
|
||||
only the intended files. For HF authentication and download options, see the
|
||||
[HF CLI guide](https://huggingface.co/docs/huggingface_hub/guides/cli).
|
||||
|
||||
In the copied SFT config, set `[data].name = "datasets/training-data"` (or
|
||||
`"/volume/datasets/training-data"`), `type = "sft"`, and the appropriate splits /
|
||||
subsets / column mapping. Verify loading in a fresh process with the same dataset
|
||||
library and options, without logging private rows. Pin and record the download
|
||||
revision; a local dataset path does not fetch `[data].revision` from the Hub.
|
||||
|
||||
The repository's basic SFT example includes `[eval]` and `[inference]`. The
|
||||
[Model Factory SFT docs](https://docs.primeintellect.ai/hosted-training/hosted-sft#online-evals)
|
||||
require chart 0.24.0+ for online eval. Check the CLI too: some versions reject those
|
||||
blocks. Preserve requested online eval and resolve missing support; for an intended
|
||||
trainer-only run, remove both blocks and their nested tables from the copied
|
||||
example and size the trainer deployment accordingly. Keep the model renderer
|
||||
consistent with any model substitution.
|
||||
|
||||
```bash
|
||||
prime train run "$CONFIG_PATH" --sft --volume "$VOLUME_NAME" \
|
||||
--gpu-type "$GPU_TYPE" --yes --plain -o json
|
||||
```
|
||||
|
||||
Add the remote secrets/source flags the job needs. For cluster-side dataset
|
||||
downloads, `prime volumes ssh "$VOLUME_NAME" --read-write` is an alternative
|
||||
requiring eligible cluster access and the account's primary SSH key. Local
|
||||
`HF_TOKEN` is not automatically forwarded over SSH; supply it securely inside the
|
||||
session. Download under `/volume/datasets/`, then explicitly end the session with
|
||||
`prime volumes stop "$VOLUME_NAME" "$SESSION_ID"` and wait for final sync.
|
||||
Exiting the SSH shell alone can leave a writer lock that blocks dispatch.
|
||||
|
||||
Use `prime volumes put/get` when no SSH allocation is available. Wait for a run's
|
||||
final volume sync before retrieving `runs/<runId>/checkpoints/`. See
|
||||
[volumes](https://docs.primeintellect.ai/hosted-training/volumes) for transfer and
|
||||
session behavior.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Retrieve Model Factory run traces
|
||||
|
||||
Uploaded traces are stored by Prime Traces and remain available after training
|
||||
pods terminate. Use the same personal/team workspace as the run and a local
|
||||
`PRIME_API_KEY` with Prime Traces read permissions. `PRIME_TEAM_ID` or saved CLI
|
||||
team settings select the workspace. See the
|
||||
[Traces overview](https://docs.primeintellect.ai/traces/overview).
|
||||
|
||||
## Inspect and download
|
||||
|
||||
Use the Model Factory run ID initially. Choose a local `TRACE_DIR` for artifacts:
|
||||
|
||||
```bash
|
||||
mkdir -p "$TRACE_DIR"
|
||||
prime traces get "$RUN_ID" --runs --plain -o json
|
||||
prime traces list --run-id "$RUN_ID" --limit 100 --plain -o json
|
||||
```
|
||||
|
||||
The list contains summaries in `.items`, each with a `trace_id`. Download the
|
||||
selected raw record to a file rather than printing large or private conversations:
|
||||
|
||||
```bash
|
||||
prime traces get "$TRACE_ID" --raw --dest "$TRACE_DIR/$TRACE_ID.json" --plain
|
||||
```
|
||||
|
||||
`--raw` retrieves the stored trace document; a summary is not the full trace.
|
||||
For the [SDK alternative](https://docs.primeintellect.ai/traces/managing-traces#download-a-trace),
|
||||
use `TracesClient.download_raw(trace_id, destination)` from a `uv run` script.
|
||||
|
||||
For a whole run, iterate the list response's `.items[].trace_id`, download each
|
||||
raw record, and follow `.next_cursor` with the same filters until it is empty:
|
||||
|
||||
```bash
|
||||
prime traces list --run-id "$RUN_ID" --limit 100 \
|
||||
--cursor "$NEXT_CURSOR" --plain -o json
|
||||
```
|
||||
|
||||
Use cursor pagination rather than repeatedly selecting numbered pages while new
|
||||
records arrive. There is no working SDK bulk-export operation documented; build
|
||||
the export from paginated summaries and individual downloads. Record exported
|
||||
IDs, count, and destination. For a final export, wait for uploads to drain and
|
||||
compare against the run summary's `trace_count`; reconcile new or missing IDs
|
||||
before claiming completeness. Keep any failed downloads visible in the report.
|
||||
|
||||
## Training steps and evaluations
|
||||
|
||||
To find episodes from one training step and their member traces:
|
||||
|
||||
```bash
|
||||
prime traces list --episodes --run-id "$RUN_ID" --run-step "$STEP" --plain -o json
|
||||
prime traces list --episode-id "$EPISODE_ID" --plain -o json
|
||||
prime traces get "$EPISODE_ID" --episodes --raw \
|
||||
--dest "$TRACE_DIR/$EPISODE_ID.episode.json" --plain
|
||||
```
|
||||
|
||||
Follow pagination for both episode and member-trace lists. Download each member
|
||||
trace separately; an episode record groups traces and is not their raw content.
|
||||
|
||||
Online evals may have their own evaluation IDs. The
|
||||
[Prime monitor](../../../src/prime_rl/monitors/prime.py) logs each environment/step's
|
||||
evaluation URL; use that ID as `--run-id` for its traces instead of assuming they
|
||||
all share the training ID. Start with the run dashboard and evaluation links or
|
||||
the orchestrator/eval logs to identify the right evaluation.
|
||||
|
||||
The training CLI also exposes a per-step sample view:
|
||||
|
||||
```bash
|
||||
prime train rollouts "$RUN_ID" --step "$STEP" --page 1 --num 100 --plain
|
||||
```
|
||||
|
||||
Its JSON includes `samples`, `total`, and `total_pages`; request remaining pages
|
||||
when needed. Use `prime train progress` to discover populated steps. Do not treat
|
||||
one sample page as a full raw trace export. For older runs backed by legacy sample
|
||||
storage, consult the [archive export documentation](https://docs.primeintellect.ai/traces/legacy-storage)
|
||||
and its November 6, 2026 retirement date.
|
||||
|
||||
## Missing traces
|
||||
|
||||
Check workspace, run/evaluation ID, upload completion/errors, and the configured
|
||||
[upload controls](https://docs.primeintellect.ai/traces/pricing-and-settings).
|
||||
Account-level opt-out can disable SDK/CLI reads while stored traces remain visible
|
||||
in the dashboard. A completed training run does not prove all traces uploaded.
|
||||
Trainer-only SFT produces no rollout traces; the Model Factory SFT docs also currently
|
||||
list online-eval trace uploads as unavailable, so verify runtime support before
|
||||
promising those artifacts.
|
||||
|
||||
`prime traces search "Traceback" --run-id "$RUN_ID" --plain` can locate failures,
|
||||
but search coverage may lag ingestion. An empty search result is not evidence
|
||||
that the raw records are absent. See
|
||||
[retrieval troubleshooting](https://docs.primeintellect.ai/traces/managing-traces#troubleshooting).
|
||||
@@ -1,13 +1,14 @@
|
||||
---
|
||||
name: training
|
||||
description: Launch and monitor prime-rl training runs. Use when starting, supervising, or debugging an RL/SFT run. Routes to `start-run` (entrypoints + how to launch) and `monitor-run` (logs, metrics, check-ins).
|
||||
description: Launch and monitor prime-rl training runs. Use when starting, supervising, or debugging an RL/SFT run. Routes Model Factory to model-factory, and local or SLURM runs to start-run and monitor-run.
|
||||
---
|
||||
|
||||
# Training
|
||||
|
||||
Two phases — start the run, then watch it.
|
||||
Choose the deployment workflow first.
|
||||
|
||||
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
|
||||
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
|
||||
- **Model Factory** — see [model-factory](../model-factory/SKILL.md) for `prime train` launches, custom source revisions, credentials, private datasets, and remote monitoring. Requests such as "run this on model factory" use this path unless the user explicitly requests SLURM.
|
||||
- **Start a local / SLURM run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
|
||||
- **Monitor a local / SLURM run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
|
||||
|
||||
Both subskills assume the `configs` skill for config-loading mechanics. Standalone evals (`uv run eval`) are the `eval` skill; online evals of a training run are configured in `start-run` and read in `monitor-run`.
|
||||
The local start/monitor subskills assume the `configs` skill for config-loading mechanics. Model Factory dispatch takes a TOML filename directly and has its own CLI flags. Standalone evals (`uv run eval`) are the `eval` skill; online evals follow the selected training workflow.
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
---
|
||||
name: monitor-run
|
||||
description: Monitor an ongoing prime-rl training run — find the output directory, tail logs, check key metrics, inspect SLURM jobs, and restart safely. Use when asked to check on a run, debug training, or investigate performance.
|
||||
description: Monitor a local or SLURM prime-rl training run — find the output directory, tail logs, check key metrics, inspect jobs, and restart safely. Model Factory monitoring uses model-factory.
|
||||
---
|
||||
|
||||
# Monitor a run
|
||||
|
||||
For a managed Model Factory run ID or dashboard link, use the [model-factory skill](../../model-factory/SKILL.md) for `prime train` status, logs, metrics, and stop commands.
|
||||
|
||||
## Runbook
|
||||
|
||||
### On launch
|
||||
@@ -106,7 +108,7 @@ grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
|
||||
### Live rollouts
|
||||
|
||||
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
|
||||
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env worker pool's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
|
||||
|
||||
### Metrics
|
||||
|
||||
@@ -138,6 +140,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
| Metric | Description |
|
||||
|--------|-------------|
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
|
||||
| `mismatch_kl_by_staleness/{bin}/{mean,std,max}` | the same KL per log2 token-staleness bin (`0`, `1`, `2-3`, `4-7`, …); bin `0` is numerical mismatch alone, the rise across bins is staleness drift |
|
||||
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
|
||||
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
|
||||
| `optim/grad_norm` | spikes may precede divergence |
|
||||
@@ -154,7 +157,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
|
||||
| orchestrator | `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `staleness/token/{mean,masked}`, `staleness/rollout/{mean,max}`, `staleness/rollout/{in_flight,in_queue}/{mean,max}`, `staleness/rollout/dropped` | per-step token and rollout staleness of trained rollouts (rollout = max token staleness) |
|
||||
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
| env worker pool | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
|
||||
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
|
||||
|
||||
@@ -214,7 +217,7 @@ stream records, newest winning.
|
||||
wc -l {run_dir}/monitors/file/traces/stream.index.jsonl
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq '.traces[].rewards'
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq 'select(.ok | not) | {id, env: .env.id, errors}'
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.index.jsonl
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orchestrator.index.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}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
|
||||
@@ -235,9 +238,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
|
||||
```
|
||||
PRL::Launcher
|
||||
├── PRL::Inference (vLLM server, GPU 0)
|
||||
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── PRL::EnvBroker (one worker pool replica per train/eval source)
|
||||
│ └── PRL::EnvWorker (spawned processes, 1..N per pool; execute episodes)
|
||||
├── PRL::Orchestrator (CPU-only; connects to each env worker pool)
|
||||
├── torchrun
|
||||
│ └── PRL::Trainer (GPU 1+)
|
||||
└── tail trainer.log
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
---
|
||||
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. Standalone evals are the `eval` skill.
|
||||
description: Launch local or SLURM prime-rl training runs with the rl, sft, and inference entrypoints, including dry runs. Model Factory uses model-factory; standalone evals use eval.
|
||||
---
|
||||
|
||||
# Start a run
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
For "run this on model factory", use the [model-factory skill](../../model-factory/SKILL.md). Explicit SLURM jobs use this skill even on a Model Factory cluster.
|
||||
|
||||
The local entrypoints below run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs and `command.txt` under `configs/attempt_<n>/`. `configs/latest` points to the current attempt. The command uses shell-safe quoting.
|
||||
|
||||
|
||||
@@ -5,8 +5,11 @@ from prime_rl.control.types import (
|
||||
Action,
|
||||
ActionNotFoundError,
|
||||
ActionRequest,
|
||||
ConfigSnapshot,
|
||||
ControlConflictError,
|
||||
InvalidActionError,
|
||||
InvalidConfigError,
|
||||
StepActionRequest,
|
||||
)
|
||||
|
||||
|
||||
@@ -23,10 +26,21 @@ def create_app(controller: Controller) -> FastAPI:
|
||||
@app.post("/v1/actions", status_code=status.HTTP_202_ACCEPTED)
|
||||
async def submit_action(request: ActionRequest) -> Action:
|
||||
try:
|
||||
return controller.submit(request.type, request.step)
|
||||
if isinstance(request, StepActionRequest):
|
||||
return controller.submit(request.type, request.step)
|
||||
return controller.submit_config(request)
|
||||
except ControlConflictError as error:
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, str(error)) from error
|
||||
except InvalidConfigError as error:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, error.detail) from error
|
||||
except InvalidActionError as error:
|
||||
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(error)) from error
|
||||
|
||||
@app.get("/v1/config")
|
||||
async def get_config() -> ConfigSnapshot:
|
||||
try:
|
||||
return controller.get_config()
|
||||
except InvalidActionError as error:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, str(error)) from error
|
||||
|
||||
return app
|
||||
|
||||
@@ -1,18 +1,49 @@
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.control.types import Action, ActionNotFoundError, ActionType, ControlConflictError, InvalidActionError
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from prime_rl.configs.diff import ConfigChange, diff_config, frozen_raw_changes
|
||||
from prime_rl.control.types import (
|
||||
Action,
|
||||
ActionNotFoundError,
|
||||
ConfigSnapshot,
|
||||
ControlConflictError,
|
||||
InvalidActionError,
|
||||
InvalidConfigError,
|
||||
StepActionType,
|
||||
UpdateConfigRequest,
|
||||
)
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
CheckConfig = Callable[[dict[str, Any]], tuple[BaseModel, list[ConfigChange]]]
|
||||
"""Validate a submitted config against the running one; returns it and its changes, or raises
|
||||
``InvalidConfigError``."""
|
||||
ApplyConfig = Callable[[BaseModel, list[ConfigChange]], None]
|
||||
"""Apply a validated config as the next revision."""
|
||||
|
||||
|
||||
class Controller:
|
||||
"""Run control. A pause only queues when submitted; ``update`` applies it at a step, so each
|
||||
step runs with one consistent decision."""
|
||||
"""Run control. A pause or checkpoint only queues when submitted; ``update`` applies it at a
|
||||
step, so each step runs with one consistent decision. A config update likewise waits for
|
||||
``apply_update``."""
|
||||
|
||||
def __init__(self, *, requires_step: bool, on_submit: Callable[[], None] = lambda: None) -> None:
|
||||
"""``requires_step``: whether a pause names its step (orchestrator) or applies at the next
|
||||
one (trainer). ``on_submit`` runs after a pause queues, from the API thread."""
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
requires_step: bool,
|
||||
on_submit: Callable[[], None] = lambda: None,
|
||||
read_config: Callable[[], tuple[int, BaseModel]] | None = None,
|
||||
check_config: CheckConfig | None = None,
|
||||
) -> None:
|
||||
"""``requires_step``: whether a pause or checkpoint names its step (orchestrator) or applies
|
||||
at the next one (trainer). ``on_submit`` runs after one queues, from the API thread. ``read_config`` and
|
||||
``check_config``: read the running config with its revision and validate a new one, for
|
||||
components that update live."""
|
||||
self.requires_step = requires_step
|
||||
self.on_submit = on_submit
|
||||
self.id_to_action: dict[str, Action] = {}
|
||||
@@ -20,6 +51,9 @@ class Controller:
|
||||
self.saved_steps: set[int] = set()
|
||||
self.step: int | None = None
|
||||
self.stop_step: int | None = None
|
||||
self.read_config = read_config
|
||||
self.check_config = check_config
|
||||
self.pending_update: tuple[Action, BaseModel] | None = None
|
||||
# The API serves from its own thread while the step loop applies actions.
|
||||
self.lock = threading.Lock()
|
||||
|
||||
@@ -35,11 +69,11 @@ class Controller:
|
||||
return action
|
||||
|
||||
def mark_saved(self, step: int) -> None:
|
||||
"""Record that this process saved ``step``, the step its pause applied to."""
|
||||
"""Record that this process saved ``step``, the step its pause or checkpoint applied to."""
|
||||
with self.lock:
|
||||
self.saved_steps.add(step)
|
||||
|
||||
def submit(self, action_type: ActionType, step: int | None = None) -> Action:
|
||||
def submit(self, action_type: StepActionType, step: int | None = None) -> Action:
|
||||
self._validate_step(step)
|
||||
with self.lock:
|
||||
self._validate_accepting(step)
|
||||
@@ -49,18 +83,53 @@ class Controller:
|
||||
self.on_submit()
|
||||
return action
|
||||
|
||||
def update(self, step: int) -> bool:
|
||||
"""Apply a pause due at ``step``. Returns whether the run pauses there."""
|
||||
def update(self, step: int) -> StepActionType | None:
|
||||
"""Apply a pause or checkpoint due at ``step``. Returns which one saves the run there."""
|
||||
with self.lock:
|
||||
self.step = step
|
||||
action = self.pending
|
||||
if action is None or action.step not in (None, step):
|
||||
return False
|
||||
return None
|
||||
self.pending = None
|
||||
action.state, action.step = "accepted", step
|
||||
self.stop_step = step
|
||||
if action.type == "pause":
|
||||
self.stop_step = step
|
||||
get_logger().info(f"Control action {action.id}: {action.type} at step {step}")
|
||||
return True
|
||||
return action.type
|
||||
|
||||
def get_config(self) -> ConfigSnapshot:
|
||||
if self.read_config is None:
|
||||
raise InvalidActionError("This component takes no config updates.")
|
||||
with self.lock:
|
||||
step, (revision, config) = self.step, self.read_config()
|
||||
return ConfigSnapshot(revision=revision, step=step, config=dump_resolved_config(config))
|
||||
|
||||
def submit_config(self, request: UpdateConfigRequest) -> Action:
|
||||
"""Validate a full new config and queue it for the next step boundary."""
|
||||
if self.check_config is None:
|
||||
raise InvalidActionError("This component takes no config updates; only the orchestrator does.")
|
||||
with self.lock:
|
||||
self._validate_accepting_update()
|
||||
revision, _ = self.read_config()
|
||||
config, changes = self.check_config(request.config)
|
||||
with self.lock:
|
||||
self._validate_accepting_update()
|
||||
if self.read_config()[0] != revision:
|
||||
raise ControlConflictError("The config changed while this update was validated; submit it again.")
|
||||
action = Action(id=uuid.uuid4().hex, type="update_config", state="pending", changes=changes)
|
||||
self.id_to_action[action.id] = action
|
||||
self.pending_update = (action, config)
|
||||
return action
|
||||
|
||||
def apply_update(self, step: int, apply: ApplyConfig) -> None:
|
||||
"""Apply the queued config update, if any, from ``step`` on."""
|
||||
with self.lock:
|
||||
if self.pending_update is None:
|
||||
return
|
||||
action, config = self.pending_update
|
||||
self.pending_update = None
|
||||
apply(config, action.changes)
|
||||
action.state, action.step = "applied", step
|
||||
|
||||
def _validate_accepting(self, step: int | None) -> None:
|
||||
if self.stop_step is not None:
|
||||
@@ -68,12 +137,40 @@ class Controller:
|
||||
f"The run paused at step {self.stop_step} and takes no more actions; resume it to submit new ones."
|
||||
)
|
||||
if self.pending is not None:
|
||||
raise ControlConflictError("A pause is already queued and the run takes no more actions.")
|
||||
raise ControlConflictError(
|
||||
f"A {self.pending.type} is already queued; wait until it is accepted, then submit again."
|
||||
)
|
||||
if step is not None and self.step is not None and step < self.step:
|
||||
raise ControlConflictError(f"Step {step} has passed, this component is at step {self.step}.")
|
||||
|
||||
def _validate_accepting_update(self) -> None:
|
||||
self._validate_accepting(None)
|
||||
if self.pending_update is not None:
|
||||
raise ControlConflictError(
|
||||
"A config update is already queued; wait until it is applied, then submit again."
|
||||
)
|
||||
|
||||
def _validate_step(self, step: int | None) -> None:
|
||||
if self.requires_step and step is None:
|
||||
raise InvalidActionError("The orchestrator pauses at a step you name: pass the trainer's accepted 'step'.")
|
||||
raise InvalidActionError("The orchestrator saves at a step you name: pass the trainer's accepted 'step'.")
|
||||
if not self.requires_step and step is not None:
|
||||
raise InvalidActionError("The trainer pauses at its next step and takes no 'step'.")
|
||||
raise InvalidActionError("The trainer saves at its next step and takes no 'step'.")
|
||||
|
||||
|
||||
def validate_update(current: BaseModel, raw: dict[str, Any]) -> tuple[BaseModel, list[ConfigChange]]:
|
||||
"""Validate a submitted full config and diff it against ``current``. Rejects changes to
|
||||
frozen fields; every other field is applied live."""
|
||||
# Checked on the raw dict first: a frozen change can itself make the config invalid, and
|
||||
# validation may rewrite the dict in place.
|
||||
frozen = frozen_raw_changes(current, dump_resolved_config(current), raw)
|
||||
try:
|
||||
config = type(current).model_validate(raw)
|
||||
except ValidationError as error:
|
||||
errors = json.loads(error.json(include_url=False, include_input=False))
|
||||
raise InvalidConfigError("The config is invalid.", errors=errors, frozen=frozen) from error
|
||||
diff = diff_config(current, config)
|
||||
if diff.frozen:
|
||||
raise InvalidConfigError(
|
||||
"The config changes fields that cannot change while the run is going.", frozen=diff.frozen
|
||||
)
|
||||
return config, diff.changes
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
from typing import Literal
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Annotated, Any, Literal
|
||||
|
||||
ActionState = Literal["pending", "accepted", "committed"]
|
||||
ActionType = Literal["pause"]
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prime_rl.configs.diff import ConfigChange
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
|
||||
ActionState = Literal["pending", "accepted", "committed", "applied"]
|
||||
"""A pause or checkpoint goes pending -> accepted -> committed, a config update pending -> applied."""
|
||||
StepActionType = Literal["checkpoint", "pause"]
|
||||
"""An action that saves the run at a step: a checkpoint keeps running after it, a pause stops."""
|
||||
ActionType = Literal["checkpoint", "pause", "update_config"]
|
||||
|
||||
|
||||
class Action(BaseModel):
|
||||
@@ -11,22 +22,74 @@ class Action(BaseModel):
|
||||
type: ActionType
|
||||
state: ActionState
|
||||
step: int | None = None
|
||||
"""The step the action applies to: the requested one, else set once the controller applies it."""
|
||||
"""The step the action applies to: the requested one, else set once the controller applies it.
|
||||
For a config update, the first step whose rollouts use the new config."""
|
||||
changes: list[ConfigChange] | None = None
|
||||
"""What a config update changes."""
|
||||
|
||||
|
||||
class StepActionRequest(BaseModel):
|
||||
type: StepActionType
|
||||
step: int | None = None
|
||||
"""The step to apply the action at, which the orchestrator requires and the trainer picks itself."""
|
||||
|
||||
|
||||
class UpdateConfigRequest(BaseModel):
|
||||
type: Literal["update_config"]
|
||||
config: dict[str, Any]
|
||||
"""The full new config, as returned by ``GET /v1/config``."""
|
||||
|
||||
|
||||
ActionRequest = Annotated[StepActionRequest | UpdateConfigRequest, Field(discriminator="type")]
|
||||
|
||||
|
||||
class ConfigSnapshot(BaseModel):
|
||||
revision: int
|
||||
step: int | None
|
||||
"""The last step the run shipped, None before the first."""
|
||||
config: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConfigUpdate:
|
||||
"""A validated live config update, as the orchestrator's components receive it."""
|
||||
|
||||
revision: int
|
||||
step: int
|
||||
"""The first step whose rollouts use the new config."""
|
||||
config: OrchestratorConfig
|
||||
"""The full new config, never mutated in place."""
|
||||
changes: tuple[ConfigChange, ...]
|
||||
|
||||
|
||||
class Reconfigurable:
|
||||
"""An orchestrator component that the orchestrator reconfigures on every applied config
|
||||
update. Components that read live config values override ``reconfigure``."""
|
||||
|
||||
def reconfigure(self, update: ConfigUpdate) -> None:
|
||||
"""Apply a validated update at a step boundary. Cannot fail: the update was
|
||||
validated when it was submitted."""
|
||||
|
||||
|
||||
class ActionNotFoundError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ActionRequest(BaseModel):
|
||||
type: ActionType
|
||||
step: int | None = None
|
||||
"""The step to apply the action at, which the orchestrator requires and the trainer picks itself."""
|
||||
|
||||
|
||||
class ControlConflictError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidActionError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidConfigError(InvalidActionError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
errors: list[Any] | None = None,
|
||||
frozen: list[str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.detail = {"message": message, "errors": errors or [], "frozen": frozen or []}
|
||||
|
||||
@@ -240,8 +240,10 @@ def resolved_config_dir(run_dir: Path, attempt: str = "latest") -> Path:
|
||||
|
||||
def main_config(run_dir: Path) -> tuple[str, dict]:
|
||||
configs = resolved_config_dir(run_dir)
|
||||
if (configs / "sft.json").exists():
|
||||
return "sft", read_json(configs / "sft.json")
|
||||
# Pretraining uses the same trainer as SFT, so the dashboard shows its runs as SFT runs.
|
||||
for name in ("sft.json", "pretrain.json"):
|
||||
if (configs / name).exists():
|
||||
return "sft", read_json(configs / name)
|
||||
if (configs / "orchestrator.json").exists() or (configs / "trainer.json").exists():
|
||||
return "rl", read_json(configs / "orchestrator.json") or read_json(configs / "trainer.json")
|
||||
if (configs / "eval.json").exists():
|
||||
@@ -836,16 +838,6 @@ def timeline_status(trace: dict) -> str:
|
||||
return "completed"
|
||||
|
||||
|
||||
def timeline_reward(trace: dict) -> float | None:
|
||||
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
|
||||
if not rewards:
|
||||
return None
|
||||
return sum(
|
||||
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
|
||||
for reward in rewards
|
||||
)
|
||||
|
||||
|
||||
def annotation_streams(run_dir: Path) -> list[Path]:
|
||||
"""The annotation streams, one chunk directory per producer, each indexed beside it."""
|
||||
directory = get_annotations_dir(run_dir)
|
||||
@@ -952,9 +944,6 @@ def activity_spans(
|
||||
ended = call_time.get("end")
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens, cached_tokens, output_tokens = token_usage(usage)
|
||||
reasoning_tokens = usage.get("reasoning_tokens")
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
mask = node.get("mask")
|
||||
spans.append(
|
||||
@@ -972,7 +961,6 @@ def activity_spans(
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
"trainable": any(mask) if isinstance(mask, list) and mask else None,
|
||||
}
|
||||
@@ -1006,6 +994,20 @@ def lifecycle_spans(trace: dict) -> list[dict]:
|
||||
return spans
|
||||
|
||||
|
||||
def new_input_tokens(activities: list[dict]) -> int | None:
|
||||
"""Fed-in tokens of one call chain, counted once: each call's prompt beyond the
|
||||
previous call's final sequence, clamped at zero (verifiers' `min_new_input_tokens`)."""
|
||||
total = None
|
||||
previous = 0
|
||||
for span in sorted(activities, key=lambda span: span["call_index"]):
|
||||
if span.get("input_tokens") is None:
|
||||
continue
|
||||
prompt = span["input_tokens"] + (span.get("cached_tokens") or 0)
|
||||
total = (total or 0) + max(0, prompt - previous)
|
||||
previous = prompt + (span.get("output_tokens") or 0)
|
||||
return total
|
||||
|
||||
|
||||
def timeline_lane(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
@@ -1042,14 +1044,15 @@ def timeline_lane(
|
||||
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
input_tokens = total("input_tokens")
|
||||
cached_tokens = total("cached_tokens")
|
||||
output_tokens = total("output_tokens")
|
||||
reasoning_tokens = total("reasoning_tokens")
|
||||
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
|
||||
total_tokens = (
|
||||
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
|
||||
)
|
||||
if branch:
|
||||
input_tokens = new_input_tokens(activities)
|
||||
else:
|
||||
# the trace counts input on shared branch prefixes once; its call list
|
||||
# interleaves branches, so the lane's spans cannot reproduce that
|
||||
input_tokens = trace.get("num_input_tokens")
|
||||
output_tokens = trace.get("num_output_tokens", output_tokens)
|
||||
total_tokens = input_tokens + output_tokens if input_tokens is not None and output_tokens is not None else None
|
||||
context_lengths = [
|
||||
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
|
||||
for span in activities
|
||||
@@ -1064,18 +1067,15 @@ def timeline_lane(
|
||||
"ended_at": ended,
|
||||
"status": status,
|
||||
"outcome": status if branch else (trace.get("stop_condition") or status),
|
||||
"reward": timeline_reward(trace),
|
||||
"reward": trace.get("reward") if trace.get("rewards") else None,
|
||||
"usage": {
|
||||
"model_calls": len(activities),
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
"cost": total("cost") if branch else (trace.get("usage") or {}).get("cost"),
|
||||
},
|
||||
"spans": spans,
|
||||
}
|
||||
@@ -1794,7 +1794,7 @@ _live_folds = LiveFolds()
|
||||
|
||||
@app.get("/api/runs/{run}/live")
|
||||
def live_traces(run: str, etag: str | None = None) -> dict:
|
||||
"""The run's in-flight traces, folded from the env servers' streamed deltas
|
||||
"""The run's in-flight traces, folded from the env worker pools' streamed deltas
|
||||
(``monitors/file/traces/live/<trace_id>.jsonl``): one row per live trace with its
|
||||
phase, turns, tokens, cost, elapsed time and last message. A trace whose file is
|
||||
gone has finished and sits in the stream. ``etag`` is the fingerprint the client
|
||||
|
||||
@@ -461,7 +461,7 @@ const INFERENCE_PANELS = [
|
||||
];
|
||||
|
||||
const TRAINER_KEY_RE = /^(perf|optim|loss|entropy|system|mismatch_kl|kl_ent_ratio|is_masked|masked_|unmasked_|max_vio|routing_|ref_kl|val)[/_]?/;
|
||||
const ORCH_KEY_RE = /^(train|batch|staleness|curriculum|eval)\//;
|
||||
const ORCHESTRATOR_KEY_RE = /^(train|batch|staleness|curriculum|eval)\//;
|
||||
|
||||
function rowProducer(row, meta) {
|
||||
if (typeof row.producer === "string") return row.producer; // stamped by FileMonitor
|
||||
@@ -469,9 +469,9 @@ function rowProducer(row, meta) {
|
||||
if (meta?.type === "sft") return "trainer";
|
||||
for (const key of Object.keys(row)) {
|
||||
if (TRAINER_KEY_RE.test(key)) return "trainer";
|
||||
if (ORCH_KEY_RE.test(key)) return "orch";
|
||||
if (ORCHESTRATOR_KEY_RE.test(key)) return "orchestrator";
|
||||
}
|
||||
return Object.keys(row).some((k) => k.startsWith("progress/")) ? "orch" : "trainer";
|
||||
return Object.keys(row).some((k) => k.startsWith("progress/")) ? "orchestrator" : "trainer";
|
||||
}
|
||||
|
||||
/* store = {byKey, timeKeys, timeZero} — the primary run's is state.metrics,
|
||||
@@ -1207,7 +1207,7 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
// the timeout rate reads yellow as soon as any episode timed out
|
||||
if (all.length) {
|
||||
const errored = all.filter((i) => series.ok?.[i] === false).length;
|
||||
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
|
||||
const truncated = all.filter((i) => series.truncated?.[i] === true).length;
|
||||
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
|
||||
for (const [label, n, what, cls] of [
|
||||
["error rate", errored, "errored", rateClass],
|
||||
@@ -1512,7 +1512,7 @@ const PANEL_INFO = [
|
||||
["progress/num_tokens", "total tokens", "tokens trained on so far"],
|
||||
["perf/mfu", "MFU", "model FLOPs utilization of the trainer"],
|
||||
["perf/throughput", "throughput", "trainer tokens per second"],
|
||||
["perf/peak_memory", "peak memory", "peak GPU memory of the trainer"],
|
||||
["perf/peak_memory", "peak memory", "peak GPU memory of the trainer from all sources, max over ranks"],
|
||||
["time/step", "step time", "wall time of one training step"],
|
||||
["time/wait_for_batch", "wait for batch", "time the trainer waited for the next batch"],
|
||||
["time/wait_for_policy", "wait for policy", "time the orchestrator waited for the next policy"],
|
||||
@@ -2654,7 +2654,7 @@ const BASE_LOG_PANES = [
|
||||
{ comp: "envs", title: "all envs", match: (f) => f.component.startsWith("env:"), merged: true },
|
||||
];
|
||||
|
||||
/* the panes this run can show: the fixed components plus one pane per env server
|
||||
/* the panes this run can show: the fixed components plus one pane per env worker pool
|
||||
(`env:<name>`), so a single env's log can be read on its own; "all envs" merges
|
||||
them all and is the default, the per-env panes are opted into */
|
||||
function logPanes() {
|
||||
@@ -3309,7 +3309,7 @@ function episodeRowHtml(ep) {
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
/* a live rollout, streamed by its env server: the same columns, a pulsing dot for
|
||||
/* a live rollout, streamed by its env worker pool: the same columns, a pulsing dot for
|
||||
its number, no arrival yet, counts that grow with every turn, no reward yet */
|
||||
function liveRowHtml(r) {
|
||||
return `<tr class="live stage-${esc(r.stage)}${r.landedAt ? " landing" : ""}" ${r.trace && !r.landedAt ? `data-live="${esc(r.trace)}"` : ""} title="${esc(r.task ?? "")}${r.last ? ` — ${esc(r.last)}` : ""}">
|
||||
@@ -3356,7 +3356,7 @@ function renderEpisodeRows(reset = false) {
|
||||
episodeRowH = 0;
|
||||
}
|
||||
if (!rows.length) {
|
||||
if (!state.filter.status.done) showTraceEmpty("no live rollouts", "rollouts show here while their env servers stream them");
|
||||
if (!state.filter.status.done) showTraceEmpty("no live rollouts", "rollouts show here while their env worker pools stream them");
|
||||
else if (traceFiltered()) showTraceEmpty("no episodes", "nothing matches the current filters");
|
||||
else showTraceEmpty("no traces yet");
|
||||
return;
|
||||
@@ -3378,7 +3378,7 @@ async function initTraces() {
|
||||
|
||||
/* ------------------------------------------------------------ live traces */
|
||||
|
||||
/* the env servers stream every live rollout turn by turn; the run's file
|
||||
/* the env worker pools stream every live rollout turn by turn; the run's file
|
||||
monitor keeps one file of deltas per live trace and drops it when the episode
|
||||
lands in the stream, so this table is exactly what is running right now */
|
||||
let liveInflight = false;
|
||||
@@ -3781,7 +3781,9 @@ async function openEpisode(line, target = {}) {
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.traceId ? episode.traces.findIndex((trace) => trace.id === target.traceId) : target.trace ?? 0;
|
||||
currentTraceIdx = target.traceId
|
||||
? episode.traces.findIndex((trace) => trace.id === target.traceId)
|
||||
: target.trace ?? traceOrder(episode.traces)[0] ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
currentEvidenceView = target.evidence ?? null;
|
||||
traceView = currentEvidenceView == null ? preferredTraceView : "transcript";
|
||||
@@ -3841,12 +3843,6 @@ function currentPath(trace, branches) {
|
||||
return branches[Math.min(currentBranchIdx, branches.length - 1)] || [];
|
||||
}
|
||||
|
||||
function traceReward(trace) {
|
||||
return Object.values(trace.rewards || {}).reduce(
|
||||
(acc, r) => acc + ((r?.score ?? 0) * (r?.weight ?? 1)), 0
|
||||
);
|
||||
}
|
||||
|
||||
function messageText(message) {
|
||||
const content = message?.content;
|
||||
if (typeof content === "string") return content;
|
||||
@@ -4567,14 +4563,23 @@ function metaRow(key, value, asId = false) {
|
||||
);
|
||||
}
|
||||
|
||||
const TRUNCATING_STOPS = new Set(["max_turns", "max_input_tokens", "max_output_tokens", "max_total_tokens", "max_turn_tokens", "compaction_failed"]);
|
||||
|
||||
/* mirrors verifiers Trace.is_truncated (not serialized): framework limits or a
|
||||
length-finished final response */
|
||||
function traceTruncated(trace) {
|
||||
if (TRUNCATING_STOPS.has(trace.stop_condition)) return true;
|
||||
const last = [...(trace.calls || [])].reverse().find((c) => !c.error);
|
||||
return !!(last && last.finish_reason === "length");
|
||||
/* mirrors verifiers Branch token counts: each call on the path adds its prompt beyond
|
||||
the previous call's final sequence (clamped at zero) plus its output */
|
||||
function branchTokens(trace, path) {
|
||||
const onPath = new Set(path);
|
||||
let input = null;
|
||||
let output = null;
|
||||
let previous = 0;
|
||||
for (const call of trace.calls || []) {
|
||||
if (!onPath.has(call.node) || !call.usage) continue;
|
||||
const usage = normalizedCallUsage(call.usage);
|
||||
if (usage.input == null) continue;
|
||||
const prompt = usage.input + (usage.cached ?? 0);
|
||||
input = (input ?? 0) + Math.max(0, prompt - previous);
|
||||
output = (output ?? 0) + (usage.output ?? 0);
|
||||
previous = prompt + (usage.output ?? 0);
|
||||
}
|
||||
return { input, output, total: input == null ? null : input + output };
|
||||
}
|
||||
|
||||
function renderMeta(ep, trace, branches) {
|
||||
@@ -4583,7 +4588,7 @@ function renderMeta(ep, trace, branches) {
|
||||
`<div class="meta-row"><span class="k">${label}</span>` +
|
||||
`<span class="tm-reward-big${value != null && value < 0 ? " neg" : ""}${value == null ? " na" : ""}" style="margin-left:auto">` +
|
||||
`${value != null ? fmtReward(value) : "n/a"}</span></div>`;
|
||||
const rewardValue = trace && Object.keys(trace.rewards || {}).length ? traceReward(trace) : null;
|
||||
const rewardValue = trace && Object.keys(trace.rewards || {}).length ? trace.reward ?? null : null;
|
||||
parts.push(headline("reward", rewardValue));
|
||||
parts.push(headline("advantage", trace?.info?.advantage ?? null));
|
||||
|
||||
@@ -4602,62 +4607,58 @@ function renderMeta(ep, trace, branches) {
|
||||
}
|
||||
|
||||
if (trace) {
|
||||
const nodes = currentPath(trace, branches).map((i) => trace.nodes[i]);
|
||||
parts.push(`<div class="meta-sec">activity</div>`);
|
||||
parts.push(metaRow("messages", nodes.filter((n) => n.message).length));
|
||||
parts.push(metaRow("turns", nodes.filter((n) => n.sampled).length));
|
||||
parts.push(metaRow("branches", branches.length));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
const tokenRows = (input, output, total) => {
|
||||
if (input != null) parts.push(metaRow("input tokens", fmtCompact(input)));
|
||||
if (output != null) parts.push(metaRow("output tokens", fmtCompact(output)));
|
||||
if (total != null) parts.push(metaRow("total tokens", fmtCompact(total)));
|
||||
};
|
||||
const activityRows = (nodes, turns) => {
|
||||
parts.push(metaRow("messages", nodes.filter((n) => n.message).length));
|
||||
parts.push(metaRow("turns", turns));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
};
|
||||
|
||||
const traces = ep.traces || [];
|
||||
if (traces.length > 1) {
|
||||
parts.push(`<div class="meta-sec">episode</div>`);
|
||||
parts.push(metaRow("traces", traces.length));
|
||||
tokenRows(ep.num_input_tokens, ep.num_output_tokens, ep.num_total_tokens);
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">trace</div>`);
|
||||
activityRows(trace.nodes || [], trace.num_turns);
|
||||
parts.push(metaRow("branches", trace.num_branches));
|
||||
const judgeRecords = Array.isArray(trace.info?.judge_calls) ? trace.info.judge_calls : [];
|
||||
if (judgeRecords.length) parts.push(metaRow("judge calls", judgeRecords.length));
|
||||
tokenRows(trace.num_input_tokens, trace.num_output_tokens, trace.num_total_tokens);
|
||||
const cost = trace.usage?.cost;
|
||||
if (cost != null) parts.push(metaRow("cost", fmtCost(cost)));
|
||||
|
||||
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
|
||||
const addUsage = (field, value) => {
|
||||
if (value != null) usage[field] = (usage[field] ?? 0) + value;
|
||||
};
|
||||
for (const call of trace.calls || []) {
|
||||
const current = normalizedCallUsage(call.usage);
|
||||
addUsage("input", current.input);
|
||||
addUsage("cached", current.cached);
|
||||
addUsage("output", current.output);
|
||||
addUsage("reasoning", current.reasoning);
|
||||
addUsage("cost", current.cost);
|
||||
if (current.input != null) {
|
||||
const context = current.input + (current.cached ?? 0);
|
||||
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
|
||||
}
|
||||
}
|
||||
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
|
||||
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
|
||||
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
|
||||
if (hasUsage) {
|
||||
parts.push(`<div class="meta-sec">usage</div>`);
|
||||
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
|
||||
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
|
||||
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
|
||||
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
|
||||
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
|
||||
if (branches.length > 1 && currentBranchIdx !== -1) {
|
||||
const branchIdx = Math.min(currentBranchIdx, branches.length - 1);
|
||||
const path = branches[branchIdx] || [];
|
||||
const tokens = branchTokens(trace, path);
|
||||
parts.push(`<div class="meta-sec">branch ${branchIdx}</div>`);
|
||||
const nodes = path.map((i) => trace.nodes[i]);
|
||||
activityRows(nodes, nodes.filter((n) => n.sampled).length);
|
||||
tokenRows(tokens.input, tokens.output, tokens.total);
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">state</div>`);
|
||||
parts.push(metaRow("stop_condition", trace.stop_condition));
|
||||
parts.push(metaRow("is_completed", trace.is_completed));
|
||||
parts.push(metaRow("is_truncated", traceTruncated(trace)));
|
||||
parts.push(metaRow("is_truncated", !!trace.is_truncated));
|
||||
parts.push(metaRow("is_timeout", !!trace.is_timeout));
|
||||
parts.push(metaRow("ok", trace.ok));
|
||||
|
||||
const durations = [];
|
||||
(function walkTiming(obj, prefix) {
|
||||
if (!obj || typeof obj !== "object") return;
|
||||
if (typeof obj.duration === "number") durations.push([prefix, obj.duration]);
|
||||
else if (typeof obj.start === "number" && obj.start > 0) {
|
||||
// an open span (no end yet) of a live trace shows its elapsed time
|
||||
if (obj.end) durations.push([prefix, obj.end - obj.start]);
|
||||
else if (currentLive) durations.push([prefix, Date.now() / 1000 - obj.start]);
|
||||
}
|
||||
const started = !("start" in obj) || obj.start > 0;
|
||||
// an open span (no end yet) of a live trace shows its elapsed time
|
||||
if (started && "start" in obj && !obj.end) {
|
||||
if (currentLive) durations.push([prefix, Date.now() / 1000 - obj.start]);
|
||||
} else if (started && typeof obj.duration === "number") durations.push([prefix, obj.duration]);
|
||||
for (const [k, v] of Object.entries(obj)) if (typeof v === "object") walkTiming(v, prefix ? `${prefix}/${k}` : k);
|
||||
})(trace.timing, "");
|
||||
if (durations.length) {
|
||||
@@ -4696,23 +4697,27 @@ function appendTimelineUsage(rows, usage, aggregate = false) {
|
||||
if (!usage) return;
|
||||
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
|
||||
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
|
||||
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
|
||||
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
|
||||
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
|
||||
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
|
||||
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
|
||||
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
}
|
||||
|
||||
// One call's input is its whole prompt, cached part included.
|
||||
function callTimelineUsage(span) {
|
||||
const input = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
return {
|
||||
input_tokens: input,
|
||||
output_tokens: span.output_tokens,
|
||||
total_tokens: input == null || span.output_tokens == null ? null : input + span.output_tokens,
|
||||
cost: span.cost,
|
||||
};
|
||||
}
|
||||
|
||||
function aggregateTimelineUsage(items) {
|
||||
const summedFields = [
|
||||
"model_calls",
|
||||
"input_tokens",
|
||||
"cached_tokens",
|
||||
"total_input_tokens",
|
||||
"output_tokens",
|
||||
"reasoning_tokens",
|
||||
"total_tokens",
|
||||
"cost",
|
||||
];
|
||||
@@ -4744,11 +4749,9 @@ function semanticCumulativeUsageRows(usage, compact = true) {
|
||||
const tokens = (value) => compact ? fmtCompact(value) : Math.round(value).toLocaleString();
|
||||
const rows = [];
|
||||
if (usage?.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage?.total_tokens != null) rows.push(["cumulative processed", tokens(usage.total_tokens)]);
|
||||
if (usage?.input_tokens != null) rows.push(["uncached input", tokens(usage.input_tokens)]);
|
||||
if (usage?.cached_tokens != null) rows.push(["cached input", tokens(usage.cached_tokens)]);
|
||||
if (usage?.input_tokens != null) rows.push(["input", tokens(usage.input_tokens)]);
|
||||
if (usage?.output_tokens != null) rows.push(["output", tokens(usage.output_tokens)]);
|
||||
if (usage?.reasoning_tokens != null) rows.push(["reasoning", tokens(usage.reasoning_tokens)]);
|
||||
if (usage?.total_tokens != null) rows.push(["total", tokens(usage.total_tokens)]);
|
||||
if (usage?.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
return rows;
|
||||
}
|
||||
@@ -4768,17 +4771,7 @@ function timelineSpanHtml(lane, span, start, total) {
|
||||
];
|
||||
if (span.track === "activity") {
|
||||
if (span.shared) rows.push(["branch role", "shared prefix"]);
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
appendTimelineUsage(rows, callTimelineUsage(span));
|
||||
} else {
|
||||
appendTimelineUsage(rows, lane.usage, true);
|
||||
}
|
||||
@@ -4885,7 +4878,6 @@ function semanticNodeKey(traceIndex, nodeIndex) {
|
||||
|
||||
function semanticNodeTip(event) {
|
||||
const span = event.span;
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
const rows = [
|
||||
["agent", event.agent.label],
|
||||
["context", String(event.contextIndex)],
|
||||
@@ -4899,16 +4891,7 @@ function semanticNodeTip(event) {
|
||||
["training branch", event.compactionAttempt.accepted ? "included" : "excluded"]
|
||||
);
|
||||
}
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
appendTimelineUsage(rows, callTimelineUsage(span));
|
||||
return timelineTipAttr({
|
||||
kind: event.compactionAttempt ? "compaction attempt" : "model call",
|
||||
title: event.compactionAttempt
|
||||
@@ -5538,7 +5521,7 @@ function semanticInspectorRows(rows) {
|
||||
function openSemanticCallInspector(event) {
|
||||
semanticSelection = { ...event, kind: "call" };
|
||||
const span = event.span;
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
const usage = callTimelineUsage(span);
|
||||
const rows = [
|
||||
["agent", event.agent.label],
|
||||
["context", event.contextIndex],
|
||||
@@ -5546,8 +5529,9 @@ function openSemanticCallInspector(event) {
|
||||
["call", event.callIndex],
|
||||
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
|
||||
["duration", span.started_at == null || span.ended_at == null ? "—" : fmtDuration(span.ended_at - span.started_at)],
|
||||
["input", totalInput == null ? "n/a" : fmtCompact(totalInput)],
|
||||
["output", span.output_tokens == null ? "n/a" : fmtCompact(span.output_tokens)],
|
||||
["input", usage.input_tokens == null ? "n/a" : fmtCompact(usage.input_tokens)],
|
||||
["output", usage.output_tokens == null ? "n/a" : fmtCompact(usage.output_tokens)],
|
||||
["total", usage.total_tokens == null ? "n/a" : fmtCompact(usage.total_tokens)],
|
||||
["cost", span.cost == null ? "n/a" : fmtCost(span.cost)],
|
||||
];
|
||||
if (event.inferredContinuation) rows.splice(2, 0, ["lineage", "recovered from physical tool flow"]);
|
||||
@@ -5825,11 +5809,17 @@ async function setTraceView(view, { persist = true } = {}) {
|
||||
savePrefs();
|
||||
}
|
||||
|
||||
/* trace indices in the order their agents started */
|
||||
function traceOrder(traces) {
|
||||
const start = (trace) => trace.timing?.start ?? Infinity;
|
||||
return traces.map((_, i) => i).sort((a, b) => start(traces[a]) - start(traces[b]));
|
||||
}
|
||||
|
||||
function renderEpisode() {
|
||||
const ep = currentEpisode;
|
||||
if (!ep) return;
|
||||
const traces = ep.traces || [];
|
||||
if (currentTraceIdx >= traces.length) currentTraceIdx = 0;
|
||||
if (currentTraceIdx >= traces.length) currentTraceIdx = traceOrder(traces)[0] ?? 0;
|
||||
const trace = traces[currentTraceIdx];
|
||||
updateHash();
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
@@ -5843,8 +5833,9 @@ function renderEpisode() {
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
? traceOrder(traces)
|
||||
.map((i) => [traces[i], i])
|
||||
.map(([trace, i]) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
|
||||
@@ -273,7 +273,7 @@
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row flt-status-row"><span class="t-label">status</span>
|
||||
<div class="seg toggle-seg flt-status">
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env worker pools">live</button>
|
||||
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -26,12 +26,14 @@ import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from prime_rl.utils.links import PRIME_EVAL_LINKS, PRIME_LINKS, WANDB_LINKS
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import CACHE_DIR
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
|
||||
STATE_DIR = CACHE_DIR / "dashboard"
|
||||
DAEMON_FILE = STATE_DIR / "daemon.json"
|
||||
DIRS_FILE = STATE_DIR / "dirs.json"
|
||||
@@ -118,7 +120,7 @@ def ensure_dashboard(output_dir: Path, logger) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
LINK_NAMES = {PRIME_LINKS: "Prime", PRIME_EVAL_LINKS: "Prime", WANDB_LINKS: "W&B"}
|
||||
LINK_NAMES = {"prime": "Prime", "wandb": "W&B"}
|
||||
|
||||
|
||||
def log_run_links(dashboard_url: str | None, links: Callable[[], dict[str, dict[str, str]]] | None = None) -> None:
|
||||
@@ -145,21 +147,19 @@ def log_run_links(dashboard_url: str | None, links: Callable[[], dict[str, dict[
|
||||
|
||||
|
||||
def run_links(
|
||||
run_dir: Path, attempt_log_dir: Path, monitors: dict[str, object | None], stop: Callable[[], bool]
|
||||
run_dir: Path, attempt_log_dir: Path, monitors: "MonitorsConfig", stop: Callable[[], bool]
|
||||
) -> Callable[[], dict[str, dict[str, str]]] | None:
|
||||
"""The ``links`` argument of ``log_run_links``: waits for every configured monitor
|
||||
in ``monitors`` (links-record key -> its config, None when off) that can open a
|
||||
page. A monitor turned off by its mode variable (``$PRIME_RUNS_MODE``, an offline
|
||||
"""The ``links`` argument of ``log_run_links``: waits for every monitor in
|
||||
``monitors`` that is on and can open a page, keyed by its config field. A monitor turned off by its mode variable (``$PRIME_RUNS_MODE``, an offline
|
||||
or disabled ``$WANDB_MODE``) opens none; one without credentials fails its
|
||||
component, which ends the wait through ``stop``."""
|
||||
from prime_rl.utils.links import wait_for_links
|
||||
|
||||
def opens_pages(key: str) -> bool:
|
||||
if key == WANDB_LINKS:
|
||||
return os.environ.get("WANDB_MODE") not in ("offline", "disabled")
|
||||
return os.environ.get("PRIME_RUNS_MODE", "online") == "online"
|
||||
|
||||
waited = [key for key, config in monitors.items() if config is not None and opens_pages(key)]
|
||||
opens_pages = {
|
||||
"prime": monitors.prime is not None and (os.environ.get("PRIME_RUNS_MODE") or "online") == "online",
|
||||
"wandb": monitors.wandb is not None and os.environ.get("WANDB_MODE") not in ("offline", "disabled"),
|
||||
}
|
||||
waited = [key for key, opens in opens_pages.items() if opens]
|
||||
if not waited:
|
||||
return None
|
||||
return functools.partial(wait_for_links, run_dir, attempt_log_dir, waited, stop)
|
||||
|
||||
+27
-21
@@ -5,25 +5,27 @@ import uuid
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
from verifiers.v1.serve import env_config_data, serve_env
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
from prime_rl.configs.env_worker_pool import EnvWorkerPoolConfig
|
||||
from prime_rl.env import run_env_worker_pool, set_episode_hook
|
||||
from prime_rl.orchestrator.utils import setup_env_worker_pool_logging
|
||||
from prime_rl.transports.payload import PayloadHook
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list[str]) -> None:
|
||||
setup_env_server_logging(log_level, json_logging)
|
||||
def setup_worker(
|
||||
log_level: str | None, json_logging: bool, sandbox_labels: list[str], bind_address: str | None
|
||||
) -> None:
|
||||
setup_env_worker_pool_logging(log_level, json_logging)
|
||||
set_base_sandbox_labels(sandbox_labels)
|
||||
# Episode streams never carry training arrays; the hook keeps them for the trainer.
|
||||
set_episode_hook(PayloadHook(bind_address))
|
||||
|
||||
|
||||
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
|
||||
"""Write the bound address once serve_env reports it (it blocks in the server loop
|
||||
afterwards). Atomic, so a waiting client never reads a partial line."""
|
||||
"""Publish the broker's bound address atomically for waiting clients."""
|
||||
address = addresses.get()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".address.tmp")
|
||||
@@ -32,33 +34,37 @@ def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
def run_pool(config: EnvWorkerPoolConfig):
|
||||
run_name = os.environ.get("PRL_RUN_NAME")
|
||||
sandbox_labels = [run_name] if run_name else []
|
||||
addresses: queue.SimpleQueue | None = None
|
||||
if config.address_file is not None:
|
||||
addresses = queue.SimpleQueue()
|
||||
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
|
||||
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
|
||||
# setup in this process and in every spawned worker.
|
||||
serve_env(
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
# Apply logging, sandbox labels, and the payload hook in the broker and every worker.
|
||||
run_env_worker_pool(
|
||||
pool=config.serve.pool,
|
||||
address=config.serve.address or "tcp://127.0.0.1:0",
|
||||
address_queue=addresses,
|
||||
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
|
||||
config_data=env_config_data(config.env),
|
||||
worker_setup=partial(
|
||||
setup_worker,
|
||||
config.log.level,
|
||||
config.log.json_logging,
|
||||
sandbox_labels,
|
||||
config.serve.address,
|
||||
),
|
||||
config_data=config.env.model_dump(mode="json"),
|
||||
max_concurrent=config.serve.max_concurrent,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for the env server. Run using `uv run env-server`"""
|
||||
set_proc_title("EnvServer")
|
||||
"""Main entry-point for the env worker pool. Run using `uv run env-worker-pool`"""
|
||||
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
|
||||
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
|
||||
# a standalone server is a run of its own.
|
||||
# the Python entrypoints and the SLURM templates alike, hands env worker pools $PRL_RUN_ID;
|
||||
# a standalone pool is a run of its own.
|
||||
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
|
||||
run_server(cli(EnvServerConfig))
|
||||
run_pool(cli(EnvWorkerPoolConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -121,18 +121,17 @@ def main():
|
||||
sys.argv = [sys.argv[0], *argv]
|
||||
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links
|
||||
from prime_rl.utils.links import PRIME_EVAL_LINKS, WANDB_LINKS
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
prepare_attempt_dirs,
|
||||
prepare_run,
|
||||
write_env_server_config,
|
||||
write_env_worker_pool_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
|
||||
# The run identity is stamped on every episode and inherited by the env servers.
|
||||
# The run identity is stamped on every episode and inherited by the env worker pools.
|
||||
prepare_run(config)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
@@ -144,16 +143,16 @@ def main():
|
||||
write_launch_artifacts(config_dir, "eval")
|
||||
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
|
||||
# One env server per source without an explicit `serve.address`, like the rl launcher's:
|
||||
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
|
||||
# One env worker pool per source without an explicit `serve.address`, like the rl launcher's:
|
||||
# `env-worker-pool @ <path>` binds an OS-assigned port and publishes it to the source's
|
||||
# address file, where the eval picks it up.
|
||||
env_servers = [source for source in config.source if source.serve.address is None]
|
||||
env_names = [source.resolved_name for source in env_servers]
|
||||
if env_servers:
|
||||
env_worker_pools = [source for source in config.source if source.serve.address is None]
|
||||
env_names = [source.resolved_name for source in env_worker_pools]
|
||||
if env_worker_pools:
|
||||
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
|
||||
for source in env_servers:
|
||||
for source in env_worker_pools:
|
||||
components.append(
|
||||
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
|
||||
(f" {source.resolved_name}", write_env_worker_pool_config(config_dir, "eval", source, config.log))
|
||||
)
|
||||
if config.dry_run:
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
|
||||
@@ -164,15 +163,15 @@ def main():
|
||||
from prime_rl.eval.eval import run_eval
|
||||
|
||||
processes: list[Popen] = []
|
||||
for source in env_servers:
|
||||
for source in env_worker_pools:
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file_handle:
|
||||
logger.info(f"Starting {name} env worker pool")
|
||||
env_worker_pool_log = log_dir / "envs" / "eval" / f"{name}.log"
|
||||
env_worker_pool_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_worker_pool_log, "w") as log_file_handle:
|
||||
processes.append(
|
||||
Popen(
|
||||
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
|
||||
["env-worker-pool", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
|
||||
stdout=log_file_handle,
|
||||
stderr=log_file_handle,
|
||||
@@ -195,8 +194,7 @@ def main():
|
||||
# Each source's Prime evaluation opens once the eval counts its tasks, so the
|
||||
# banner waits for the links next to the running eval.
|
||||
eval_done = threading.Event()
|
||||
monitors = {PRIME_EVAL_LINKS: config.monitors.prime, WANDB_LINKS: config.monitors.wandb}
|
||||
links = run_links(config.run_dir, log_dir, monitors, eval_done.is_set)
|
||||
links = run_links(config.run_dir, log_dir, config.monitors, eval_done.is_set)
|
||||
banner = threading.Thread(target=log_run_links, args=(dashboard_url, links), daemon=True)
|
||||
banner.start()
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.configs.supervised import SupervisedTrainerConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links
|
||||
from prime_rl.utils.config import dump_resolved_config, find_package_resource
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
launcher_attempt_env,
|
||||
prepare_attempt_dirs,
|
||||
prepare_run,
|
||||
resolve_latest_ckpt_step,
|
||||
write_env_worker_pool_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
TRAINER_CONFIG = "trainer.json"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
ONLINE_EVAL_CONFIG = "eval.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def eval_env_worker_pools(config: SupervisedTrainerConfig) -> list[OnlineEvalSourceConfig]:
|
||||
"""Every launcher-managed eval source. A source with ``serve.address`` set is
|
||||
externally managed — the launcher neither writes its config nor spawns a server for it."""
|
||||
if config.eval is None:
|
||||
return []
|
||||
return [source for source in config.eval.source if source.serve.address is None]
|
||||
|
||||
|
||||
def get_ckpt_base(config: SupervisedTrainerConfig) -> Path:
|
||||
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
|
||||
|
||||
|
||||
def resolve_resume_step(config: SupervisedTrainerConfig) -> int | None:
|
||||
if config.resume is None:
|
||||
return None
|
||||
if config.resume.dir is not None:
|
||||
return config.resume.dir_step
|
||||
if config.resume.step is not None:
|
||||
return config.resume.step
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_online_eval_config(config: SupervisedTrainerConfig) -> SFTOnlineEvalConfig:
|
||||
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
|
||||
fields filled from the SFT config. The launcher spawns the env worker pools itself; the
|
||||
online-eval process finds each one through the address it publishes in the shared
|
||||
config attempt."""
|
||||
assert config.eval is not None
|
||||
eval_config = config.eval.model_copy(deep=True)
|
||||
run_fields = dict(
|
||||
model=config.model.name,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
# Same run dir as the trainer: the dashboard reads the eval's
|
||||
# file-monitor artifacts from the run directory, so a separate
|
||||
# output dir would hide them. The train-vs-eval record collision
|
||||
# is resolved by record merging in prime_rl.monitors.prime, not
|
||||
# by directory separation.
|
||||
output_dir=config.run_dir,
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=config.monitors,
|
||||
)
|
||||
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
|
||||
|
||||
|
||||
def config_components(
|
||||
config: SupervisedTrainerConfig, config_dir: Path, entrypoint: str
|
||||
) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved configs a launch leaves in ``config_dir``: the entrypoint's config and, with
|
||||
online evals, the inference, online-eval and env-worker-pool configs."""
|
||||
components: list[tuple[str, Path | str]] = [(entrypoint, config_dir / f"{entrypoint}.json")]
|
||||
if config.deployment.type == "multi_node":
|
||||
components.append(("Trainer", config_dir / TRAINER_CONFIG))
|
||||
if config.eval is not None:
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
|
||||
if eval_env_worker_pools(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_config(config: SupervisedTrainerConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, "w") as f:
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def write_eval_subconfigs(config: SupervisedTrainerConfig, config_dir: Path, strip_router: bool = False) -> None:
|
||||
"""Write the inference, online-eval, and env-worker-pool configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
|
||||
if strip_router:
|
||||
# Per-rank processes run bare engines; the sbatch starts the single global router.
|
||||
inference_dict["router"] = None
|
||||
with open(config_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
|
||||
|
||||
# One EnvWorkerPoolConfig per launcher-managed eval source: `env-worker-pool @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# online-eval process picks it up.
|
||||
for source in eval_env_worker_pools(config):
|
||||
write_env_worker_pool_config(config_dir, "eval", source, config.log)
|
||||
|
||||
|
||||
def write_slurm_script(
|
||||
config: SupervisedTrainerConfig,
|
||||
config_path: Path,
|
||||
run_config_path: Path,
|
||||
log_dir: Path,
|
||||
script_path: Path,
|
||||
prl_run_id: str,
|
||||
wandb_shared: bool,
|
||||
entrypoint: str,
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk. The trainer runs ``config_path``; a multi-node
|
||||
job's run owner registers the Prime run from ``run_config_path``."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
}
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
entrypoint=entrypoint,
|
||||
)
|
||||
else:
|
||||
online_eval = config.eval is not None
|
||||
eval_vars = {}
|
||||
if online_eval:
|
||||
assert config.inference is not None
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
eval_vars = {
|
||||
"router": config.inference.router,
|
||||
"router_port": config.inference.server.port,
|
||||
"backend_port": config.inference.backend_port,
|
||||
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"online_eval_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source in eval_env_worker_pools(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
run_config_path=run_config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
wandb_shared=wandb_shared,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
entrypoint=entrypoint,
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def launch_slurm(config: SupervisedTrainerConfig, entrypoint: str):
|
||||
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
logger.info(f"Starting {entrypoint} run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, entrypoint)
|
||||
config_path = config_dir / f"{entrypoint}.json"
|
||||
if config.deployment.type == "multi_node":
|
||||
# The job's run owner registers the Prime run with the whole config; nothing runs it.
|
||||
write_config(config, config_path, exclude={"dry_run", "clean"})
|
||||
trainer_config_path = config_dir / TRAINER_CONFIG
|
||||
exclude = {"deployment", "slurm", "dry_run", "clean"}
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, trainer_config_path, exclude=exclude)
|
||||
else:
|
||||
write_config(config, config_path, exclude={"slurm", "dry_run", "clean"})
|
||||
trainer_config_path = config_path
|
||||
|
||||
# Trainer and online-eval processes log to a single shared W&B run.
|
||||
wandb_shared = online_eval and config.monitors.wandb is not None
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(
|
||||
f"Configs:\n{format_config_message(config_dir, entrypoint, config_components(config, config_dir, entrypoint))}"
|
||||
)
|
||||
script_path = launcher_dir / f"{entrypoint}.sbatch"
|
||||
write_slurm_script(
|
||||
config,
|
||||
trainer_config_path,
|
||||
config_path,
|
||||
log_dir,
|
||||
script_path,
|
||||
os.environ["PRL_RUN_ID"],
|
||||
wandb_shared,
|
||||
entrypoint,
|
||||
)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
eval=online_eval,
|
||||
inference=online_eval,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_worker_pools(config)]} if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_run_links(dashboard_url)
|
||||
|
||||
|
||||
def launch_local(config: SupervisedTrainerConfig, entrypoint: str):
|
||||
"""Run SFT training locally with process monitoring and cleanup."""
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
logger.info(f"Starting {entrypoint} run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, entrypoint)
|
||||
config_path = config_dir / f"{entrypoint}.json"
|
||||
write_config(config, config_path)
|
||||
if config.eval is not None:
|
||||
write_eval_subconfigs(config, config_dir)
|
||||
logger.info(
|
||||
f"Configs:\n{format_config_message(config_dir, entrypoint, config_components(config, config_dir, entrypoint))}"
|
||||
)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start the run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
eval=config.eval is not None,
|
||||
inference=config.inference is not None,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_worker_pools(config)]},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Partition GPUs (inference first, then the trainer) only when the launcher must split
|
||||
# them between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
|
||||
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
|
||||
)
|
||||
|
||||
# Trainer and online-eval 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 online-eval 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": "online-eval",
|
||||
"WANDB_PROGRAM": f"uv run {entrypoint}",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
with ProcessGroup() as processes:
|
||||
# Optionally, start the inference server for online evals
|
||||
if config.inference is not None:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
|
||||
# Start one env worker pool per eval source. The online-eval process waits for each
|
||||
# server's published address and polls until it answers.
|
||||
for source in eval_env_worker_pools(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} env worker pool")
|
||||
processes.start(
|
||||
f"env/eval/{name}",
|
||||
["env-worker-pool", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting online evals")
|
||||
processes.start(
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "online-eval",
|
||||
},
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting {entrypoint} trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**wandb_shared_env,
|
||||
**launcher_attempt_env(config_dir, log_dir),
|
||||
}
|
||||
if config.eval is not None:
|
||||
trainer_env["LOGURU_FORCE_COLORS"] = "1"
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
f"prime_rl.trainer.{entrypoint}.train",
|
||||
config_path,
|
||||
config.deployment.num_train_gpus,
|
||||
log_dir,
|
||||
config.log.ranks_filter,
|
||||
),
|
||||
env=trainer_env,
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
links = run_links(config.run_dir, log_dir, config.monitors, lambda: bool(processes.error_queue))
|
||||
log_run_links(dashboard_url, links)
|
||||
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
|
||||
logger.success("Training finished!")
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SupervisedTrainerConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the online-eval process would replay stale broadcasts (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 broadcasts; the online-eval process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
|
||||
def launch(config: SupervisedTrainerConfig, entrypoint: str):
|
||||
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
|
||||
# [deployment] stripped, so the model validator cannot enforce this.
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
|
||||
raise ValueError(
|
||||
"NCCL weight broadcast requires launcher-managed inference. "
|
||||
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
prepare_run(config, config.ckpt.output_dir if config.ckpt else None)
|
||||
|
||||
if config.eval is not None and not config.dry_run:
|
||||
clean_stale_eval_artifacts(config)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.trainer.sft.data import pre_download_data
|
||||
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init or config.init_from_scratch)
|
||||
pre_download_data(config.data, config.env_vars)
|
||||
if config.val is not None:
|
||||
pre_download_data(config.val.data, config.env_vars)
|
||||
|
||||
from prime_rl.monitors.prime import launch_run
|
||||
|
||||
# On SLURM the job registers the run: the in-job entrypoint (single node) or the
|
||||
# batch script's run owner (multi node), so that a live process owns its status.
|
||||
if config.slurm is not None:
|
||||
launch_slurm(config, entrypoint)
|
||||
return
|
||||
with launch_run(config, None if config.dry_run else config.monitors.prime):
|
||||
launch_local(config, entrypoint)
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.configs.pretrain import PretrainConfig
|
||||
from prime_rl.entrypoints.launcher import launch
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Pretrain")
|
||||
launch(cli(PretrainConfig), "pretrain")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+129
-41
@@ -1,8 +1,11 @@
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
@@ -12,7 +15,6 @@ from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links
|
||||
from prime_rl.entrypoints.inference import mooncake_offloads, vllm_overrides_fragment, write_pd_configs
|
||||
from prime_rl.utils.config import cli, dump_resolved_config, dump_rl_components
|
||||
from prime_rl.utils.links import PRIME_LINKS, WANDB_LINKS
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
@@ -25,7 +27,7 @@ from prime_rl.utils.pathing import (
|
||||
prepare_attempt_dirs,
|
||||
prepare_run,
|
||||
resolve_latest_ckpt_step,
|
||||
write_env_server_config,
|
||||
write_env_worker_pool_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
@@ -37,6 +39,7 @@ from prime_rl.utils.process import (
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
RL_CONFIG = "rl.json"
|
||||
RL_SBATCH = "rl.sbatch"
|
||||
@@ -47,22 +50,25 @@ INFERENCE_CONFIG = "inference.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
MODELEXPRESS_BIN_DIR = Path(__file__).resolve().parents[3] / "third_party" / "modelexpress" / "bin"
|
||||
MODELEXPRESS_READY_TIMEOUT_S = 120
|
||||
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
|
||||
|
||||
def env_worker_pools(config: RLConfig) -> list[tuple[str, EnvConfig]]:
|
||||
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
|
||||
runs one env server per source; each binds an OS-assigned port and publishes it to
|
||||
runs one env worker pool per source; each binds an OS-assigned port and publishes it to
|
||||
its address file, where the orchestrator picks it up. A source with ``serve.address``
|
||||
set is externally managed — its server runs elsewhere and only the orchestrator
|
||||
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
|
||||
set is externally managed — its pool runs elsewhere and only the orchestrator
|
||||
connects to it — so the launcher neither writes its TOML nor starts a pool for it."""
|
||||
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
|
||||
|
||||
|
||||
def env_server_names(config: RLConfig, split: str) -> list[str]:
|
||||
"""Names of the launcher-managed env servers for one split."""
|
||||
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
|
||||
def env_worker_pool_names(config: RLConfig, split: str) -> list[str]:
|
||||
"""Names of the launcher-managed env worker pools for one split."""
|
||||
return [source.resolved_name for source_split, source in env_worker_pools(config) if source_split == split]
|
||||
|
||||
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | dict[str, Any] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(output_dir / RL_CONFIG, "w") as f:
|
||||
@@ -77,11 +83,80 @@ def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str,
|
||||
]
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
if env_servers(config):
|
||||
if env_worker_pools(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def wait_for_port(host: str, port: int, processes: ProcessGroup, name: str, timeout: float) -> None:
|
||||
"""Block until ``host:port`` accepts TCP connections; fail if ``name`` exits first."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=1):
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
if processes.stop_events[name].is_set():
|
||||
raise RuntimeError(f"{name} exited before listening on {host}:{port}")
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(f"{name} did not listen on {host}:{port} within {timeout}s")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def start_modelexpress(processes: ProcessGroup, port: int, log_dir: Path) -> None:
|
||||
"""Start a run-scoped ModelExpress server backed by its own Redis."""
|
||||
server, redis = MODELEXPRESS_BIN_DIR / "modelexpress-server", MODELEXPRESS_BIN_DIR / "redis-server"
|
||||
if not (server.is_file() and redis.is_file()):
|
||||
raise FileNotFoundError(
|
||||
f"ModelExpress server binaries are missing in {MODELEXPRESS_BIN_DIR}; run scripts/install_modelexpress.sh"
|
||||
)
|
||||
state_dir = log_dir / "modelexpress"
|
||||
(state_dir / "cache").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
redis_port = get_free_port()
|
||||
processes.start(
|
||||
"redis",
|
||||
[
|
||||
str(redis),
|
||||
"--port",
|
||||
str(redis_port),
|
||||
"--bind",
|
||||
"127.0.0.1",
|
||||
"--save",
|
||||
"",
|
||||
"--appendonly",
|
||||
"no",
|
||||
"--dir",
|
||||
str(state_dir),
|
||||
],
|
||||
env=dict(os.environ),
|
||||
log_path=state_dir / "redis.log",
|
||||
)
|
||||
wait_for_port("127.0.0.1", redis_port, processes, "redis", MODELEXPRESS_READY_TIMEOUT_S)
|
||||
|
||||
processes.start(
|
||||
"modelexpress",
|
||||
[
|
||||
str(server),
|
||||
"--port",
|
||||
str(port),
|
||||
"--metrics-port",
|
||||
"0",
|
||||
"--cache-directory",
|
||||
str(state_dir / "cache"),
|
||||
],
|
||||
env={
|
||||
**os.environ,
|
||||
"MX_METADATA_BACKEND": "redis",
|
||||
"REDIS_URL": f"redis://127.0.0.1:{redis_port}",
|
||||
"MX_HEARTBEAT_TIMEOUT_SECS": "31536000",
|
||||
},
|
||||
log_path=state_dir / "server.log",
|
||||
)
|
||||
wait_for_port("127.0.0.1", port, processes, "modelexpress", MODELEXPRESS_READY_TIMEOUT_S)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as JSON files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -92,11 +167,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
if config.inference is not None:
|
||||
write_pd_configs(config.inference, output_dir)
|
||||
|
||||
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
|
||||
# One EnvWorkerPoolConfig per launcher-managed source: `env-worker-pool @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# orchestrator picks it up.
|
||||
for split, source in env_servers(config):
|
||||
write_env_server_config(output_dir, split, source, config.orchestrator.log)
|
||||
for split, source in env_worker_pools(config):
|
||||
write_env_worker_pool_config(output_dir, split, source, config.orchestrator.log)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -122,7 +197,7 @@ def rl_local(config: RLConfig):
|
||||
trainer=True,
|
||||
orchestrator=True,
|
||||
inference=config.inference is not None,
|
||||
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
|
||||
env_names={split: env_worker_pool_names(config, split) for split in ("train", "eval")},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
@@ -157,6 +232,10 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
|
||||
with ProcessGroup() as processes:
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "modelexpress":
|
||||
logger.info(f"Starting ModelExpress server on port {config.weight_broadcast.port}")
|
||||
start_modelexpress(processes, config.weight_broadcast.port, log_dir)
|
||||
|
||||
if config.inference:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
processes.start(
|
||||
@@ -194,15 +273,15 @@ def rl_local(config: RLConfig):
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start one env server per source. The orchestrator waits for each server's
|
||||
# published address and polls until it answers, so the servers and the
|
||||
# Start one env worker pool per source. The orchestrator waits for each broker's
|
||||
# published address and polls until it answers, so the pools and the
|
||||
# orchestrator start in parallel.
|
||||
for split, source in env_servers(config):
|
||||
for split, source in env_worker_pools(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
logger.info(f"Starting {name} env worker pool")
|
||||
processes.start(
|
||||
f"{split} env server {name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
|
||||
f"{split} env worker pool {name}",
|
||||
["env-worker-pool", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
|
||||
)
|
||||
@@ -254,8 +333,8 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
monitors = {PRIME_LINKS: config.orchestrator.monitors.prime, WANDB_LINKS: config.orchestrator.monitors.wandb}
|
||||
log_run_links(dashboard_url, run_links(config.run_dir, log_dir, monitors, lambda: bool(processes.error_queue)))
|
||||
links = run_links(config.run_dir, log_dir, config.orchestrator.monitors, lambda: bool(processes.error_queue))
|
||||
log_run_links(dashboard_url, links)
|
||||
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
processes.wait("trainer", "orchestrator")
|
||||
@@ -289,22 +368,23 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
else {}
|
||||
)
|
||||
|
||||
# Env servers launch next to the orchestrator, one per launcher-managed train/eval source.
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
# Env worker pools launch on every inference node, one replica per launcher-managed train/eval source.
|
||||
train_env_names = env_worker_pool_names(config, "train")
|
||||
eval_env_names = env_worker_pool_names(config, "eval")
|
||||
|
||||
nixl_broadcast = (
|
||||
# NIXL and ModelExpress weight broadcasts both rendezvous through a ModelExpress server.
|
||||
mx_broadcast = (
|
||||
config.weight_broadcast
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nixl"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type in ("nixl", "modelexpress")
|
||||
else None
|
||||
)
|
||||
launch_modelexpress = nixl_broadcast is not None and config.slurm.launch_modelexpress
|
||||
modelexpress_vars = {
|
||||
"use_nixl_broadcast": nixl_broadcast is not None,
|
||||
"launch_modelexpress": launch_modelexpress,
|
||||
"modelexpress_host": nixl_broadcast.host if nixl_broadcast is not None else "",
|
||||
"modelexpress_port": nixl_broadcast.port if nixl_broadcast is not None else 0,
|
||||
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
|
||||
"use_nixl_broadcast": mx_broadcast is not None and mx_broadcast.type == "nixl",
|
||||
"uses_modelexpress_server": mx_broadcast is not None,
|
||||
"launch_modelexpress": mx_broadcast is not None and config.slurm.launch_modelexpress,
|
||||
"modelexpress_host": mx_broadcast.host if mx_broadcast is not None else "",
|
||||
"modelexpress_port": mx_broadcast.port if mx_broadcast is not None else 0,
|
||||
"modelexpress_redis_port": 6380 if mx_broadcast is not None and mx_broadcast.port == 6379 else 6379,
|
||||
}
|
||||
|
||||
ckpt_dir = get_ckpt_dir(config.trainer.ckpt.output_dir or config.run_dir) if config.trainer.ckpt else None
|
||||
@@ -431,8 +511,8 @@ def rl_slurm(config: RLConfig):
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
train_env_names = env_worker_pool_names(config, "train")
|
||||
eval_env_names = env_worker_pool_names(config, "eval")
|
||||
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
@@ -442,11 +522,15 @@ def rl_slurm(config: RLConfig):
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
)
|
||||
else:
|
||||
# The job's run owner registers the Prime run with the whole config; nothing runs it.
|
||||
# It keeps [slurm], which multi-node needs, so it drops the copy in [inference].
|
||||
write_config(config, config_dir, exclude={"dry_run": True, "clean": True, "inference": {"slurm"}})
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
|
||||
components = [("RL", config_dir / RL_CONFIG), *rl_config_components(config, config_dir)]
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', components)}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
train_env_names = env_worker_pool_names(config, "train")
|
||||
eval_env_names = env_worker_pool_names(config, "eval")
|
||||
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
@@ -480,7 +564,6 @@ def rl_slurm(config: RLConfig):
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
# TODO: fetch the run id from the Prime SDK once runs are registered there.
|
||||
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
|
||||
prepare_run(config, ckpt_output_dir)
|
||||
|
||||
@@ -511,9 +594,14 @@ def rl(config: RLConfig):
|
||||
|
||||
pre_download_model(config.trainer.model.name, skip_weights=config.trainer.model.debug.random_init)
|
||||
|
||||
from prime_rl.monitors.prime import launch_run
|
||||
|
||||
# On SLURM the job registers the run: the in-job `rl` (single node) or the
|
||||
# batch script's run owner (multi node), so that a live process owns its status.
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
else:
|
||||
return
|
||||
with launch_run(config, None if config.dry_run else config.orchestrator.monitors.prime):
|
||||
rl_local(config)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.configs.pretrain import PretrainConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.monitors.prime import launch_run
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""``python -m prime_rl.entrypoints.run_owner {rl,sft,pretrain} <config> <command...>``: run a
|
||||
multi-node SLURM job's step as the owner of its Prime run (``launch_run``). The step's
|
||||
clean exit finishes the run; its non-zero exit, or SLURM's SIGTERM on cancel or time
|
||||
limit, fails it."""
|
||||
kind, path, *command = sys.argv[1:]
|
||||
config_cls = {"rl": RLConfig, "sft": SFTConfig, "pretrain": PretrainConfig}[kind]
|
||||
config = config_cls.model_validate_json(Path(path).read_text())
|
||||
prime = config.orchestrator.monitors.prime if isinstance(config, RLConfig) else config.monitors.prime
|
||||
step: subprocess.Popen | None = None
|
||||
|
||||
def forward(signum: int, frame: Any) -> None:
|
||||
if step is not None:
|
||||
step.send_signal(signum)
|
||||
|
||||
def terminate(signum: int, frame: Any) -> None:
|
||||
# srun relays the signal to the step's tasks, which tear down on their own
|
||||
# (e.g. finish an in-flight checkpoint); a later SIGTERM only reaches srun.
|
||||
forward(signum, frame)
|
||||
signal.signal(signal.SIGTERM, forward)
|
||||
raise SystemExit(128 + signum) from RuntimeError("SLURM terminated the job")
|
||||
|
||||
signal.signal(signal.SIGTERM, terminate)
|
||||
try:
|
||||
with launch_run(config, prime):
|
||||
# Started inside launch_run, so the step inherits the run's $RUN_ID.
|
||||
step = subprocess.Popen(command)
|
||||
code = step.wait()
|
||||
if code != 0:
|
||||
raise SystemExit(code) from RuntimeError(f"The SLURM job step exited with code {code}")
|
||||
finally:
|
||||
# The batch script must outlive the step: SLURM ends the job's steps with it.
|
||||
if step is not None:
|
||||
step.wait()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,492 +1,12 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_run_links, run_links
|
||||
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
|
||||
from prime_rl.utils.links import PRIME_LINKS, WANDB_LINKS
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
launcher_attempt_env,
|
||||
prepare_attempt_dirs,
|
||||
prepare_run,
|
||||
resolve_latest_ckpt_step,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
ONLINE_EVAL_CONFIG = "eval.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def eval_env_servers(config: SFTConfig) -> list[OnlineEvalSourceConfig]:
|
||||
"""Every launcher-managed eval source. A source with ``serve.address`` set is
|
||||
externally managed — the launcher neither writes its config nor spawns a server for it."""
|
||||
if config.eval is None:
|
||||
return []
|
||||
return [source for source in config.eval.source if source.serve.address is None]
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
|
||||
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
|
||||
|
||||
|
||||
def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
if config.resume is None:
|
||||
return None
|
||||
if config.resume.dir is not None:
|
||||
return config.resume.dir_step
|
||||
if config.resume.step is not None:
|
||||
return config.resume.step
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_online_eval_monitors(monitors: TrainMonitorsConfig) -> EvalMonitorsConfig:
|
||||
"""The online-eval process's monitors: same W&B and file config as the trainer's,
|
||||
with the platform monitor switched to the evaluation flavor under the same name."""
|
||||
return EvalMonitorsConfig(
|
||||
wandb=monitors.wandb,
|
||||
file=monitors.file,
|
||||
prime=PrimeEvalMonitorConfig(name=monitors.prime.name) if monitors.prime is not None else None,
|
||||
)
|
||||
|
||||
|
||||
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
|
||||
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
|
||||
fields filled from the SFT config. The launcher spawns the env servers itself; the
|
||||
online-eval process finds each one through the address it publishes in the shared
|
||||
config attempt."""
|
||||
assert config.eval is not None
|
||||
eval_config = config.eval.model_copy(deep=True)
|
||||
run_fields = dict(
|
||||
model=config.model.name,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
# Same run dir as the trainer: the dashboard reads the eval's
|
||||
# file-monitor artifacts from the run directory, so a separate
|
||||
# output dir would hide them. The train-vs-eval record collision
|
||||
# is resolved by record merging in prime_rl.monitors.prime, not
|
||||
# by directory separation.
|
||||
output_dir=config.run_dir,
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=build_online_eval_monitors(config.monitors),
|
||||
)
|
||||
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
|
||||
|
||||
|
||||
def sft_config_components(config: SFTConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved configs a launch leaves in ``config_dir``: the SFT config and, with
|
||||
online evals, the inference, online-eval and env-server configs."""
|
||||
components: list[tuple[str, Path | str]] = [("SFT", config_dir / SFT_CONFIG)]
|
||||
if config.eval is not None:
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
|
||||
if eval_env_servers(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_path, "w") as f:
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
|
||||
"""Write the inference, online-eval, and env-server configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
|
||||
if strip_router:
|
||||
# Per-rank processes run bare engines; the sbatch starts the single global router.
|
||||
inference_dict["router"] = None
|
||||
with open(config_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
|
||||
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# online-eval process picks it up.
|
||||
for source in eval_env_servers(config):
|
||||
write_env_server_config(config_dir, "eval", source, config.log)
|
||||
|
||||
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
}
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
online_eval = config.eval is not None
|
||||
eval_vars = {}
|
||||
if online_eval:
|
||||
assert config.inference is not None
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
eval_vars = {
|
||||
"router": config.inference.router,
|
||||
"router_port": config.inference.server.port,
|
||||
"backend_port": config.inference.backend_port,
|
||||
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"online_eval_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
wandb_shared=wandb_shared,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
|
||||
# Trainer and online-eval processes log to a single shared W&B run.
|
||||
wandb_shared = online_eval and config.monitors.wandb is not None
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
eval=online_eval,
|
||||
inference=online_eval,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_run_links(dashboard_url)
|
||||
|
||||
|
||||
def sft_local(config: SFTConfig):
|
||||
"""Run SFT training locally with process monitoring and cleanup."""
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
if config.eval is not None:
|
||||
write_eval_subconfigs(config, config_dir)
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
eval=config.eval is not None,
|
||||
inference=config.inference is not None,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Partition GPUs (inference first, then the trainer) only when the launcher must split
|
||||
# them between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
|
||||
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
|
||||
)
|
||||
|
||||
# Trainer and online-eval 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 online-eval 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": "online-eval",
|
||||
"WANDB_PROGRAM": "uv run sft",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
with ProcessGroup() as processes:
|
||||
# Optionally, start the inference server for online evals
|
||||
if config.inference is not None:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
|
||||
# Start one env server per eval source. The online-eval process waits for each
|
||||
# server's published address and polls until it answers.
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
processes.start(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting online evals")
|
||||
processes.start(
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "online-eval",
|
||||
},
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**wandb_shared_env,
|
||||
**launcher_attempt_env(config_dir, log_dir),
|
||||
}
|
||||
if config.eval is not None:
|
||||
trainer_env["LOGURU_FORCE_COLORS"] = "1"
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.sft.train",
|
||||
config_path,
|
||||
config.deployment.num_train_gpus,
|
||||
log_dir,
|
||||
config.log.ranks_filter,
|
||||
),
|
||||
env=trainer_env,
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
monitors = {PRIME_LINKS: config.monitors.prime, WANDB_LINKS: config.monitors.wandb}
|
||||
log_run_links(dashboard_url, run_links(config.run_dir, log_dir, monitors, lambda: bool(processes.error_queue)))
|
||||
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
|
||||
logger.success("SFT training finished!")
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the online-eval process would replay stale broadcasts (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 broadcasts; the online-eval process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
|
||||
def sft(config: SFTConfig):
|
||||
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
|
||||
# [deployment] stripped, so the model validator cannot enforce this.
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
|
||||
raise ValueError(
|
||||
"NCCL weight broadcast requires launcher-managed inference. "
|
||||
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
|
||||
prepare_run(config, config.ckpt.output_dir if config.ckpt else None)
|
||||
|
||||
if config.eval is not None and not config.dry_run:
|
||||
clean_stale_eval_artifacts(config)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.trainer.sft.data import pre_download_data
|
||||
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
|
||||
pre_download_data(config.data, config.env_vars)
|
||||
if config.val is not None:
|
||||
pre_download_data(config.val.data, config.env_vars)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
sft_local(config)
|
||||
from prime_rl.entrypoints.launcher import launch
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("SFT")
|
||||
sft(cli(SFTConfig))
|
||||
launch(cli(SFTConfig), "sft")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
from prime_rl.env.client import EnvClient
|
||||
from prime_rl.env.delta import EpisodeAssembly
|
||||
from prime_rl.env.pool import run_env_worker_pool
|
||||
from prime_rl.env.worker import set_episode_hook
|
||||
|
||||
__all__ = ["EnvClient", "EpisodeAssembly", "run_env_worker_pool", "set_episode_hook"]
|
||||
Vendored
+301
@@ -0,0 +1,301 @@
|
||||
"""ZMQ client for the env worker pool.
|
||||
|
||||
A DEALER socket + msgpack, with a single receive loop matching replies to
|
||||
per-request futures by `request_id` and routing a run's `delta` frames to its
|
||||
assembly (`env/delta.py`). The loop drains every queued frame per wakeup and
|
||||
handles the batch in arrival order, so a busy event loop costs one turn per batch
|
||||
rather than one per delta. Speaks the typed pydantic request/response models
|
||||
(`env/types.py`) end-to-end: a request is `model_dump`ed onto the wire; a run's
|
||||
traces stream back turn by turn and the assembled record is `model_validate`d into a
|
||||
`WireEpisode` once the reply lands — `Trace`s typed as `Trace[WireTaskData]`
|
||||
(non-strict task, so env fields survive without importing the env). Health is just
|
||||
another request (no dedicated probe thread).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
import msgpack
|
||||
import zmq
|
||||
import zmq.asyncio
|
||||
from verifiers.v1.configs.client import ClientConfig
|
||||
from verifiers.v1.configs.sampling import SamplingConfig
|
||||
from verifiers.v1.episode import WireEpisode
|
||||
|
||||
from prime_rl.env.delta import EpisodeAssembly, unpack
|
||||
from prime_rl.env.types import (
|
||||
BaseRequest,
|
||||
BaseResponse,
|
||||
CancelRequest,
|
||||
HealthRequest,
|
||||
HealthResponse,
|
||||
RunRequest,
|
||||
RunResponse,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
ResponseT = TypeVar("ResponseT", bound=BaseResponse)
|
||||
DecodedT = TypeVar("DecodedT")
|
||||
|
||||
# How much of the queue one wakeup drains before the loop yields.
|
||||
MAX_BATCH_FRAMES = 512
|
||||
MAX_BATCH_BYTES = 16 << 20
|
||||
INLINE_DECODE_BYTES = 1 << 20
|
||||
"""A batch with fewer delta bytes decodes on the loop: unpacking a turn's delta takes
|
||||
microseconds, less than a worker-thread round trip on a busy loop."""
|
||||
|
||||
|
||||
def _unpack_all(payloads: list[memoryview]) -> list[object]:
|
||||
"""`unpack` each payload; one that fails yields its exception instead."""
|
||||
decoded: list[object] = []
|
||||
for payload in payloads:
|
||||
try:
|
||||
decoded.append(unpack(payload))
|
||||
except Exception as e: # noqa: BLE001 - logged by the caller, in arrival order
|
||||
decoded.append(e)
|
||||
return decoded
|
||||
|
||||
|
||||
class EnvClient:
|
||||
"""Receive streamed episodes, decoding each drained batch of frames at once."""
|
||||
|
||||
def __init__(self, address: str) -> None:
|
||||
self.address = address
|
||||
self.ctx = zmq.asyncio.Context()
|
||||
self.socket = self.ctx.socket(zmq.DEALER)
|
||||
self.socket.setsockopt(zmq.LINGER, 0)
|
||||
self.socket.setsockopt(zmq.SNDHWM, 0)
|
||||
self.socket.setsockopt(zmq.RCVHWM, 0)
|
||||
self.socket.connect(address)
|
||||
self._pending: dict[str, asyncio.Future[bytes]] = {}
|
||||
self._deltas: dict[str, Callable[[dict], None]] = {}
|
||||
# Strong refs to in-flight fire-and-forget cancels: the loop only
|
||||
# holds weak references to tasks, so an unreferenced one can be
|
||||
# garbage-collected before it ever sends
|
||||
self._cancel_tasks: set[asyncio.Task] = set()
|
||||
self._receiver: asyncio.Task | None = None
|
||||
self._decode_slots = asyncio.BoundedSemaphore(1)
|
||||
|
||||
def _ensure_receiver(self) -> None:
|
||||
if self._receiver is None:
|
||||
self._receiver = asyncio.create_task(self._receive_loop())
|
||||
|
||||
async def _receive_loop(self) -> None:
|
||||
# The one receiver serves every in-flight request. Awaiting each frame would
|
||||
# cost a loop turn per delta, which a busy loop turns into a hard cap on how
|
||||
# fast a pool's stream drains; so each wakeup takes everything queued.
|
||||
while True:
|
||||
try:
|
||||
batch = [await self.socket.recv_multipart(copy=False)]
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
size = sum(len(frame) for frame in batch[0])
|
||||
while len(batch) < MAX_BATCH_FRAMES and size < MAX_BATCH_BYTES:
|
||||
try:
|
||||
# A non-blocking recv returns an already-resolved future.
|
||||
frames = self.socket.recv_multipart(flags=zmq.NOBLOCK, copy=False).result()
|
||||
except zmq.Again:
|
||||
break
|
||||
batch.append(frames)
|
||||
size += sum(len(frame) for frame in frames)
|
||||
await self._handle_batch(batch)
|
||||
# A recv with frames already queued resolves without yielding: give the
|
||||
# rest of the loop a turn between batches of a deep backlog.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def _handle_batch(self, batch: list[list[zmq.Frame]]) -> None:
|
||||
"""Decode a batch's deltas, then apply each delta and resolve each reply in
|
||||
arrival order, so a run's reply lands after its last delta. A bad frame or a
|
||||
delta handler that raises is logged and skipped rather than allowed to end
|
||||
the loop or lose its neighbours."""
|
||||
# (request_id, data, delta handler) — a reply carries no handler
|
||||
routed: list[tuple[str, zmq.Frame, Callable[[dict], None] | None]] = []
|
||||
for frames in batch:
|
||||
try:
|
||||
if len(frames) != 3:
|
||||
raise ValueError(
|
||||
f"expected [request_id, kind, data], got {len(frames)} frames - "
|
||||
"is the env worker pool speaking the same serve protocol?"
|
||||
)
|
||||
request_id_frame, kind_frame, data_frame = frames
|
||||
request_id = request_id_frame.bytes.decode()
|
||||
kind = kind_frame.bytes
|
||||
except Exception: # keep receiving for the other requests
|
||||
get_logger().opt(exception=True).warning("Dropped malformed env worker pool frame")
|
||||
continue
|
||||
if kind != b"delta":
|
||||
routed.append((request_id, data_frame, None))
|
||||
elif (on_delta := self._deltas.get(request_id)) is not None:
|
||||
routed.append((request_id, data_frame, on_delta))
|
||||
# The views retain their ZMQ frames while a cancelled worker finishes.
|
||||
payloads = [data_frame.buffer.toreadonly() for _, data_frame, on_delta in routed if on_delta is not None]
|
||||
if sum(payload.nbytes for payload in payloads) <= INLINE_DECODE_BYTES:
|
||||
decoded = iter(_unpack_all(payloads))
|
||||
else:
|
||||
decoded = iter(await asyncio.to_thread(_unpack_all, payloads))
|
||||
for request_id, data_frame, on_delta in routed:
|
||||
if on_delta is None:
|
||||
future = self._pending.pop(request_id, None)
|
||||
if future is not None and not future.done():
|
||||
future.set_result(data_frame.bytes)
|
||||
continue
|
||||
delta = next(decoded)
|
||||
if isinstance(delta, Exception):
|
||||
get_logger().opt(exception=delta).warning("Dropped malformed env worker pool frame")
|
||||
continue
|
||||
# Cancellation may remove the handler while the worker decodes.
|
||||
if self._deltas.get(request_id) is not on_delta:
|
||||
continue
|
||||
try:
|
||||
on_delta(delta)
|
||||
except Exception: # keep receiving for the other requests
|
||||
get_logger().opt(exception=True).warning("Dropped malformed env worker pool frame")
|
||||
|
||||
async def _request(
|
||||
self,
|
||||
request: BaseRequest,
|
||||
response_type: type[ResponseT],
|
||||
timeout: float | None = None,
|
||||
on_delta: Callable[[dict], None] | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> ResponseT:
|
||||
"""Send a typed request and validate the reply into `response_type`. A
|
||||
`timeout` is only used for health polling — rollouts run untimed. `on_delta`
|
||||
receives each decoded `delta` the request streams before its reply."""
|
||||
self._ensure_receiver()
|
||||
request_id = request_id or uuid.uuid4().hex
|
||||
future: asyncio.Future[bytes] = asyncio.get_running_loop().create_future()
|
||||
self._pending[request_id] = future
|
||||
if on_delta is not None:
|
||||
self._deltas[request_id] = on_delta
|
||||
payload = msgpack.packb(request.model_dump(mode="json"), use_bin_type=True)
|
||||
await self.socket.send_multipart([request_id.encode(), request.method.encode(), payload])
|
||||
try:
|
||||
data = await asyncio.wait_for(future, timeout)
|
||||
except TimeoutError:
|
||||
self._pending.pop(request_id, None)
|
||||
raise
|
||||
except asyncio.CancelledError:
|
||||
self._pending.pop(request_id, None)
|
||||
if request.method == RunRequest.method:
|
||||
self._cancel_run(request_id)
|
||||
raise
|
||||
finally:
|
||||
self._deltas.pop(request_id, None)
|
||||
response = response_type.model_validate(unpack(data))
|
||||
if not response.success:
|
||||
raise RuntimeError(response.error or "env worker pool request failed")
|
||||
return response
|
||||
|
||||
async def _decode(self, decode: Callable[..., DecodedT], *args: object) -> DecodedT:
|
||||
"""Validate a finished episode off the loop, one at a time per client. The
|
||||
receive loop decodes its own batches, so a large episode validating here
|
||||
never holds up another run's deltas."""
|
||||
await self._decode_slots.acquire()
|
||||
decoding = asyncio.create_task(asyncio.to_thread(decode, *args))
|
||||
# Hold the slot until the worker finishes so cancellation cannot overlap decodes.
|
||||
decoding.add_done_callback(lambda _: self._decode_slots.release())
|
||||
try:
|
||||
return await asyncio.shield(decoding)
|
||||
except asyncio.CancelledError:
|
||||
decoding.add_done_callback(lambda task: None if task.cancelled() else task.exception())
|
||||
raise
|
||||
|
||||
def _cancel_run(self, run_request_id: str) -> None:
|
||||
"""Fire-and-forget: tell the pool the caller abandoned the run, so it aborts
|
||||
the rollout (or frees what it kept for an episode already sent). A task on the
|
||||
loop outlives the cancelled caller."""
|
||||
task = asyncio.get_running_loop().create_task(self._send_cancel(run_request_id))
|
||||
self._cancel_tasks.add(task)
|
||||
task.add_done_callback(self._cancel_tasks.discard)
|
||||
|
||||
async def _send_cancel(self, run_request_id: str) -> None:
|
||||
"""Best-effort worker-side abort of an abandoned run."""
|
||||
with contextlib.suppress(Exception):
|
||||
payload = msgpack.packb(
|
||||
CancelRequest(request_id=run_request_id).model_dump(mode="json"),
|
||||
use_bin_type=True,
|
||||
)
|
||||
await self.socket.send_multipart([uuid.uuid4().hex.encode(), CancelRequest.method.encode(), payload])
|
||||
|
||||
async def health(self, timeout: float = 2.0) -> bool:
|
||||
try:
|
||||
return (await self._request(HealthRequest(), HealthResponse, timeout=timeout)).success
|
||||
except TimeoutError:
|
||||
return False
|
||||
|
||||
async def wait_for_pool_startup(self, timeout: float = 120.0, interval: float = 1.0) -> None:
|
||||
"""Poll `health` until the broker answers or `timeout` elapses."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if await self.health(timeout=min(interval, 2.0)):
|
||||
return
|
||||
await asyncio.sleep(interval)
|
||||
raise TimeoutError(f"env worker pool at {self.address} did not become healthy in {timeout}s")
|
||||
|
||||
async def run(
|
||||
self,
|
||||
client: ClientConfig,
|
||||
model: str,
|
||||
sampling: SamplingConfig,
|
||||
task_data: dict,
|
||||
on_delta: Callable[[dict], None] | None = None,
|
||||
) -> WireEpisode:
|
||||
"""Run one rollout; return its episode record — flat traces (typed
|
||||
`Trace[WireTaskData]`) plus the shared stamp. The worker takes the task
|
||||
itself (`task_data`, its dumped `TaskData`). The traces stream in as the
|
||||
rollout runs, one delta per turn or phase change (`env.delta`); `on_delta`
|
||||
sees each as it lands, so a caller can relay or persist the stream. The
|
||||
episode returned is assembled from the same deltas."""
|
||||
assembly = EpisodeAssembly()
|
||||
|
||||
def apply(delta: dict) -> None:
|
||||
assembly.apply(delta)
|
||||
if on_delta is not None:
|
||||
on_delta(delta)
|
||||
|
||||
request_id = uuid.uuid4().hex
|
||||
response = await self._request(
|
||||
RunRequest(
|
||||
task_data=task_data,
|
||||
client=client,
|
||||
model=model,
|
||||
sampling=sampling,
|
||||
),
|
||||
RunResponse,
|
||||
on_delta=apply,
|
||||
request_id=request_id,
|
||||
)
|
||||
assert response.head is not None
|
||||
try:
|
||||
return await self._decode(
|
||||
WireEpisode.model_validate,
|
||||
assembly.finish(response.head, response.traces),
|
||||
)
|
||||
except BaseException:
|
||||
# The reply already arrived, so the worker counts the episode delivered;
|
||||
# tell it this caller never got the episode.
|
||||
self._cancel_run(request_id)
|
||||
raise
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._receiver is not None:
|
||||
self._receiver.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._receiver
|
||||
self._receiver = None
|
||||
# Let scheduled fire-and-forget cancels reach the socket first, or a
|
||||
# run cancelled right before close() leaves its worker-side rollout
|
||||
# running. Pop before awaiting: awaiting finished tasks never yields
|
||||
# (since CPython 3.12 a gather of them completes eagerly), so their
|
||||
# queued `discard` callbacks cannot be what empties the set
|
||||
while self._cancel_tasks:
|
||||
task = self._cancel_tasks.pop()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
self.socket.close()
|
||||
self.ctx.term()
|
||||
Vendored
+305
@@ -0,0 +1,305 @@
|
||||
"""Incremental trace deltas for episode streams and file writers.
|
||||
|
||||
The worker streams a served episode as it grows. Each trace announces its own changes
|
||||
(`Trace.notify`, fired by the rollout at every phase change and by the interception proxy
|
||||
after every recorded turn); the `DeltaStreamer` then diffs the run's live traces against
|
||||
what it has already sent and ships only the new part — the trace header once, then
|
||||
appended nodes / calls / errors, semantic links on earlier nodes, the scalar
|
||||
fields whose value changed (timing spans, stop condition, rewards, ...), and the
|
||||
`pending` preview — the messages of the request in flight that no node holds yet, so a
|
||||
watcher sees a tool result before the model has answered it. The `Trace` is
|
||||
append-only at turn granularity except for links. Nodes stream without their per-token
|
||||
training arrays (`TRAINING_ARRAY_FIELDS`): a host that trains on them keeps them itself
|
||||
(`set_episode_hook`). Apart from links and the preview, every byte of the
|
||||
episode crosses the wire once and the stream costs about what a single reply would; the
|
||||
reply that ends the run carries only the episode head and per-trace counts the client
|
||||
checks its assembly against. A cursor advances only once its delta is on the wire, so a
|
||||
send that fails is simply diffed again at the next flush.
|
||||
|
||||
The client applies deltas into raw dicts (`EpisodeAssembly`) — cheap enough to hand a
|
||||
caller after every turn — and validates the assembled record into a `WireEpisode` once,
|
||||
when the run's reply lands.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from typing import TYPE_CHECKING, Any, Self
|
||||
|
||||
import msgpack
|
||||
from pydantic import BaseModel
|
||||
|
||||
from prime_rl.env.encoding import msgpack_encoder
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from verifiers.v1.trace import Trace
|
||||
|
||||
HEADER_FIELDS = ("version", "id", "attempt", "verifiers", "task", "run")
|
||||
"""Sent once, when a trace (or a retry of its agent run) first appears."""
|
||||
|
||||
LIST_FIELDS = (
|
||||
"nodes",
|
||||
"calls",
|
||||
"errors",
|
||||
"extra_usage",
|
||||
"request_rewrites",
|
||||
"response_rewrites",
|
||||
)
|
||||
"""Append-only on the worker: each delta carries the items past the sent count."""
|
||||
|
||||
SCALAR_FIELDS = (
|
||||
"agent",
|
||||
"tools",
|
||||
"mm_token_type_id_map",
|
||||
"rewards",
|
||||
"metrics",
|
||||
"info",
|
||||
"root_reply",
|
||||
"is_completed",
|
||||
"ok",
|
||||
"stop_condition",
|
||||
"is_timeout",
|
||||
"dropped",
|
||||
"timing",
|
||||
"num_input_tokens",
|
||||
"num_output_tokens",
|
||||
"num_total_tokens",
|
||||
"reward",
|
||||
"usage",
|
||||
"is_truncated",
|
||||
"num_turns",
|
||||
"num_branches",
|
||||
"last_reply",
|
||||
"has_error",
|
||||
"is_format_violation",
|
||||
)
|
||||
"""Re-sent whole whenever their dumped value changes."""
|
||||
|
||||
|
||||
TRAINING_ARRAY_FIELDS = frozenset({"routed_experts", "sampling_mask", "top_logprobs"})
|
||||
"""Node fields holding per-token training arrays; never streamed."""
|
||||
|
||||
|
||||
def pack(payload: Any) -> bytes:
|
||||
return msgpack.packb(payload, default=msgpack_encoder, use_bin_type=True)
|
||||
|
||||
|
||||
def unpack(data: bytes) -> Any:
|
||||
# Node updates are keyed by node index (int).
|
||||
return msgpack.unpackb(data, raw=False, strict_map_key=False)
|
||||
|
||||
|
||||
def dump(model: BaseModel, **kwargs: Any) -> dict:
|
||||
# Task data and agent configs are subclasses of their declared types; dump the
|
||||
# runtime type so env-specific fields survive the wire.
|
||||
return model.model_dump(mode="python", serialize_as_any=True, **kwargs)
|
||||
|
||||
|
||||
class TraceCursor:
|
||||
"""What of one trace has been sent."""
|
||||
|
||||
def __init__(self, attempt: int) -> None:
|
||||
self.attempt = attempt
|
||||
self.sent = dict.fromkeys(LIST_FIELDS, 0)
|
||||
self.links: list[int] = []
|
||||
"""Per sent node, how many of its semantic links went out with or after it."""
|
||||
self.scalars: dict[str, bytes] = {}
|
||||
self.pending: bytes = pack([])
|
||||
|
||||
|
||||
class DeltaStreamer:
|
||||
"""Sends the current traces' changes as deltas, one flush per burst of changes.
|
||||
|
||||
`watch` subscribes a minted trace (pass it as the runner's `on_trace`); each
|
||||
`Trace.notify` schedules a flush, and changes landing in the same loop iteration
|
||||
ride one flush. Use as an async context manager around the rollout: a clean exit
|
||||
flushes the final state; a cancelled rollout settles pending sends without a final flush."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
traces: Callable[[], Iterable[Trace]],
|
||||
send: Callable[[dict], Awaitable[None]],
|
||||
) -> None:
|
||||
self.traces = traces
|
||||
self.send = send
|
||||
self.cursors: dict[str, TraceCursor] = {}
|
||||
self._scheduled: asyncio.Handle | None = None
|
||||
self._flushes: set[asyncio.Task] = set()
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb) -> None:
|
||||
if self._scheduled is not None:
|
||||
self._scheduled.cancel()
|
||||
self._scheduled = None
|
||||
if exc_type is None:
|
||||
# let in-flight flushes finish, then send whatever the run left behind
|
||||
await asyncio.gather(*self._flushes, return_exceptions=True)
|
||||
await self.flush()
|
||||
else:
|
||||
for task in self._flushes:
|
||||
task.cancel()
|
||||
await asyncio.gather(*self._flushes, return_exceptions=True)
|
||||
|
||||
def watch(self, trace: Trace) -> None:
|
||||
trace.watch(self._changed)
|
||||
self._changed(trace)
|
||||
|
||||
def _changed(self, trace: Trace) -> None:
|
||||
if self._scheduled is not None:
|
||||
return
|
||||
self._scheduled = asyncio.get_running_loop().call_soon(self._start_flush)
|
||||
|
||||
def _start_flush(self) -> None:
|
||||
self._scheduled = None
|
||||
task = asyncio.create_task(self.flush())
|
||||
self._flushes.add(task)
|
||||
task.add_done_callback(self._flushes.discard)
|
||||
|
||||
async def flush(self) -> None:
|
||||
# Serialized: deltas must leave in diff order, and the reply after the last.
|
||||
async with self._lock:
|
||||
for trace_id, delta, cursor in self.diff():
|
||||
try:
|
||||
await self.send(delta)
|
||||
except Exception: # the cursor stays put: the next flush diffs it again
|
||||
get_logger().opt(exception=True).warning(f"Failed to send trace delta trace={trace_id}")
|
||||
continue
|
||||
if cursor is None:
|
||||
self.cursors.pop(trace_id, None)
|
||||
else:
|
||||
self.cursors[trace_id] = cursor
|
||||
|
||||
def diff(self) -> list[tuple[str, dict, TraceCursor | None]]:
|
||||
"""Each trace's delta against its sent cursor, with the cursor as it stands once
|
||||
that delta is sent (None for a discard). Nothing here is committed: `flush`
|
||||
stores a cursor only after its delta left."""
|
||||
traces = list(self.traces())
|
||||
live = {trace.id for trace in traces}
|
||||
deltas: list[tuple[str, dict, TraceCursor | None]] = []
|
||||
for trace_id in [trace_id for trace_id in self.cursors if trace_id not in live]:
|
||||
# A retried attempt abandons its traces; the client drops them too.
|
||||
deltas.append((trace_id, {"trace": trace_id, "discard": True}, None))
|
||||
for trace in traces:
|
||||
delta: dict[str, Any] = {"trace": trace.id}
|
||||
sent = self.cursors.get(trace.id)
|
||||
if sent is not None and sent.attempt != trace.attempt:
|
||||
# A retried agent run replaces its trace under the same id: the client
|
||||
# drops the abandoned attempt, then the new one opens from scratch.
|
||||
deltas.append((trace.id, {"trace": trace.id, "discard": True}, None))
|
||||
sent = None
|
||||
cursor = copy.deepcopy(sent) if sent is not None else TraceCursor(trace.attempt)
|
||||
if sent is None:
|
||||
delta["open"] = dump(trace, include=set(HEADER_FIELDS))
|
||||
links: dict[int, list[dict]] = {}
|
||||
for index in range(cursor.sent["nodes"]):
|
||||
node_links = trace.nodes[index].semantic_parents
|
||||
if len(node_links) > cursor.links[index]:
|
||||
links[index] = [dump(link) for link in node_links[cursor.links[index] :]]
|
||||
cursor.links[index] = len(node_links)
|
||||
if links:
|
||||
delta["links"] = links
|
||||
for field in LIST_FIELDS:
|
||||
items = getattr(trace, field)
|
||||
sent = cursor.sent[field]
|
||||
if len(items) > sent:
|
||||
# Nodes' per-token streams ride as raw-bytes arrays.
|
||||
is_nodes = field == "nodes"
|
||||
delta[field] = [
|
||||
dump(
|
||||
item,
|
||||
context={"token_arrays": True} if is_nodes else None,
|
||||
exclude=TRAINING_ARRAY_FIELDS if is_nodes else None,
|
||||
)
|
||||
for item in items[sent:]
|
||||
]
|
||||
cursor.sent[field] = len(items)
|
||||
if field == "nodes":
|
||||
cursor.links.extend(len(node.semantic_parents) for node in items[sent:])
|
||||
changed: dict[str, Any] = {}
|
||||
for field, value in dump(trace, include=set(SCALAR_FIELDS)).items():
|
||||
packed = pack(value)
|
||||
if cursor.scalars.get(field) != packed:
|
||||
cursor.scalars[field] = packed
|
||||
changed[field] = value
|
||||
if changed:
|
||||
delta["set"] = changed
|
||||
pending = [dump(message) for message in trace.pending]
|
||||
packed = pack(pending)
|
||||
if packed != cursor.pending:
|
||||
cursor.pending = packed
|
||||
# nodes landing clear the preview on the client by themselves
|
||||
if pending or "nodes" not in delta:
|
||||
delta["pending"] = pending
|
||||
if len(delta) > 1:
|
||||
deltas.append((trace.id, delta, cursor))
|
||||
return deltas
|
||||
|
||||
|
||||
class EpisodeAssembly:
|
||||
"""The client's growing picture of one served episode: raw trace dicts in arrival
|
||||
order, each shaped like a dumped `Trace` plus its `pending` preview."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.traces: dict[str, dict] = {}
|
||||
|
||||
def apply(self, delta: dict) -> None:
|
||||
trace_id = delta["trace"]
|
||||
if delta.get("discard"):
|
||||
self.traces.pop(trace_id, None)
|
||||
return
|
||||
trace = self.traces.get(trace_id)
|
||||
if trace is None:
|
||||
trace = self.traces[trace_id] = {
|
||||
**delta["open"],
|
||||
**{field: [] for field in LIST_FIELDS},
|
||||
"pending": [],
|
||||
}
|
||||
for index, links in (delta.get("links") or {}).items():
|
||||
trace["nodes"][int(index)]["semantic_parents"].extend(links)
|
||||
# a later `links` delta grows a node's semantic_parents in place, so the node
|
||||
# is copied: the delta stays as it was when the caller received it
|
||||
if "nodes" in delta:
|
||||
trace["nodes"].extend(
|
||||
{**node, "semantic_parents": list(node.get("semantic_parents") or [])} for node in delta["nodes"]
|
||||
)
|
||||
for field in LIST_FIELDS:
|
||||
if field in delta and field != "nodes":
|
||||
trace[field].extend(delta[field])
|
||||
trace.update(delta.get("set") or {})
|
||||
# a committed turn absorbs the preview; an explicit preview replaces it
|
||||
if "nodes" in delta:
|
||||
trace["pending"] = []
|
||||
if "pending" in delta:
|
||||
trace["pending"] = delta["pending"]
|
||||
|
||||
def finish(self, head: dict, summaries: list[TraceSummary]) -> dict:
|
||||
"""The full episode record: `head` (the episode without its traces) joined with
|
||||
the assembled traces in the worker's order. A count mismatch means a delta was
|
||||
lost, which the wire never does in a live connection — fail loudly."""
|
||||
traces = []
|
||||
for summary in summaries:
|
||||
trace = self.traces.get(summary.id)
|
||||
if trace is None:
|
||||
raise RuntimeError(f"served episode is missing trace {summary.id}")
|
||||
trace = {key: value for key, value in trace.items() if key != "pending"}
|
||||
if len(trace["nodes"]) != summary.nodes or len(trace["calls"]) != summary.calls:
|
||||
raise RuntimeError(
|
||||
f"served trace {summary.id} assembled {len(trace['nodes'])} nodes / "
|
||||
f"{len(trace['calls'])} calls, worker reports {summary.nodes} / {summary.calls}"
|
||||
)
|
||||
traces.append(trace)
|
||||
return {**head, "traces": traces}
|
||||
|
||||
|
||||
class TraceSummary(BaseModel):
|
||||
"""A finished trace's identity and size, for the client's assembly check."""
|
||||
|
||||
id: str
|
||||
nodes: int
|
||||
calls: int
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
"""msgpack encoding for the env-serve wire."""
|
||||
|
||||
import dataclasses
|
||||
import sys
|
||||
from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import numpy as np
|
||||
from pydantic_core import to_jsonable_python
|
||||
|
||||
# Marker key inside the encoded payload so a decoder can recognize a
|
||||
# tensor round-trip without disturbing arbitrary user dicts.
|
||||
TENSOR_TAG = "__torch_tensor__"
|
||||
|
||||
|
||||
def _encode_array_like(arr: "np.ndarray") -> dict:
|
||||
return {
|
||||
TENSOR_TAG: True,
|
||||
"dtype": str(arr.dtype),
|
||||
"shape": list(arr.shape),
|
||||
"data": arr.tobytes(),
|
||||
}
|
||||
|
||||
|
||||
def msgpack_encoder(obj):
|
||||
"""
|
||||
Custom encoder for non-standard types.
|
||||
|
||||
IMPORTANT: msgpack traverses lists/dicts in optimized C code. This function
|
||||
is ONLY called for types msgpack doesn't recognize. This avoids the massive
|
||||
performance penalty of recursing through millions of tokens in Python.
|
||||
|
||||
Handles: Path, UUID, sets, Enum, datetime, Pydantic models, numpy scalars,
|
||||
numpy arrays, torch tensors, and dataclasses (e.g. renderers'
|
||||
``MultiModalData`` / ``PlaceholderRange``). Tensors and ndarrays are
|
||||
encoded as ``{__torch_tensor__: True, dtype, shape, data}``.
|
||||
Other types use Pydantic's JSON conversions; unsupported types still raise.
|
||||
Does NOT handle: lists, dicts, basic types (msgpack does this natively in C).
|
||||
"""
|
||||
if isinstance(obj, (Path, UUID)):
|
||||
return str(obj)
|
||||
elif isinstance(obj, (set, frozenset)):
|
||||
return list(obj)
|
||||
elif isinstance(obj, Enum):
|
||||
return obj.value
|
||||
elif isinstance(obj, (datetime, date)):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, (np.integer, np.floating)):
|
||||
return obj.item()
|
||||
elif isinstance(obj, np.ndarray):
|
||||
return _encode_array_like(obj)
|
||||
elif (_torch := sys.modules.get("torch")) is not None and isinstance(obj, _torch.Tensor):
|
||||
# Read torch off ``sys.modules`` instead of importing: text-only
|
||||
# consumers never load torch, so this branch stays cold for them.
|
||||
# Any tensor reaching the encoder implies torch is already in the
|
||||
# process (you can't construct one otherwise).
|
||||
arr = obj.detach().cpu().contiguous().numpy()
|
||||
return _encode_array_like(arr)
|
||||
elif hasattr(obj, "model_dump"):
|
||||
return obj.model_dump()
|
||||
elif dataclasses.is_dataclass(obj) and not isinstance(obj, type):
|
||||
return dataclasses.asdict(obj)
|
||||
else:
|
||||
return to_jsonable_python(obj)
|
||||
Vendored
+356
@@ -0,0 +1,356 @@
|
||||
"""Env worker pool: a ROUTER broker over N worker processes.
|
||||
|
||||
A lone `EnvWorker` runs every rollout as an `asyncio.Task` on one event loop, so
|
||||
CPU-bound work (renderer tokenization, scoring) competes for that loop; the pool
|
||||
spreads that work across processes.
|
||||
|
||||
A broker binds the client-facing ROUTER, starts one worker process and scales up to
|
||||
`max_workers` on demand — each an ordinary `EnvWorker` bound to its own ipc address —
|
||||
load-balancing requests to the least-busy worker over a `DEALER` per worker. The
|
||||
worker's `client_id` (its reply identity) is the broker's DEALER identity; the broker
|
||||
holds the real client identity in `pending` and routes the reply back by `request_id`.
|
||||
`health` is answered inline (no worker needed); everything else goes to a worker.
|
||||
|
||||
Scaling is elastic but upscale-only: a new worker is spawned when in-flight requests
|
||||
reach 90% of current capacity (`workers * multiplex`). Workers are spawned `spawn`-style
|
||||
(own env, own loop) and monitor a death pipe so an orphaned worker self-exits if the
|
||||
broker dies. TODO: downscale idle workers, per-worker restart-on-death, stats/lag
|
||||
monitors (rollout errors are returned as data, not crashes, so worker death is rare).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import signal
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
import msgpack
|
||||
import zmq
|
||||
import zmq.asyncio
|
||||
from verifiers.v1.utils.loaders import resolve_env_config
|
||||
|
||||
from prime_rl.configs.env_worker_pool import ElasticPoolConfig, PoolConfig, StaticPoolConfig
|
||||
from prime_rl.env.types import CancelResponse, HealthResponse
|
||||
from prime_rl.env.worker import LATE_CANCEL_SECONDS, EnvWorker
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
_HEALTH = msgpack.packb(HealthResponse().model_dump(mode="json"), use_bin_type=True)
|
||||
_CANCEL_MISS = msgpack.packb(CancelResponse(cancelled=False).model_dump(mode="json"), use_bin_type=True)
|
||||
|
||||
|
||||
def _arm_teardown(death_pipe=None) -> None:
|
||||
"""Arm a broker or worker process for clean
|
||||
teardown: it inherits no signal handlers, so by default SIGTERM kills it abruptly, skipping
|
||||
asyncio.run()'s serving() cleanup and orphaning host tunnels (and sandboxes).
|
||||
|
||||
- SIGTERM -> KeyboardInterrupt so the event loop runs its finallys (run_env_worker_pool swallows it);
|
||||
- with `death_pipe`, a worker self-SIGTERMs when the broker dies (pipe EOF, even on
|
||||
SIGKILL) so the worker is not orphaned."""
|
||||
|
||||
def on_sigterm(*_) -> None:
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
raise KeyboardInterrupt
|
||||
|
||||
signal.signal(signal.SIGTERM, on_sigterm)
|
||||
if death_pipe is None:
|
||||
return
|
||||
|
||||
def _watch() -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
death_pipe.recv()
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
|
||||
threading.Thread(target=_watch, daemon=True).start()
|
||||
|
||||
|
||||
class EnvWorkerPool:
|
||||
"""One source's pool replica: a ROUTER broker with least-busy worker dispatch.
|
||||
|
||||
An elastic pool starts with a single worker and spawns another whenever in-flight
|
||||
requests reach 90% of current capacity (`workers * multiplex`), up to `max_workers`.
|
||||
Upscale-only for now — workers are never reclaimed. A static pool pre-spawns all
|
||||
`num_workers` upfront."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pool: ElasticPoolConfig | StaticPoolConfig,
|
||||
address: str,
|
||||
config_data: dict,
|
||||
max_concurrent: int | None,
|
||||
worker_setup: Callable[[], None] | None,
|
||||
) -> None:
|
||||
self.pool = pool
|
||||
self.elastic = isinstance(pool, ElasticPoolConfig)
|
||||
self.max_workers = pool.max_workers if self.elastic else pool.num_workers
|
||||
self.config_data = config_data
|
||||
self.max_concurrent = max_concurrent
|
||||
self.worker_setup = worker_setup
|
||||
self._ipc_dir = tempfile.mkdtemp(prefix="prl-env-pool-", dir="/tmp")
|
||||
self.workers: list[dict] = []
|
||||
self._mpctx = mp.get_context("spawn")
|
||||
self._poller: zmq.asyncio.Poller | None = None
|
||||
|
||||
self.ctx = zmq.asyncio.Context()
|
||||
self.frontend = self.ctx.socket(zmq.ROUTER)
|
||||
self.frontend.setsockopt(zmq.ROUTER_MANDATORY, 1)
|
||||
self.frontend.setsockopt(zmq.SNDHWM, 0)
|
||||
self.frontend.setsockopt(zmq.RCVHWM, 0)
|
||||
self.frontend.setsockopt(zmq.LINGER, 0)
|
||||
self.frontend.bind(address)
|
||||
self.address = self.frontend.getsockopt_string(zmq.LAST_ENDPOINT)
|
||||
|
||||
def _worker_path(self, i: int) -> str:
|
||||
return f"{self._ipc_dir}/{i}"
|
||||
|
||||
def _spawn_worker(self) -> None:
|
||||
i = len(self.workers) # upscale-only, so the next index is the current count
|
||||
address = f"ipc://{self._worker_path(i)}"
|
||||
parent_conn, child_conn = self._mpctx.Pipe()
|
||||
proc = self._mpctx.Process(
|
||||
target=run_env_worker,
|
||||
kwargs=dict(
|
||||
address=address,
|
||||
config_data=self.config_data,
|
||||
max_concurrent=self.max_concurrent,
|
||||
death_pipe=child_conn,
|
||||
worker_setup=self.worker_setup,
|
||||
),
|
||||
daemon=False,
|
||||
)
|
||||
proc.start()
|
||||
child_conn.close() # parent keeps the write end (its close signals death)
|
||||
dealer = self.ctx.socket(zmq.DEALER)
|
||||
dealer.setsockopt(zmq.LINGER, 0)
|
||||
dealer.connect(address) # connect before bind is fine — ZMQ queues
|
||||
self.workers.append(
|
||||
{
|
||||
"process": proc,
|
||||
"dealer": dealer,
|
||||
"pipe": parent_conn,
|
||||
"active": 0,
|
||||
"index": i,
|
||||
}
|
||||
)
|
||||
if self._poller is not None:
|
||||
self._poller.register(dealer, zmq.POLLIN)
|
||||
|
||||
def _maybe_scale_up(self, in_flight: int) -> None:
|
||||
"""Spawn one more worker when in-flight rollout slots reach 90% of capacity.
|
||||
|
||||
A new worker starts at `active=0`, so least-busy dispatch funnels the backlog to
|
||||
it as it comes online (a few seconds to load the env) — fine, since we only scale
|
||||
up once already saturated. `max_workers=None` scales without a cap."""
|
||||
if self.max_workers is not None and len(self.workers) >= self.max_workers:
|
||||
return
|
||||
if in_flight >= 0.9 * len(self.workers) * self.pool.multiplex:
|
||||
self._spawn_worker()
|
||||
get_logger().info(
|
||||
f"Grew env worker pool to {len(self.workers)} worker(s) max_workers={self._cap_str} in_flight={in_flight}"
|
||||
)
|
||||
|
||||
@property
|
||||
def _cap_str(self) -> str:
|
||||
return "inf" if self.max_workers is None else str(self.max_workers)
|
||||
|
||||
async def run(self) -> None:
|
||||
self._poller = zmq.asyncio.Poller()
|
||||
self._poller.register(self.frontend, zmq.POLLIN)
|
||||
# Elastic: start with one and scale up on demand. Static: pre-spawn the lot.
|
||||
for _ in range(1 if self.elastic else self.max_workers):
|
||||
self._spawn_worker()
|
||||
# request_id -> {client_id, worker}
|
||||
pending: dict[bytes, dict] = {}
|
||||
# request_id -> (replied_at, worker), oldest first: a late cancel still reaches
|
||||
# the worker that may hold the run's kept arrays (`LATE_CANCEL_SECONDS`).
|
||||
replied: dict[bytes, tuple[float, dict]] = {}
|
||||
sizing = (
|
||||
f"max_workers={self._cap_str} multiplex={self.pool.multiplex}"
|
||||
if self.elastic
|
||||
else f"num_workers={self.max_workers}"
|
||||
)
|
||||
get_logger().info(
|
||||
f"Started env worker pool address={self.address} pool={self.pool.type} workers={len(self.workers)} {sizing}"
|
||||
)
|
||||
try:
|
||||
in_flight = 0
|
||||
while True:
|
||||
events = dict(await self._poller.poll())
|
||||
if self.frontend in events:
|
||||
frames = await self.frontend.recv_multipart()
|
||||
# Drop malformed requests without skipping ready worker replies.
|
||||
if len(frames) != 4:
|
||||
get_logger().warning(f"Dropped malformed request frames={len(frames)} expected=4")
|
||||
else:
|
||||
client_id, request_id, method, payload = frames
|
||||
if method == b"health":
|
||||
await self.frontend.send_multipart([client_id, request_id, b"reply", _HEALTH])
|
||||
elif method == b"cancel":
|
||||
# Route the cancel to the worker holding the target run,
|
||||
# or to the one that replied to it within
|
||||
# `LATE_CANCEL_SECONDS` (it may hold the run's kept
|
||||
# arrays); any other target (or an unparseable payload
|
||||
# — one bad frame must not tear down the broker) is
|
||||
# answered inline
|
||||
try:
|
||||
body = msgpack.unpackb(payload, raw=False)
|
||||
target = str(body.get("request_id", "")).encode()
|
||||
except Exception: # noqa: BLE001 - one bad frame must not kill the broker
|
||||
target = b""
|
||||
target_entry = pending.get(target)
|
||||
late = replied.get(target)
|
||||
if target_entry is not None:
|
||||
worker = target_entry["worker"]
|
||||
elif late is not None and time.monotonic() - late[0] < LATE_CANCEL_SECONDS:
|
||||
worker = late[1]
|
||||
else:
|
||||
worker = None
|
||||
if worker is None:
|
||||
await self.frontend.send_multipart([client_id, request_id, b"reply", _CANCEL_MISS])
|
||||
else:
|
||||
worker["active"] += 1
|
||||
pending[request_id] = {
|
||||
"client_id": client_id,
|
||||
"worker": worker,
|
||||
}
|
||||
in_flight += 1
|
||||
await worker["dealer"].send_multipart([request_id, method, payload])
|
||||
else:
|
||||
worker = min(self.workers, key=lambda w: w["active"])
|
||||
worker["active"] += 1
|
||||
pending[request_id] = {
|
||||
"client_id": client_id,
|
||||
"worker": worker,
|
||||
}
|
||||
in_flight += 1
|
||||
# forward without client_id — the DEALER identity is the worker's
|
||||
# `client_id`; we hold the real one in `pending`.
|
||||
await worker["dealer"].send_multipart([request_id, method, payload])
|
||||
if self.elastic:
|
||||
self._maybe_scale_up(in_flight)
|
||||
for w in self.workers:
|
||||
if w["dealer"] in events:
|
||||
request_id, kind, data = await w["dealer"].recv_multipart(copy=False)
|
||||
# Copy only the routing key; relay the Frames unchanged. A
|
||||
# `delta` is one of many for its request — only the `reply`
|
||||
# closes the request out.
|
||||
if kind.bytes == b"reply":
|
||||
entry = pending.pop(request_id.bytes, None)
|
||||
if entry is None:
|
||||
continue
|
||||
entry["worker"]["active"] -= 1
|
||||
in_flight -= 1
|
||||
now = time.monotonic()
|
||||
replied[request_id.bytes] = (now, entry["worker"])
|
||||
for old, (replied_at, _) in list(replied.items()):
|
||||
if now - replied_at < LATE_CANCEL_SECONDS:
|
||||
break
|
||||
del replied[old]
|
||||
else:
|
||||
entry = pending.get(request_id.bytes)
|
||||
if entry is None:
|
||||
continue
|
||||
try:
|
||||
await self.frontend.send_multipart([entry["client_id"], request_id, kind, data], copy=False)
|
||||
except zmq.ZMQError:
|
||||
# The client cannot take this episode. Free it at the worker;
|
||||
# the empty request id leaves the cancel reply untracked.
|
||||
with contextlib.suppress(UnicodeDecodeError):
|
||||
await w["dealer"].send_multipart(
|
||||
[
|
||||
b"",
|
||||
b"cancel",
|
||||
msgpack.packb(
|
||||
{"request_id": request_id.bytes.decode()},
|
||||
use_bin_type=True,
|
||||
),
|
||||
]
|
||||
)
|
||||
except (asyncio.CancelledError, KeyboardInterrupt):
|
||||
pass
|
||||
finally:
|
||||
self._shutdown()
|
||||
|
||||
def _shutdown(self) -> None:
|
||||
for w in self.workers:
|
||||
with contextlib.suppress(Exception):
|
||||
w["pipe"].close()
|
||||
with contextlib.suppress(Exception):
|
||||
w["process"].terminate()
|
||||
for w in self.workers:
|
||||
with contextlib.suppress(Exception):
|
||||
w["process"].join(timeout=10)
|
||||
if w["process"].is_alive():
|
||||
with contextlib.suppress(Exception):
|
||||
w["process"].kill()
|
||||
with contextlib.suppress(Exception):
|
||||
w["dealer"].close()
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(self._worker_path(w["index"]))
|
||||
with contextlib.suppress(OSError):
|
||||
os.rmdir(self._ipc_dir)
|
||||
self.frontend.close()
|
||||
self.ctx.term()
|
||||
get_logger().info(f"Stopped env worker pool address={self.address}")
|
||||
|
||||
|
||||
def run_env_worker(
|
||||
*,
|
||||
address: str,
|
||||
config_data: dict,
|
||||
max_concurrent: int | None,
|
||||
death_pipe,
|
||||
worker_setup: Callable[[], None] | None,
|
||||
) -> None:
|
||||
"""A pool worker process: one `EnvWorker` on its ipc address. It self-terminates if
|
||||
the broker dies — see `_arm_teardown`."""
|
||||
set_proc_title("EnvWorker")
|
||||
_arm_teardown(death_pipe)
|
||||
if worker_setup is not None:
|
||||
worker_setup()
|
||||
try:
|
||||
asyncio.run(EnvWorker(resolve_env_config(config_data), address, max_concurrent).run())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except Exception:
|
||||
get_logger().opt(exception=True).error("Failed to run env worker")
|
||||
raise
|
||||
|
||||
|
||||
def run_env_worker_pool(
|
||||
*,
|
||||
pool: PoolConfig,
|
||||
address: str,
|
||||
config_data: dict,
|
||||
max_concurrent: int | None,
|
||||
address_queue=None,
|
||||
worker_setup: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Run one source's pool replica: a ZMQ broker over env worker processes. Reports
|
||||
the bound address on `address_queue` (for a spawner that passed an OS-assigned `:0`).
|
||||
|
||||
`config_data` is the env config as plain data (`model_dump(mode="json")`), since a
|
||||
dynamically-narrowed config type can't be pickled into spawned workers.
|
||||
|
||||
`worker_setup` (a picklable callable) runs in this process and every spawned worker —
|
||||
without it a spawned worker inherits no log handlers and its logs are silently dropped."""
|
||||
# Graceful SIGTERM (run asyncio teardown). The re-raised KeyboardInterrupt is swallowed
|
||||
# below for a clean exit (no spurious traceback).
|
||||
set_proc_title("EnvBroker")
|
||||
_arm_teardown()
|
||||
if worker_setup is not None:
|
||||
worker_setup()
|
||||
try:
|
||||
broker = EnvWorkerPool(pool, address, config_data, max_concurrent, worker_setup)
|
||||
if address_queue is not None:
|
||||
address_queue.put(broker.address)
|
||||
asyncio.run(broker.run())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except Exception:
|
||||
get_logger().opt(exception=True).error("Failed to run env worker pool")
|
||||
raise
|
||||
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
from typing import ClassVar
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from verifiers.v1.configs.client import ClientConfig
|
||||
from verifiers.v1.configs.sampling import SamplingConfig
|
||||
|
||||
from prime_rl.env.delta import TraceSummary
|
||||
|
||||
|
||||
class BaseRequest(BaseModel):
|
||||
"""`method` is sent as its own route frame, not as payload data."""
|
||||
|
||||
method: ClassVar[str]
|
||||
|
||||
|
||||
class BaseResponse(BaseModel):
|
||||
success: bool = True
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class HealthRequest(BaseRequest):
|
||||
method: ClassVar[str] = "health"
|
||||
|
||||
|
||||
class HealthResponse(BaseResponse):
|
||||
pass
|
||||
|
||||
|
||||
class CancelRequest(BaseRequest):
|
||||
"""Abort an in-flight run by its wire ``request_id``. Idempotent — a
|
||||
finished or unknown run cancels successfully with ``cancelled=False``."""
|
||||
|
||||
method: ClassVar[str] = "cancel"
|
||||
request_id: str
|
||||
|
||||
|
||||
class CancelResponse(BaseResponse):
|
||||
cancelled: bool = False
|
||||
"""Whether a live run was found and aborted."""
|
||||
|
||||
|
||||
class RunRequest(BaseRequest):
|
||||
"""One env-rollout, shipping the task itself: `task_data` is the dumped
|
||||
`TaskData` the worker validates into the taskset's declared type."""
|
||||
|
||||
method: ClassVar[str] = "run"
|
||||
task_data: dict
|
||||
client: ClientConfig
|
||||
model: str
|
||||
sampling: SamplingConfig
|
||||
|
||||
|
||||
class RunResponse(BaseResponse):
|
||||
"""The end of a run whose traces already streamed as deltas (`env.delta`)."""
|
||||
|
||||
head: dict | None = None
|
||||
"""The rollout's episode without its traces — its standing (`id`/`env`/`errors`,
|
||||
carrying episode-level errors even when no trace minted); task-specific data
|
||||
preserved in `model_extra`."""
|
||||
|
||||
traces: list[TraceSummary] = Field(default_factory=list)
|
||||
"""The finished traces in episode order, with the sizes the client's assembly
|
||||
must match."""
|
||||
Vendored
+280
@@ -0,0 +1,280 @@
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from typing import Protocol
|
||||
|
||||
import msgpack
|
||||
import zmq
|
||||
import zmq.asyncio
|
||||
from verifiers.v1.clients import ModelContext
|
||||
from verifiers.v1.configs.env import EnvConfig
|
||||
from verifiers.v1.configs.sampling import SamplingConfig
|
||||
from verifiers.v1.episode import Episode
|
||||
from verifiers.v1.task import Task
|
||||
from verifiers.v1.utils.loaders import load_environment
|
||||
|
||||
from prime_rl.env.delta import DeltaStreamer, TraceSummary, dump, pack
|
||||
from prime_rl.env.encoding import msgpack_encoder
|
||||
from prime_rl.env.types import (
|
||||
BaseResponse,
|
||||
CancelRequest,
|
||||
CancelResponse,
|
||||
HealthResponse,
|
||||
RunRequest,
|
||||
RunResponse,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class EpisodeHook(Protocol):
|
||||
"""Takes finished episodes' per-token training arrays (routing rows, sampling masks,
|
||||
top-k heads) before the episodes leave the worker."""
|
||||
|
||||
def keep(self, episode: Episode, sampling: SamplingConfig) -> None:
|
||||
"""Keep the episode's arrays; may leave references to them in `trace.info`.
|
||||
Runs off the event loop, before the episode's final flush."""
|
||||
|
||||
def discard(self, episode: Episode) -> None:
|
||||
"""Free what `keep` kept for an episode that was not delivered."""
|
||||
|
||||
|
||||
_episode_hook: EpisodeHook | None = None
|
||||
|
||||
LATE_CANCEL_SECONDS = 10.0
|
||||
"""How long a delivered episode stays discardable: a client whose caller cancels the run
|
||||
after the reply left drops the reply and sends a cancel right away."""
|
||||
|
||||
|
||||
def set_episode_hook(hook: EpisodeHook | None) -> None:
|
||||
"""Install a hook that keeps finished episodes' training arrays. Streamed nodes never
|
||||
carry them, so the hook is the only way they leave the worker. Every episode it
|
||||
keeps is either delivered in its run's reply or handed back to `discard`, and so is
|
||||
a delivered one whose client cancels the run within `LATE_CANCEL_SECONDS`."""
|
||||
global _episode_hook
|
||||
_episode_hook = hook
|
||||
|
||||
|
||||
class _Keeping:
|
||||
"""One episode's `keep`, run off the event loop. A failed or abandoned `keep` hands
|
||||
the episode to `discard` exactly once, and only after `keep` has returned: in the
|
||||
thread when `keep` finishes last, else in `abandon`."""
|
||||
|
||||
def __init__(self, hook: EpisodeHook, episode: Episode) -> None:
|
||||
self.hook = hook
|
||||
self.episode = episode
|
||||
self._lock = threading.Lock()
|
||||
self._kept = False
|
||||
self._abandoned = False
|
||||
|
||||
def run(self, sampling: SamplingConfig) -> None:
|
||||
try:
|
||||
self.hook.keep(self.episode, sampling)
|
||||
except BaseException:
|
||||
self.hook.discard(self.episode)
|
||||
raise
|
||||
with self._lock:
|
||||
self._kept = True
|
||||
discard = self._abandoned
|
||||
if discard:
|
||||
self.hook.discard(self.episode)
|
||||
|
||||
def abandon(self) -> None:
|
||||
with self._lock:
|
||||
self._abandoned = True
|
||||
discard = self._kept
|
||||
if discard:
|
||||
self.hook.discard(self.episode)
|
||||
|
||||
|
||||
class EnvWorker:
|
||||
"""Execute episodes through one Verifiers env and stream their traces over ZMQ."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: EnvConfig,
|
||||
address: str,
|
||||
max_concurrent: int | None,
|
||||
) -> None:
|
||||
self.address = address
|
||||
self.taskset_id = config.taskset.id
|
||||
self.env = load_environment(config)
|
||||
self.task_cls = type(self.env.taskset).task_type()
|
||||
self.data_cls = self.task_cls.data_type()
|
||||
# A dispatched task is its client-side model_dump(): a field excluded from
|
||||
# serialization would vanish on the wire and rebuild silently defaulted, so
|
||||
# refuse to serve such a taskset.
|
||||
excluded = [name for name, field in self.data_cls.model_fields.items() if field.exclude]
|
||||
if excluded:
|
||||
raise ValueError(
|
||||
f"{self.data_cls.__name__} excludes {excluded} from serialization — "
|
||||
"a served task must survive the wire whole (drop exclude=True)"
|
||||
)
|
||||
# This worker's episode bound (`serve.max_concurrent`), spanning requests.
|
||||
self._gate = asyncio.Semaphore(max_concurrent) if max_concurrent else None
|
||||
# In-flight run tasks by wire request_id, so a `cancel` can abort them
|
||||
self._running: dict[str, asyncio.Task] = {}
|
||||
# Episodes the hook kept, by run request, until their reply is sent.
|
||||
self._kept: dict[bytes, tuple[EpisodeHook, Episode]] = {}
|
||||
self._delivered: dict[str, tuple[float, EpisodeHook, Episode]] = {}
|
||||
"""Recently delivered kept episodes, oldest first, for a cancel that arrives late."""
|
||||
self.ctx = zmq.asyncio.Context()
|
||||
self.frontend = self.ctx.socket(zmq.ROUTER)
|
||||
self.frontend.setsockopt(zmq.ROUTER_MANDATORY, 1)
|
||||
self.frontend.setsockopt(zmq.SNDHWM, 0)
|
||||
self.frontend.setsockopt(zmq.RCVHWM, 0)
|
||||
self.frontend.setsockopt(zmq.LINGER, 0)
|
||||
self.frontend.bind(self.address)
|
||||
# Resolve the concrete endpoint — when bound to an OS-assigned port
|
||||
# (address ending in `:0`), this is how we learn the actual port.
|
||||
self.address = self.frontend.getsockopt_string(zmq.LAST_ENDPOINT)
|
||||
|
||||
def _build_task(self, task_data: dict) -> Task:
|
||||
"""Rebuild a request's task from its wire data: validate into the taskset's
|
||||
declared `TaskData` type and wrap it in the declared `Task` with the config's
|
||||
task subtree — the same construction the taskset's own `load()` performs. The
|
||||
client owns the taskset; this worker never `load()`s data, so pool workers
|
||||
don't each pull the dataset."""
|
||||
data = self.data_cls.model_validate(task_data)
|
||||
return self.task_cls(data, self.env.config.taskset.task)
|
||||
|
||||
async def _run(self, req: RunRequest, client_id: bytes, request_id: bytes) -> RunResponse:
|
||||
# No client is built or cached here — each rollout constructs its own from
|
||||
# `req.client` and closes it, so a training run's changing model leaves nothing behind.
|
||||
ctx = ModelContext(client=req.client, model=req.model, sampling=req.sampling)
|
||||
(slot,) = self.env.slots(self._build_task(req.task_data))
|
||||
|
||||
async def send_delta(delta: dict) -> None:
|
||||
await self.frontend.send_multipart([client_id, request_id, b"delta", pack(delta)], copy=False)
|
||||
|
||||
# The gate spans requests: it bounds this worker's episodes in flight. The
|
||||
# streamer ships each trace as it changes; the reply below carries only the rest.
|
||||
hook = _episode_hook
|
||||
async with DeltaStreamer(lambda: slot.traces, send_delta) as streamer:
|
||||
episode = await self.env.run_slot(slot, ctx, self._gate, on_trace=streamer.watch)
|
||||
if hook is not None:
|
||||
# Before the final flush, so what the hook writes to the traces streams.
|
||||
keeping = _Keeping(hook, episode)
|
||||
try:
|
||||
# The thread runs to the end even when this await is cancelled.
|
||||
await asyncio.shield(asyncio.to_thread(keeping.run, ctx.sampling))
|
||||
except asyncio.CancelledError:
|
||||
keeping.abandon()
|
||||
raise
|
||||
self._kept[request_id] = (hook, episode)
|
||||
return RunResponse(
|
||||
head=dump(episode, exclude={"traces"}),
|
||||
traces=[
|
||||
TraceSummary(id=trace.id, nodes=len(trace.nodes), calls=len(trace.calls)) for trace in episode.traces
|
||||
],
|
||||
)
|
||||
|
||||
async def _handle(self, client_id: bytes, request_id: bytes, method: bytes, payload: bytes) -> None:
|
||||
try:
|
||||
route = method.decode()
|
||||
raw = msgpack.unpackb(payload, raw=False)
|
||||
if route == "health":
|
||||
response: BaseResponse = HealthResponse()
|
||||
elif route == "run":
|
||||
# Registered in the dispatch loop, before this task first runs
|
||||
try:
|
||||
response = await self._run(RunRequest.model_validate(raw), client_id, request_id)
|
||||
finally:
|
||||
self._running.pop(request_id.decode(), None)
|
||||
elif route == "cancel":
|
||||
target = CancelRequest.model_validate(raw).request_id
|
||||
running = self._running.get(target)
|
||||
if running is not None:
|
||||
running.cancel()
|
||||
get_logger().info(f"Cancelled run on client request request_id={target}")
|
||||
# The client dropped the reply, or will: nothing will take the arrays.
|
||||
self._expire_delivered()
|
||||
kept = self._kept.pop(target.encode(), None)
|
||||
if kept is None and (late := self._delivered.pop(target, None)):
|
||||
kept = late[1:]
|
||||
if kept is not None:
|
||||
hook, episode = kept
|
||||
hook.discard(episode)
|
||||
response = CancelResponse(cancelled=running is not None)
|
||||
else:
|
||||
response = BaseResponse(success=False, error=f"unknown method {route!r}")
|
||||
except asyncio.CancelledError:
|
||||
# An aborted run still replies so broker/client accounting stays
|
||||
# exact; the requesting client has already given up on the result
|
||||
response = BaseResponse(success=False, error="Cancelled: rollout aborted")
|
||||
except Exception as e: # a failed request is data, not a crash — report and keep serving
|
||||
get_logger().opt(exception=True).warning(
|
||||
f"Failed request method={method.decode(errors='replace')} - {type(e).__name__}: {e}"
|
||||
)
|
||||
response = BaseResponse(success=False, error=f"{type(e).__name__}: {e}")
|
||||
try:
|
||||
data = msgpack.packb(
|
||||
response.model_dump(mode="python"),
|
||||
default=msgpack_encoder,
|
||||
use_bin_type=True,
|
||||
)
|
||||
except Exception as e:
|
||||
# Encoding failures must also reply so clients don't wait indefinitely.
|
||||
get_logger().opt(exception=True).warning(f"Failed to encode response - {type(e).__name__}: {e}")
|
||||
response = BaseResponse(success=False, error=f"{type(e).__name__}: {e}")
|
||||
data = msgpack.packb(response.model_dump(), use_bin_type=True)
|
||||
delivered = False
|
||||
try:
|
||||
await self.frontend.send_multipart([client_id, request_id, b"reply", data], copy=False)
|
||||
delivered = response.success
|
||||
except zmq.ZMQError as e:
|
||||
get_logger().warning(f"Failed to send response - {type(e).__name__}: {e}")
|
||||
finally:
|
||||
# Also on a cancel (shutdown) while the reply is sending.
|
||||
kept = self._kept.pop(request_id, None)
|
||||
if kept is not None:
|
||||
hook, episode = kept
|
||||
if delivered:
|
||||
self._remember_delivered(request_id.decode(), hook, episode)
|
||||
else:
|
||||
hook.discard(episode)
|
||||
|
||||
def _remember_delivered(self, request_id: str, hook: EpisodeHook, episode: Episode) -> None:
|
||||
self._delivered[request_id] = (time.monotonic(), hook, episode)
|
||||
asyncio.get_running_loop().call_later(LATE_CANCEL_SECONDS, self._expire_delivered)
|
||||
|
||||
def _expire_delivered(self) -> None:
|
||||
now = time.monotonic()
|
||||
for request_id, (delivered_at, _, _) in list(self._delivered.items()):
|
||||
if now - delivered_at < LATE_CANCEL_SECONDS:
|
||||
break
|
||||
del self._delivered[request_id]
|
||||
|
||||
async def run(self) -> None:
|
||||
get_logger().info(f"Started env worker taskset={self.taskset_id} address={self.address}")
|
||||
poller = zmq.asyncio.Poller()
|
||||
poller.register(self.frontend, zmq.POLLIN)
|
||||
tasks: set[asyncio.Task] = set()
|
||||
# Shared servers and the interception live across requests in this worker.
|
||||
async with self.env.serving():
|
||||
try:
|
||||
while True:
|
||||
events = dict(await poller.poll(timeout=100))
|
||||
if self.frontend not in events:
|
||||
continue
|
||||
frames = await self.frontend.recv_multipart()
|
||||
if len(frames) != 4:
|
||||
get_logger().warning(f"Dropped malformed request frames={len(frames)} expected=4")
|
||||
continue
|
||||
client_id, request_id, method, payload = frames
|
||||
task = asyncio.create_task(self._handle(client_id, request_id, method, payload))
|
||||
if method == b"run":
|
||||
# Register at dispatch, not handler start: a cancel
|
||||
# processed ahead of the run's handler task must still
|
||||
# find its target (ZMQ preserves per-client frame
|
||||
# order, so the run always arrives first)
|
||||
self._running[request_id.decode()] = task
|
||||
tasks.add(task)
|
||||
task.add_done_callback(tasks.discard)
|
||||
except (asyncio.CancelledError, KeyboardInterrupt):
|
||||
pass
|
||||
finally:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
self.frontend.close()
|
||||
self.ctx.term()
|
||||
get_logger().info(f"Stopped env worker taskset={self.taskset_id} address={self.address}")
|
||||
+35
-24
@@ -7,7 +7,7 @@ admits episodes under the adaptive ``ConcurrencyController``, fed by the
|
||||
measurements and are never cancelled on load - a controller cut only blocks admission
|
||||
until the pool drains.
|
||||
|
||||
Env servers belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
|
||||
Env worker pools belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
|
||||
``rl``: a source without an explicit ``serve.address`` is found through the address file
|
||||
its server publishes; one with an address is reached directly."""
|
||||
|
||||
@@ -56,7 +56,7 @@ class EvalRunner:
|
||||
def __init__(self, config: EvalConfig | SFTOnlineEvalConfig, *, run_dir: Path) -> None:
|
||||
self.config = config
|
||||
self.run_dir = run_dir
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
intercept_vf_logging(logger="verifiers.v1", level=config.log.level)
|
||||
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
@@ -77,7 +77,7 @@ class EvalRunner:
|
||||
|
||||
# The heartbeat is beaten only by landed episodes — the first episode is its
|
||||
# first beat. No startup ping on purpose: the run-start to first-episode gap
|
||||
# (pool boot, env servers, the first episode's full duration) would otherwise
|
||||
# (pool boot, env worker pools, the first episode's full duration) would otherwise
|
||||
# sit inside the ping stream as an abnormally long silence and flip a healthy
|
||||
# run stale. Until then the heartbeat has simply never been pinged.
|
||||
if config.heartbeat is not None:
|
||||
@@ -260,37 +260,48 @@ class EvalRunner:
|
||||
|
||||
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."""
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict. Aggregation
|
||||
runs in worker threads, as it takes seconds for a large epoch."""
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
|
||||
await monitors.log_eval_epoch(batch.env_name, batch.step, batch.episodes.vf_episodes)
|
||||
|
||||
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)
|
||||
effective_episodes = await asyncio.to_thread(lambda: effective.vf_episodes)
|
||||
if effective_episodes:
|
||||
await monitors.log(effective_episodes, batch.step, "eval", "effective")
|
||||
annotations = await asyncio.to_thread(stamp_batch, effective_episodes, batch.step)
|
||||
await monitors.log_annotations(annotations)
|
||||
await monitors.log_eval_epoch(batch.env_name, batch.step, episodes.vf_episodes)
|
||||
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
def epoch_metrics() -> dict[str, float]:
|
||||
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 |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
return metrics
|
||||
|
||||
await monitors.log(await asyncio.to_thread(epoch_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
|
||||
await asyncio.to_thread(self.log_eval_batch, batch, total_attempts=total_attempts, elapsed=elapsed)
|
||||
|
||||
def log_eval_batch(self, batch: EvalBatch, *, total_attempts: int, elapsed: float) -> None:
|
||||
episodes = batch.episodes
|
||||
eff, full = episodes.effective.metrics, episodes.metrics
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
|
||||
@@ -24,6 +24,7 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_routed_experts_cut_loaded_prefix_hits()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_glm5_next_kda_conv_weights()
|
||||
monkey_patch_online_mxfp8_moe_keep_kernel_on_reload()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_skip_prompt_routing_for_chat()
|
||||
@@ -314,6 +315,34 @@ def monkey_patch_online_mxfp8_moe_keep_kernel_on_reload():
|
||||
Mxfp8OnlineMoEMethod._setup_kernel = _setup_kernel
|
||||
|
||||
|
||||
def monkey_patch_glm5_next_kda_conv_weights():
|
||||
"""Make GLM-5.3 Flash's merged KDA conv weight a view of the q/k/v conv weights.
|
||||
|
||||
vLLM builds `_merged_conv_weight` once as a `torch.cat` copy, so weight updates never reach it.
|
||||
After loading, store the three weights as slices of one buffer and point the cache at it;
|
||||
reloads copy into parameter storage in place, so updates land in the buffer.
|
||||
|
||||
Remove when vLLM keeps the q/k/v conv weights in one merged parameter
|
||||
(https://github.com/vllm-project/vllm/pull/60991).
|
||||
"""
|
||||
from vllm.models.glm5next.common.kda import Glm5NextLinearAttention
|
||||
from vllm.models.glm5next.common.model import Glm5NextForCausalLM, Glm5NextForConditionalGeneration
|
||||
|
||||
@torch.no_grad()
|
||||
def process_weights_after_loading(self) -> None:
|
||||
for module in self.modules():
|
||||
if isinstance(module, Glm5NextLinearAttention):
|
||||
convs = (module.q_conv1d, module.k_conv1d, module.v_conv1d)
|
||||
merged = torch.cat([conv.weight.data for conv in convs])
|
||||
for conv, part in zip(convs, merged.chunk(3)):
|
||||
conv.weight.data = part
|
||||
# merged shape needs to be [3C, K] instead of [3C, 1, K]
|
||||
module._merged_conv_weight = merged.flatten(1)
|
||||
|
||||
Glm5NextForCausalLM.process_weights_after_loading = process_weights_after_loading
|
||||
Glm5NextForConditionalGeneration.process_weights_after_loading = process_weights_after_loading
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ WORKER_EXTENSION_CLS = {
|
||||
"nccl": "prime_rl.inference.vllm.worker.nccl.NCCLWeightUpdateWorker",
|
||||
"filesystem": "prime_rl.inference.vllm.worker.filesystem.FileSystemWeightUpdateWorker",
|
||||
"nixl": "prime_rl.inference.vllm.worker.nixl.NIXLWeightUpdateWorker",
|
||||
"modelexpress": "prime_rl.inference.vllm.worker.modelexpress.ModelExpressWeightUpdateWorker",
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +64,15 @@ async def update_weights(request: Request):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/update_weights_from_modelexpress")
|
||||
async def update_weights_from_modelexpress(request: Request):
|
||||
data = await request.json()
|
||||
client = engine_client(request)
|
||||
await client.collective_rpc("update_weights_from_modelexpress", args=(data["version_uid"],))
|
||||
await client.update_weight_version(str(data["weight_version"]))
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request, weight_version: str):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
@@ -118,10 +128,10 @@ async def init_broadcaster(request: Request):
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
session_id = data.get("session_id", "default")
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
|
||||
)
|
||||
args = (host, port, rank_offset, inference_world_size, timeout, session_id)
|
||||
if "staging_buffer_bytes" in data:
|
||||
args += (data["staging_buffer_bytes"], data["staging_buffers_count"])
|
||||
await engine_client(request).collective_rpc("init_broadcaster", args=args)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""vLLM extension using the public ModelExpress generator client."""
|
||||
|
||||
import atexit
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
import torch
|
||||
from modelexpress_rl import (
|
||||
ModelExpressGeneratorClient,
|
||||
ModelExpressGeneratorConfig,
|
||||
VllmGeneratorContext,
|
||||
WeightSource,
|
||||
WeightVersionRef,
|
||||
)
|
||||
from torch import nn
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
else:
|
||||
Worker = object
|
||||
|
||||
|
||||
class ModelExpressWeightUpdateWorker(Worker):
|
||||
def liveness_probe(self) -> None:
|
||||
return None
|
||||
|
||||
def init_broadcaster(
|
||||
self,
|
||||
host,
|
||||
port,
|
||||
rank_offset,
|
||||
inference_world_size,
|
||||
timeout,
|
||||
session_id="default",
|
||||
staging_buffer_bytes=None,
|
||||
staging_buffers_count=1,
|
||||
):
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.trainer.models import get_custom_causal_lm_cls
|
||||
from prime_rl.trainer.models.conversion_ops import apply_prime_to_hf
|
||||
|
||||
# The trainer publishes PrimeRL-native tensors, so the conversion chain must come from the
|
||||
# PrimeRL config class registered on import above, not vLLM's own config class.
|
||||
model_config = self.model_runner.model_config
|
||||
hf_config = AutoConfig.from_pretrained(model_config.model, trust_remote_code=model_config.trust_remote_code)
|
||||
chain = get_custom_causal_lm_cls(hf_config).conversion_chain(hf_config)
|
||||
worker_id = f"{session_id}:{rank_offset + self.rank}"
|
||||
self._generator = ModelExpressGeneratorClient.initialize(
|
||||
ModelExpressGeneratorConfig(
|
||||
engine_context=VllmGeneratorContext(
|
||||
model=cast(nn.Module, self.model_runner.get_model()),
|
||||
vllm_config=self.vllm_config,
|
||||
convert_native_to_hf=(lambda tensors: apply_prime_to_hf(tensors, chain)) if chain else None,
|
||||
),
|
||||
model_name=self.model_runner.model_config.model,
|
||||
server_url=f"{host}:{port}",
|
||||
source_order=(WeightSource.TRAINER,),
|
||||
worker_id=worker_id,
|
||||
staging_buffer_bytes=staging_buffer_bytes,
|
||||
staging_buffers_count=staging_buffers_count,
|
||||
)
|
||||
)
|
||||
atexit.register(self._generator.close)
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_modelexpress(self, version_uid: str) -> None:
|
||||
if not version_uid:
|
||||
raise ValueError("modelexpress requires version_uid")
|
||||
version = WeightVersionRef(version_uid)
|
||||
staged = self._generator.stage_weight(version=version)
|
||||
try:
|
||||
self._generator.apply_weight(staged)
|
||||
finally:
|
||||
staged.release()
|
||||
@@ -15,13 +15,12 @@ from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
|
||||
from prime_rl.configs.monitors import (
|
||||
FileMonitorConfig,
|
||||
PrimeEvalMonitorConfig,
|
||||
PrimeTrainMonitorConfig,
|
||||
PrimeMonitorConfig,
|
||||
WandbMonitorConfig,
|
||||
)
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.file import FileMonitor
|
||||
from prime_rl.monitors.prime import PrimeEvalMonitor, PrimeTrainMonitor
|
||||
from prime_rl.monitors.prime import PrimeMonitor
|
||||
from prime_rl.monitors.wandb import WandbMonitor
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
@@ -32,8 +31,7 @@ if TYPE_CHECKING:
|
||||
__all__ = [
|
||||
"Monitor",
|
||||
"WandbMonitor",
|
||||
"PrimeTrainMonitor",
|
||||
"PrimeEvalMonitor",
|
||||
"PrimeMonitor",
|
||||
"FileMonitor",
|
||||
"setup",
|
||||
"get",
|
||||
@@ -47,7 +45,7 @@ MONITORS: list[Monitor] = []
|
||||
|
||||
async def setup(
|
||||
wandb: WandbMonitorConfig | None = None,
|
||||
prime: PrimeTrainMonitorConfig | PrimeEvalMonitorConfig | None = None,
|
||||
prime: PrimeMonitorConfig | None = None,
|
||||
file: FileMonitorConfig | None = None,
|
||||
*,
|
||||
output_dir: Path,
|
||||
@@ -69,10 +67,10 @@ async def setup(
|
||||
return
|
||||
|
||||
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
|
||||
if isinstance(prime, PrimeTrainMonitorConfig):
|
||||
monitors.append(("prime", PrimeTrainMonitor(prime), dict(config=run_config, output_dir=output_dir)))
|
||||
elif isinstance(prime, PrimeEvalMonitorConfig):
|
||||
monitors.append(("prime", PrimeEvalMonitor(prime), dict(config=run_config, output_dir=output_dir)))
|
||||
if prime is not None:
|
||||
monitors.append(
|
||||
("prime", PrimeMonitor(prime), dict(config=run_config, output_dir=output_dir, producer=producer))
|
||||
)
|
||||
if wandb is not None:
|
||||
monitors.append(
|
||||
(
|
||||
|
||||
@@ -58,7 +58,7 @@ class Monitor(ABC):
|
||||
Monitors that only carry scalars ignore them."""
|
||||
|
||||
async def log_live(self, events: list[dict[str, Any]]) -> None:
|
||||
"""Log the env servers' stream of in-flight traces: ``{"delta", "dispatch"}`` for
|
||||
"""Log the env worker pools' stream of in-flight traces: ``{"delta", "dispatch"}`` for
|
||||
each delta as it arrived, ``{"done": trace_id}`` when a trace's episode finished.
|
||||
Monitors that only carry finished work ignore it."""
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ from prime_rl.configs.monitors import FileMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
|
||||
from prime_rl.monitors.file.traces.index import index_row
|
||||
from prime_rl.monitors.file.traces.index import index_record, index_row
|
||||
from prime_rl.monitors.file.traces.live import get_live_dir, get_pending_dir
|
||||
from prime_rl.monitors.file.traces.update import update_index_row
|
||||
from prime_rl.utils.pathing import get_eval_plan_path, get_file_monitor_dir
|
||||
@@ -121,8 +121,7 @@ class FileMonitor(Monitor):
|
||||
appends.pop(path, None)
|
||||
path.unlink(missing_ok=True)
|
||||
continue
|
||||
# Training arrays stay on the wire; live records only need display data.
|
||||
line = {key: value for key, value in delta.items() if key != "routing_repairs"}
|
||||
line = dict(delta)
|
||||
if "nodes" in line:
|
||||
line["nodes"] = [
|
||||
{key: _live_value(value) for key, value in node.items() if key not in LIVE_NODE_EXCLUDE}
|
||||
@@ -160,14 +159,17 @@ class FileMonitor(Monitor):
|
||||
|
||||
def write() -> None:
|
||||
stream, index = self._stream(get_trace_stream(self.output_dir))
|
||||
# An index row goes out with every episode: summarising the record here,
|
||||
# while it is already in hand, saves every reader from parsing a stream
|
||||
# An index row goes out with every episode: summarising the episode here,
|
||||
# while it is still in hand, saves every reader from parsing a stream
|
||||
# that outgrows memory long before the run does.
|
||||
for episode in episodes:
|
||||
record = episode.to_record(float_decimals=self.config.float_decimals)
|
||||
chunk, offset = stream.append(orjson.dumps(record, default=str, option=OPTS))
|
||||
# `to_json` encodes in short steps, so a long episode never holds the GIL
|
||||
# (and the event loop) for the whole encode.
|
||||
line = episode.to_json(float_decimals=self.config.float_decimals)
|
||||
chunk, offset = stream.append(line, b"\n")
|
||||
self._logged += 1
|
||||
index.write(orjson.dumps(index_row(self._logged, record, chunk, offset), default=str, option=OPTS))
|
||||
row = index_row(self._logged, index_record(episode), chunk, offset)
|
||||
index.write(orjson.dumps(row, default=str, option=OPTS))
|
||||
stream.flush()
|
||||
index.flush()
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ def get_trace_stream(output_dir: Path) -> Path:
|
||||
|
||||
|
||||
def get_annotations_dir(output_dir: Path) -> Path:
|
||||
"""One stream per producer of trace updates: orch ship-time facts, trainer streams."""
|
||||
"""One stream per producer of trace updates: orchestrator ship-time facts, trainer streams."""
|
||||
return get_trace_dir(output_dir) / "annotations"
|
||||
|
||||
|
||||
|
||||
@@ -78,13 +78,16 @@ class ChunkedJsonl:
|
||||
self.file = open(chunk_path(directory, self.number), "ab")
|
||||
self.size = self.file.tell()
|
||||
|
||||
def append(self, line: bytes) -> tuple[int, int]:
|
||||
"""Write one line; returns ``(chunk, offset)``, the address a reader seeks to."""
|
||||
if self.size and self.size + len(line) > self.max_bytes:
|
||||
def append(self, *parts: bytes) -> tuple[int, int]:
|
||||
"""Write one line, given in parts so a long line is never copied to add its
|
||||
newline; returns ``(chunk, offset)``, the address a reader seeks to."""
|
||||
size = sum(map(len, parts))
|
||||
if self.size and self.size + size > self.max_bytes:
|
||||
self._roll()
|
||||
offset = self.size
|
||||
self.file.write(line)
|
||||
self.size += len(line)
|
||||
for part in parts:
|
||||
self.file.write(part)
|
||||
self.size += size
|
||||
return self.number, offset
|
||||
|
||||
def flush(self) -> None:
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
"""The episode index - one compact row per episode, so a reader never has to parse
|
||||
the stream to browse it.
|
||||
|
||||
The file monitor writes a row as each episode lands, when the record is already in
|
||||
hand and summarising it is nearly free, and records the chunk and byte offset it wrote
|
||||
the episode at so a reader can seek straight to one. A stream another producer wrote
|
||||
has no index, so its reader derives the same rows itself.
|
||||
The file monitor writes a row as each episode lands, while the episode is still in
|
||||
hand, and records the chunk and byte offset it wrote the episode at so a reader can
|
||||
seek straight to one. A stream another producer wrote has no index, so its reader
|
||||
derives the same rows itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
def index_record(episode: vf.Episode) -> dict[str, Any]:
|
||||
"""The part of the episode's record (`to_record`) that `summarize_episode` reads:
|
||||
everything but the nodes and model calls. Built one trace at a time, so no single
|
||||
call holds the GIL for a whole long episode."""
|
||||
record = episode.model_dump(mode="json", exclude={"traces"}, exclude_none=True)
|
||||
record["traces"] = [
|
||||
trace.model_dump(mode="json", exclude={"nodes", "calls"}, exclude_none=True) for trace in episode.traces
|
||||
]
|
||||
return record
|
||||
|
||||
|
||||
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
|
||||
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
|
||||
"""Flatten a trace timing tree to phase -> seconds."""
|
||||
if isinstance(obj.get("duration"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
|
||||
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
|
||||
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
|
||||
for key, value in obj.items():
|
||||
if isinstance(value, dict):
|
||||
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
|
||||
@@ -29,21 +45,6 @@ def episode_kind(rec: dict) -> str:
|
||||
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
|
||||
|
||||
|
||||
TRUNCATING_STOPS = frozenset(
|
||||
{"max_turns", "max_input_tokens", "max_output_tokens", "max_total_tokens", "max_turn_tokens", "compaction_failed"}
|
||||
)
|
||||
"""The stop conditions ``verifiers.v1.Trace.is_truncated`` counts as truncation."""
|
||||
|
||||
|
||||
def trace_truncated(trace: dict) -> bool:
|
||||
"""``Trace.is_truncated`` for a dumped trace: a framework limit stopped it, or its
|
||||
last successful model call ran out of length."""
|
||||
if trace.get("stop_condition") in TRUNCATING_STOPS:
|
||||
return True
|
||||
last = next((call for call in reversed(trace.get("calls") or []) if call.get("error") is None), None)
|
||||
return bool(last and last.get("finish_reason") == "length")
|
||||
|
||||
|
||||
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"""One index row: what the table, the filters, the chart and the sort need.
|
||||
|
||||
@@ -52,31 +53,18 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
rewards, advantages = [], []
|
||||
input_tokens = rec.get("num_input_tokens")
|
||||
output_tokens = rec.get("num_output_tokens")
|
||||
turns = branches = 0
|
||||
branches = 0
|
||||
stop_condition = None
|
||||
truncated = False
|
||||
timeout = bool(rec.get("is_timeout"))
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
costs: list[float] = []
|
||||
for trace in rec.get("traces") or []:
|
||||
costs.extend(
|
||||
usage["cost"]
|
||||
for call in trace.get("calls") or []
|
||||
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
|
||||
)
|
||||
nodes = trace.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if "parent" in node}
|
||||
branches += max(0, len(nodes) - len(parents))
|
||||
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
|
||||
rewards.append(
|
||||
sum(
|
||||
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
|
||||
for r in trace["rewards"].values()
|
||||
if isinstance(r, dict)
|
||||
)
|
||||
)
|
||||
branches += trace.get("num_branches") or 0
|
||||
# skip reward-less seats (e.g. a judge) in the episode mean
|
||||
if trace.get("rewards") and isinstance(trace.get("reward"), (int, float)):
|
||||
rewards.append(trace["reward"])
|
||||
for name, r in (trace.get("rewards") or {}).items():
|
||||
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
|
||||
reward_parts.setdefault(name, []).append(r["score"])
|
||||
@@ -88,18 +76,15 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
advantage = (trace.get("info") or {}).get("advantage")
|
||||
if advantage is not None:
|
||||
advantages.append(advantage)
|
||||
for node in nodes:
|
||||
if node.get("sampled"):
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
truncated = truncated or trace_truncated(trace)
|
||||
truncated = truncated or bool(trace.get("is_truncated"))
|
||||
timeout = timeout or bool(trace.get("is_timeout"))
|
||||
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
|
||||
"timing": timing,
|
||||
"cost": sum(costs) if costs else None,
|
||||
"cost": (rec.get("usage") or {}).get("cost"),
|
||||
"line": line,
|
||||
"offset": offset,
|
||||
"id": rec.get("id"),
|
||||
@@ -115,7 +100,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"advantage": sum(advantages) / len(advantages) if advantages else None,
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"turns": turns,
|
||||
"turns": rec.get("num_turns"),
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
"truncated": truncated,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Live traces: the in-flight rollouts, one file of deltas per trace.
|
||||
|
||||
Env servers stream every rollout as it happens (``verifiers.v1.serve.delta``): the
|
||||
Env worker pools stream every rollout as it happens (``prime_rl.env.delta``): the
|
||||
trace's header when it is minted, then each committed turn and each phase change. The
|
||||
file monitor appends those deltas to ``traces/live/<trace_id>.jsonl`` — the first line
|
||||
also carries the ``dispatch`` identity (kind, env, group, task, step) — and deletes the
|
||||
@@ -24,8 +24,8 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import orjson
|
||||
from verifiers.v1.serve import EpisodeAssembly
|
||||
|
||||
from prime_rl.env import EpisodeAssembly
|
||||
from prime_rl.monitors.file.traces import get_trace_dir
|
||||
|
||||
STAGES = ("pending", "boot", "setup", "running", "finalize", "scoring", "done", "error")
|
||||
@@ -182,26 +182,21 @@ def message_text(message: dict[str, Any]) -> str:
|
||||
|
||||
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
|
||||
calls = record.get("calls") or []
|
||||
usage = [call.get("usage") or {} for call in calls]
|
||||
# The newest node is usually a tool result; the assistant's latest words say more.
|
||||
last = ""
|
||||
for node in reversed(record.get("nodes") or []):
|
||||
message = node.get("message") or {}
|
||||
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
|
||||
break
|
||||
costs = [u["cost"] for u in usage if u.get("cost") is not None]
|
||||
nodes = record.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
|
||||
return {
|
||||
"trace": record.get("id"),
|
||||
"agent": (record.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(record),
|
||||
"turns": len(calls),
|
||||
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
|
||||
"turns": record.get("num_turns"),
|
||||
"branches": record.get("num_branches"),
|
||||
"input_tokens": record.get("num_input_tokens"),
|
||||
"output_tokens": record.get("num_output_tokens"),
|
||||
"cost": sum(costs) if costs else None,
|
||||
"cost": (record.get("usage") or {}).get("cost"),
|
||||
"stop_condition": record.get("stop_condition"),
|
||||
"errors": len(record.get("errors") or []),
|
||||
"pending": len(record.get("pending") or []),
|
||||
|
||||
+196
-239
@@ -3,19 +3,25 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import atexit
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import prime_runs as pr
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
from prime_runs.config import Config
|
||||
|
||||
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import PrimeMonitorConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.supervised import SupervisedTrainerConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.links import PRIME_EVAL_LINKS, PRIME_LINKS, publish_link, register_links
|
||||
from prime_rl.utils.links import publish_link, register_links
|
||||
from prime_rl.utils.pathing import get_platform_run_path
|
||||
from prime_rl.utils.record import read_record, update_record, write_record
|
||||
from prime_rl.utils.record import update_record
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -29,47 +35,10 @@ EVAL_ID_VAR = "PRIME_RUNS_EVAL_ID"
|
||||
FINISH_TIMEOUT = 60.0
|
||||
|
||||
|
||||
def write_platform_record(output_dir: Path, record: dict[str, Any]) -> None:
|
||||
"""Leave the run's platform identity in the run directory for the dashboard's
|
||||
"View on Prime" link."""
|
||||
write_record(get_platform_run_path(output_dir), record)
|
||||
|
||||
|
||||
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
|
||||
return read_record(get_platform_run_path(output_dir))
|
||||
|
||||
|
||||
def _merge_platform_record(
|
||||
output_dir: Path,
|
||||
merge: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
) -> None:
|
||||
"""Locked read-modify-write of the platform record: the trainer and the
|
||||
online-eval process merge into the SAME run.json. Best-effort, see
|
||||
``update_record``."""
|
||||
update_record(get_platform_run_path(output_dir), merge)
|
||||
|
||||
|
||||
def update_platform_record(output_dir: Path, update: dict[str, Any]) -> None:
|
||||
"""Best-effort locked read-modify-write of the platform record: `update`
|
||||
overlays the current record (preserving keys it doesn't set). Use for
|
||||
every writer that shares the file — a naive overwrite drops concurrent
|
||||
writers' keys."""
|
||||
_merge_platform_record(output_dir, lambda record: {**record, **update})
|
||||
|
||||
|
||||
OFF_HINT = "turn the monitor off with --no-monitors.prime"
|
||||
|
||||
|
||||
def prime_mode() -> str:
|
||||
"""$PRIME_RUNS_MODE when set, else online. Like the W&B monitor, a configured
|
||||
monitor without credentials fails the run instead of leaving it untracked."""
|
||||
if mode := os.getenv(pr.MODE_ENV):
|
||||
return mode
|
||||
if not (os.getenv("PRIME_API_KEY") or PrimeConfig().api_key):
|
||||
raise RuntimeError(
|
||||
f"The prime monitor found no Prime API key. Authenticate with `prime login` (or set PRIME_API_KEY), or {OFF_HINT}"
|
||||
)
|
||||
return "online"
|
||||
NO_KEY = (
|
||||
f"The prime monitor found no Prime API key. Authenticate with `prime login` (or set PRIME_API_KEY), or {OFF_HINT}"
|
||||
)
|
||||
|
||||
|
||||
def _base_url() -> str | None:
|
||||
@@ -79,9 +48,98 @@ def _base_url() -> str | None:
|
||||
return base.rstrip("/").removesuffix("/rft") if base else None
|
||||
|
||||
|
||||
class PrimeTrainMonitor(Monitor):
|
||||
def register(
|
||||
config: RLConfig | OrchestratorConfig | SupervisedTrainerConfig | None,
|
||||
name: str | None,
|
||||
mode: str,
|
||||
id: str | None = None,
|
||||
) -> pr.Run:
|
||||
"""Attach to the platform run ``id``, or register ``config``'s training run with the
|
||||
whole config: an ``rl`` launch's covers the trainer and inference too."""
|
||||
init_kwargs: dict[str, Any]
|
||||
if id is not None:
|
||||
init_kwargs = {"id": id}
|
||||
elif config is None:
|
||||
# The RFT API requires a base model.
|
||||
init_kwargs = {"name": name, "model": "unknown"}
|
||||
else:
|
||||
if isinstance(config, SupervisedTrainerConfig):
|
||||
model = config.model.name
|
||||
# SFT and pretraining train on a dataset, not on environments, and have no rollouts.
|
||||
environments = []
|
||||
training = pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.data.batch_size,
|
||||
seq_len=config.data.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
)
|
||||
else:
|
||||
orchestrator = config.orchestrator if isinstance(config, RLConfig) else config
|
||||
model = orchestrator.model.name
|
||||
environments = [env.env_id for env in orchestrator.train.source]
|
||||
training = pr.TrainingSpec(
|
||||
max_steps=orchestrator.max_steps or 0,
|
||||
batch_size=orchestrator.batch_size,
|
||||
rollouts_per_example=max(
|
||||
(source.group_size for source in orchestrator.train.source), default=orchestrator.train.group_size
|
||||
),
|
||||
seq_len=orchestrator.seq_len,
|
||||
wandb_project=orchestrator.monitors.wandb.project if orchestrator.monitors.wandb else None,
|
||||
)
|
||||
init_kwargs = dict(
|
||||
name=name,
|
||||
model=model,
|
||||
environments=environments,
|
||||
training=training,
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
try:
|
||||
return pr.init(kind="train", mode=mode, base_url=_base_url(), finish_timeout=FINISH_TIMEOUT, **init_kwargs)
|
||||
except (pr.ConfigurationError, pr.APIError) as e:
|
||||
# An attached run's error is the launcher's to explain.
|
||||
if id is not None:
|
||||
raise
|
||||
if "needs an API key" in str(e):
|
||||
raise RuntimeError(NO_KEY) from e
|
||||
# Registering fails without a team, or for a team outside the external-runs allowlist.
|
||||
raise RuntimeError(
|
||||
f"Failed to register the Prime run ({type(e).__name__}: {e}). Select a team with "
|
||||
f"`prime switch` (or set PRIME_TEAM_ID), or {OFF_HINT}"
|
||||
) from e
|
||||
|
||||
|
||||
@contextmanager
|
||||
def launch_run(config: RLConfig | SupervisedTrainerConfig, prime: PrimeMonitorConfig | None) -> Iterator[None]:
|
||||
"""Register the launch's Prime run around starting its components, which attach to
|
||||
it: its id becomes ``$PRL_RUN_ID`` and ``$RUN_ID``. A launch that fails marks the
|
||||
run failed, and one that ends cleanly finishes it once every component exited - the
|
||||
components only flush their attached run. So the process that registers the run
|
||||
supervises the launch: the local ``rl`` or ``sft`` launcher, or a multi-node SLURM
|
||||
job's ``run_owner``. A run a managed launch pre-created (``$RUN_ID``) is the platform's."""
|
||||
if prime is None or os.getenv("RUN_ID") or (os.getenv(pr.MODE_ENV) or "online") != "online":
|
||||
yield
|
||||
return
|
||||
run = register(config, prime.name, "online")
|
||||
os.environ["PRL_RUN_ID"] = os.environ["RUN_ID"] = run.id
|
||||
try:
|
||||
yield
|
||||
except BaseException as e:
|
||||
# A failed component exits the launcher with a SystemExit chained to its error.
|
||||
run.fail(e.__cause__ or e, timeout=FINISH_TIMEOUT)
|
||||
raise
|
||||
run.finish(timeout=FINISH_TIMEOUT)
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs metrics and episodes to the Prime platform through ``prime_runs``.
|
||||
|
||||
A training run's processes log to one Prime training run: the ``rl`` or ``sft``
|
||||
launcher registers it (``launch_run``) and its components attach through ``$RUN_ID``.
|
||||
The process that registered a run finishes it; an attached process only flushes, and
|
||||
a component started without a launcher registers and finishes its own. A standalone eval instead opens one evaluation per env and epoch when
|
||||
the epoch starts (``log_eval_plan``), streams its episodes into it, and finishes
|
||||
it with the epoch's aggregates (``log_eval_epoch``).
|
||||
|
||||
The run handle owns the RFT lifecycle (register or attach, finalize), the
|
||||
per-step metrics POSTs, the episode uploads to Prime Traces, and the
|
||||
terminal status. Delivery is BEST-EFFORT: the SDK's atexit hook
|
||||
@@ -96,93 +154,57 @@ class PrimeTrainMonitor(Monitor):
|
||||
and backpressure, so they never stall the loop.
|
||||
"""
|
||||
|
||||
config: PrimeTrainMonitorConfig
|
||||
run: pr.Run
|
||||
config: PrimeMonitorConfig
|
||||
|
||||
async def init(self, config: BaseConfig | None = None, output_dir: Path | None = None) -> None:
|
||||
init_kwargs: dict[str, Any]
|
||||
if run_id := os.getenv("RUN_ID"):
|
||||
# A managed launch pre-created the platform run and injected its id -
|
||||
# attach instead of registering a duplicate. The platform owns the
|
||||
# attached run's failure/completion marking; a clean finish() is
|
||||
# delivered best-effort and does not by itself mark it completed.
|
||||
init_kwargs = {"id": run_id}
|
||||
elif isinstance(config, SFTConfig):
|
||||
# SFT trains on a dataset, not on environments, and has no rollouts - the
|
||||
# platform run is registered without both.
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
model=config.model.name,
|
||||
environments=[],
|
||||
training=pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.data.batch_size,
|
||||
seq_len=config.data.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
),
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
elif config is not None:
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
model=config.model.name,
|
||||
environments=[env.env_id for env in config.train.source],
|
||||
training=pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=max(
|
||||
(source.group_size for source in config.train.source), default=config.train.group_size
|
||||
),
|
||||
seq_len=config.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
),
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
else:
|
||||
# The RFT API requires a base model; "unknown" is what the
|
||||
# pre-SDK register sent for a config-less init.
|
||||
init_kwargs = {"name": self.config.name, "model": "unknown"}
|
||||
|
||||
mode = prime_mode()
|
||||
try:
|
||||
self.run = await asyncio.to_thread(
|
||||
pr.init, kind="train", mode=mode, base_url=_base_url(), finish_timeout=FINISH_TIMEOUT, **init_kwargs
|
||||
)
|
||||
except (pr.ConfigurationError, pr.APIError) as e:
|
||||
# Registering fails without a team, or for a team outside the external-runs
|
||||
# allowlist. An attached run's error is the launcher's to explain.
|
||||
if "id" in init_kwargs:
|
||||
raise
|
||||
raise RuntimeError(
|
||||
f"Failed to register the Prime run ({type(e).__name__}: {e}). Select a team with "
|
||||
f"`prime switch` (or set PRIME_TEAM_ID), or {OFF_HINT}"
|
||||
) from e
|
||||
async def init(self, config: BaseConfig | None, output_dir: Path, producer: str | None = None) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.producer = producer
|
||||
self.mode = mode = os.getenv(pr.MODE_ENV) or "online"
|
||||
self.run: pr.Run | None = None
|
||||
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
|
||||
# episodes do not retry the platform on every arrival
|
||||
self.runs: dict[tuple[str, int], pr.Run | None] = {}
|
||||
if isinstance(config, EvalConfig):
|
||||
await self._init_evaluations(config)
|
||||
return
|
||||
# The SFT online-eval process and the RL trainer log into the run their launcher registers.
|
||||
attaches = isinstance(config, (SFTOnlineEvalConfig, TrainerConfig))
|
||||
run_id = os.getenv("RUN_ID")
|
||||
if attaches and run_id is None and mode == "online":
|
||||
raise RuntimeError(f"This process logs to its launcher's run: launch it with `rl` or `sft`, or {OFF_HINT}")
|
||||
# The launcher registered the run (or a managed launch pre-created it) - attach
|
||||
# instead of registering a duplicate. The registering process owns the attached
|
||||
# run's failure marking; a clean finish() completes it.
|
||||
train_config = None if attaches else config
|
||||
self.run = await asyncio.to_thread(register, train_config, self.config.name, mode, run_id)
|
||||
if self.run.url:
|
||||
attached = " (attached via $RUN_ID)" if self.run.attached else ""
|
||||
self.logger.info(f"Logging metrics and episodes to Prime run {self.run.id} ({self.run.url}){attached}")
|
||||
else:
|
||||
self.logger.info("Prime run disabled")
|
||||
if output_dir is not None:
|
||||
if not attaches:
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(self._record, output_dir)
|
||||
await asyncio.to_thread(self._record_run)
|
||||
|
||||
def _record(self, output_dir: Path) -> None:
|
||||
register_links(output_dir, PRIME_LINKS, 1 if self.run.url else 0)
|
||||
def _record_run(self) -> None:
|
||||
register_links(self.output_dir, "prime", 1 if self.run.url else 0)
|
||||
if self.run.url:
|
||||
# Merge, not overwrite: a concurrent eval process (SFT online evals share
|
||||
# the trainer's run dir) may already have written its evaluations record.
|
||||
update_platform_record(output_dir, {"kind": "train", "id": self.run.id, "url": self.run.url})
|
||||
publish_link(output_dir, PRIME_LINKS, "run", self.run.url)
|
||||
record = {"kind": "train", "id": self.run.id, "url": self.run.url}
|
||||
update_record(get_platform_run_path(self.output_dir), lambda _: record)
|
||||
publish_link(self.output_dir, "prime", "run", self.run.url)
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# A standalone eval's evaluations carry their own aggregates (``log_eval_epoch``).
|
||||
if self.run is None:
|
||||
return
|
||||
# The SDK also drops non-finite values, but silently; sanitize first so
|
||||
# the dropped paths are named in the log.
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# A queue put that can block briefly under backpressure - off the loop. The SDK
|
||||
# stamps `_timestamp` on every row, so step=None rows keep a time anchor.
|
||||
await asyncio.to_thread(self.run.log_metrics, metrics, step=step)
|
||||
# A queue put that never blocks. The SDK stamps `_timestamp` on every row, so
|
||||
# step=None rows keep a time anchor.
|
||||
self.run.log_metrics(metrics, step=step)
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Every episode ships whole as it arrives (the ``all`` subset), errored and
|
||||
@@ -191,41 +213,44 @@ class PrimeTrainMonitor(Monitor):
|
||||
stamps at emit time."""
|
||||
if subset != "all" or not episodes:
|
||||
return
|
||||
# A queue put that can block briefly under backpressure - off the loop.
|
||||
await asyncio.to_thread(self.run.log_episodes, episodes)
|
||||
if self.run is not None:
|
||||
# A queue put that never blocks.
|
||||
self.run.log_episodes(episodes)
|
||||
return
|
||||
by_env: dict[str, list[vf.Episode]] = {}
|
||||
for episode in episodes:
|
||||
if episode.env.name is not None:
|
||||
by_env.setdefault(episode.env.name, []).append(episode)
|
||||
for env_name, batch in by_env.items():
|
||||
run = await self.run_for(env_name, step)
|
||||
if run is not None:
|
||||
run.log_episodes(batch)
|
||||
|
||||
async def finalize(self, paused: bool = False) -> None:
|
||||
# Drains queued uploads so the final step's metrics and episodes land,
|
||||
# then finalizes (idempotent on the platform side); an attached run's
|
||||
# failure marking stays with the launcher. A paused run only drains and
|
||||
# stays open: it continues on resume, and its owner sets its status.
|
||||
await asyncio.to_thread(self.run.flush if paused else self.run.finish)
|
||||
# An epoch the run did not finish leaves its evaluation open: close it as cancelled.
|
||||
for (env_name, step), run in self.runs.items():
|
||||
if run is None or run.finished:
|
||||
continue
|
||||
try:
|
||||
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
|
||||
if self.run is None:
|
||||
return
|
||||
if paused or self.run.attached:
|
||||
# Drain only: a paused run continues on resume, and an attached run is
|
||||
# finished by the process that registered it, once every component exited.
|
||||
# A clean exit is not a crash.
|
||||
await asyncio.to_thread(self.run.flush, FINISH_TIMEOUT)
|
||||
atexit.unregister(self.run._atexit_hook)
|
||||
return
|
||||
# Drains queued uploads so the final step's metrics and episodes land, then finalizes.
|
||||
await asyncio.to_thread(self.run.finish)
|
||||
|
||||
|
||||
class PrimeEvalMonitor(Monitor):
|
||||
"""Streams each eval epoch to the Prime platform through ``prime_runs``: one
|
||||
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
|
||||
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
|
||||
(``log_eval_epoch``), so the platform page follows the run from its first episode.
|
||||
|
||||
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
|
||||
the parent training run, which is what the run dashboard groups into its `eval`
|
||||
section. The orchestrator's in-process evals reach it through the train monitor, but
|
||||
an eval process of its own (SFT online evals) has no other way there, so without
|
||||
this the run shows every metric group except the one its evals produced."""
|
||||
|
||||
config: PrimeEvalMonitorConfig
|
||||
|
||||
async def init(self, config: BaseConfig | None = None, output_dir: Path | None = None) -> None:
|
||||
self.mode = prime_mode()
|
||||
self.model: str = config.model if config is not None else "unknown"
|
||||
self.sources = {source.resolved_name: source for source in config.source} if config is not None else {}
|
||||
async def _init_evaluations(self, config: EvalConfig) -> None:
|
||||
self.model: str = config.model
|
||||
self.sources = {source.resolved_name: source for source in config.source}
|
||||
self.run_id = os.getenv("PRL_RUN_ID")
|
||||
self.output_dir = output_dir
|
||||
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
|
||||
# episodes do not retry the platform on every arrival
|
||||
self.runs: dict[tuple[str, int], pr.Run | None] = {}
|
||||
self.parent: pr.Run | None = None
|
||||
self._lock = asyncio.Lock()
|
||||
self.evaluation_id = os.getenv(EVAL_ID_VAR)
|
||||
if self.evaluation_id and len(self.sources) != 1:
|
||||
@@ -233,62 +258,20 @@ class PrimeEvalMonitor(Monitor):
|
||||
f"${EVAL_ID_VAR} names one platform evaluation, so the run needs "
|
||||
f"exactly one eval source (got {len(self.sources)})"
|
||||
)
|
||||
if self.mode == "online":
|
||||
self.logger.info("Streaming eval epochs to the Prime platform")
|
||||
self.parent = await asyncio.to_thread(self._attach_parent)
|
||||
if output_dir is not None:
|
||||
# Merge, not overwrite: when the eval process shares the
|
||||
# trainer's run dir (SFT online evals), the train record's
|
||||
# platform link (kind/id/url) must survive; a standalone
|
||||
# eval keeps the plain eval-shaped record. Locked RMW.
|
||||
def _eval_init_update(record: dict[str, Any]) -> dict[str, Any]:
|
||||
if record.get("kind") == "train":
|
||||
record.setdefault("evaluations", {})
|
||||
record["run_id"] = self.run_id
|
||||
return record
|
||||
return {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
|
||||
online = self.mode == "online"
|
||||
# Evaluations open lazily, when their epoch starts; fail at launch instead.
|
||||
if online and not Config().api_key:
|
||||
raise RuntimeError(NO_KEY)
|
||||
self.logger.info("Streaming eval epochs to the Prime platform" if online else "Prime evaluations disabled")
|
||||
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(_merge_platform_record, output_dir, _eval_init_update)
|
||||
else:
|
||||
self.logger.info("Prime evaluations disabled")
|
||||
if output_dir is not None:
|
||||
expected = len(self.sources) if self.mode == "online" else 0
|
||||
await asyncio.to_thread(register_links, output_dir, PRIME_EVAL_LINKS, expected)
|
||||
def record() -> None:
|
||||
if online:
|
||||
record = {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
|
||||
update_record(get_platform_run_path(self.output_dir), lambda _: record)
|
||||
register_links(self.output_dir, "prime", len(self.sources) if online else 0)
|
||||
|
||||
def _attach_parent(self) -> pr.Run | None:
|
||||
"""The parent training run this eval process belongs to, for metrics only.
|
||||
Blocking: runs in a worker thread.
|
||||
|
||||
Attaching is a local handle, not a request, so a run that turns out to be
|
||||
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
|
||||
drop the SDK's atexit crash hook, because an eval process that exits while the
|
||||
trainer is still going would otherwise report the WHOLE run failed."""
|
||||
run_id = os.getenv("RUN_ID")
|
||||
if not run_id:
|
||||
return None
|
||||
run = pr.init(
|
||||
kind="train",
|
||||
mode=self.mode,
|
||||
base_url=_base_url(),
|
||||
id=run_id,
|
||||
finish_timeout=FINISH_TIMEOUT,
|
||||
)
|
||||
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
|
||||
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
|
||||
return run
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
|
||||
Only there: a standalone eval has no parent, and the per-epoch evaluation
|
||||
carries its own aggregates through ``log_eval_epoch``."""
|
||||
if self.parent is None:
|
||||
return
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# A queue put that can block briefly under backpressure - off the loop.
|
||||
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(record)
|
||||
|
||||
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
|
||||
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
|
||||
@@ -336,19 +319,17 @@ class PrimeEvalMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to open the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
|
||||
self.runs[key] = None
|
||||
if self.output_dir is not None:
|
||||
await asyncio.to_thread(publish_link, self.output_dir, PRIME_EVAL_LINKS, env_name, None)
|
||||
await asyncio.to_thread(publish_link, self.output_dir, "prime", env_name, None)
|
||||
return None
|
||||
self.runs[key] = run
|
||||
if run.url:
|
||||
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
|
||||
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
|
||||
if self.output_dir is not None:
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(self._record, env_name, step, run)
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(self._record_evaluation, env_name, step, run)
|
||||
return run
|
||||
|
||||
def _record(self, env_name: str, step: int, run: pr.Run) -> None:
|
||||
def _record_evaluation(self, env_name: str, step: int, run: pr.Run) -> None:
|
||||
if run.url:
|
||||
|
||||
def update(record: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -357,26 +338,16 @@ class PrimeEvalMonitor(Monitor):
|
||||
record.setdefault("evaluations", {})[env_name] = {"step": step, "id": run.id, "url": run.url}
|
||||
return record
|
||||
|
||||
_merge_platform_record(self.output_dir, update)
|
||||
publish_link(self.output_dir, PRIME_EVAL_LINKS, env_name, run.url)
|
||||
update_record(get_platform_run_path(self.output_dir), update)
|
||||
publish_link(self.output_dir, "prime", env_name, run.url)
|
||||
|
||||
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
|
||||
await self.run_for(env_name, step, expected)
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Every eval episode as it lands (the ``all`` subset is the arrival stream)."""
|
||||
if kind != "eval" or subset != "all":
|
||||
return
|
||||
by_env: dict[str, list[vf.Episode]] = {}
|
||||
for episode in episodes:
|
||||
if episode.env.name is not None:
|
||||
by_env.setdefault(episode.env.name, []).append(episode)
|
||||
for env_name, batch in by_env.items():
|
||||
run = await self.run_for(env_name, step)
|
||||
if run is not None:
|
||||
await asyncio.to_thread(run.log_episodes, batch) # a queue put, off the loop
|
||||
if self.run is None:
|
||||
await self.run_for(env_name, step, expected)
|
||||
|
||||
async def log_eval_epoch(self, env_name: str, step: int, episodes: list[vf.Episode]) -> None:
|
||||
if self.run is not None:
|
||||
return
|
||||
run = await self.run_for(env_name, step)
|
||||
if run is None:
|
||||
return
|
||||
@@ -386,17 +357,3 @@ class PrimeEvalMonitor(Monitor):
|
||||
self.logger.warning(f"Failed to finish the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
|
||||
return
|
||||
self.logger.info(f"Uploaded {env_name} (Step {step}) evaluation - {run.url}")
|
||||
|
||||
async def finalize(self, paused: bool = False) -> None:
|
||||
# An epoch the run did not finish leaves its evaluation open: close it as cancelled.
|
||||
for (env_name, step), run in self.runs.items():
|
||||
if run is None or run.finished:
|
||||
continue
|
||||
try:
|
||||
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
|
||||
if self.parent is not None:
|
||||
# Drain only. The parent run belongs to the trainer and the platform: an
|
||||
# eval process must never report its status, not even a clean completion.
|
||||
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.wandb.overview import ensure_overview_view
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.links import WANDB_LINKS, publish_link, register_links
|
||||
from prime_rl.utils.links import publish_link, register_links
|
||||
from prime_rl.utils.logger import format_time
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -117,10 +117,10 @@ class WandbMonitor(Monitor):
|
||||
try:
|
||||
self.wandb = init_wandb(max_retries)
|
||||
except UsageError as e:
|
||||
raise RuntimeError(
|
||||
f"The W&B monitor could not start ({e}). Authenticate with `wandb login` (or set WANDB_API_KEY), "
|
||||
"or turn the monitor off with --no-monitors.wandb"
|
||||
) from e
|
||||
hint = "Authenticate with `wandb login` (or set WANDB_API_KEY), or turn the monitor off with --no-monitors.wandb"
|
||||
if "No API key" in str(e):
|
||||
raise RuntimeError(f"The W&B monitor found no W&B API key. {hint}") from e
|
||||
raise RuntimeError(f"The W&B monitor could not start ({e}). {hint}") from e
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
# key prefixes that arrived via step=None (wall-time rows); their time axis
|
||||
@@ -149,9 +149,9 @@ class WandbMonitor(Monitor):
|
||||
|
||||
@staticmethod
|
||||
def _record(output_dir: Path, url: str | None) -> None:
|
||||
register_links(output_dir, WANDB_LINKS, 1 if url else 0)
|
||||
register_links(output_dir, "wandb", 1 if url else 0)
|
||||
if url:
|
||||
publish_link(output_dir, WANDB_LINKS, "run", url)
|
||||
publish_link(output_dir, "wandb", "run", url)
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# every log carries the monitor's own wall-time stamp
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, MultimodalAdapter
|
||||
from prime_rl.multimodal.registry import get_multimodal_adapter
|
||||
|
||||
__all__ = [
|
||||
"ForwardPolicy",
|
||||
"MaterializedMM",
|
||||
"MultimodalAdapter",
|
||||
"get_multimodal_adapter",
|
||||
]
|
||||
@@ -1,40 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol
|
||||
|
||||
import torch
|
||||
from PIL.Image import Image
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ForwardPolicy:
|
||||
pass_position_ids: bool = True
|
||||
requires_mm_token_type_ids: bool = False
|
||||
defer_context_parallelism: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MaterializedMM:
|
||||
kwargs: dict[str, torch.Tensor]
|
||||
forward_policy: ForwardPolicy
|
||||
|
||||
|
||||
class MultimodalAdapter(Protocol):
|
||||
model_types: frozenset[str]
|
||||
forward_policy: ForwardPolicy
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM: ...
|
||||
|
||||
|
||||
def required_tensors(values: Any, keys: tuple[str, ...]) -> dict[str, torch.Tensor]:
|
||||
data = dict(values)
|
||||
missing = [key for key in keys if key not in data]
|
||||
if missing:
|
||||
raise ValueError(f"Image processor did not return {', '.join(missing)}")
|
||||
return {key: torch.as_tensor(data[key]).contiguous() for key in keys}
|
||||
@@ -1,33 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PIL.Image import Image
|
||||
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
|
||||
|
||||
|
||||
class KimiK25Adapter:
|
||||
model_types = frozenset({"kimi_k25"})
|
||||
forward_policy = ForwardPolicy()
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM:
|
||||
preprocess = getattr(image_processor, "preprocess", None)
|
||||
if preprocess is None:
|
||||
raise ValueError("Kimi image processor is missing preprocess")
|
||||
media = [{"type": "image", "image": image} for image in images]
|
||||
kwargs = required_tensors(
|
||||
preprocess(media, return_tensors="pt"),
|
||||
("pixel_values", "grid_thws"),
|
||||
)
|
||||
lengths = [1] * len(kwargs["grid_thws"].reshape(-1, 3))
|
||||
if lengths != placeholder_lengths:
|
||||
raise ValueError(
|
||||
f"Kimi image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
|
||||
)
|
||||
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
|
||||
@@ -1,35 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PIL.Image import Image
|
||||
|
||||
from prime_rl.multimodal.base import ForwardPolicy, MaterializedMM, required_tensors
|
||||
|
||||
|
||||
class QwenVLAdapter:
|
||||
model_types = frozenset({"qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe"})
|
||||
forward_policy = ForwardPolicy(
|
||||
pass_position_ids=False,
|
||||
requires_mm_token_type_ids=True,
|
||||
defer_context_parallelism=True,
|
||||
)
|
||||
|
||||
def materialize(
|
||||
self,
|
||||
image_processor: Any,
|
||||
images: list[Image],
|
||||
placeholder_lengths: list[int],
|
||||
) -> MaterializedMM:
|
||||
kwargs = required_tensors(
|
||||
image_processor(images=images, return_tensors="pt"),
|
||||
("pixel_values", "image_grid_thw"),
|
||||
)
|
||||
merge_size = int(image_processor.merge_size)
|
||||
# HF Qwen-VL / renderer pad count: T*H*W / merge_size^2.
|
||||
lengths = [int(grid.prod()) // (merge_size * merge_size) for grid in kwargs["image_grid_thw"].reshape(-1, 3)]
|
||||
if lengths != placeholder_lengths:
|
||||
raise ValueError(
|
||||
f"Qwen image placeholder lengths differ from vLLM: expected {placeholder_lengths}, got {lengths}"
|
||||
)
|
||||
return MaterializedMM(kwargs=kwargs, forward_policy=self.forward_policy)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user