Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52455b41fc | ||
|
|
4f4d7e4402 | ||
|
|
1e5318108d | ||
|
|
3309613436 | ||
|
|
8793c37118 | ||
|
|
ae28fb70c5 | ||
|
|
2ff7f53d47 | ||
|
|
c13a7ec75b | ||
|
|
ee058677f2 | ||
|
|
9fff742eae | ||
|
|
73140dec35 | ||
|
|
0936378085 | ||
|
|
41a8ed0190 | ||
|
|
9cde4d74f5 | ||
|
|
32c48f5d9a | ||
|
|
8b2eb329e1 | ||
|
|
be89bbdaa1 | ||
|
|
a1e0edbb4f | ||
|
|
8493109b7d | ||
|
|
c9ce5f3d30 | ||
|
|
9570bccc28 | ||
|
|
c5406f8d09 | ||
|
|
9b39a10949 | ||
|
|
f7e8ab6456 | ||
|
|
84e94bf05c | ||
|
|
37b48a996e | ||
|
|
88faa6dc22 | ||
|
|
083b8fe9ec | ||
|
|
853208336e | ||
|
|
31281d88f9 | ||
|
|
bc250759bf | ||
|
|
1983d8dfed | ||
|
|
26681fc6c7 | ||
|
|
6b0906c900 | ||
|
|
5e963f027a | ||
|
|
72834b3b52 | ||
|
|
0bcb868e91 | ||
|
|
746d8a96d0 | ||
|
|
765bbeba7b | ||
|
|
fec3acd8e7 | ||
|
|
adda4731fe | ||
|
|
a3f1f892c5 | ||
|
|
e6acff78aa |
@@ -192,6 +192,12 @@ jobs:
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
# CVE-2026-93318: pin the BuildKit builder to the patched release so
|
||||
# the version is deterministic on the self-hosted runners (otherwise
|
||||
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
|
||||
# persistent runner may keep a stale local copy of it).
|
||||
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
@@ -207,7 +213,12 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
|
||||
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
|
||||
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
|
||||
# version, so pre-fix deps-${key} images would otherwise be reused
|
||||
# as the runtime base instead of being rebuilt by the pinned v0.33.1
|
||||
# builder.
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
|
||||
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
|
||||
echo "image=${image}" >> "$GITHUB_OUTPUT"
|
||||
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
|
||||
@@ -222,8 +233,10 @@ jobs:
|
||||
file: ./Dockerfile.cuda
|
||||
target: dependencies
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
|
||||
# builders (cache writers since 2026-08-16) must not be re-imported.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: ${{ steps.dependency.outputs.image }}
|
||||
|
||||
@@ -240,8 +253,10 @@ jobs:
|
||||
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
|
||||
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
|
||||
# builders (cache writers since 2026-08-16) must not be re-imported.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
|
||||
@@ -6,6 +6,10 @@ on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
@@ -15,15 +19,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- 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"
|
||||
- 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 tests
|
||||
|
||||
@@ -5,20 +5,103 @@ on:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
name: Select tests
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
|
||||
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
|
||||
id: filter
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
filters: |
|
||||
unit:
|
||||
- &runtime
|
||||
- '.github/workflows/gpu_tests.yaml'
|
||||
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
|
||||
- 'deps/**'
|
||||
- 'packages/**/pyproject.toml'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
|
||||
- 'src/prime_rl/*.py'
|
||||
- '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'
|
||||
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
|
||||
- 'src/prime_rl/entrypoints/{eval,env_server}.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 "reverse_text_sft", "reverse_text_sft_lora" else empty end,
|
||||
if $all or $rl then
|
||||
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
|
||||
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
|
||||
else empty end
|
||||
]')
|
||||
echo "tests=$tests" >> "$GITHUB_OUTPUT"
|
||||
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
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: github.event_name == 'push' || github.event.pull_request.draft == false
|
||||
if: needs.changes.outputs.unit == 'true'
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -29,12 +112,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- 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
|
||||
- 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
|
||||
@@ -50,46 +137,20 @@ jobs:
|
||||
|
||||
integration-tests:
|
||||
name: Integration tests (${{ matrix.test }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
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: github.event_name == 'push' || github.event.pull_request.draft == false
|
||||
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:
|
||||
- test: reverse_text_sft
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
test: ${{ fromJSON(needs.changes.outputs.integration) }}
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -100,12 +161,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- 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
|
||||
- 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
|
||||
@@ -120,7 +185,7 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -129,3 +194,47 @@ jobs:
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
eval-tests:
|
||||
name: Integration tests (gsm8k_eval)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.eval == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- 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 eval 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
|
||||
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: gsm8k_eval-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
@@ -9,6 +9,10 @@ on:
|
||||
# This will trigger the workflow for pull requests to any branch
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
ruff:
|
||||
name: Ruff
|
||||
|
||||
@@ -6,19 +6,14 @@
|
||||
#
|
||||
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
|
||||
#
|
||||
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
|
||||
# conversion cache, which takes far longer than the 3600s default.
|
||||
#
|
||||
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
|
||||
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
|
||||
# already the default here.
|
||||
# To buy memory back for quicker testing on fewer nodes, set `offload = "full"` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and disables gradient clipping;
|
||||
# the lighter `offload = "optimizer"` is already the default here.
|
||||
#
|
||||
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
|
||||
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
|
||||
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
|
||||
|
||||
dist_timeout_seconds = 14400
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
|
||||
@@ -6,9 +6,6 @@ level = "debug"
|
||||
[model]
|
||||
name = "PrimeIntellect/MiniMax-M2.5-bf16"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
@@ -16,6 +13,7 @@ num_infer_nodes = 12
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-minimax"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
@@ -35,7 +33,6 @@ fused_lm_head_token_chunk_size = 1024
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
|
||||
@@ -22,10 +22,6 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -36,7 +32,6 @@ keep_last = 1
|
||||
name = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
@@ -54,9 +49,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
|
||||
@@ -110,4 +102,3 @@ max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_prefix_caching = true
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -24,8 +24,6 @@ group_size = 16
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.model.lora]
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -21,8 +21,6 @@ group_size = 16
|
||||
[orchestrator.concurrency]
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.model.lora]
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -9,8 +9,7 @@ step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
offload = "full"
|
||||
|
||||
[optim]
|
||||
lr = 0.0
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: d4fb80a56f...89dcc7ffcb
Vendored
+1
-1
Submodule deps/renderers updated: d43c43015a...41f9290949
Vendored
+1
-1
Submodule deps/verifiers updated: 7ba657f2a4...2cb0a6d33a
+1
-1
@@ -100,7 +100,7 @@ Backend shape checks and token alignment apply only to the selected compute path
|
||||
|
||||
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed.
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
|
||||
+1
-1
@@ -139,7 +139,7 @@ algo.type = "echo"
|
||||
|
||||
### The Algorithm Classes
|
||||
|
||||
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
|
||||
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
|
||||
|
||||
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
|
||||
|
||||
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
|
||||
|
||||
```toml
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
|
||||
| Workflow | Trigger | What runs | Where |
|
||||
|---|---|---|---|
|
||||
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `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 | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
|
||||
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
|
||||
|
||||
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
|
||||
|
||||
## Resume
|
||||
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
|
||||
|
||||
```bash
|
||||
uv run eval @ eval.toml --run.name my-eval
|
||||
@@ -92,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
|
||||
|
||||
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
|
||||
|
||||
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
|
||||
|
||||
## Monitors
|
||||
|
||||
|
||||
+7
-7
@@ -86,9 +86,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|---|---|
|
||||
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
|
||||
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
|
||||
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
|
||||
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
|
||||
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
|
||||
| `trainer.model.offload` | CPU offloading: `optimizer` (default) offloads optimizer state between steps; `full` offloads gradients, FP32 masters, and optimizer state and runs the optimizer (AdamW or SignSGD) on CPU during backward; `none` disables offloading. |
|
||||
|
||||
### Expert Parallelism
|
||||
|
||||
@@ -143,15 +141,15 @@ Activation offloading still applies to tensors saved by autograd, but tensors re
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
|
||||
State-only optimizer offload is enabled by default (`model.offload = "optimizer"`). For full offload, set `model.offload = "full"`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
|
||||
|
||||
### LM Head Chunking
|
||||
|
||||
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `1024` for RL training:
|
||||
The vanilla LM head materializes a `[batch * seq, vocab]` logits tensor on every step — a major memory tax when the vocabulary is large (often >100K). `fused_lm_head_token_chunk_size` swaps in a custom fused linear + logprob/entropy kernel that streams through `chunk_size` tokens at a time, avoiding the materialization. It defaults to `8192` for RL training:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
fused_lm_head_token_chunk_size = 1024 # default
|
||||
fused_lm_head_token_chunk_size = 8192 # default
|
||||
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
|
||||
```
|
||||
|
||||
@@ -173,7 +171,7 @@ freq = 1
|
||||
max_inflight_activations = 1
|
||||
```
|
||||
|
||||
The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
The defaults already cover: fused LM head chunking (`8192`), `torch.compile` (fullgraph=False), AC (full mode), AC offloading (`max_inflight_activations=5`), and optimizer CPU offload. Walks through every memory lever in order: FSDP+EP shard the weights, CP shards the activations along the token dim, AC + AC offloading shrink the activation footprint, fused LM head chunks the loss, `torch.compile` reduces fragmentation, optim offload moves Adam state off GPU. Apply selectively — each knob has a throughput cost.
|
||||
|
||||
## SLURM
|
||||
|
||||
@@ -181,6 +179,8 @@ The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
Compile and JIT caches are node-local by default: the launcher sets `TRITON_CACHE_DIR=/tmp/triton-<uid>` for every component, and `VLLM_CACHE_ROOT=/tmp/.vllm-cache-<uid>` and `FLASHINFER_WORKSPACE_BASE=/tmp/.flashinfer-cache-<uid>` for inference. Ranks writing one cache on a shared filesystem can crash or hang. Override them in `[env_vars]` or a component's `env_vars`.
|
||||
|
||||
### Activation
|
||||
|
||||
A SLURM config is usually a thin overlay that adds `[slurm]` (and `[deployment]` for multi-node) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [Configuration § TOML Composition](configuration.md#toml-composition):
|
||||
|
||||
@@ -159,6 +159,10 @@ messages = "conversation"
|
||||
tools = "schemas"
|
||||
```
|
||||
|
||||
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
|
||||
|
||||
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
|
||||
|
||||
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
|
||||
|
||||
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
|
||||
|
||||
@@ -5,10 +5,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
@@ -25,10 +21,6 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -41,7 +33,6 @@ name = "zai-org/GLM-4.5-Air"
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
@@ -57,9 +48,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
@@ -171,12 +159,6 @@ env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -23,11 +23,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
partition = "all"
|
||||
|
||||
@@ -39,10 +34,6 @@ num_infer_nodes = 1
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -52,7 +43,6 @@ keep_last = 1
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
@@ -62,8 +52,7 @@ name = "zai-org/GLM-4.5-Air"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
offload = "full"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
@@ -73,9 +62,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
@@ -104,12 +90,6 @@ thinking_retention = "all"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -19,11 +19,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
partition = "all"
|
||||
@@ -40,10 +35,6 @@ num_infer_replicas = 4
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -53,7 +44,6 @@ keep_last = 1
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
@@ -118,14 +108,8 @@ env.agent.timeout.rollout = 3600
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -6,10 +6,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
@@ -26,10 +22,6 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
@@ -42,7 +34,6 @@ name = "zai-org/GLM-4.5-Air"
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
@@ -58,9 +49,6 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
@@ -166,12 +154,6 @@ env.taskset.id = "terminal-bench-2"
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
[model]
|
||||
cp = 1
|
||||
optim_cpu_offload = false
|
||||
offload = "none"
|
||||
ac_offloading = "None"
|
||||
|
||||
[model.compile]
|
||||
|
||||
@@ -2,14 +2,13 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
offload = "optimizer"
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[model.ac]
|
||||
|
||||
@@ -89,6 +89,7 @@ attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
cp = 4 # context parallel for the 131K seq len
|
||||
ep = 8
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
@@ -97,7 +98,6 @@ type = "fp8"
|
||||
type = "deepgemm_fp8"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@ level = "debug"
|
||||
[model]
|
||||
name = "PrimeIntellect/INTELLECT-3-Base"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
@@ -16,6 +13,7 @@ num_infer_nodes = 12
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
@@ -35,7 +33,6 @@ fused_lm_head_token_chunk_size = 1024
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
@@ -6,9 +6,6 @@ level = "debug"
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
@@ -16,6 +13,7 @@ num_infer_nodes = 2
|
||||
|
||||
[slurm]
|
||||
job_name = "math-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
@@ -33,7 +31,6 @@ ep = 8
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
|
||||
@@ -2,7 +2,6 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
||||
|
||||
@@ -6,9 +6,6 @@ level = "debug"
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
@@ -16,6 +13,7 @@ num_infer_nodes = 2
|
||||
|
||||
[slurm]
|
||||
job_name = "swe-qwen30b"
|
||||
partition = "all"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
@@ -34,7 +32,6 @@ cp = 2
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
|
||||
@@ -3,6 +3,7 @@ seq_len = 32768
|
||||
|
||||
[slurm]
|
||||
job_name = "general-agent-qwen3-30b-a3b-rlm"
|
||||
partition = "all"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -26,7 +27,6 @@ name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
||||
cp = 2
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
|
||||
@@ -38,8 +38,6 @@ group_size = 16
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 1024
|
||||
|
||||
[orchestrator.model.lora]
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node.
|
||||
max_steps = 1000
|
||||
dist_timeout_seconds = 3600
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.6-35B-A3B"
|
||||
|
||||
@@ -19,7 +19,6 @@ freeze_vision_encoder = true
|
||||
rank = 16
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
|
||||
@@ -28,10 +28,11 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
|
||||
sandbox-backed environments to pace provisioning during autoscaling. None disables
|
||||
rate limiting."""
|
||||
dispatch_per_minute: int | None = Field(None, ge=1)
|
||||
"""Rate limit on episode dispatch: at most this many episodes start per minute. Each
|
||||
episode counts once, so a group of ``group_size`` episodes counts ``group_size``
|
||||
times. Use it for sandbox-backed environments to pace provisioning during
|
||||
autoscaling. None disables it."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat for the run: pinged by landed episodes — the first
|
||||
|
||||
@@ -29,15 +29,6 @@ class ServerConfig(BaseConfig):
|
||||
# not depend on vLLM, and importing it costs seconds in every config-parsing process.
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
|
||||
# vLLM all2all backend options for expert-parallel deployments.
|
||||
All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
QuantizationType = Literal["fp8_per_block"]
|
||||
|
||||
|
||||
@@ -59,18 +50,9 @@ class VllmConfig(BaseConfig):
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""HF model name or local path."""
|
||||
|
||||
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
||||
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models."""
|
||||
|
||||
max_model_len: int | None = None
|
||||
"""Maximum model context length. If None, uses the model config's value."""
|
||||
|
||||
enforce_eager: bool = False
|
||||
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance."""
|
||||
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code when loading the model."""
|
||||
|
||||
chat_template: str | None = None
|
||||
"""Chat template — a Jinja2 template string or path to a template file. If None, uses the model's default."""
|
||||
|
||||
@@ -98,9 +80,6 @@ class VllmConfig(BaseConfig):
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Set to 0 for headless mode."""
|
||||
|
||||
seed: int = 0
|
||||
"""Seed the inference components."""
|
||||
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization."""
|
||||
|
||||
@@ -113,10 +92,6 @@ class VllmConfig(BaseConfig):
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA."""
|
||||
|
||||
max_loras: int = 1
|
||||
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
|
||||
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
|
||||
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
|
||||
|
||||
@@ -126,9 +101,6 @@ class VllmConfig(BaseConfig):
|
||||
enable_expert_parallel: bool = False
|
||||
"""Enable expert parallelism for MoE models."""
|
||||
|
||||
all2all_backend: All2AllBackend = "allgather_reducescatter"
|
||||
"""All-to-all backend for expert-parallel communication."""
|
||||
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB)."""
|
||||
|
||||
@@ -138,9 +110,6 @@ class VllmConfig(BaseConfig):
|
||||
expert parallelism is disabled, or under EPLB (redundant expert slots need all
|
||||
logical expert weights)."""
|
||||
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO)."""
|
||||
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses."""
|
||||
|
||||
@@ -565,6 +534,8 @@ class InferenceConfig(BaseConfig):
|
||||
|
||||
@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 = "inference"
|
||||
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:
|
||||
|
||||
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
|
||||
from pydantic.fields import FieldInfo
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
from verifiers.v1.configs.agent import agent_config_fields
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
@@ -18,9 +19,9 @@ from prime_rl.configs.shared import (
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PolicyClientConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
@@ -28,19 +29,8 @@ from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
rank: int | None = Field(None, ge=1)
|
||||
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
|
||||
|
||||
alpha: float | None = Field(None, ge=0)
|
||||
"""LoRA alpha for this run. If None, uses the trainer's alpha."""
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
client: PolicyClientConfig = Field(default_factory=PolicyClientConfig)
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
@@ -90,70 +80,6 @@ class TrainSamplingConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict, omitting None values."""
|
||||
args: dict[str, Any] = {
|
||||
"temperature": self.temperature,
|
||||
"top_p": self.top_p,
|
||||
"logprobs": True,
|
||||
}
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
|
||||
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
"""Nucleus sampling threshold. None defers to the inference server default."""
|
||||
|
||||
top_k: int | None = None
|
||||
"""Top-k sampling. None defers to the inference server default."""
|
||||
|
||||
min_p: float | None = Field(None, ge=0)
|
||||
"""Min-p sampling threshold. None defers to the inference server default."""
|
||||
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. None defers to the inference server default."""
|
||||
|
||||
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
|
||||
"""Reasoning effort constraint for reasoning models."""
|
||||
|
||||
extra_body: dict[str, Any] = {}
|
||||
"""Extra body parameters forwarded to the inference server."""
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
|
||||
args: dict[str, Any] = {}
|
||||
if self.temperature is not None:
|
||||
args["temperature"] = self.temperature
|
||||
if self.top_p is not None:
|
||||
args["top_p"] = self.top_p
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
if self.reasoning_effort is not None:
|
||||
args["reasoning_effort"] = self.reasoning_effort
|
||||
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if self.min_p is not None:
|
||||
extra_body["min_p"] = self.min_p
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
|
||||
@@ -316,9 +242,37 @@ class TrainSourceConfig(EnvConfig):
|
||||
"""User-authored task sampler and admission gates. The default cycles
|
||||
through the taskset and admits every finalized group."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_policy_sampling(self):
|
||||
if self.algo.sampling.source != "policy":
|
||||
return self
|
||||
# The source owns the distribution replayed by the trainer; agents may
|
||||
# change generation limits and rendering without changing that distribution.
|
||||
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
|
||||
supported = (
|
||||
agent_options
|
||||
| TrainSamplingConfig.model_fields.keys()
|
||||
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
|
||||
)
|
||||
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
|
||||
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
|
||||
raise ValueError(
|
||||
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
|
||||
)
|
||||
for name, agent in agent_config_fields(self.env).items():
|
||||
if agent.sampling is None:
|
||||
continue
|
||||
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
|
||||
raise ValueError(
|
||||
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
|
||||
"Set distribution parameters on the source's sampling config; agent sampling only supports "
|
||||
f"{sorted(agent_options)}."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
sampling: vf.SamplingConfig = vf.SamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
@@ -409,7 +363,7 @@ class EvalSourcesConfig(SourceGroupConfig):
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
|
||||
"""Sampling that every eval source inherits; can differ from training sampling."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
@@ -472,15 +426,6 @@ class CheckpointConfig(BaseConfig):
|
||||
interval: int | None = Field(None, ge=1)
|
||||
"""Step interval at which to save the orchestrator checkpoint."""
|
||||
|
||||
wait_for_weights_timeout: int | None = Field(None, ge=1)
|
||||
"""Wait up to this many seconds for the startup weight directory to appear (the trainer broadcasts the incoming policy — v0 from scratch, the resumed step's version on resume — before the first step). If None, fall back to a default timeout. Raise this for large models on slow shared filesystems."""
|
||||
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
keep_interval: int | None = Field(None, ge=1)
|
||||
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
@@ -550,10 +495,10 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Role for each policy admin client when collecting P/D inference metrics."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint configuration."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume the orchestrator from a checkpoint. None starts from scratch; an empty block resumes from the latest checkpoint, ``resume.step`` from that step, ``resume.dir`` from an external checkpoint step directory. Without ``ckpt`` the run loads but saves no new checkpoints."""
|
||||
"""Checkpoint configuration."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
"""Transport used to receive updated weights from the trainer."""
|
||||
@@ -564,8 +509,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
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``."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
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)
|
||||
"""Samples to train on per step."""
|
||||
|
||||
@@ -360,6 +360,13 @@ 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.
|
||||
if inference is not None:
|
||||
require_equal(
|
||||
"deployment.gpus_per_node",
|
||||
{
|
||||
"deployment.gpus_per_node": self.deployment.gpus_per_node,
|
||||
"inference.deployment.gpus_per_node": inference.deployment.gpus_per_node,
|
||||
},
|
||||
)
|
||||
require_equal(
|
||||
"model.name",
|
||||
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
|
||||
@@ -433,17 +440,8 @@ class RLConfig(BaseConfig):
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
if "inference_world_size" in self.weight_broadcast.model_fields_set:
|
||||
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
|
||||
update = {}
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
update["inference_world_size"] = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
|
||||
self.orchestrator.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
|
||||
@@ -479,37 +477,6 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
|
||||
@@ -659,6 +626,11 @@ class RLConfig(BaseConfig):
|
||||
dp = self.inference.vllm.data_parallel_size
|
||||
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
|
||||
self.inference.vllm.api_server_count = dp
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
|
||||
world_size = dp * self.inference.vllm.tensor_parallel_size
|
||||
self.trainer.weight_broadcast.inference_world_size = world_size
|
||||
self.orchestrator.weight_broadcast.inference_world_size = world_size
|
||||
|
||||
elif self.deployment.type == "multi_node": # multi-node
|
||||
self.orchestrator.num_train_workers = (
|
||||
@@ -809,6 +781,8 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
|
||||
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:
|
||||
|
||||
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
|
||||
tools: str = "tools"
|
||||
"""Column with the tool schemas in OpenAI function-calling format."""
|
||||
|
||||
message_loss_mask: str = "message_loss_mask"
|
||||
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
|
||||
|
||||
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
|
||||
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
|
||||
|
||||
@@ -323,8 +326,8 @@ class SFTConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
dist_timeout_seconds: int = 900
|
||||
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
@@ -385,13 +388,13 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_disables_grad_clipping(self):
|
||||
if self.model.full_offload and self.optim.max_norm is not None:
|
||||
if self.model.offload == "full" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
@@ -439,8 +442,6 @@ class SFTConfig(BaseConfig):
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.eval.retrigger_on_resume:
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
@@ -618,12 +619,6 @@ class SFTConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -648,6 +643,8 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@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:
|
||||
|
||||
@@ -39,9 +39,10 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseConfig):
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
timeout: int = 3600
|
||||
"""Timeout in seconds for the broadcast handshake and transfer, including the orchestrator's wait
|
||||
for the trainer's startup broadcast. The trainer fails the run when no consumer acknowledges an
|
||||
offered version in time. Raise it for large models on slow shared filesystems."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
@@ -122,8 +123,8 @@ class ResumeConfig(BaseConfig):
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
job_name: str = "prime-rl"
|
||||
"""SLURM job name."""
|
||||
job_name: str | None = None
|
||||
"""SLURM job name. Defaults to ``run.name`` for ``rl`` and ``sft``, and to ``inference`` for ``inference``."""
|
||||
|
||||
project_dir: Path = Path(".")
|
||||
"""Path to the project root, used to source .env, activate .venv, and run uv sync."""
|
||||
@@ -131,8 +132,8 @@ class SlurmConfig(BaseConfig):
|
||||
template_path: Path | None = None
|
||||
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
|
||||
|
||||
partition: str = "cluster"
|
||||
"""SLURM partition (#SBATCH --partition)."""
|
||||
partition: str | None = None
|
||||
"""SLURM partition (#SBATCH --partition). If None, the job goes to the cluster's default partition."""
|
||||
|
||||
nodelist: str | None = None
|
||||
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
|
||||
@@ -153,7 +154,7 @@ class SlurmConfig(BaseConfig):
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
"""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."""
|
||||
|
||||
shared_fs: bool = True
|
||||
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
|
||||
@@ -223,9 +224,6 @@ class ClientConfig(BaseClientConfig):
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
dynamo: DynamoConfig | None = None
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class VLLMClientConfig(ClientConfig):
|
||||
"""Client defaults for the live inference deployment managed by training."""
|
||||
@@ -234,6 +232,13 @@ class VLLMClientConfig(ClientConfig):
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
|
||||
|
||||
class PolicyClientConfig(VLLMClientConfig):
|
||||
"""Client of the policy deployment the orchestrator drives (weight updates, admin plane)."""
|
||||
|
||||
dynamo: DynamoConfig | None = None
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
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``."""
|
||||
|
||||
@@ -3,7 +3,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -42,41 +42,13 @@ class ActivationCheckpointConfig(BaseConfig):
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
pin_memory: bool = True
|
||||
"""Pin offloaded activations to CPU memory."""
|
||||
"""Offload tensors saved for backward to pinned CPU memory during the forward pass."""
|
||||
|
||||
max_inflight_activations: int = Field(5, ge=1)
|
||||
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
|
||||
"""Max activations kept on GPU while their offload copies are in flight on the side stream. Higher values give more copy/compute overlap at the cost of GPU memory."""
|
||||
|
||||
|
||||
class OptimizerInBackwardOffloadConfig(BaseConfig):
|
||||
"""Full CPU optimizer offload: FP32 masters, optimizer state (AdamW moments; SignSGD is
|
||||
stateless), and accumulated gradients live in CPU RAM, each optimizer chunk runs on CPU as
|
||||
soon as its last gradient arrives, and the refreshed BF16 weights stream back while backward
|
||||
is still executing.
|
||||
|
||||
Gradient numerics: gradients are reduced across ranks in FP32 (``reduce_dtype``) but FSDP2
|
||||
materializes them in the sharded parameter's dtype, which is BF16 for the offload compute
|
||||
model — so each gradient is rounded to BF16 once before the FP32 CPU update. Masters,
|
||||
moments, accumulation, and optimizer arithmetic remain FP32. For gradient numerics
|
||||
bit-faithful to that path, disable offloading.
|
||||
"""
|
||||
|
||||
numa_bind: bool = True
|
||||
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
|
||||
|
||||
|
||||
def _normalize_optimizer_in_backward_offload(value: Any) -> Any:
|
||||
if value is True:
|
||||
return {}
|
||||
if value is False:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
OptimizerInBackwardOffload = Annotated[
|
||||
OptimizerInBackwardOffloadConfig | None, BeforeValidator(_normalize_optimizer_in_backward_offload)
|
||||
]
|
||||
OffloadMode: TypeAlias = Literal["none", "optimizer", "full"]
|
||||
|
||||
|
||||
class CompileConfig(BaseConfig):
|
||||
@@ -95,14 +67,6 @@ class FusionsConfig(BaseConfig):
|
||||
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
|
||||
|
||||
|
||||
class IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
|
||||
topk_pattern: str | None = None
|
||||
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
rank: int = Field(16, ge=1)
|
||||
"""Rank of the low-rank decomposition matrices."""
|
||||
@@ -288,14 +252,8 @@ class ModelConfig(BaseModelConfig):
|
||||
ac_offloading: ActivationOffloadingConfig | None = ActivationOffloadingConfig()
|
||||
"""Activation offloading configuration. If None, activation offloading is disabled."""
|
||||
|
||||
fsdp_cpu_offload: bool = False
|
||||
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
|
||||
|
||||
optim_cpu_offload: bool = True
|
||||
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
|
||||
|
||||
full_offload: OptimizerInBackwardOffload = None
|
||||
"""Full CPU optimizer offload: FP32 masters, moments, and gradients live in CPU RAM and the optimizer runs on CPU, overlapped with backward. Enable with ``true`` or a ``[model.full_offload]`` section; disabled by default."""
|
||||
offload: OffloadMode = "optimizer"
|
||||
"""CPU offloading. ``optimizer`` keeps optimizer states (momentum, variance) in CPU RAM and weights on GPU. ``full`` keeps FP32 masters, optimizer states, and accumulated gradients in CPU RAM and runs each optimizer chunk on CPU as soon as its last gradient arrives, overlapped with backward; it supports AdamW and SignSGD only, disables gradient clipping, and rounds each gradient to BF16 once before the FP32 CPU update. ``none`` keeps everything on GPU."""
|
||||
|
||||
reshard_after_forward: bool = True
|
||||
"""Reshard the model after each forward pass."""
|
||||
@@ -329,9 +287,6 @@ class ModelConfig(BaseModelConfig):
|
||||
dsa_backend: DSABackend = "tilelang"
|
||||
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
freeze_moe_router: bool | Literal["auto"] = "auto"
|
||||
"""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."""
|
||||
|
||||
@@ -358,20 +313,9 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ac_offloading_requires_ac(self):
|
||||
"""Automatically enable activation checkpointing when activation offloading is enabled."""
|
||||
if self.ac_offloading is not None and self.ac is None:
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
|
||||
raise ValueError("Cannot combine fsdp_cpu_offload with optimizer CPU offloading.")
|
||||
if self.optim_cpu_offload and self.full_offload:
|
||||
raise ValueError(
|
||||
"Cannot enable both optim_cpu_offload and full_offload. "
|
||||
"Set optim_cpu_offload=false when enabling full optimizer offload."
|
||||
)
|
||||
"""Activation offloading requires activation checkpointing, so ``ac = None`` disables both."""
|
||||
if self.ac is None:
|
||||
self.ac_offloading = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -612,6 +556,9 @@ class DataLoaderConfig(BaseConfig):
|
||||
fake: FakeDataLoaderConfig | None = None
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
num_workers: int = Field(1, ge=0)
|
||||
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
@@ -665,8 +612,8 @@ class TrainerConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
dist_timeout_seconds: int = 900
|
||||
"""Timeout in seconds for torch distributed ops: a hung collective (e.g. a dead rank) fails the run after this long."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
@@ -708,13 +655,13 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_requires_supported_optimizer(self):
|
||||
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
if self.model.offload == "full" and self.optim.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def full_optimizer_offload_disables_grad_clipping(self):
|
||||
if self.model.full_offload and self.optim.max_norm is not None:
|
||||
if self.model.offload == "full" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
@@ -748,12 +695,6 @@ class TrainerConfig(BaseConfig):
|
||||
validate_scheduler(self.scheduler, self.max_steps)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_opt_and_fsdp_offload(self):
|
||||
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
|
||||
@@ -86,8 +86,8 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
|
||||
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
|
||||
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
|
||||
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
|
||||
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
|
||||
propagate("ckpt.keep_last", "trainer.ckpt.keep_last")
|
||||
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval")
|
||||
|
||||
# [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.)
|
||||
# ``monitors.wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
|
||||
@@ -133,6 +133,10 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
|
||||
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
|
||||
|
||||
# [deployment] gpus_per_node → inference: the nested inference deployment sizes its
|
||||
# engines per node from its own copy.
|
||||
propagate("deployment.gpus_per_node", "inference.deployment.gpus_per_node")
|
||||
|
||||
# [slurm] → inference: a multi-node RL run drives its inference deployment under
|
||||
# the same SLURM allocation, so the nested inference inherits [slurm]. This is
|
||||
# what lets the nested InferenceConfig's multi-node / disaggregated SLURM check
|
||||
|
||||
+2
-2
@@ -225,9 +225,9 @@ requires-dist = [
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# verifiers pins harbor==0.24.0, published inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
harbor = "2026-10-08T00:00:00Z"
|
||||
tokenspeed-mla = false
|
||||
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
|
||||
flashinfer-python = false
|
||||
|
||||
@@ -42,7 +42,7 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
|
||||
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enable_prefix_caching = true`).
|
||||
|
||||
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--vllm.max-model-len None`.
|
||||
|
||||
|
||||
@@ -26,12 +26,11 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
|
||||
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
|
||||
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
|
||||
- Friendly errors: required-field boxes, validator errors point at the offending flag, unknown flags get a "did you mean" hint.
|
||||
- State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`.
|
||||
- State-only optimizer offload is enabled by default (`model.offload = "optimizer"`).
|
||||
- For gradients, FP32 masters, optimizer state, and optimizer-in-backward CPU execution, set
|
||||
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
|
||||
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
|
||||
halves the host RAM footprint), and disables gradient clipping. Use a
|
||||
`[model.full_offload]` table only to disable NUMA binding.
|
||||
`model.offload = "full"`. This mode uses the native CPU optimizer kernel, only supports
|
||||
AdamW and SignSGD (SignSGD is stateless and halves the host RAM footprint), disables
|
||||
gradient clipping, and pins each rank's CPUs to its GPU's NUMA node.
|
||||
|
||||
## `rl` — RL training
|
||||
|
||||
|
||||
@@ -320,6 +320,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_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
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -342,6 +344,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
ckpt_dir=ckpt_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
@@ -387,6 +390,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
ckpt_dir=ckpt_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
|
||||
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.eval import resume
|
||||
@@ -24,7 +26,7 @@ class Eval:
|
||||
|
||||
async def run(self) -> None:
|
||||
config = self.config
|
||||
landed: list[dict] = []
|
||||
landed: list[vf.WireEpisode] = []
|
||||
if config.resume:
|
||||
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
|
||||
landed = resume.take_landed(config.run_dir)
|
||||
@@ -41,17 +43,14 @@ class Eval:
|
||||
)
|
||||
resume.stamp_config(config.run_dir, dump_resolved_config(config))
|
||||
await self.runner.setup()
|
||||
restored: list = []
|
||||
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
|
||||
if config.resume:
|
||||
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
|
||||
self.runner.eval_source.restore(owed, groups)
|
||||
get_logger().info(
|
||||
f"Resuming from the trace stream: {len(restored)} episodes restored, "
|
||||
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
|
||||
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
|
||||
)
|
||||
|
||||
await self.runner.start()
|
||||
fired = self.runner.eval_source.trigger(0)
|
||||
await self.runner.run_epoch(fired, 0, restored=restored)
|
||||
await self.runner.drain()
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ class OnlineEval:
|
||||
|
||||
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
|
||||
# so nothing dispatches until ``run_epoch`` switches modes below.
|
||||
fired = runner.eval_source.trigger(step, force=force)
|
||||
fired, _ = runner.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
|
||||
if reload_weights:
|
||||
|
||||
+14
-50
@@ -1,20 +1,18 @@
|
||||
"""Resume an interrupted eval from its trace stream.
|
||||
|
||||
The stream records what landed, so it is what a resume continues from. The run's ok
|
||||
episodes are read back and rejoin the epoch as if they had just arrived - through the
|
||||
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
|
||||
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
|
||||
The stream records what landed, so it is what a resume continues from. Successful
|
||||
episodes rejoin the epoch through the monitors as if they had just arrived,
|
||||
so the rebuilt stream, the epoch's metrics and the platform upload cover the
|
||||
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
|
||||
ones the interruption cut off are owed again.
|
||||
|
||||
A landed episode counts toward the task with its ``task.key``, so a resumed run may
|
||||
select more or fewer examples or rollouts per example than the interrupted one: the
|
||||
kept episodes are matched to the new selection and the rest is owed. The resumed
|
||||
config is not checked against the interrupted one: any of it may be overridden.
|
||||
The shared Verifiers rollout planner matches these episodes to the current tasks
|
||||
by content hash. The resumed config is not checked against the interrupted one:
|
||||
any of it may be overridden.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.monitors.file.traces import get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
CONFIG_NAME = "eval.json"
|
||||
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
|
||||
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
|
||||
|
||||
|
||||
def take_landed(run_dir: Path) -> list[dict]:
|
||||
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
|
||||
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
|
||||
"""Successful episodes from every attempt; the planner deduplicates them.
|
||||
The current file monitor directory joins the archives so the resumed attempt writes a
|
||||
fresh stream, plan and metrics; nothing is deleted."""
|
||||
current = get_file_monitor_dir(run_dir)
|
||||
stream = get_trace_stream(run_dir).relative_to(current)
|
||||
landed: dict[str, dict] = {}
|
||||
landed: list[vf.WireEpisode] = []
|
||||
for directory in [*archives(run_dir), current]:
|
||||
if (directory / stream).is_dir():
|
||||
for record in read_records(directory / stream):
|
||||
if record.get("ok"):
|
||||
landed.setdefault(record["id"], record)
|
||||
episode = vf.WireEpisode.model_validate(record)
|
||||
if episode.ok and "traces" in record:
|
||||
landed.append(episode)
|
||||
if current.is_dir():
|
||||
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
|
||||
return list(landed.values())
|
||||
|
||||
|
||||
def plan(
|
||||
landed: list[dict], eval_envs: EvalEnvs
|
||||
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
|
||||
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
|
||||
order, the rollouts still owed per env and task key, and the group id a task's kept
|
||||
episodes carry, so the owed ones complete that group rather than open another."""
|
||||
targets: dict[str, Counter[str]] = {}
|
||||
for env in eval_envs:
|
||||
targets[env.name] = Counter(task.key for task in env.examples)
|
||||
for key in targets[env.name]:
|
||||
targets[env.name][key] *= env.config.group_size
|
||||
kept: list[vf.WireEpisode] = []
|
||||
counts: dict[str, Counter[str]] = defaultdict(Counter)
|
||||
groups: dict[str, dict[str, str]] = defaultdict(dict)
|
||||
for record in landed:
|
||||
env_name = record["env"].get("name") or record["env"]["id"]
|
||||
key = record["task"]["key"]
|
||||
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
|
||||
continue
|
||||
kept.append(vf.WireEpisode.model_validate(record))
|
||||
counts[env_name][key] += 1
|
||||
if (group := record.get("group") or {}).get("id"):
|
||||
groups[env_name].setdefault(key, group["id"])
|
||||
owed = {
|
||||
env_name: {
|
||||
key: target - counts[env_name][key]
|
||||
for key, target in target_counts.items()
|
||||
if target > counts[env_name][key]
|
||||
}
|
||||
for env_name, target_counts in targets.items()
|
||||
}
|
||||
return kept, owed, dict(groups)
|
||||
return landed
|
||||
|
||||
@@ -105,7 +105,7 @@ class EvalRunner:
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
# only used when the engine doesn't report its max context length.
|
||||
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
|
||||
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
|
||||
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=None,
|
||||
@@ -114,10 +114,11 @@ class EvalRunner:
|
||||
eval_source=self.eval_source,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
dispatch_per_minute=config.dispatch_per_minute,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
|
||||
@@ -10,7 +10,7 @@ from typing import Literal
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
|
||||
from prime_rl.orchestrator.clients import (
|
||||
ADMIN_TIMEOUT_S,
|
||||
UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
@@ -100,7 +100,7 @@ def _discovery_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
return headers
|
||||
|
||||
|
||||
def resolve_dynamo_discovery_url(client_config: ClientConfig) -> str:
|
||||
def resolve_dynamo_discovery_url(client_config: PolicyClientConfig) -> str:
|
||||
dynamo = client_config.dynamo
|
||||
if dynamo is None or not dynamo.enabled:
|
||||
raise ValueError("Dynamo discovery is not enabled")
|
||||
@@ -156,7 +156,7 @@ class DynamoAdminPlane(AdminPlane):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
client_config: PolicyClientConfig,
|
||||
model_name: str,
|
||||
*,
|
||||
poll_interval: float = 1.0,
|
||||
|
||||
@@ -12,24 +12,16 @@ def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, A
|
||||
if routed_experts is None:
|
||||
return None
|
||||
|
||||
array = np.asarray(routed_experts)
|
||||
assert array.ndim == 3
|
||||
assert np.issubdtype(array.dtype, np.integer)
|
||||
dtype = np.uint8
|
||||
if array.size:
|
||||
assert array.min() >= 0
|
||||
if array.max() > np.iinfo(np.uint8).max:
|
||||
# Models with >256 experts (e.g. NemotronH Super/Ultra: 512) need wider
|
||||
# indices. The payload self-describes via "dtype" so consumers pick it up.
|
||||
assert array.max() <= np.iinfo(np.uint16).max
|
||||
dtype = np.uint16
|
||||
|
||||
compact = np.ascontiguousarray(array.astype(dtype, copy=False))
|
||||
# vLLM's capturer picks uint8 or uint16 from the model's expert count, so every request of a
|
||||
# model has the same dtype and the orchestrator can pack them into one micro batch.
|
||||
compact = np.ascontiguousarray(routed_experts)
|
||||
assert compact.ndim == 3
|
||||
assert compact.dtype in (np.uint8, np.uint16), compact.dtype
|
||||
return {
|
||||
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
|
||||
"shape": list(compact.shape),
|
||||
"start": start,
|
||||
"dtype": np.dtype(dtype).name,
|
||||
"dtype": compact.dtype.name,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import fcntl
|
||||
import os
|
||||
import time
|
||||
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
|
||||
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.
|
||||
Metrics are not forwarded; the evaluation is the epoch."""
|
||||
|
||||
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
|
||||
|
||||
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
# (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:
|
||||
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
)
|
||||
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
|
||||
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
|
||||
else:
|
||||
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
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:
|
||||
pass
|
||||
"""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)
|
||||
|
||||
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."""
|
||||
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
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)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
|
||||
is — a bundle of sampling and the per-token training signal. This package
|
||||
turns the signal half into runtime objects (the sampling half is the env's
|
||||
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
|
||||
turns the signal half into runtime objects (the sampling half is interpreted by
|
||||
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
|
||||
@@ -22,7 +22,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
|
||||
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
|
||||
# (its TrainEnv interprets the sampling half). Every algorithm is
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
@@ -75,7 +75,6 @@ __all__ = [
|
||||
"RAEAlgorithm",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
"connect_frozen_client",
|
||||
"assign_advantages",
|
||||
"stamp_loss_routing",
|
||||
]
|
||||
|
||||
@@ -2,41 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
|
||||
|
||||
|
||||
def iter_trainable_traces(episodes: list[vf.Episode]):
|
||||
"""Yield clean trainable traces that contain sampled tokens."""
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
if trace.has_error or not trace.agent.trainable:
|
||||
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
|
||||
continue
|
||||
if any(any(node.mask) for node in trace.nodes):
|
||||
yield episode, trace
|
||||
|
||||
@@ -696,11 +696,10 @@ def _distribute_group(
|
||||
|
||||
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
|
||||
"""
|
||||
Pad a micro batch with the given padding size sample
|
||||
Return the padded micro batch.
|
||||
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
|
||||
Args:
|
||||
micro_batch: The micro batch to pad.
|
||||
padding_size: The number of padding tokens to add.
|
||||
pad_to_multiple_of: The multiple to pad the sequence length up to.
|
||||
Returns:
|
||||
The padded micro batch.
|
||||
"""
|
||||
|
||||
@@ -20,7 +20,8 @@ from verifiers.v1.configs.client import (
|
||||
resolve_headers,
|
||||
)
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.shared import ClientConfig, PolicyClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -208,7 +209,7 @@ class AdminPlane:
|
||||
await client.aclose()
|
||||
|
||||
|
||||
def setup_admin_plane(client_config: ClientConfig, model_name: str) -> AdminPlane:
|
||||
def setup_admin_plane(client_config: PolicyClientConfig, model_name: str) -> AdminPlane:
|
||||
dynamo = client_config.dynamo
|
||||
if dynamo is not None and dynamo.enabled:
|
||||
from prime_rl.inference.dynamo import DynamoAdminPlane
|
||||
@@ -228,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
|
||||
await admin.aclose()
|
||||
|
||||
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
|
||||
|
||||
def setup_client(
|
||||
client_config: ClientConfig,
|
||||
client_type: str = "openai_chat_completions",
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.algo.base import iter_trainable_traces
|
||||
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
|
||||
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
|
||||
|
||||
@@ -48,7 +49,7 @@ class Curriculum:
|
||||
self.gates[name] = gate
|
||||
|
||||
def on_result(self, group: list[vf.Episode]) -> bool:
|
||||
"""Observe every result, evaluate every gate, and combine with AND."""
|
||||
"""Observe every result and admit trainable groups that pass every gate."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
task_keys = {episode.task.key for episode in group}
|
||||
@@ -63,7 +64,7 @@ class Curriculum:
|
||||
if not isinstance(decision, bool):
|
||||
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
|
||||
decisions.append(decision)
|
||||
return all(decisions)
|
||||
return all(decisions) and any(iter_trainable_traces(group))
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
|
||||
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
|
||||
advantage
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
if episode.ok and not trace.has_error and trace.agent.trainable
|
||||
for node in trace.nodes
|
||||
for advantage in node.advantages or []
|
||||
]
|
||||
|
||||
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
|
||||
trace.reward
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
|
||||
]
|
||||
if not rewards:
|
||||
return
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
the concurrency controller moves it via ``set_limit``; refills are
|
||||
burst-capped so a raised (or drained) cap never lands all its prefills at
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Optional rate limiting via ``AsyncLimiter(dispatch_per_minute, 60)``, one token per episode.
|
||||
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
|
||||
episode returned by the environment, as a ``DispatchFailure`` when no
|
||||
episode was produced, or under the group's ``GroupCancellation`` when the
|
||||
@@ -139,13 +139,15 @@ class Dispatcher:
|
||||
progress: Progress | None,
|
||||
initial_max_inflight: int,
|
||||
max_inflight_ceiling: int | None,
|
||||
tasks_per_minute: float | None,
|
||||
dispatch_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
policy_weights_change: bool = True,
|
||||
on_episode_complete: Callable[[int], None] | None = None,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.policy_weights_change = policy_weights_change
|
||||
self.progress = progress
|
||||
self.train_envs = train_envs
|
||||
self.eval_envs = eval_envs
|
||||
@@ -166,7 +168,7 @@ class Dispatcher:
|
||||
self.max_inflight = initial_max_inflight
|
||||
self.current_inflight = 0
|
||||
self.rate_limiter: AsyncLimiter | None = (
|
||||
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
|
||||
AsyncLimiter(dispatch_per_minute, time_period=60) if dispatch_per_minute else None
|
||||
)
|
||||
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
|
||||
# window. Replacing a completed episode is always free (each natural
|
||||
@@ -214,10 +216,10 @@ class Dispatcher:
|
||||
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.clients, self.policy.model_name, True
|
||||
return source.clients, source.clients.model_name, False
|
||||
env = self.train_envs.get(env_name)
|
||||
if env.uses_live_policy:
|
||||
return env.clients, self.policy.model_name, True
|
||||
return env.clients, env.clients.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -316,7 +318,7 @@ class Dispatcher:
|
||||
return [
|
||||
(self.progress.step - 1) - meta.policy_version
|
||||
for meta in self.inflight.values()
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
|
||||
]
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
@@ -423,7 +425,7 @@ class Dispatcher:
|
||||
gid
|
||||
for gid, group in self.groups.items()
|
||||
if group.kind == "train"
|
||||
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
|
||||
and self.train_envs.get(group.env_name).uses_live_policy
|
||||
and group.policy_version_at_start < min_version
|
||||
]
|
||||
cancelled = 0
|
||||
@@ -556,10 +558,8 @@ class Dispatcher:
|
||||
if env_collection is None:
|
||||
return False
|
||||
env = env_collection.get(group.env_name)
|
||||
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
|
||||
# version would invalidate its prefix cache every weight update for
|
||||
# no reason.
|
||||
if live_sourced:
|
||||
# Only endpoints receiving policy weight updates need a cache salt.
|
||||
if live_sourced and self.policy_weights_change:
|
||||
cache_salt = str(group.policy_version_at_start)
|
||||
else:
|
||||
cache_salt = None
|
||||
@@ -665,10 +665,6 @@ class Dispatcher:
|
||||
)
|
||||
return
|
||||
|
||||
if not episode.traces and episode.ok:
|
||||
episode.ok = False
|
||||
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
|
||||
|
||||
for trace in episode.traces:
|
||||
if trace.is_timeout and not trace.has_error and meta.kind == "train":
|
||||
# Training keeps a timed-out rollout out of the batch: an error,
|
||||
@@ -676,14 +672,6 @@ class Dispatcher:
|
||||
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure (``has_error`` reads ``ok``).
|
||||
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
|
||||
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if trace.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if trace.last_error is not None:
|
||||
@@ -691,8 +679,14 @@ class Dispatcher:
|
||||
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{trace.last_error.type}: {trace.last_error.message}"
|
||||
)
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not episode.ok:
|
||||
if not any(trace.has_error for trace in episode.traces):
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
error = episode.last_error
|
||||
get_logger().warning(
|
||||
f"Episode failed in group {meta.group_id} ({meta.env_name})"
|
||||
+ (f" — {error.type}: {error.message}" if error is not None else "")
|
||||
)
|
||||
if self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(episode.num_total_tokens)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
@@ -722,7 +716,7 @@ class Dispatcher:
|
||||
live_policy = meta.kind == "eval"
|
||||
if meta.kind == "train":
|
||||
assert self.train_envs is not None
|
||||
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
|
||||
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
|
||||
work: vf.WorkInfo = (
|
||||
vf.EvalWorkInfo(step=meta.step, policy=policy)
|
||||
|
||||
@@ -26,11 +26,13 @@ from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from renderers import RendererConfig
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import env_address_file
|
||||
|
||||
@@ -65,7 +67,7 @@ class Env:
|
||||
self.address_file = address_file
|
||||
"""Where a launcher-managed server publishes its address; read when ``address``
|
||||
is None."""
|
||||
self.sampling_args: dict = {}
|
||||
self.sampling = vf.SamplingConfig()
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count; ``None`` means the selected tasks never end."""
|
||||
self.tasks: Iterator[vf.Task] | None = None
|
||||
@@ -108,10 +110,10 @@ class Env:
|
||||
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
sampling = self.sampling
|
||||
if cache_salt is not None:
|
||||
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
return vf.SamplingConfig(**sampling)
|
||||
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
|
||||
return sampling
|
||||
|
||||
async def run(
|
||||
self,
|
||||
@@ -121,25 +123,16 @@ class Env:
|
||||
task_data: dict,
|
||||
on_delta: Callable[[dict], None] | None = None,
|
||||
) -> vf.WireEpisode:
|
||||
"""Run and return one typed episode. A failed multi-trace episode marks
|
||||
its otherwise-clean traces failed so partial episodes never train.
|
||||
"""Run and return the native typed episode.
|
||||
``on_delta`` sees each delta of the env server's stream — a turn or a phase
|
||||
change of one of the episode's traces — as it lands."""
|
||||
episode = await self.env_client.run(
|
||||
return await self.env_client.run(
|
||||
task_data=task_data,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling=self._sampling(cache_salt),
|
||||
on_delta=on_delta,
|
||||
)
|
||||
for trace in episode.traces:
|
||||
if not episode.ok and trace.ok:
|
||||
error = episode.last_error or vf.Error(
|
||||
type="EpisodeFailed", message="A sibling trace in this episode failed"
|
||||
)
|
||||
trace.errors = [*trace.errors, error]
|
||||
trace.ok = False
|
||||
return episode
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
@@ -150,17 +143,39 @@ class TrainEnv(Env):
|
||||
config: TrainSourceConfig,
|
||||
address: str | None,
|
||||
address_file: Path,
|
||||
generation_source: GenerationSource,
|
||||
clients: InferenceClient,
|
||||
renderer_config: RendererConfig | None,
|
||||
algorithm: Algorithm,
|
||||
):
|
||||
super().__init__(config, address, address_file)
|
||||
self.generation_source = generation_source
|
||||
# Train rollouts are generated from `clients`: the policy, or the frozen
|
||||
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
|
||||
self.clients = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected: InferenceClient | None = None
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = (
|
||||
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
|
||||
self.uses_live_policy = config.algo.sampling.source == "policy"
|
||||
self.sampling = vf.SamplingConfig(
|
||||
**config.sampling.model_dump(exclude_none=True),
|
||||
# Only policy rollouts need sampling logprobs for importance ratios.
|
||||
logprobs=True if self.uses_live_policy else None,
|
||||
)
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
|
||||
|
||||
async def setup(self) -> None:
|
||||
async def connect_source() -> None:
|
||||
source = self.config.algo.sampling.source
|
||||
if isinstance(source, FrozenModelConfig):
|
||||
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
|
||||
self.clients = self.connected
|
||||
|
||||
await asyncio.gather(connect_source(), self.algorithm.setup())
|
||||
|
||||
async def aclose(self) -> None:
|
||||
for clients in (self.connected, self.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
@@ -168,7 +183,7 @@ class EvalEnv(Env):
|
||||
|
||||
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
|
||||
super().__init__(config, address, address_file)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.sampling = config.sampling
|
||||
self.examples: list[vf.Task] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -218,9 +233,8 @@ class Envs(Generic[EnvT]):
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments, each paired with its
|
||||
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
"""Collection of training environments, each with its runtime
|
||||
:class:`Algorithm`, built from the env's resolved algorithm config."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -238,7 +252,8 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
env_address_file(config_dir, "train", config.resolved_name),
|
||||
GenerationSource(config.algo.sampling, clients, renderer_config),
|
||||
clients,
|
||||
renderer_config,
|
||||
build_algorithm(config.algo, clients),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
import uuid
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import Iterable
|
||||
from itertools import zip_longest
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.utils.eval import plan_rollouts
|
||||
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
|
||||
|
||||
@@ -42,54 +45,50 @@ class EvalSource:
|
||||
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
self.owed: dict[str, dict[str, int]] | None = None
|
||||
self.groups: dict[str, dict[str, str]] = {}
|
||||
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
|
||||
"""Rollouts the next trigger still owes per env and task key, the rest having
|
||||
landed before a resume; a task without an entry is complete. ``groups`` is the
|
||||
group id the landed rollouts of a task carry, which the owed ones join."""
|
||||
self.owed = owed
|
||||
self.groups = groups
|
||||
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
"""Fire eligible envs for ``step`` and return their names. On resume
|
||||
def trigger(
|
||||
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
|
||||
) -> tuple[list[str], list[vf.WireEpisode]]:
|
||||
"""Fire eligible envs and return their names and matched saved episodes. On resume
|
||||
``first_trigger`` is False, so the startup/base eval doesn't re-run.
|
||||
``force`` fires every env regardless of interval (e.g. the evals process's
|
||||
final-checkpoint eval)."""
|
||||
is_first, self.first_trigger = self.first_trigger, False
|
||||
if is_first and self.skip_first_step:
|
||||
return []
|
||||
return [], []
|
||||
fired = [
|
||||
name
|
||||
for name, interval in self.intervals.items()
|
||||
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
|
||||
]
|
||||
owed, self.owed = self.owed, None
|
||||
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
|
||||
for episode in completed:
|
||||
saved[episode.env.name or episode.env.id].append(episode)
|
||||
restored: list[vf.WireEpisode] = []
|
||||
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
# rollouts back-to-back, so per-example prefix-cache locality holds
|
||||
iters = [iter(self.tasks_by_env[name]) for name in fired]
|
||||
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
|
||||
for round_tasks in zip_longest(*iters):
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
for env_name, planned in zip(fired, round_tasks, strict=True):
|
||||
if planned is None:
|
||||
continue
|
||||
rollouts = self.group_sizes[env_name]
|
||||
if owed is not None:
|
||||
# duplicate tasks share a key: each takes up to a group of what the key owes
|
||||
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
|
||||
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
|
||||
task, kept, rollouts = planned
|
||||
# Each selected occurrence owns one group, including its restored episodes.
|
||||
group = vf.GroupInfo(id=str(uuid.uuid4()))
|
||||
for episode in kept:
|
||||
episode.group = group
|
||||
restored.extend(kept)
|
||||
if rollouts > 0:
|
||||
group_id = self.groups.get(env_name, {}).get(task.key)
|
||||
self.queue.append(
|
||||
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
|
||||
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
|
||||
)
|
||||
return fired
|
||||
return fired, restored
|
||||
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
"""Resolve the model source used to generate an env's train episodes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
|
||||
from prime_rl.orchestrator.algo import connect_frozen_client
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference clients.
|
||||
|
||||
``clients`` is what train rollouts are generated from: the policy clients,
|
||||
swapped for a connected frozen endpoint in :meth:`setup` when the source is
|
||||
an inline frozen model. A frozen source *generates* rollouts, so it uses
|
||||
the renderer (token-in/out) client (built from ``renderer_config``) — the
|
||||
rollout must carry tokens for training."""
|
||||
|
||||
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
|
||||
assert config.source is not None, "sampling.source must be resolved by config validation"
|
||||
self.config = config
|
||||
self.clients: InferenceClient = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect clients to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected = self.clients
|
||||
|
||||
@property
|
||||
def uses_live_policy(self) -> bool:
|
||||
return self.config.source == "policy"
|
||||
|
||||
def sampling_args(self, args: dict) -> dict:
|
||||
"""Source-specific sampling-arg overrides. Sampling logprobs are only
|
||||
needed for importance ratios on policy-sampled tokens — frozen
|
||||
endpoints may reject the knob."""
|
||||
if not self.uses_live_policy:
|
||||
args.pop("logprobs", None)
|
||||
return args
|
||||
@@ -86,11 +86,6 @@ SHUTDOWN_TIMEOUT_S = 300
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# Default wait for the trainer's startup weight broadcast when no ckpt block
|
||||
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
|
||||
# broadcast is always coming, so wait rather than fail immediately.
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -282,10 +277,7 @@ class Orchestrator:
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
*(env.generation_source.setup() for env in self.train_envs),
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
await asyncio.gather(*(env.setup() for env in self.train_envs))
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
@@ -305,9 +297,6 @@ class Orchestrator:
|
||||
# scratch). The startup broadcast is always coming, so wait for it rather
|
||||
# than failing immediately when it is not there yet.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -333,7 +322,7 @@ class Orchestrator:
|
||||
progress=self.progress,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
dispatch_per_minute=config.dispatch_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
@@ -386,7 +375,7 @@ class Orchestrator:
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
|
||||
await self.watcher.sync_startup(sync_version, timeout=config.weight_broadcast.timeout)
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -415,16 +404,20 @@ class Orchestrator:
|
||||
# CancelledError, KeyboardInterrupt, or a real error), so the teardown
|
||||
# logs a forced-cleanup warning instead of a clean-exit success.
|
||||
clean_exit = False
|
||||
loop_done = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
loop_done = True
|
||||
await self.wait_for_final_broadcast()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship). Saved before finalize, which tells the launcher the run is done.
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
# first ship). Saved before finalize, which tells the launcher the run is done. Only once the
|
||||
# step loop finished (the last step is fully shipped); a crash mid-loop leaves no consistent
|
||||
# state for that step, and the trainer has no checkpoint for it.
|
||||
if loop_done and self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
@@ -441,7 +434,7 @@ class Orchestrator:
|
||||
await monitors.finalize()
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
await self.stop()
|
||||
await self.stop(clean_exit)
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished")
|
||||
else:
|
||||
@@ -769,7 +762,7 @@ class Orchestrator:
|
||||
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
|
||||
return
|
||||
is_final = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
fired = self.eval_source.trigger(step, force=is_final)
|
||||
fired, _ = self.eval_source.trigger(step, force=is_final)
|
||||
if not fired:
|
||||
return
|
||||
self.eval_triggered_steps.add(step)
|
||||
@@ -994,7 +987,7 @@ class Orchestrator:
|
||||
self.update_dispatch_gate()
|
||||
self.version_advanced.set()
|
||||
|
||||
async def stop(self) -> None:
|
||||
async def stop(self, clean_exit: bool) -> None:
|
||||
"""Bounded best-effort teardown of all components. Has a global
|
||||
timeout so a wedged peer can't keep the process alive forever —
|
||||
training artifacts are already persisted before this is reached."""
|
||||
@@ -1024,11 +1017,9 @@ class Orchestrator:
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
if self.train_envs is not None:
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
get_logger().debug("Stopping train env clients")
|
||||
for env in self.train_envs:
|
||||
for clients in (env.generation_source.connected, env.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
await env.aclose()
|
||||
|
||||
get_logger().info("Stopping orchestrator components")
|
||||
t0 = time.perf_counter()
|
||||
@@ -1039,7 +1030,7 @@ class Orchestrator:
|
||||
f"Orchestrator shutdown did not complete within {SHUTDOWN_TIMEOUT_S}s; "
|
||||
"forcing process exit. Training artifacts are already persisted."
|
||||
)
|
||||
os._exit(0)
|
||||
os._exit(0 if clean_exit else 1)
|
||||
await task
|
||||
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@@ -255,7 +255,7 @@ class TrainSink:
|
||||
return
|
||||
|
||||
samples_by_trace: dict[str, list[TrainingSample]] = {}
|
||||
temperature = env.sampling_args["temperature"]
|
||||
temperature = env.config.sampling.temperature
|
||||
for trace in survivors:
|
||||
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
|
||||
for sample in samples:
|
||||
|
||||
@@ -24,7 +24,7 @@ class WeightWatcher:
|
||||
policy: Policy,
|
||||
observers: list[VersionObserver],
|
||||
ckpt_step: int = 0,
|
||||
poll_interval: float = 1.0,
|
||||
poll_interval: float = 0.1,
|
||||
) -> None:
|
||||
self.receiver = receiver
|
||||
self.policy = policy
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
@@ -599,17 +601,25 @@ while true; do
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
{%- if cleanup_grace_period %}
|
||||
{%- if cleanup_grace_period and ckpt_dir %}
|
||||
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
|
||||
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
|
||||
# wall-time) we stay alive for the grace period and signal nothing: this lets an
|
||||
# in-flight trainer checkpoint on this node finish, and — because the task has
|
||||
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
|
||||
# on peer nodes. We then propagate the exit code so the allocation tears down. A
|
||||
# clean (zero) exit cannot trip --kill-on-bad-exit, so we tear down immediately.
|
||||
# wall-time) we stay alive and signal nothing while the newest trainer checkpoint
|
||||
# is still being written (no DCP `.metadata` yet), up to the grace period: this lets
|
||||
# it finish on this node, and — because the task has not exited yet — keeps
|
||||
# --kill-on-bad-exit from reaping checkpointing trainers on peer nodes. We then
|
||||
# propagate the exit code so the allocation tears down. A clean (zero) exit cannot
|
||||
# trip --kill-on-bad-exit, so we tear down immediately.
|
||||
if [ "$EXIT_CODE" -ne 0 ]; then
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
|
||||
sleep {{ cleanup_grace_period }}
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for an in-flight trainer checkpoint to finish before teardown"
|
||||
GRACE_DEADLINE=$((SECONDS + {{ cleanup_grace_period }}))
|
||||
while [ "$SECONDS" -lt "$GRACE_DEADLINE" ]; do
|
||||
LATEST_CKPT=$(ls -d {{ ckpt_dir }}/step_*/trainer 2>/dev/null | sort -V | tail -n 1)
|
||||
if [ -z "$LATEST_CKPT" ] || [ -f "$LATEST_CKPT/.metadata" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
fi
|
||||
{%- endif %}
|
||||
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --exclusive
|
||||
{%- if partition %}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- endif %}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
|
||||
@@ -25,6 +25,7 @@ from prime_rl.trainer.models.fusions import (
|
||||
write_back_loaded_packed_optimizer_state,
|
||||
)
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.utils import get_dcp_group
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
@@ -204,11 +205,11 @@ class CheckpointManager:
|
||||
# FileExistsError (EEXIST + stale is_dir() metadata).
|
||||
if self.world.is_master:
|
||||
dataloader_dir.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
torch.distributed.barrier(group=get_dcp_group())
|
||||
torch.save(dataloader.state_dict(), dataloader_dir / f"rank_{self.world.rank}.pt")
|
||||
|
||||
# Save sharded state
|
||||
dcp_save(state_dict, checkpoint_id=path)
|
||||
dcp_save(state_dict, checkpoint_id=path, process_group=get_dcp_group())
|
||||
|
||||
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
|
||||
|
||||
@@ -228,7 +229,7 @@ class CheckpointManager:
|
||||
# Load sharded state
|
||||
app_state = AppState(model, optimizers if not self.skip_optimizer else [], scheduler, progress)
|
||||
state_dict = {"app": app_state}
|
||||
dcp_load(state_dict=state_dict, checkpoint_id=path)
|
||||
dcp_load(state_dict=state_dict, checkpoint_id=path, process_group=get_dcp_group())
|
||||
if self.skip_optimizer:
|
||||
for optimizer in optimizers:
|
||||
if isinstance(optimizer, OffloadOptimizer):
|
||||
@@ -282,7 +283,7 @@ class CheckpointManager:
|
||||
# re-raise FileExistsError on a parallel FS (see save_to_path).
|
||||
if self.world.is_master:
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
torch.distributed.barrier()
|
||||
torch.distributed.barrier(group=get_dcp_group())
|
||||
|
||||
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
|
||||
@@ -16,10 +16,9 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_common import FSDPMeshInfo, ShardPlacementResult
|
||||
from torch.distributed.fsdp._fully_shard._fsdp_init import _get_mesh_info
|
||||
from torch.distributed.tensor import Shard
|
||||
@@ -63,7 +62,8 @@ from prime_rl.trainer.models.qwen3_8_flash_next.indexer import SparseAttentionIn
|
||||
from prime_rl.trainer.models.qwen3_8_flash_next.ngram_embedding import NGramEmbedding
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.utils import get_dcp_group
|
||||
from prime_rl.trainer.world import get_world, wait_for_master
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
@@ -108,6 +108,9 @@ DTYPE_MAP = {
|
||||
"float32": torch.float32,
|
||||
}
|
||||
|
||||
# The one-time HF <-> PrimeRL conversion runs on the master alone and can take hours for large models.
|
||||
CONVERSION_TIMEOUT_S = 4 * 3600
|
||||
|
||||
# We increase the torch.compile recompile limit and cache size as we found this
|
||||
# necessary for training INTELLECT-3 with Muon.
|
||||
torch._dynamo.config.recompile_limit = 16 # default: 8
|
||||
@@ -353,22 +356,15 @@ def get_model(
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.dsa_backend = config.dsa_backend
|
||||
if config.index_cache is not None:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
model_config.index_topk_pattern = config.index_cache.topk_pattern
|
||||
# Explicit override supersedes the model's native IndexShare schedule.
|
||||
model_config.indexer_types = None
|
||||
else:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
@@ -509,7 +505,7 @@ def _expert_shard_placement_fn(
|
||||
|
||||
def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
|
||||
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
|
||||
offload_policy: OffloadPolicy = OffloadPolicy()
|
||||
|
||||
fused_shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
|
||||
hsdp_mesh = parallel_dims.get_mesh("hsdp")
|
||||
@@ -695,7 +691,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
|
||||
def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
device = "cpu" if config.fsdp_cpu_offload else "cuda"
|
||||
device = "cuda"
|
||||
model.to_empty(device=device)
|
||||
torch.distributed.barrier()
|
||||
|
||||
@@ -705,7 +701,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
logger = get_logger()
|
||||
if config.debug.random_init:
|
||||
logger.warning("Randomly initializing model. Skipping loading weights from HF.")
|
||||
_move_buffers_to_cuda(model, config)
|
||||
return
|
||||
|
||||
if not Path(config.name).exists():
|
||||
@@ -760,7 +755,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
del snapshot_state_dict
|
||||
|
||||
# All ranks wait for master rank to finish conversion
|
||||
torch.distributed.barrier()
|
||||
wait_for_master(f"model_conversion:{config.name}", timeout=CONVERSION_TIMEOUT_S)
|
||||
if snapshot_path.name == "prime" and not (snapshot_path / ".prime-v1").is_file():
|
||||
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
|
||||
|
||||
@@ -773,9 +768,9 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
dcp_load(
|
||||
state_dict,
|
||||
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
|
||||
process_group=get_dcp_group(),
|
||||
)
|
||||
write_back_loaded_packed_parameters(model, state_dict)
|
||||
_move_buffers_to_cuda(model, config)
|
||||
|
||||
lora_modules = [m for m in model.modules() if hasattr(m, "_init_lora_parameters")]
|
||||
if lora_modules:
|
||||
@@ -841,16 +836,8 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
mark_dynamic_int_args()
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
layer = language_model.layers[layer_id]
|
||||
if isinstance(layer, CheckpointWrapper) and any(
|
||||
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
|
||||
):
|
||||
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
|
||||
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
|
||||
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
|
||||
layer = layer._checkpoint_wrapped_module
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
@@ -891,15 +878,6 @@ def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.
|
||||
return frozen_vision_encoder
|
||||
|
||||
|
||||
def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
|
||||
"""FSDP CPU offloading only manages parameters, not buffers. Move buffers to CUDA."""
|
||||
if not config.fsdp_cpu_offload:
|
||||
return
|
||||
for _, buffer in model.named_buffers():
|
||||
if buffer.device.type == "cpu":
|
||||
buffer.data = buffer.data.to("cuda")
|
||||
|
||||
|
||||
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
@@ -1011,24 +989,22 @@ def setup_model(
|
||||
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
|
||||
)
|
||||
|
||||
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if loading_from_checkpoint_later:
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
)
|
||||
device = "cpu" if config.fsdp_cpu_offload else "cuda"
|
||||
device = "cuda"
|
||||
model.to_empty(device=device)
|
||||
torch.distributed.barrier()
|
||||
model.init_buffers_post_meta()
|
||||
_move_buffers_to_cuda(model, config)
|
||||
else:
|
||||
load_dcp_from_hf(model, config, parallel_dims)
|
||||
|
||||
|
||||
@@ -367,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
|
||||
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
|
||||
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
mhc_states = decoder_layer(
|
||||
mhc_states,
|
||||
input_ids=input_ids,
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
|
||||
if weight.ndim != 2:
|
||||
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
|
||||
|
||||
rows, cols = weight.shape
|
||||
pad_rows = (block_size - rows % block_size) % block_size
|
||||
pad_cols = (block_size - cols % block_size) % block_size
|
||||
|
||||
if pad_rows or pad_cols:
|
||||
padded = torch.zeros(
|
||||
rows + pad_rows,
|
||||
cols + pad_cols,
|
||||
dtype=weight.dtype,
|
||||
device=weight.device,
|
||||
)
|
||||
padded[:rows, :cols] = weight
|
||||
else:
|
||||
padded = weight.contiguous()
|
||||
|
||||
padded_rows, padded_cols = padded.shape
|
||||
blocks = padded.view(
|
||||
padded_rows // block_size,
|
||||
block_size,
|
||||
padded_cols // block_size,
|
||||
block_size,
|
||||
).permute(0, 2, 1, 3)
|
||||
|
||||
fp8_max = torch.finfo(torch.float8_e4m3fn).max
|
||||
max_abs = blocks.float().abs().amax(dim=(2, 3))
|
||||
scales = (max_abs / fp8_max).clamp(min=1e-12)
|
||||
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
|
||||
|
||||
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
|
||||
return quantized, scales.float().contiguous()
|
||||
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
cached_indices = None
|
||||
use_index_cache = getattr(self.config, "use_index_cache", False)
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states, next_cached_indices = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings,
|
||||
|
||||
@@ -12,6 +12,7 @@ import triton.language as tl
|
||||
FP8_MAX = 448.0
|
||||
FP8_MIN = -448.0
|
||||
FP8_EPS = 1e-10
|
||||
KEY_ALIGNMENT = 16
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
|
||||
return x_q, x_s
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
|
||||
],
|
||||
key=["S_Q", "S_K_BUCKET", "H", "D"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_fp8_indexer_kernel(
|
||||
Q_fp8,
|
||||
@@ -116,7 +106,6 @@ def _triton_fp8_indexer_kernel(
|
||||
stride_ws,
|
||||
H: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
S_K_BUCKET: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
@@ -201,6 +190,8 @@ def fp8_indexer(
|
||||
|
||||
q_flat = q.reshape(S_q * H, D).contiguous()
|
||||
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
|
||||
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
|
||||
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
|
||||
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
|
||||
|
||||
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
|
||||
@@ -209,12 +200,10 @@ def fp8_indexer(
|
||||
q_scales = q_scales.view(S_q, H)
|
||||
w = w * q_scales
|
||||
|
||||
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
|
||||
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
|
||||
|
||||
grid = lambda meta: (
|
||||
triton.cdiv(S_q, meta["BLOCK_M"]),
|
||||
triton.cdiv(S_k, meta["BLOCK_N"]),
|
||||
)
|
||||
BLOCK_M, BLOCK_N = 64, 128
|
||||
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
|
||||
_triton_fp8_indexer_kernel[grid](
|
||||
q_fp8,
|
||||
k_fp8,
|
||||
@@ -224,16 +213,17 @@ def fp8_indexer(
|
||||
ks,
|
||||
ke,
|
||||
S_q,
|
||||
S_k,
|
||||
S_k_aligned,
|
||||
q_fp8.stride(0),
|
||||
q_fp8.stride(1),
|
||||
k_fp8.stride(0),
|
||||
w.stride(0),
|
||||
H=H,
|
||||
D=D,
|
||||
# Packed document tails change S_k between batches. Reuse tuning within
|
||||
# a size bucket; exact S_k still controls strides and all bounds masks.
|
||||
S_K_BUCKET=triton.next_power_of_2(S_k),
|
||||
BLOCK_M=BLOCK_M,
|
||||
BLOCK_N=BLOCK_N,
|
||||
num_warps=4,
|
||||
num_stages=2,
|
||||
)
|
||||
|
||||
actual_topk = min(topk, S_k)
|
||||
|
||||
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
|
||||
}
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
|
||||
__all__ = ["RMSNorm", "RMSNormConfig"]
|
||||
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
cu_seqlens,
|
||||
|
||||
@@ -13,6 +13,8 @@ from prime_rl.utils.cp import CPContext
|
||||
# FLA's stacked output buffer. Keep CP convolution eager until this is fixed:
|
||||
# https://github.com/pytorch/pytorch/issues/155632
|
||||
causal_conv1d_with_context_parallelism = torch.compiler.disable(causal_conv1d)
|
||||
# CP setup searchsorts tensor-valued sequence boundaries; keep it outside the compiled graph.
|
||||
build_cp_context_eager = torch.compiler.disable(build_cp_context)
|
||||
|
||||
|
||||
class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
@@ -65,7 +67,7 @@ class Qwen3_5GatedDeltaNet(nn.Module):
|
||||
|
||||
context = None
|
||||
if self.cp_context.cp_enabled:
|
||||
context = build_cp_context(
|
||||
context = build_cp_context_eager(
|
||||
cu_seqlens=cu_seqlens.to(device=hidden_states.device, dtype=torch.int32),
|
||||
group=self.cp_context.cp_group,
|
||||
conv1d_kernel_size=self.conv_kernel_size,
|
||||
|
||||
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -5,7 +5,7 @@ from torch import nn
|
||||
from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.optim import AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.configs.trainer import OffloadMode, OptimizerConfig
|
||||
from prime_rl.trainer.models.fusions import get_model_packed_parameters
|
||||
from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer
|
||||
from prime_rl.trainer.optim.base import OptimizerLike
|
||||
@@ -51,21 +51,20 @@ def setup_optimizer(
|
||||
config: OptimizerConfig,
|
||||
named_params: list[tuple[str, nn.Parameter]],
|
||||
parallel_dims: ParallelDims,
|
||||
cpu_offload: bool = False,
|
||||
full_offload_config: OptimizerInBackwardOffloadConfig | None = None,
|
||||
offload: OffloadMode = "none",
|
||||
model: nn.Module | None = None,
|
||||
full_offload_dtype_policy: dict[int, tuple[torch.dtype, torch.dtype]] | None = None,
|
||||
) -> tuple[OptimizerLike, GradientOffloadManager | None]:
|
||||
if cpu_offload and full_offload_config is not None:
|
||||
raise ValueError("State-only and full optimizer CPU offload cannot both be enabled")
|
||||
if full_offload_config is not None and config.type not in ("adamw", "sign_sgd"):
|
||||
cpu_offload = offload == "optimizer"
|
||||
full_offload = offload == "full"
|
||||
if full_offload and config.type not in ("adamw", "sign_sgd"):
|
||||
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
|
||||
if full_offload_config is not None and config.max_norm is not None:
|
||||
if full_offload and config.max_norm is not None:
|
||||
get_logger().warning("Disabling gradient clipping because CPU optimizer offload updates during backward")
|
||||
config.max_norm = None
|
||||
optimizer_named_params = named_params
|
||||
master_weights = None
|
||||
if full_offload_config is not None:
|
||||
if full_offload:
|
||||
if model is None:
|
||||
raise ValueError("CPU optimizer offload requires the model")
|
||||
if full_offload_dtype_policy is None:
|
||||
@@ -82,12 +81,11 @@ def setup_optimizer(
|
||||
model=model,
|
||||
)
|
||||
|
||||
if full_offload_config is not None:
|
||||
if full_offload:
|
||||
assert master_weights is not None
|
||||
get_logger().info("Using CPU offload for gradients and the optimizer step")
|
||||
optimizer = FullCPUOffloadOptimizer(
|
||||
optimizer,
|
||||
offload_config=full_offload_config,
|
||||
master_weights=master_weights,
|
||||
dp_replicate=parallel_dims.dp_replicate,
|
||||
)
|
||||
|
||||
@@ -14,7 +14,6 @@ from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.optim import AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.optim.base import OffloadOptimizer
|
||||
from prime_rl.trainer.optim.cpu_adam import adamw_step as native_cpu_adamw_step
|
||||
from prime_rl.trainer.optim.cpu_adam import copy_or_add_bfloat16_multi_ as native_copy_or_add_bfloat16_multi_
|
||||
@@ -714,12 +713,10 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
|
||||
def __init__(
|
||||
self,
|
||||
optimizer: Optimizer,
|
||||
offload_config: OptimizerInBackwardOffloadConfig,
|
||||
master_weights: dict[int, _MasterWeight],
|
||||
dp_replicate: int = 1,
|
||||
):
|
||||
self.optimizer = optimizer
|
||||
self.offload_config = offload_config
|
||||
self._initialized = False
|
||||
self._master_weights = master_weights
|
||||
self._chunks = self._build_chunks()
|
||||
|
||||
@@ -112,7 +112,7 @@ class ParallelDims:
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
# Mesh for data loading and per-step token counts
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
@@ -172,7 +172,7 @@ class ParallelDims:
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
# Mesh for data loading and per-step token counts
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
@@ -263,13 +263,6 @@ class ParallelDims:
|
||||
def non_data_parallel_size(self):
|
||||
return self.cp * self.pp
|
||||
|
||||
@cached_property
|
||||
def seq_len_divisor(self):
|
||||
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
|
||||
# when load balancing is enabled (by default).
|
||||
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
|
||||
return self.cp * 2
|
||||
|
||||
@cached_property
|
||||
def logger(self):
|
||||
return get_logger()
|
||||
@@ -309,7 +302,7 @@ def resolve_ep(config: ModelConfig) -> None:
|
||||
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
|
||||
|
||||
|
||||
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
|
||||
def get_parallel_dims(config: ModelConfig) -> ParallelDims:
|
||||
assert isinstance(config.ep, int), (
|
||||
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
|
||||
"Call resolve_ep(config) first."
|
||||
@@ -325,12 +318,4 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
|
||||
world_size=dist.get_world_size(),
|
||||
)
|
||||
|
||||
# Validate sequence length against parallel dimensions requirements
|
||||
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
|
||||
raise ValueError(
|
||||
f"Sequence length ({seq_len}) must be divisible by "
|
||||
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
|
||||
f"This requirement comes from context parallel (CP={config.cp})."
|
||||
)
|
||||
|
||||
return parallel_dims
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -7,6 +7,8 @@ from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.multimodal import ForwardPolicy, MultimodalAdapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transports.batch import (
|
||||
BatchReceiver,
|
||||
@@ -47,8 +49,11 @@ class TensorMicroBatch(TypedDict):
|
||||
# maximum mask size. A row containing only -1 has no mask.
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None
|
||||
|
||||
# Materialized immediately before this microbatch's forward pass.
|
||||
# Multimodal inputs. The data loader sets mm_refs (undecoded image references), and prepare_micro_batch
|
||||
# replaces them with mm_kwargs (CPU tensors for the vision encoder) and mm_forward_policy.
|
||||
mm_refs: MMRefs | None
|
||||
mm_kwargs: NotRequired[dict[str, Tensor] | None]
|
||||
mm_forward_policy: NotRequired[ForwardPolicy | None]
|
||||
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None
|
||||
|
||||
@@ -172,6 +177,23 @@ class FakeDataLoader:
|
||||
}
|
||||
|
||||
|
||||
def prepare_micro_batch(
|
||||
micro_batch: TensorMicroBatch, processor: Any | None, mm_adapter: MultimodalAdapter | None
|
||||
) -> TensorMicroBatch:
|
||||
"""Prepare a micro batch for the training loop. Currently only multimodal samples need preparation."""
|
||||
micro_batch["mm_kwargs"] = None
|
||||
micro_batch["mm_forward_policy"] = None
|
||||
mm_refs = micro_batch.get("mm_refs")
|
||||
if mm_refs is not None:
|
||||
if processor is None or mm_adapter is None:
|
||||
raise ValueError("Received multimodal samples but [model.vlm] is not set")
|
||||
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
|
||||
micro_batch["mm_kwargs"] = materialized.kwargs
|
||||
micro_batch["mm_forward_policy"] = materialized.forward_policy
|
||||
micro_batch["mm_refs"] = None
|
||||
return micro_batch
|
||||
|
||||
|
||||
class DataLoader:
|
||||
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
|
||||
|
||||
from contextlib import nullcontext
|
||||
from functools import partial
|
||||
import time
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
@@ -17,7 +18,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer
|
||||
from prime_rl.trainer.scheduler import setup_scheduler
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader, prepare_micro_batch
|
||||
from prime_rl.utils.cp import (
|
||||
gather_for_cp,
|
||||
gather_for_cp_wo_grad,
|
||||
@@ -37,7 +38,6 @@ from prime_rl.trainer.rl.loss import (
|
||||
shift_tensor_right,
|
||||
)
|
||||
from prime_rl.multimodal import get_multimodal_adapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.trainer.rl.annotations import AnnotationWriter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
@@ -71,6 +71,7 @@ from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.worker_pool import WorkerPool
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -105,10 +106,10 @@ def train(config: TrainerConfig):
|
||||
# Set precision
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
|
||||
enable_gloo=config.model.offload == "full",
|
||||
)
|
||||
if config.model.full_offload is not None:
|
||||
setup_full_cpu_optimizer_offload(config.model.full_offload)
|
||||
if config.model.offload == "full":
|
||||
setup_full_cpu_optimizer_offload()
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
@@ -147,6 +148,8 @@ def train(config: TrainerConfig):
|
||||
if processor is None:
|
||||
raise ValueError("Multimodal training requires a model image processor")
|
||||
mm_adapter = get_multimodal_adapter(model.config.model_type)
|
||||
prepare = partial(prepare_micro_batch, processor=processor, mm_adapter=mm_adapter)
|
||||
micro_batch_workers = WorkerPool(config.data.num_workers)
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
@@ -162,11 +165,10 @@ def train(config: TrainerConfig):
|
||||
config.optim,
|
||||
list(model.named_parameters()),
|
||||
parallel_dims,
|
||||
cpu_offload=config.model.optim_cpu_offload,
|
||||
full_offload_config=config.model.full_offload,
|
||||
offload=config.model.offload,
|
||||
model=model,
|
||||
full_offload_dtype_policy=(
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.offload == "full" else None
|
||||
),
|
||||
)
|
||||
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
|
||||
@@ -336,7 +338,9 @@ def train(config: TrainerConfig):
|
||||
cp_size = parallel_dims.cp
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
step_local_num_tokens = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
|
||||
step_local_num_tokens += micro_batch["input_ids"].shape[1]
|
||||
input_ids = micro_batch["input_ids"].to("cuda")
|
||||
position_ids = micro_batch["position_ids"].to("cuda")
|
||||
advantages = micro_batch["advantages"].to("cuda")
|
||||
@@ -365,17 +369,10 @@ def train(config: TrainerConfig):
|
||||
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
|
||||
)
|
||||
|
||||
mm_kwargs = None
|
||||
mm_forward_policy = None
|
||||
mm_refs = micro_batch.get("mm_refs")
|
||||
if mm_refs is not None:
|
||||
if processor is None or mm_adapter is None:
|
||||
raise ValueError("Received multimodal samples but [model.vlm] is not set")
|
||||
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
|
||||
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
|
||||
mm_forward_policy = materialized.forward_policy
|
||||
micro_batch["mm_refs"] = None
|
||||
del materialized, mm_refs
|
||||
mm_kwargs = micro_batch.pop("mm_kwargs")
|
||||
if mm_kwargs is not None:
|
||||
mm_kwargs = {key: value.to("cuda") for key, value in mm_kwargs.items()}
|
||||
mm_forward_policy = micro_batch.pop("mm_forward_policy")
|
||||
mm_token_type_ids = (
|
||||
micro_batch["mm_token_type_ids"].to("cuda")
|
||||
if micro_batch.get("mm_token_type_ids") is not None
|
||||
@@ -510,7 +507,9 @@ def train(config: TrainerConfig):
|
||||
# Add relevant tensors to tensor dict for logging purposes
|
||||
entropy = out["entropy"][loss_mask].detach().to("cpu")
|
||||
tensors["entropy/all"].append(entropy)
|
||||
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
|
||||
# Every CP rank computes the whole sequence's loss, and the global normalizers count each
|
||||
# sequence once per CP rank (gradients still sum correctly), so undo that for the logged value.
|
||||
tensors["loss"].append((loss.detach() * cp_size).to("cpu").unsqueeze(0))
|
||||
|
||||
env_names = micro_batch["env_names"]
|
||||
masked_env_names = [env_name for env_name, keep in zip(env_names, loss_mask.flatten().tolist()) if keep]
|
||||
@@ -631,9 +630,10 @@ def train(config: TrainerConfig):
|
||||
if is_moe_model:
|
||||
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
|
||||
|
||||
# Compute step metrics
|
||||
num_local_tokens = seq_len * batch_size
|
||||
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
|
||||
# The dp mesh excludes cp, whose ranks hold the same rows.
|
||||
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
|
||||
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
|
||||
num_tokens = global_num_tokens.item()
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += batch_size
|
||||
perf_counter = get_perf_counter(model, seq_len)
|
||||
@@ -732,6 +732,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
if gradient_manager is not None:
|
||||
gradient_manager.close()
|
||||
micro_batch_workers.close()
|
||||
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("RL trainer finished")
|
||||
|
||||
@@ -249,6 +249,13 @@ class RendererResolver:
|
||||
renderer = create_renderer(self.tokenizer, config)
|
||||
if self.processor is not None and hasattr(renderer, "_processor"):
|
||||
renderer._processor = self.processor
|
||||
if not getattr(renderer, "is_prefix_stable", False):
|
||||
get_logger().warning(
|
||||
f"SFT renderer {type(renderer).__name__} does not guarantee prefix stability. "
|
||||
"SFT renders each conversation once to produce one training sample; "
|
||||
"it does not expand N assistant turns into N samples. Depending on the template, "
|
||||
"reasoning from earlier turns may be omitted from the training sample."
|
||||
)
|
||||
self.renderers[config] = renderer
|
||||
return renderer
|
||||
|
||||
@@ -279,7 +286,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
# Default names are optional: a dataset carries either messages or
|
||||
# prompt/completion, and tools only for tool use. A name set in the
|
||||
# config must exist.
|
||||
for field in ("messages", "prompt", "completion", "tools"):
|
||||
for field in ("messages", "prompt", "completion", "tools", "message_loss_mask"):
|
||||
column = getattr(columns, field)
|
||||
if column != field and column not in dataset.column_names:
|
||||
raise ValueError(f"data.columns.{field} is {column!r}, but the dataset has only {dataset.column_names}")
|
||||
@@ -342,9 +349,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
# Defer to the renderer's sampled_mask by default: a role filter would
|
||||
# drop sampled stop markers attributed to the next message (e.g. GLM's
|
||||
# turn-closing <|user|> / <|observation|>).
|
||||
# Let the renderer identify sampled targets when assistant loss is enabled.
|
||||
role_to_mask = None if self.loss_mask_config.assistant else should_mask
|
||||
|
||||
# Non-assistant roles are opted into the loss via the renderer's
|
||||
@@ -359,6 +364,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
tools=tools,
|
||||
content_sft_roles=content_sft_roles or None,
|
||||
ensure_final_stop=True,
|
||||
message_loss_mask=example.get(self.columns.message_loss_mask),
|
||||
)
|
||||
input_ids = list(sample.token_ids)
|
||||
loss_mask = list(sample.loss_mask)
|
||||
@@ -474,12 +480,13 @@ class SFTDataset(StatefulIterableDataset):
|
||||
|
||||
|
||||
class CatDataset(StatefulIterableDataset):
|
||||
"""Concatenate text and multimodal samples into one fixed-length row."""
|
||||
"""Pack samples into rows of at most `seq_len` tokens, padded to a multiple of `pad_to_multiple_of`."""
|
||||
|
||||
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
|
||||
def __init__(self, dataset: StatefulIterableDataset, seq_len: int, pad_to_multiple_of: int):
|
||||
self.logger = get_logger()
|
||||
self.dataset = dataset
|
||||
self.seq_len = seq_len
|
||||
self.pad_to_multiple_of = pad_to_multiple_of
|
||||
self.pending_sample: Sample | None = None
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
@@ -583,7 +590,7 @@ class CatDataset(StatefulIterableDataset):
|
||||
if kept > 0:
|
||||
result["seq_lens"].append(kept)
|
||||
remaining -= kept
|
||||
pad_len = seq_len - len(result["input_ids"])
|
||||
pad_len = -len(result["input_ids"]) % self.pad_to_multiple_of
|
||||
if pad_len > 0:
|
||||
result["input_ids"].extend([0] * pad_len)
|
||||
result["position_ids"].extend(range(pad_len))
|
||||
@@ -753,8 +760,8 @@ def setup_dataset(
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
|
||||
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size)
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig, cp: int) -> StatefulDataLoader:
|
||||
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size, pad_to_multiple_of=cp)
|
||||
return StatefulDataLoader(
|
||||
packing_dataset,
|
||||
batch_size=1,
|
||||
|
||||
@@ -100,10 +100,10 @@ def train(config: SFTConfig):
|
||||
# Set precision
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
|
||||
enable_gloo=config.model.offload == "full",
|
||||
)
|
||||
if config.model.full_offload is not None:
|
||||
setup_full_cpu_optimizer_offload(config.model.full_offload)
|
||||
if config.model.offload == "full":
|
||||
setup_full_cpu_optimizer_offload()
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
@@ -113,7 +113,7 @@ def train(config: SFTConfig):
|
||||
resolve_ep(config.model)
|
||||
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
|
||||
parallel_dims = get_parallel_dims(config.model)
|
||||
|
||||
total_micro_batches = config.data.batch_size * config.model.cp
|
||||
micro_batches_per_step = world.world_size * config.data.micro_batch_size
|
||||
@@ -162,11 +162,10 @@ def train(config: SFTConfig):
|
||||
config.optim,
|
||||
list(model.named_parameters()),
|
||||
parallel_dims,
|
||||
cpu_offload=config.model.optim_cpu_offload,
|
||||
full_offload_config=config.model.full_offload,
|
||||
offload=config.model.offload,
|
||||
model=model,
|
||||
full_offload_dtype_policy=(
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.offload == "full" else None
|
||||
),
|
||||
)
|
||||
|
||||
@@ -192,7 +191,7 @@ def train(config: SFTConfig):
|
||||
processor=processor,
|
||||
multimodal=multimodal,
|
||||
)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataloader = setup_dataloader(dataset, config.data, config.model.cp)
|
||||
|
||||
val_raw_dataset = None
|
||||
if config.val is not None:
|
||||
@@ -257,7 +256,7 @@ def train(config: SFTConfig):
|
||||
|
||||
if cp_enabled:
|
||||
# CP requires the sequence length to be divisible by cp_size. CatDataset
|
||||
# pads every pack to seq_len; shard_for_cp raises on violations.
|
||||
# pads every pack to a multiple of it; shard_for_cp raises on violations.
|
||||
defer_vlm_cp_to_model = (
|
||||
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
|
||||
)
|
||||
@@ -345,7 +344,7 @@ def train(config: SFTConfig):
|
||||
processor=processor,
|
||||
multimodal=multimodal,
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data, config.model.cp)
|
||||
|
||||
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
|
||||
mean_loss, nan_count = run_eval_loop(val_dataloader)
|
||||
@@ -451,7 +450,9 @@ def train(config: SFTConfig):
|
||||
)
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
step_local_num_tokens = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
step_local_num_tokens += micro_batch["input_ids"].shape[1]
|
||||
if config.log.log_data:
|
||||
print_sample(
|
||||
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
|
||||
@@ -549,14 +550,10 @@ def train(config: SFTConfig):
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
|
||||
# Compute step metrics. CP shards the same sequences across cp ranks
|
||||
# (sequence-sharded data parallelism on the seq dim), so the unique
|
||||
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
|
||||
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
|
||||
# the RL trainer's accounting (rl/train.py).
|
||||
dp_size = parallel_dims.get_mesh("dp").size()
|
||||
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
|
||||
num_tokens = dp_size * num_local_tokens
|
||||
# The dp mesh excludes cp, whose ranks hold the same rows.
|
||||
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
|
||||
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
|
||||
num_tokens = global_num_tokens.item()
|
||||
progress.total_tokens += num_tokens
|
||||
dataset_progress = get_dataset_progress(dataloader)
|
||||
progress.total_samples = dataset_progress["step"]
|
||||
|
||||
@@ -5,6 +5,7 @@ import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from datetime import timedelta
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -21,10 +22,10 @@ from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_ckpt_dir
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.optim import GradientOffloadManager
|
||||
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
DCP_TIMEOUT = timedelta(hours=4)
|
||||
|
||||
|
||||
class GarbageCollection:
|
||||
@@ -176,9 +177,8 @@ def configure_cpu_optimizer_threads() -> None:
|
||||
)
|
||||
|
||||
|
||||
def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig") -> None:
|
||||
if config.numa_bind:
|
||||
bind_process_to_gpu_numa_node()
|
||||
def setup_full_cpu_optimizer_offload() -> None:
|
||||
bind_process_to_gpu_numa_node()
|
||||
configure_cpu_optimizer_threads()
|
||||
|
||||
|
||||
@@ -205,6 +205,15 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
|
||||
get_logger().debug(f"Initialized torch distributed in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@cache
|
||||
def get_dcp_group() -> dist.ProcessGroup:
|
||||
"""A gloo group for DCP checkpoint save/load. DCP's collectives wait for the slowest rank's
|
||||
writes or reads (and, on the first HF load, its download), which can outlast
|
||||
``dist_timeout_seconds``; on this group they wait up to ``DCP_TIMEOUT`` instead. Every rank must
|
||||
make its first call at the same point."""
|
||||
return dist.new_group(backend="gloo", timeout=DCP_TIMEOUT)
|
||||
|
||||
|
||||
def print_sample(input_ids: list[int], loss_mask: list[bool], tokenizer: PreTrainedTokenizer):
|
||||
"""
|
||||
Visualize the loss mask of a tokenized sample using rich.
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import os
|
||||
from datetime import timedelta
|
||||
|
||||
import torch.distributed as dist
|
||||
|
||||
|
||||
class World:
|
||||
@@ -42,3 +45,15 @@ def get_world() -> World:
|
||||
def reset_world():
|
||||
global _WORLD
|
||||
_WORLD = None
|
||||
|
||||
|
||||
def wait_for_master(key: str, timeout: float) -> None:
|
||||
"""A barrier for work only the master does, which can outlast ``dist_timeout_seconds`` (a model
|
||||
conversion, waiting for a weight broadcast's receiver). The other ranks wait on the c10d store,
|
||||
not in an NCCL collective, whose watchdog kills them after ``dist_timeout_seconds``. The master
|
||||
calls it with the same ``key`` when it is done."""
|
||||
store = dist.distributed_c10d._get_default_store()
|
||||
if get_world().is_master:
|
||||
store.set(key, "done")
|
||||
else:
|
||||
store.wait([key], timedelta(seconds=timeout))
|
||||
|
||||
@@ -10,7 +10,7 @@ import torch.nn as nn
|
||||
|
||||
from prime_rl.configs.shared import WeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import AdminPlane
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.world import get_world, wait_for_master
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
|
||||
|
||||
@@ -63,6 +63,7 @@ class WeightSender(ABC):
|
||||
(step_dir / SENDER_READY_MARKER).touch()
|
||||
self._wait_for_receiver_ready(step_dir)
|
||||
(step_dir / STARTED_MARKER).touch()
|
||||
wait_for_master(f"weight_broadcast/{step}", self.timeout)
|
||||
self._broadcast(model, step, step_dir)
|
||||
if self.world.is_master:
|
||||
(step_dir / FINISHED_MARKER).touch()
|
||||
@@ -94,9 +95,8 @@ class WeightSender(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
"""Move v{step}'s weights to the consumer. Rank synchronization is the
|
||||
transport's own job — non-master ranks must be held back until the
|
||||
master finished the handshake (see ``NCCLWeightSender._broadcast``)."""
|
||||
"""Move v{step}'s weights to the consumer. All ranks enter only after
|
||||
the master finished the handshake."""
|
||||
|
||||
def _clean(self, step: int) -> None:
|
||||
"""Remove old broadcast dirs, keeping ``step`` and ``step - 1`` (a
|
||||
@@ -153,7 +153,7 @@ class WeightReceiver(ABC):
|
||||
while not sender_ready.exists():
|
||||
if cancelled is not None and cancelled():
|
||||
raise asyncio.CancelledError
|
||||
await asyncio.sleep(0.2)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
def _ack(self, step: int) -> None:
|
||||
"""Acknowledge the offered version — unblocks the waiting trainer."""
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
@@ -52,7 +51,6 @@ class FileSystemWeightSender(WeightSender):
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
else:
|
||||
dist.barrier()
|
||||
state_dict = gather_weights_parallel(model)
|
||||
state_dict = convert_state_dict_to_hf(model, state_dict)
|
||||
self.logger.debug(f"Saving weights to {step_dir}")
|
||||
|
||||
@@ -3,7 +3,6 @@ from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch import Tensor
|
||||
from torch.distributed.tensor import DTensor
|
||||
@@ -189,13 +188,6 @@ class NCCLWeightSender(WeightSender):
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
# The master enters only after the receiver acknowledged the handshake,
|
||||
# but all ranks must be held back until then: the broadcast preparation
|
||||
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
|
||||
# ranks, and if those start before the receiver has paused inference,
|
||||
# the collectives sit unmatched until NCCL's watchdog kills the process.
|
||||
if self.world.world_size > 1:
|
||||
dist.barrier()
|
||||
self.nccl_broadcast_sender.send(model)
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user