Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88faa6dc22 | ||
|
|
083b8fe9ec | ||
|
|
853208336e | ||
|
|
31281d88f9 | ||
|
|
bc250759bf | ||
|
|
1983d8dfed | ||
|
|
26681fc6c7 | ||
|
|
6b0906c900 | ||
|
|
5e963f027a | ||
|
|
72834b3b52 | ||
|
|
0bcb868e91 | ||
|
|
746d8a96d0 | ||
|
|
765bbeba7b | ||
|
|
fec3acd8e7 | ||
|
|
adda4731fe | ||
|
|
a3f1f892c5 | ||
|
|
e6acff78aa | ||
|
|
3587b285f5 | ||
|
|
f3827c4ed2 | ||
|
|
93a0fe0d6b | ||
|
|
db2c00e9ed | ||
|
|
4250d895bc | ||
|
|
78bc69ccc4 | ||
|
|
81052082a9 | ||
|
|
b9c0bfe87b | ||
|
|
51879014fc | ||
|
|
52e985ae9d | ||
|
|
63b3e85864 | ||
|
|
7133f8f8f2 | ||
|
|
b029ef253e | ||
|
|
eae8bd9462 | ||
|
|
c8af127357 | ||
|
|
2b688edcf6 | ||
|
|
883b8f32c5 | ||
|
|
407e8ba223 | ||
|
|
cf9962c13b | ||
|
|
34e26e39a5 | ||
|
|
8acaaf2baa | ||
|
|
f42630873d | ||
|
|
1eeea3a047 | ||
|
|
d9adc1e867 | ||
|
|
0bd0a71254 | ||
|
|
a27c5f195a | ||
|
|
c8ce6fa283 | ||
|
|
4c7c0d5d18 | ||
|
|
1f537d187b | ||
|
|
f6fc1f7adc | ||
|
|
716d1cfac8 | ||
|
|
87766fda3c | ||
|
|
73c4736352 |
+2
-1
@@ -1,4 +1,5 @@
|
||||
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
|
||||
.git
|
||||
**/.git
|
||||
outputs
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
@@ -172,7 +172,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
ref: ${{ needs.prepare.outputs.full_sha }}
|
||||
fetch-depth: 0
|
||||
submodules: false
|
||||
|
||||
@@ -193,21 +193,55 @@ jobs:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "0.11.9"
|
||||
enable-cache: false
|
||||
|
||||
- name: Resolve dependency image and package versions
|
||||
id: dependency
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${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"
|
||||
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push dependencies
|
||||
id: dependencies
|
||||
if: steps.dependency.outputs.digest == ''
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
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
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: ${{ steps.dependency.outputs.image }}
|
||||
|
||||
- name: Build and push
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
# zstd compresses the multi-GB venv layers several times faster than gzip at a
|
||||
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
|
||||
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
|
||||
# or Docker >= 23.
|
||||
target: runtime
|
||||
build-args: |
|
||||
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
|
||||
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
|
||||
# The per-job builder is ephemeral; mode=max caches builder-stage
|
||||
# layers so warm builds skip the dependency sync.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=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
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
@@ -223,6 +257,8 @@ jobs:
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
|
||||
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
@@ -236,6 +272,7 @@ jobs:
|
||||
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
|
||||
echo "| **Commit** | \`${IMAGE_SHA}\` |"
|
||||
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
|
||||
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
manifest:
|
||||
|
||||
@@ -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
|
||||
@@ -75,7 +80,7 @@ jobs:
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import validate_shared_ckpt_config
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
|
||||
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
|
||||
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
|
||||
|
||||
@@ -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
|
||||
runs-on: vm
|
||||
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: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
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: vm
|
||||
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
|
||||
|
||||
+55
-78
@@ -1,21 +1,27 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
|
||||
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
|
||||
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
ARG DEPENDENCY_IMAGE=dependencies
|
||||
|
||||
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
|
||||
|
||||
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates python3.12 python3.12-venv \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
|
||||
|
||||
# Every pyproject.toml + uv.lock, so the dependency sync below caches
|
||||
# independently of source edits.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
|
||||
# .git is ~735 MB, changes every commit, and would land in the registry cache.
|
||||
COPY --exclude=.git . /ctx
|
||||
FROM python-builder AS manifests
|
||||
COPY . /ctx
|
||||
RUN mkdir -p /manifests \
|
||||
&& cd /ctx \
|
||||
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
|
||||
&& cp uv.lock /manifests/
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
|
||||
&& make install \
|
||||
&& rm -rf /tmp/ucx
|
||||
|
||||
# Download the latest installer
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies
|
||||
@@ -91,51 +91,11 @@ WORKDIR /app
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
|
||||
# Third-party deps only — source edits don't bust this layer. First-party
|
||||
# editables install in the source-layer sync below. No build-context bind
|
||||
# mount here: .git would bust the cache every commit.
|
||||
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
|
||||
# The runtime dependency image contains no first-party source or editable installs.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
--no-install-package renderers \
|
||||
--no-install-package prime-pydantic-config
|
||||
|
||||
COPY pyproject.toml /app/pyproject.toml
|
||||
COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY k8s /app/k8s
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
|
||||
# Use submodule git metadata from the build context when present. Docker copies
|
||||
# only the submodule .git pointer files into /app/deps, so we temporarily link
|
||||
# /app/.git/modules to the read-only context before resolving versions.
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
--mount=type=bind,source=.,target=/build-context,readonly \
|
||||
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
|
||||
&& \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& \
|
||||
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
--no-install-local
|
||||
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
@@ -185,7 +145,7 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -263,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
|
||||
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
|
||||
|
||||
# Install uv for development use
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
|
||||
USER appuser
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
# Copy the application from the builder, splitting the venv's largest trees into their
|
||||
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
|
||||
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
|
||||
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
|
||||
# per-tree copies above, or the data lands in the image twice.
|
||||
# The volatile /app remainder goes last so a source edit re-pushes one layer,
|
||||
# not all of them.
|
||||
# Split the largest dependency trees so compression and pulls can run in parallel.
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
|
||||
@@ -283,17 +236,17 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=.venv/lib/python3.12/site-packages/nvidia \
|
||||
--exclude=.venv/lib/python3.12/site-packages/torch \
|
||||
--exclude=.venv/lib/python3.12/site-packages/vllm \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app /app
|
||||
--exclude=lib/python3.12/site-packages/nvidia \
|
||||
--exclude=lib/python3.12/site-packages/torch \
|
||||
--exclude=lib/python3.12/site-packages/vllm \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app/.venv /app/.venv
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
|
||||
&& if [ "$(uname -m)" = "x86_64" ]; then \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
|
||||
fi
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
@@ -304,6 +257,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
|
||||
ENV HF_HUB_ETAG_TIMEOUT=500
|
||||
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
|
||||
|
||||
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity for K8s
|
||||
FROM python-builder AS application-builder
|
||||
WORKDIR /app
|
||||
COPY pyproject.toml uv.lock README.md /app/
|
||||
COPY src /app/src
|
||||
COPY packages /app/packages
|
||||
COPY deps /app/deps
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
COPY scripts/docker_application.py /build/docker_application.py
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
ARG PYDANTIC_CONFIG_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
|
||||
|
||||
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
|
||||
FROM ${DEPENDENCY_IMAGE} AS runtime
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
|
||||
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
|
||||
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
@@ -35,8 +35,8 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
|
||||
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
|
||||
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
|
||||
4. End-to-end post-training: SFT, RL training, and evals.
|
||||
5. Multi-node deployment with Slurm and Kubernetes support.
|
||||
6. Multimodal support for VLMs such as Qwen3-VL.
|
||||
5. Multi-node deployment with Slurm support.
|
||||
6. Multimodal support for VLMs such as Qwen3.5.
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
|
||||
|
||||
@@ -44,16 +44,14 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
|
||||
## Models support
|
||||
|
||||
|
||||
The trainer works with both Hugging Face and Prime custom `ModelForCausalLM` out of the box. For selected families (especially large MoE) we also ship highly optimized training code under `src/prime_rl/trainer/models/`, including expert parallelism (EP) for MoE layers and context parallelism (CP) for long sequences (see the table), and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels).
|
||||
|
||||
With `[model] impl = "auto"` (the default), the trainer selects that custom stack when the Hugging Face config type is registered.
|
||||
The trainer runs the PrimeRL model implementations under `src/prime_rl/trainer/models/`: dense Llama, Qwen3 and Qwen3.5, plus the families in the table below, with expert parallelism (EP) for MoE layers, context parallelism (CP) for long sequences, and additional kernels like [quack-kernels](https://github.com/quack-kernels/quack-kernels). Other architectures fail at trainer setup.
|
||||
|
||||
| Family | Example IDs | MoE | EP | CP |
|
||||
|--------|-------------|-----|----|-----|
|
||||
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ |
|
||||
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
|
||||
@@ -178,12 +176,12 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
|
||||
2. [**Wordle**](examples/basic/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
|
||||
3. [**Alphabet Sort**](examples/basic/alphabet-sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
|
||||
4. [**Wiki Search**](examples/basic/wiki-search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
|
||||
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
|
||||
5. [**Hendrycks Sanity**](examples/basic/hendrycks-sanity/README.md): Run a sanity check experiment on `Qwen3-1.7B` using a subset of MATH filtered to problems that `DeepSeek-R1-Distill-Qwen-1.5B` partially solves (20-80%). Useful for algorithm ablations.
|
||||
|
||||
### Advanced Training: 32 - 2048 GPUs:
|
||||
|
||||
Follow this guide to train large models on hard reasoning and agentic tasks.
|
||||
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
|
||||
These guides are designed to be run from a Slurm cluster.
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
|
||||
@@ -23,7 +23,6 @@ max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
impl = "custom"
|
||||
ep = 8
|
||||
|
||||
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
|
||||
|
||||
@@ -24,7 +24,6 @@ interval = 100
|
||||
project = "minimax-swe"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
ep = 8
|
||||
cp = 4
|
||||
|
||||
@@ -9,8 +9,8 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
|
||||
[slurm]
|
||||
job_name = "nemotron-3-super-swe"
|
||||
partition = "prod"
|
||||
# Nemotron-H needs the mamba-ssm kernels; sync that group, then clear this run's orphaned sandboxes.
|
||||
pre_run_command = 'uv sync --all-extras --all-packages --group mamba-ssm ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
|
||||
# Sync the env (the gpu extra brings Nemotron-H's mamba-ssm kernels), then clear this run's orphaned sandboxes.
|
||||
pre_run_command = 'uv sync --all-extras --all-packages ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -40,7 +40,6 @@ dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
# Hybrid-Mamba model: ring CP is unsupported, so use ulysses (capped at 8 by n_groups).
|
||||
cp = 8
|
||||
|
||||
@@ -15,9 +15,6 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ name = "hendrycks-sanity"
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
name = "Qwen/Qwen3-1.7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
|
||||
@@ -35,7 +35,6 @@ env.agent.runtime.type = "subprocess"
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
|
||||
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: 4fd5921071...da75527ca8
+3
-11
@@ -16,19 +16,14 @@ This page covers the specialized features layered on top of the core training st
|
||||
|
||||
## Custom Modeling
|
||||
|
||||
`prime-rl` ships custom optimized model implementations for several MoE families. With `model.impl = "auto"` (default) the trainer picks the custom path when the HF config type is registered, falling back to plain HF otherwise. To force one:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom" # or "hf" to force the HF path
|
||||
```
|
||||
The trainer only runs `prime-rl`'s own model implementations, selected from the HF config type. Besides dense Llama, Qwen3 and Qwen3.5, these cover the families below. Other architectures fail at trainer setup.
|
||||
|
||||
| Family | HF config types | EP | CP |
|
||||
|---|---|---|---|
|
||||
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
|
||||
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
|
||||
| Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
|
||||
| Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ |
|
||||
| MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ |
|
||||
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
|
||||
@@ -37,8 +32,6 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
|
||||
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
|
||||
|
||||
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
|
||||
|
||||
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
|
||||
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
|
||||
|
||||
@@ -161,7 +154,6 @@ Add `[model.vlm]` and bfloat16 dtypes:
|
||||
```toml
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
impl = "custom"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
@@ -195,7 +187,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
+14
-4
@@ -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 |
|
||||
|---|---|---|
|
||||
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
|
||||
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
|
||||
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
|
||||
|
||||
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
|
||||
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
|
||||
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
|
||||
|
||||
## Async / Off-Policy Training
|
||||
|
||||
@@ -188,7 +188,7 @@ $$
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
|
||||
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens — for `rl`, the sum of its weights, which is the same count while weights are 0/1 — so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
|
||||
|
||||
### IPO Loss
|
||||
|
||||
@@ -325,6 +325,16 @@ type = "grpo"
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
A **length-weighted baseline** (`length_weighted_baseline = true` on the `grpo`-family algorithms) replaces the plain group mean with $b = \sum_i L_i s_i / \sum_i L_i$, where $L_i$ is the number of trainable (policy-sampled, loss-masked) tokens of rollout $i$, summed across all its turns; it applies after the length penalty. With token-level loss normalization, long rollouts carry more gradient weight, so this baseline makes the per-token advantage zero-mean across the group's tokens rather than across rollouts.
|
||||
|
||||
**Prompt-mean loss aggregation** (`loss_aggregation = "prompt"` on `grpo` and `echo`; default `"token"`). By default every `rl` token in the batch weighs the same, so prompts whose groups produce long trajectories dominate the gradient. With `"prompt"`, the loss is MiMo-V2.6's prompt-mean (Eq. 1): the mean over prompt groups $q$ of $\frac{1}{T_q}\sum_{t \in q} \mathcal{L}_{rl,t}$, where $T_q$ is the group's total trainable tokens. MiMo uses it to keep response length from growing too fast. `score_group` gives each trainable token of the group the `rl` weight $1/T_q$, so each group's weights sum to 1 and $N_{rl}$ (the summed weights) is the number of groups in the step. Zero-advantage tokens are still dropped from the `rl` component, so a group with a zero-advantage rollout keeps less than its full weight of 1. All envs with an `rl` loss in a run must use the same `loss_aggregation`.
|
||||
|
||||
```toml
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
loss_aggregation = "prompt"
|
||||
```
|
||||
|
||||
### Hierarchical GRPO
|
||||
|
||||
GRPO gives each rollout its reward minus the average reward of comparable rollouts. In an ordinary single-agent group, every rollout answers the same task, so one group average is enough.
|
||||
|
||||
@@ -246,7 +246,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
- [**Wordle**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wordle) — `Qwen3-1.7B` playing Wordle. Multi-turn SFT + RL; 2–4 H100s.
|
||||
- [**Alphabet Sort**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/alphabet-sort) — `Qwen3-4B-Instruct-2507` sorting names alphabetically. Multi-turn LoRA RL without SFT warmup; one H100.
|
||||
- [**Wiki Search**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/wiki-search) — `Qwen3-4B-Instruct-2507` answering trivia by searching a Wikipedia corpus. Multi-turn with tool use.
|
||||
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `DeepSeek-R1-Distill-Qwen-1.5B` on a filtered MATH subset. Useful for algorithm ablations.
|
||||
- [**Hendrycks Sanity**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/basic/hendrycks-sanity) — `Qwen3-1.7B` on a filtered MATH subset. Useful for algorithm ablations.
|
||||
|
||||
**Advanced** (32–2048 GPUs, SLURM):
|
||||
|
||||
|
||||
+1
-2
@@ -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.
|
||||
@@ -117,7 +117,6 @@ Then run the full RL stack on reverse-text:
|
||||
```bash
|
||||
uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
|
||||
--model.name samsja/mini-glm-moe \
|
||||
--trainer.model.impl custom \
|
||||
--inference.vllm.gpu-memory-utilization 0.7 \
|
||||
--inference.vllm.max-model-len 2048
|
||||
```
|
||||
|
||||
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
|
||||
+3
-3
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -311,8 +311,8 @@ top_p = 0.95
|
||||
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
|
||||
```
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
+4
-7
@@ -92,13 +92,12 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|
||||
### Expert Parallelism
|
||||
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
|
||||
|
||||
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
|
||||
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op). `"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
@@ -116,7 +115,6 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ulysses" # "ring"
|
||||
@@ -157,7 +155,7 @@ fused_lm_head_token_chunk_size = 1024 # default
|
||||
# fused_lm_head_token_chunk_size = "disabled" # vanilla LM head
|
||||
```
|
||||
|
||||
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet). Only available with `model.impl = "custom"`.
|
||||
Drop the chunk size further when peak memory is still tight (e.g. with very long sequences); raise it to amortize kernel-launch overhead. SFT training silently disables this (not supported yet).
|
||||
|
||||
## Memory-Tight Recipe
|
||||
|
||||
@@ -165,7 +163,6 @@ The kitchen-sink config for fitting large MoE on limited GPUs at acceptable thro
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8
|
||||
cp = 2
|
||||
|
||||
@@ -244,7 +241,7 @@ Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transf
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
|
||||
+8
-2
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `orchestrator.train.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
|
||||
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
|
||||
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
|
||||
@@ -158,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:
|
||||
@@ -191,7 +196,7 @@ The same config selects the renderer for RL under `[orchestrator.renderer]`. The
|
||||
|
||||
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
|
||||
|
||||
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
|
||||
**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE).
|
||||
|
||||
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
|
||||
|
||||
@@ -280,6 +285,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
- `optim/grad_norm` — spikes precede divergence.
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
|
||||
- For MoE: `expert_load/{cv,max_mean,cold_frac}/{mean,max}` — expert load per layer over the whole step, from token counts summed across all ranks, as the mean and max over MoE layers. `cv` is std/mean of the per-expert token counts, `max_mean` the busiest expert's count over the mean, and `cold_frac` the fraction of experts receiving under 0.1x the mean. A trainable router that drifts shows up as a rising `cv`/`cold_frac` (MiMo-V2.6 §5.4).
|
||||
|
||||
**Performance:**
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -45,7 +41,6 @@ dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -59,7 +54,6 @@ enable_router_replay = true
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
@@ -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"
|
||||
@@ -60,7 +55,6 @@ enable_router_replay = true
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
@@ -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"
|
||||
@@ -46,7 +42,6 @@ dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
@@ -113,5 +113,17 @@ This will start a SFT run with the following configuration:
|
||||
|
||||
- The model is `zai-org/GLM-5.3-BF16`
|
||||
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
|
||||
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
|
||||
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
|
||||
|
||||
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
|
||||
|
||||
### 12 nodes at 16k
|
||||
|
||||
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
|
||||
```
|
||||
|
||||
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# 12-node, 16k-token overlay: enough GPUs that the model state fits without CP or offloading,
|
||||
# so each GPU runs one 16k sequence per micro-batch and blocks compile with fullgraph.
|
||||
# Compose after the data overlay, e.g. base.toml @ math-10k.toml @ 16k-12-node.toml.
|
||||
|
||||
[model]
|
||||
cp = 1
|
||||
optim_cpu_offload = false
|
||||
ac_offloading = "None"
|
||||
|
||||
[model.compile]
|
||||
fullgraph = true
|
||||
|
||||
[data]
|
||||
seq_len = 16384
|
||||
batch_size = 96
|
||||
micro_batch_size = 1
|
||||
|
||||
[deployment]
|
||||
num_train_nodes = 12
|
||||
@@ -2,15 +2,14 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
@@ -85,7 +85,6 @@ dist_timeout_seconds = 1800
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
cp = 4 # context parallel for the 131K seq len
|
||||
|
||||
@@ -24,7 +24,6 @@ interval = 100
|
||||
project = "intellect-3.1"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
ep = 8
|
||||
cp = 2
|
||||
|
||||
@@ -24,7 +24,6 @@ interval = 100
|
||||
project = "qwen30b-math"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
ep = 8
|
||||
|
||||
|
||||
@@ -2,11 +2,9 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
ep = 8
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ interval = 100
|
||||
project = "qwen30b-swe"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
ep = 8
|
||||
cp = 2
|
||||
|
||||
@@ -11,9 +11,6 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model]
|
||||
impl = "auto"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Hendrycks Sanity
|
||||
|
||||
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
|
||||
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems that `DeepSeek-R1-Distill-Qwen-1.5B` solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%. This example trains `Qwen3-1.7B` on that subset; the 20-80% band was measured for the distill model, not for `Qwen3-1.7B`.
|
||||
|
||||
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
name = "Qwen/Qwen3-1.7B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
|
||||
@@ -98,123 +98,3 @@ uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B
|
||||
```
|
||||
|
||||
Way better! Now we get an **average reward of ~0.8**.
|
||||
|
||||
## Kubernetes Deployment
|
||||
|
||||
If you're running on Kubernetes, you can deploy this example using the provided Helm chart. The Helm chart automatically configures all components with proper networking and shared storage.
|
||||
|
||||
### Step 1: Deploy for SFT Training
|
||||
|
||||
The reverse-text example is configured with `autoStart: true` for RL training, but we need to run SFT first. Deploy with autoStart disabled:
|
||||
|
||||
```bash
|
||||
cd k8s
|
||||
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml \
|
||||
--set orchestrator.autoStart=false \
|
||||
--set inference.autoStart=false \
|
||||
--set trainer.autoStart=false
|
||||
|
||||
# Check pods are ready
|
||||
kubectl get pods -l app=prime-rl,example=reverse-text
|
||||
# All pods should show 1/1 Running
|
||||
```
|
||||
|
||||
### Step 2: Run SFT Training
|
||||
|
||||
Exec into the trainer pod and run SFT:
|
||||
|
||||
```bash
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
|
||||
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
|
||||
```
|
||||
|
||||
### Step 3: Deploy RL Training
|
||||
|
||||
Now upgrade the deployment to enable autoStart (uses the default `autoStart: true` from reverse-text.yaml):
|
||||
|
||||
```bash
|
||||
# Exit the pod first (Ctrl+D)
|
||||
cd k8s
|
||||
helm upgrade my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# Check pods have restarted
|
||||
kubectl get pods -l app=prime-rl,example=reverse-text
|
||||
```
|
||||
|
||||
The RL components will automatically start. Monitor the logs:
|
||||
|
||||
```bash
|
||||
# View inference server logs
|
||||
kubectl logs -f my-exp-inference-0
|
||||
|
||||
# View orchestrator logs
|
||||
kubectl logs -f my-exp-orchestrator-0
|
||||
|
||||
# View trainer logs
|
||||
kubectl logs -f my-exp-trainer-0
|
||||
```
|
||||
|
||||
### Alternative: Manual RL Training
|
||||
|
||||
If you prefer to run RL components manually, keep `autoStart: false` and exec into each pod:
|
||||
|
||||
```bash
|
||||
# Terminal 1 - Inference
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml
|
||||
|
||||
# Terminal 2 - Orchestrator
|
||||
kubectl exec -it my-exp-orchestrator-0 -- bash
|
||||
uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url '["'$INFERENCE_URL'"]'
|
||||
|
||||
# Terminal 3 - Trainer
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs
|
||||
```
|
||||
|
||||
### Access Outputs and Checkpoints
|
||||
|
||||
All outputs are written to `/data/outputs` on the shared NFS storage:
|
||||
|
||||
```bash
|
||||
# Exec into any pod to access outputs
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
ls -lh /data/outputs/weights/
|
||||
ls -lh /data/outputs/rollouts/
|
||||
```
|
||||
|
||||
### Step 4: Run Evaluation
|
||||
|
||||
To evaluate the trained RL model:
|
||||
|
||||
```bash
|
||||
# Exec into trainer pod
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# If inference server isn't running with the RL model, start it in another terminal:
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL
|
||||
```
|
||||
|
||||
### Clean Up
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
|
||||
kubectl delete pvc my-exp-shared-data
|
||||
```
|
||||
|
||||
**What the Helm chart provides:**
|
||||
- Predictably named pods: `<release-name>-trainer-0`, `<release-name>-inference-0`, `<release-name>-orchestrator-0`
|
||||
- Shared NFS storage at `/data` for model checkpoints and outputs
|
||||
- GPU resources (1 GPU per inference/trainer pod)
|
||||
- Kubernetes services for component communication
|
||||
- Auto-start capability with proper networking configured
|
||||
|
||||
See the [K8s deployment guide](../../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# VLM SFT
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training (`[model.vlm]` set) requires a PrimeRL VLM implementation (see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
|
||||
@@ -6,7 +6,6 @@ dist_timeout_seconds = 3600
|
||||
name = "Qwen/Qwen3.6-35B-A3B"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
ep = 8 # keep in sync with deployment.num_train_gpus
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ max_steps = 20
|
||||
name = "Qwen/Qwen3.5-0.8B"
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
impl = "custom"
|
||||
|
||||
[renderer]
|
||||
name = "auto"
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
# Kubernetes Deployment with Helm
|
||||
|
||||
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Deploy with the reverse-text example
|
||||
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# Verify deployment
|
||||
kubectl get pods -l app.kubernetes.io/instance=my-exp
|
||||
|
||||
# Exec into trainer and run training
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
cd /data && uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Kubernetes cluster with GPU nodes
|
||||
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
|
||||
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
|
||||
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS)
|
||||
|
||||
## Chart Structure
|
||||
|
||||
```
|
||||
prime-rl/
|
||||
├── Chart.yaml
|
||||
├── values.yaml # Default configuration
|
||||
├── examples/
|
||||
│ ├── reverse-text.yaml # Example values for reverse-text
|
||||
│ └── reverse-text/ # Split orchestrator/inference/trainer configs the example runs
|
||||
└── templates/
|
||||
├── deployment.yaml # StatefulSets for orchestrator, inference, trainer
|
||||
├── service.yaml # Headless services for pod discovery
|
||||
└── pvc.yaml # Shared storage
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
See [values.yaml](./prime-rl/values.yaml) for all available options. Common overrides:
|
||||
|
||||
```bash
|
||||
# Custom GPU allocation
|
||||
helm install my-exp ./prime-rl \
|
||||
--set inference.gpu.count=4 \
|
||||
--set trainer.gpu.count=2
|
||||
|
||||
# With secrets for W&B/HF
|
||||
kubectl create secret generic prime-rl-secrets \
|
||||
--from-literal=wandb-api-key=YOUR_KEY \
|
||||
--from-literal=hf-token=YOUR_TOKEN
|
||||
|
||||
helm install my-exp ./prime-rl \
|
||||
--set config.secrets.enabled=true \
|
||||
--set config.secrets.name=prime-rl-secrets
|
||||
```
|
||||
|
||||
## Uninstalling
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
|
||||
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
|
||||
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
|
||||
```
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
|
||||
@@ -1,16 +0,0 @@
|
||||
apiVersion: v2
|
||||
name: prime-rl
|
||||
description: A Helm chart for deploying PRIME-RL training infrastructure on Kubernetes
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "main"
|
||||
keywords:
|
||||
- machine-learning
|
||||
- reinforcement-learning
|
||||
- training
|
||||
- gpu
|
||||
maintainers:
|
||||
- name: Prime Intellect
|
||||
url: https://github.com/PrimeIntellect-ai/prime-rl
|
||||
sources:
|
||||
- https://github.com/PrimeIntellect-ai/prime-rl
|
||||
@@ -1,44 +0,0 @@
|
||||
# Values for reverse_text example
|
||||
# Small model (Qwen3-0.6B) - runs on single consumer GPU
|
||||
|
||||
config:
|
||||
example: "reverse-text"
|
||||
|
||||
image:
|
||||
tag: "main"
|
||||
|
||||
# Orchestrator - no GPU needed
|
||||
orchestrator:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
|
||||
resources:
|
||||
requests:
|
||||
memory: "1Gi"
|
||||
cpu: "500m"
|
||||
|
||||
# Inference - 1 GPU
|
||||
inference:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml ; sleep infinity"
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
# Trainer - 1 GPU
|
||||
trainer:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs ; sleep infinity"
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -1,27 +0,0 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
batch_size = 128
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[train]
|
||||
group_size = 16
|
||||
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
@@ -1,14 +0,0 @@
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
seq_len = 2048
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
@@ -1,59 +0,0 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "prime-rl.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
*/}}
|
||||
{{- define "prime-rl.fullname" -}}
|
||||
{{- if .Values.fullnameOverride }}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||
{{- if contains $name .Release.Name }}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "prime-rl.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "prime-rl.labels" -}}
|
||||
helm.sh/chart: {{ include "prime-rl.chart" . }}
|
||||
{{ include "prime-rl.selectorLabels" . }}
|
||||
{{- if .Chart.AppVersion }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
{{- end }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Selector labels
|
||||
*/}}
|
||||
{{- define "prime-rl.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ include "prime-rl.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Component labels
|
||||
*/}}
|
||||
{{- define "prime-rl.componentLabels" -}}
|
||||
app: prime-rl
|
||||
{{- if .Values.config.example }}
|
||||
example: {{ .Values.config.example }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -1,378 +0,0 @@
|
||||
{{- if .Values.orchestrator.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-orchestrator-headless
|
||||
replicas: {{ .Values.orchestrator.replicas }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: orchestrator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
{{- with .Values.orchestrator.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-orchestrator
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.orchestrator.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.orchestrator.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.orchestrator.service.port }}
|
||||
name: api
|
||||
- containerPort: {{ .Values.orchestrator.service.ncclPort }}
|
||||
name: nccl
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "orchestrator"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.orchestrator.replicas }}"
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
{{- $replicas := int .Values.inference.replicas }}
|
||||
{{- $urls := list }}
|
||||
{{- range $i := until $replicas }}
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.orchestrator.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.orchestrator.resources | nindent 10 }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-inference-headless
|
||||
replicas: {{ .Values.inference.replicas }}
|
||||
podManagementPolicy: Parallel
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: inference
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: inference
|
||||
spec:
|
||||
{{- if .Values.inference.runtimeClassName }}
|
||||
runtimeClassName: {{ .Values.inference.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-inference
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.inference.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.inference.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.inference.service.port }}
|
||||
name: api
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "inference"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.inference.replicas }}"
|
||||
{{- with .Values.inference.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
{{- if .Values.inference.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
|
||||
{{- end }}
|
||||
memory: {{ .Values.inference.resources.requests.memory }}
|
||||
cpu: {{ .Values.inference.resources.requests.cpu }}
|
||||
limits:
|
||||
{{- if .Values.inference.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
|
||||
{{- end }}
|
||||
{{- if .Values.inference.resources.limits }}
|
||||
memory: {{ .Values.inference.resources.limits.memory }}
|
||||
cpu: {{ .Values.inference.resources.limits.cpu }}
|
||||
{{- end }}
|
||||
{{- if and .Values.inference.probes .Values.inference.probes.enabled }}
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.startup.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.startup.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /liveness
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.liveness.timeoutSeconds }}
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.readiness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.readiness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.readiness.timeoutSeconds }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-trainer-headless
|
||||
replicas: {{ .Values.trainer.replicas }}
|
||||
podManagementPolicy: Parallel
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: trainer
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: trainer
|
||||
spec:
|
||||
{{- if .Values.trainer.runtimeClassName }}
|
||||
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-trainer
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.trainer.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.trainer.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.trainer.service.port }}
|
||||
name: api
|
||||
- containerPort: {{ .Values.trainer.service.ncclPort }}
|
||||
name: nccl
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "trainer"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.trainer.replicas }}"
|
||||
{{- if .Values.trainer.pytorchCudaAllocConf }}
|
||||
- name: PYTORCH_CUDA_ALLOC_CONF
|
||||
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
|
||||
{{- end }}
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
{{- $replicas := int .Values.inference.replicas }}
|
||||
{{- $urls := list }}
|
||||
{{- range $i := until $replicas }}
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.trainer.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
{{- if .Values.trainer.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
|
||||
{{- end }}
|
||||
memory: {{ .Values.trainer.resources.requests.memory }}
|
||||
cpu: {{ .Values.trainer.resources.requests.cpu }}
|
||||
limits:
|
||||
{{- if .Values.trainer.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
|
||||
{{- end }}
|
||||
{{- if .Values.trainer.resources.limits }}
|
||||
memory: {{ .Values.trainer.resources.limits.memory }}
|
||||
cpu: {{ .Values.trainer.resources.limits.cpu }}
|
||||
{{- end }}
|
||||
{{- if and .Values.trainer.probes .Values.trainer.probes.enabled }}
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.startup.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.startup.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.liveness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.liveness.timeoutSeconds }}
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.readiness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.readiness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.readiness.timeoutSeconds }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -1,16 +0,0 @@
|
||||
{{- if .Values.storage.enabled }}
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-shared-data
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
spec:
|
||||
accessModes:
|
||||
{{- toYaml .Values.storage.accessModes | nindent 4 }}
|
||||
storageClassName: {{ .Values.storage.storageClassName }}
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.storage.size }}
|
||||
{{- end }}
|
||||
@@ -1,141 +0,0 @@
|
||||
{{- if .Values.orchestrator.enabled }}
|
||||
{{- if .Values.orchestrator.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
type: {{ .Values.orchestrator.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
ports:
|
||||
- port: {{ .Values.orchestrator.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
- port: {{ .Values.orchestrator.service.ncclPort }}
|
||||
targetPort: nccl
|
||||
protocol: TCP
|
||||
name: nccl
|
||||
{{- end }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
ports:
|
||||
- port: {{ .Values.orchestrator.service.port }}
|
||||
name: api
|
||||
- port: {{ .Values.orchestrator.service.ncclPort }}
|
||||
name: nccl
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
{{- if .Values.inference.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
type: {{ .Values.inference.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
ports:
|
||||
- port: {{ .Values.inference.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
{{- if .Values.trainer.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
type: {{ .Values.trainer.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
ports:
|
||||
- port: {{ .Values.trainer.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
- port: {{ .Values.trainer.service.ncclPort }}
|
||||
targetPort: nccl
|
||||
protocol: TCP
|
||||
name: nccl
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
ports:
|
||||
- port: {{ .Values.inference.service.port }}
|
||||
name: api
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
ports:
|
||||
- port: {{ .Values.trainer.service.port }}
|
||||
name: api
|
||||
- port: {{ .Values.trainer.service.ncclPort }}
|
||||
name: nccl
|
||||
{{- end }}
|
||||
@@ -1,156 +0,0 @@
|
||||
# Default values for prime-rl
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
# Global settings
|
||||
namespace: default
|
||||
|
||||
# Docker image configuration
|
||||
image:
|
||||
repository: primeintellect/prime-rl
|
||||
pullPolicy: IfNotPresent
|
||||
tag: "main"
|
||||
|
||||
# Shared storage configuration
|
||||
storage:
|
||||
enabled: true
|
||||
# PVC name will be automatically set to {{ .Release.Name }}-shared-data
|
||||
storageClassName: nfs
|
||||
accessModes:
|
||||
- ReadWriteMany
|
||||
size: 1Ti
|
||||
mountPath: /data
|
||||
|
||||
# Orchestrator component
|
||||
orchestrator:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
# Example command - use $INFERENCE_URL directly (the first inference server URL)
|
||||
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
|
||||
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
|
||||
# inference replica, put a router in front and point --client.base-url at it; admin operations
|
||||
# (weight updates, health checks) fan out to every replica via
|
||||
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "2Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
ncclPort: 29501
|
||||
|
||||
env: []
|
||||
# - name: CUSTOM_ENV
|
||||
# value: "value"
|
||||
|
||||
nodeSelector: {}
|
||||
# nvidia.com/gpu.present: "true" # Orchestrator doesn't need GPUs
|
||||
|
||||
# Inference component
|
||||
inference:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
command: "" # e.g., "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml"
|
||||
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows long model loading time (up to 45 min by default)
|
||||
startup:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 270 # 270 * 10s = 45 min max startup time
|
||||
timeoutSeconds: 5
|
||||
liveness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 10
|
||||
readiness:
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
timeoutSeconds: 5
|
||||
|
||||
# Trainer component
|
||||
trainer:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
command: "" # e.g., "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs"
|
||||
|
||||
# Helps reduce CUDA memory fragmentation with PyTorch allocator
|
||||
pytorchCudaAllocConf: "expandable_segments:True"
|
||||
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
ncclPort: 29501
|
||||
|
||||
env: []
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for trainer (requires metrics_server config)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows time for model loading
|
||||
startup:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 60 # 60 * 10s = 10 min max startup time
|
||||
timeoutSeconds: 30
|
||||
liveness:
|
||||
periodSeconds: 30
|
||||
failureThreshold: 6 # 6 * 30s = 3 min before restart
|
||||
timeoutSeconds: 30
|
||||
readiness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 30
|
||||
|
||||
# Additional configuration
|
||||
config:
|
||||
# Example name (used for labeling)
|
||||
example: "reverse-text"
|
||||
|
||||
# Secrets (optional)
|
||||
secrets:
|
||||
enabled: false
|
||||
name: prime-rl-secrets
|
||||
# wandbApiKey: ""
|
||||
# hfToken: ""
|
||||
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.shared import VLLMClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FrozenModelConfig(ClientConfig):
|
||||
class FrozenModelConfig(VLLMClientConfig):
|
||||
"""An externally hosted model behind an OpenAI-compatible endpoint: the
|
||||
client config plus the served model's ``name``.
|
||||
|
||||
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
|
||||
name: str
|
||||
"""Served model name, sent as the ``model`` field of every request."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
)
|
||||
return self
|
||||
base_url: str
|
||||
|
||||
|
||||
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
|
||||
@@ -208,6 +201,12 @@ class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""Use the token-length-weighted group mean reward ``sum_i(L_i * r_i) / sum_i(L_i)`` as the baseline instead of the plain mean, where ``L_i`` is the number of trainable (mask-True, policy-sampled) tokens of rollout ``i`` summed across all its turns."""
|
||||
|
||||
loss_aggregation: Literal["token", "prompt"] = "token"
|
||||
"""How the rl loss weights tokens across prompt groups. ``token``: every loss token in the batch weighs the same, so groups with more total tokens dominate the gradient. ``prompt``: prompt-mean (MiMo-V2.6 Eq. 1) — each trainable token of group ``q`` gets rl weight ``1 / T_q`` (``T_q`` = the group's trainable tokens), and the trainer divides the rl loss by the summed weights, i.e. the number of groups. All rl envs of a run must use the same value."""
|
||||
|
||||
|
||||
class EchoAlgoConfig(GRPOAlgoConfig):
|
||||
type: Literal["echo"] = "echo" # type: ignore[assignment]
|
||||
|
||||
@@ -6,8 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
RunConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
@@ -15,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
@@ -44,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
@@ -56,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
client: ClientConfig = Field(default_factory=ClientConfig)
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
|
||||
@@ -21,7 +21,7 @@ class ServerConfig(BaseConfig):
|
||||
"""Port to bind to."""
|
||||
|
||||
liveness_timeout_seconds: float = Field(30.0, gt=0)
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high."""
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
|
||||
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
|
||||
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
|
||||
"vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
|
||||
# an adapter named like a served base model, so serve the base under another name.
|
||||
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
|
||||
namespace.served_model_name = [f"{self.vllm.model}-base"]
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
@@ -14,13 +14,14 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
@@ -39,7 +40,7 @@ class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
@@ -480,55 +481,11 @@ class CheckpointConfig(BaseConfig):
|
||||
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."""
|
||||
|
||||
skip_progress: bool = False
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
inference_world_size: int = Field(1, ge=1)
|
||||
"""Total inference workers across all servers."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
in-flight episode cap from engine KV capacity and learned per-env episode
|
||||
costs; these fields only bound and seed it."""
|
||||
in-flight episode cap from engine KV pressure; these fields only bound and
|
||||
seed it."""
|
||||
|
||||
initial_inflight: int | None = Field(None, ge=1)
|
||||
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
|
||||
@@ -610,15 +567,12 @@ class OrchestratorConfig(BaseConfig):
|
||||
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."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
batch_size: int = Field(128, ge=1)
|
||||
"""Samples to train on per step."""
|
||||
|
||||
constant_trainer_batch_size: bool = True
|
||||
"""Require each batch to reach its effective sample target."""
|
||||
|
||||
token_batch_size: int | None = Field(None, ge=1)
|
||||
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
|
||||
|
||||
@@ -665,6 +619,19 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_cfg.algo.validate_env(env_cfg.env)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_loss_aggregation(self):
|
||||
"""The trainer divides the rl loss by the batch's summed rl weights, so token-mean (weight
|
||||
1 per token) and prompt-mean (weight 1 per group) envs can't share a batch."""
|
||||
algos = [env.algo for env in self.train.source if env.algo.action_loss_type == "rl"]
|
||||
aggregations = {algo.loss_aggregation if isinstance(algo, GRPOAlgoConfig) else "token" for algo in algos}
|
||||
if len(aggregations) > 1:
|
||||
raise ValueError(
|
||||
"All train envs with an rl loss must use the same loss_aggregation: a prompt-mean group "
|
||||
"would weigh as much as a single token of a token-mean env."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def setup_truncated_sampling(self):
|
||||
"""Truncated policy sampling trains with sampling replay (rollout
|
||||
@@ -755,17 +722,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_batching(self):
|
||||
has_rollout_batch = self.batch_size is not None
|
||||
has_token_batch = self.token_batch_size is not None
|
||||
|
||||
if has_rollout_batch and has_token_batch:
|
||||
raise ValueError("Set exactly one of batch_size or token_batch_size")
|
||||
|
||||
if not has_rollout_batch and not has_token_batch:
|
||||
self.batch_size = 128
|
||||
|
||||
group_sizes = [source.group_size for source in self.train.source] or [self.train.group_size]
|
||||
if self.batch_size is not None and any(self.batch_size % size for size in group_sizes):
|
||||
if any(self.batch_size % size for size in group_sizes):
|
||||
raise ValueError(
|
||||
f"Batch size {self.batch_size} must be divisible by every train source's group_size {sorted(set(group_sizes))}"
|
||||
)
|
||||
|
||||
@@ -8,50 +8,24 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TransportConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_seq_len,
|
||||
validate_shared_tokenizer,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
@@ -128,50 +102,6 @@ class SharedModelConfig(BaseConfig):
|
||||
"""VLM configuration. Set this to enable vision-language model support."""
|
||||
|
||||
|
||||
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer."""
|
||||
|
||||
|
||||
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer."""
|
||||
|
||||
|
||||
SharedWeightBroadcastConfig: TypeAlias = Annotated[
|
||||
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
@@ -290,7 +220,7 @@ class RLConfig(BaseConfig):
|
||||
seq_len: int | None = None
|
||||
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
|
||||
|
||||
weight_broadcast: SharedWeightBroadcastConfig | None = None
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
|
||||
rollout_transport: TransportConfig | None = None
|
||||
|
||||
@@ -395,15 +325,6 @@ class RLConfig(BaseConfig):
|
||||
sub.output_dir = run_dir
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_resume(self):
|
||||
"""Propagate the top-level resume onto the sub-configs."""
|
||||
if self.resume is None:
|
||||
return self
|
||||
self.trainer.resume = self.resume.model_copy()
|
||||
self.orchestrator.resume = self.resume.model_copy()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Default the W&B and Prime platform run names to ``run.name``.
|
||||
@@ -427,13 +348,70 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_configs(self):
|
||||
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
validate_shared_seq_len(self.trainer, self.orchestrator)
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
"""Cross-component constraints for values set per sub-config rather than through the
|
||||
shared fields (``propagate_shared_fields`` already rejects shared vs sub-config conflicts)."""
|
||||
trainer, orchestrator, inference = self.trainer, self.orchestrator, self.inference
|
||||
|
||||
def require_equal(name: str, values: dict[str, Any]) -> None:
|
||||
if len({repr(v) for v in values.values()}) > 1:
|
||||
found = ", ".join(f"{path}={value!r}" for path, value in values.items())
|
||||
raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.")
|
||||
|
||||
# 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(
|
||||
"model.name",
|
||||
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
|
||||
)
|
||||
else:
|
||||
require_equal(
|
||||
"model.name",
|
||||
{"trainer.model.name": trainer.model.name, "orchestrator.model.name": orchestrator.model.name},
|
||||
)
|
||||
# ``tokenizer.name`` / ``trust_remote_code`` may differ (e.g. FP8-quantized inference variants).
|
||||
chat_templates = {
|
||||
"trainer.tokenizer.chat_template": trainer.tokenizer.chat_template,
|
||||
"orchestrator.tokenizer.chat_template": orchestrator.tokenizer.chat_template,
|
||||
}
|
||||
if inference is not None:
|
||||
chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template
|
||||
require_equal("tokenizer.chat_template", chat_templates)
|
||||
require_equal(
|
||||
"max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps}
|
||||
)
|
||||
require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume})
|
||||
if trainer.model.seq_len < orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len "
|
||||
f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces."
|
||||
)
|
||||
if (trainer.ckpt is None) != (orchestrator.ckpt is None):
|
||||
raise ValueError(
|
||||
"Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]."
|
||||
)
|
||||
if trainer.ckpt and orchestrator.ckpt:
|
||||
require_equal(
|
||||
"ckpt.interval",
|
||||
{
|
||||
"trainer.ckpt.interval": trainer.ckpt.interval,
|
||||
"orchestrator.ckpt.interval": orchestrator.ckpt.interval,
|
||||
},
|
||||
)
|
||||
trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb
|
||||
if (trainer_wandb is None) != (orchestrator_wandb is None):
|
||||
raise ValueError(
|
||||
"W&B must be configured on both trainer and orchestrator, otherwise only one side's "
|
||||
"metrics are logged. Use the shared [monitors.wandb]."
|
||||
)
|
||||
if trainer_wandb and orchestrator_wandb:
|
||||
require_equal(
|
||||
"monitors.wandb.project",
|
||||
{
|
||||
"trainer.monitors.wandb.project": trainer_wandb.project,
|
||||
"orchestrator.monitors.wandb.project": orchestrator_wandb.project,
|
||||
},
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -446,52 +424,19 @@ class RLConfig(BaseConfig):
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
|
||||
self.weight_broadcast = FileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
|
||||
self.weight_broadcast = NCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
common_config = dict(
|
||||
host=self.weight_broadcast.host,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = {}
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(
|
||||
session_id=self.weight_broadcast.session_id,
|
||||
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
|
||||
)
|
||||
trainer_config_type = TrainerNIXLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
|
||||
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
|
||||
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
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)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -641,17 +586,17 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
|
||||
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -705,6 +650,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 = (
|
||||
|
||||
@@ -10,27 +10,28 @@ from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
ResumeConfig,
|
||||
RunConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
AdamWConfig,
|
||||
CheckpointConfig,
|
||||
ConstantSchedulerConfig,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
GCConfig,
|
||||
ModelConfig,
|
||||
NCCLWeightBroadcastConfig,
|
||||
OptimizerConfig,
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
@@ -100,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."""
|
||||
|
||||
@@ -275,6 +279,20 @@ class SFTConfig(BaseConfig):
|
||||
self.model.moe_router_dtype = "bfloat16"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_weight_decay_auto(self):
|
||||
"""Resolve ``optim.weight_decay='auto'``: SFT keeps the historical 0.01 default — standard L2 regularization for supervised training."""
|
||||
if self.optim.weight_decay == "auto":
|
||||
self.optim.weight_decay = 0.01
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = False
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
@@ -456,7 +474,7 @@ class SFTConfig(BaseConfig):
|
||||
self.weight_broadcast.inference_world_size = (
|
||||
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
)
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
@@ -507,7 +525,7 @@ class SFTConfig(BaseConfig):
|
||||
vllm.api_server_count = vllm.data_parallel_size
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
|
||||
self.inference.weight_broadcast.type = self.weight_broadcast.type
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
host = self.inference.server.host or "localhost"
|
||||
client = self.eval.client
|
||||
@@ -609,13 +627,6 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("Muon optimizer does not support FSDP CPU offload")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import AfterValidator, Field, model_validator
|
||||
from verifiers.v1.configs.client import BaseClientConfig
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -43,6 +44,48 @@ class BaseWeightBroadcastConfig(BaseConfig):
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
inference_world_size: int = Field(1, ge=1)
|
||||
"""Total inference workers across all servers. Set automatically by ``rl`` and ``sft``."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""Weight transfer from trainer to inference. ``rl`` copies its ``[weight_broadcast]`` to the trainer and orchestrator."""
|
||||
|
||||
|
||||
class RunConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name. Auto-generated as ``<envs>--<model>--<short-id>`` when unset, so every launch gets a fresh, readable run directory; set an explicit name (e.g. an experiment name) to get a predictable run directory, which is also required to resume a previous run. Unless set explicitly, the W&B run name and the Prime platform run name inherit it."""
|
||||
@@ -170,22 +213,10 @@ class DynamoConfig(BaseConfig):
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
class ClientConfig(BaseClientConfig):
|
||||
wait_for_ready_timeout: int = 3600
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
|
||||
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
"""Static headers sent with every request."""
|
||||
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
@@ -196,6 +227,13 @@ class ClientConfig(BaseConfig):
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class VLLMClientConfig(ClientConfig):
|
||||
"""Client defaults for the live inference deployment managed by training."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
|
||||
|
||||
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``."""
|
||||
@@ -228,14 +266,6 @@ class HeartbeatConfig(BaseConfig):
|
||||
rate limit. Size it well under the monitor's period."""
|
||||
|
||||
|
||||
class MetricsServerConfig(BaseConfig):
|
||||
port: int = Field(8000, ge=1, le=65535)
|
||||
"""Port to expose metrics and health endpoints on."""
|
||||
|
||||
host: str = "0.0.0.0"
|
||||
"""Host to bind the server to."""
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
@@ -22,6 +22,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
|
||||
DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"]
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
@@ -314,9 +315,6 @@ class ModelConfig(BaseModelConfig):
|
||||
cp_style: Literal["ring", "ulysses"] = "ring"
|
||||
"""CP communication style. ``ring`` uses ring-attention all-gather/reduce-scatter (requires custom kernels per attention type). ``ulysses`` uses all-to-all to redistribute Q/K/V from sequence-sharded to head-sharded, runs vanilla attention locally on the full sequence, then all-to-all back — works out-of-the-box with any attention kernel (softmax FA, linear attention, mamba, etc.)."""
|
||||
|
||||
impl: Literal["hf", "custom", "auto"] = "auto"
|
||||
"""Model implementation. ``auto`` selects ``custom`` if supported by the model, otherwise ``hf``."""
|
||||
|
||||
optimization_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""dtype for model optimization."""
|
||||
|
||||
@@ -324,15 +322,18 @@ class ModelConfig(BaseModelConfig):
|
||||
"""dtype for gradient/parameter reductions."""
|
||||
|
||||
moe_router_dtype: Literal["bfloat16", "float32", "auto"] = "auto"
|
||||
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
"""Compute dtype for MoE router gates. ``float32`` keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. ``auto`` (default) resolves to ``float32`` for RL and ``bfloat16`` for SFT. Router score functions (sigmoid/softmax) run in fp32 regardless. A no-op for non-MoE models."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
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 = False
|
||||
"""Freeze MoE router parameters during training."""
|
||||
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."""
|
||||
|
||||
lora: LoRAConfig | None = None
|
||||
"""LoRA configuration. If None, LoRA is disabled."""
|
||||
@@ -343,20 +344,6 @@ class ModelConfig(BaseModelConfig):
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
"""Trust remote code only if the model is from HF."""
|
||||
if self.trust_remote_code:
|
||||
if self.impl not in ("hf", "auto"):
|
||||
raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_only_with_custom_impl(self):
|
||||
if self.vlm is not None and self.impl != "custom":
|
||||
raise ValueError("VLM training requires model.impl='custom'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_cp_requires_ulysses(self):
|
||||
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
|
||||
@@ -367,11 +354,6 @@ class ModelConfig(BaseModelConfig):
|
||||
def validate_cp(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, 3, or 4")
|
||||
if self.cp > 1 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError(
|
||||
"Context parallelism requires model.impl='custom' or 'auto' "
|
||||
"(resolved to a custom PrimeRL implementation)"
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -392,19 +374,6 @@ class ModelConfig(BaseModelConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def flash_attention_4_only_with_custom_impl(self):
|
||||
# "auto" may resolve to FA4 on Blackwell, so apply the same impl constraint.
|
||||
if self.attn in ("flash_attention_4", "auto") and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Flash attention 4 is only supported with model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def quantization_only_with_custom_impl(self):
|
||||
if self.quantization is not None and self.impl not in ("custom", "auto"):
|
||||
raise ValueError(f"{self.quantization.type} training is only supported with model.impl='custom' or 'auto'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_moe_runtime(self):
|
||||
if self.ep == 1:
|
||||
@@ -490,23 +459,13 @@ class BaseOptimizerConfig(BaseConfig):
|
||||
lr: float = Field(1e-6, ge=0)
|
||||
"""Peak learning rate."""
|
||||
|
||||
weight_decay: float = Field(0.01, ge=0)
|
||||
"""L2 weight-decay coefficient."""
|
||||
weight_decay: Annotated[float, Field(ge=0)] | Literal["auto"] = "auto"
|
||||
"""L2 weight-decay coefficient. ``"auto"`` (default) resolves to ``0.0`` for RL and ``0.01`` for SFT."""
|
||||
|
||||
max_norm: float | None = Field(1.0, ge=0)
|
||||
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
|
||||
|
||||
|
||||
class SGDConfig(BaseOptimizerConfig):
|
||||
type: Literal["sgd"] = "sgd"
|
||||
|
||||
nesterov: bool = True
|
||||
"""Use Nesterov momentum."""
|
||||
|
||||
momentum: float = 0.9
|
||||
"""SGD momentum factor."""
|
||||
|
||||
|
||||
class AdamWConfig(BaseOptimizerConfig):
|
||||
type: Literal["adamw"] = "adamw"
|
||||
|
||||
@@ -534,9 +493,7 @@ class SignSGDConfig(BaseOptimizerConfig):
|
||||
type: Literal["sign_sgd"] = "sign_sgd"
|
||||
|
||||
|
||||
OptimizerConfig: TypeAlias = Annotated[
|
||||
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
|
||||
]
|
||||
OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
@@ -552,9 +509,6 @@ class CheckpointConfig(BaseConfig):
|
||||
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."""
|
||||
|
||||
skip_progress: bool = False
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
skip_scheduler: bool = False
|
||||
"""Skip loading the scheduler from checkpoint."""
|
||||
|
||||
@@ -658,47 +612,8 @@ class DataLoaderConfig(BaseConfig):
|
||||
fake: FakeDataLoaderConfig | None = None
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: int = 1
|
||||
"""Number of inference workers."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
num_workers: int = Field(0, 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):
|
||||
@@ -759,9 +674,6 @@ class TrainerConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
metrics_server: MetricsServerConfig | None = None
|
||||
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
@@ -772,6 +684,20 @@ class TrainerConfig(BaseConfig):
|
||||
self.model.moe_router_dtype = "float32"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_weight_decay_auto(self):
|
||||
"""Resolve ``optim.weight_decay='auto'``: RL optimizes the reward objective, not a fixed dataset — L2 decay toward zero fights it, so default to no weight decay."""
|
||||
if self.optim.weight_decay == "auto":
|
||||
self.optim.weight_decay = 0.0
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = True
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
@@ -852,17 +778,3 @@ class TrainerConfig(BaseConfig):
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def ep_only_with_custom_impl(self):
|
||||
if self.model.ep != 1 and self.model.ep != "auto" and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("EP is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def router_replay_only_with_custom_impl(self):
|
||||
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
|
||||
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
|
||||
|
||||
return self
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from typing import Any
|
||||
|
||||
|
||||
def propagate_shared_fields(data: Any) -> Any:
|
||||
@@ -128,6 +124,8 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"inference.vllm.chat_template",
|
||||
)
|
||||
|
||||
propagate("resume", "trainer.resume", "orchestrator.resume")
|
||||
|
||||
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
|
||||
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
|
||||
|
||||
@@ -147,7 +145,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# - shared ``[tokenizer] chat_template`` (already filled all three above,
|
||||
# this re-fill is a no-op via fill-if-absent), and
|
||||
# - ``[trainer.tokenizer] chat_template`` set directly without shared
|
||||
# (only path that reaches inference; ``validate_shared_tokenizer``
|
||||
# (only path that reaches inference; ``RLConfig.validate_shared_configs``
|
||||
# would otherwise complain about the missing inference value).
|
||||
trainer_chat_template = get("trainer.tokenizer.chat_template")
|
||||
if trainer_chat_template is not None:
|
||||
@@ -190,130 +188,3 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
raise ValueError("\n".join(lines))
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def validate_shared_ckpt_config(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.ckpt and not orchestrator.ckpt:
|
||||
raise ValueError(
|
||||
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
|
||||
)
|
||||
if orchestrator.ckpt and not trainer.ckpt:
|
||||
raise ValueError(
|
||||
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
|
||||
)
|
||||
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
|
||||
raise ValueError(
|
||||
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
|
||||
)
|
||||
if trainer.resume != orchestrator.resume:
|
||||
raise ValueError(
|
||||
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_model_name(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
# Orchestrator must match inference (it queries the inference server)
|
||||
if inference is not None:
|
||||
if inference.vllm.model != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
"The orchestrator queries the inference server and must use the same model name."
|
||||
)
|
||||
return
|
||||
|
||||
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
|
||||
return
|
||||
if trainer.model.name != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_wandb_config(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Trainer W&B config is specified, but orchestrator W&B config is not. "
|
||||
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Orchestrator W&B config is specified, but trainer W&B config is not. "
|
||||
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if trainer.monitors.wandb and orchestrator.monitors.wandb:
|
||||
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
|
||||
raise ValueError(
|
||||
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_max_steps(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.max_steps != orchestrator.max_steps:
|
||||
raise ValueError(
|
||||
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_seq_len(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.model.seq_len < orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
|
||||
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_tokenizer(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
# Validate chat_template is consistent across all components.
|
||||
# We only check chat_template (not name/trust_remote_code) because those
|
||||
# are auto-derived from model names which may legitimately differ (e.g.
|
||||
# when inference uses an FP8 quantized variant of the same model).
|
||||
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
|
||||
raise ValueError(
|
||||
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
|
||||
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
|
||||
f"Use the shared [tokenizer] config to set chat_template for both."
|
||||
)
|
||||
if inference is not None:
|
||||
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
|
||||
raise ValueError(
|
||||
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
|
||||
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
|
||||
f"Use the shared [tokenizer] config to set chat_template for all components."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_weight_broadcast(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
|
||||
)
|
||||
|
||||
+18
-14
@@ -11,13 +11,12 @@ dependencies = [
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"numpy>=2.2.6",
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.8.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"prime-runs[train]>=0.1.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -32,8 +31,6 @@ dependencies = [
|
||||
"verifiers[harbor]>=0.3.2.dev158",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
]
|
||||
|
||||
@@ -56,12 +53,14 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.30.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.31.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
"dion ; sys_platform == 'linux'",
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
# DSA sparse MLA backward kernel (CuTe DSL); >=1.29 matches the pinned CUTLASS DSL 4.7.
|
||||
"nvidia-cudnn-frontend>=1.30.0 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
@@ -91,13 +90,15 @@ disagg = [
|
||||
"deep-ep ; sys_platform == 'linux'",
|
||||
"deep-gemm ; sys_platform == 'linux'",
|
||||
"nixl ; sys_platform == 'linux'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
sonic-moe = ["sonic-moe ; sys_platform == 'linux'"]
|
||||
# FlashMLA sparse prefill forward for `model.dsa_backend = "cudnn_flashmla"` (sm_90a + sm_100f).
|
||||
# FlashMLA is not on PyPI and only an x86_64 wheel is published.
|
||||
flash-mla = ["flash-mla ; sys_platform == 'linux' and platform_machine == 'x86_64'"]
|
||||
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
|
||||
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
|
||||
kernels = [
|
||||
@@ -111,12 +112,10 @@ all = [
|
||||
"prime-rl[sonic-moe]",
|
||||
"prime-rl[flash-attn-3]",
|
||||
"prime-rl[flash-attn-cute]",
|
||||
"prime-rl[flash-mla]",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
mamba-ssm = [
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
@@ -148,7 +147,7 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
@@ -226,10 +225,12 @@ 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
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
@@ -253,6 +254,7 @@ deep-gemm = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
flash-mla = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
@@ -278,8 +280,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -293,6 +295,8 @@ prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
# FlashMLA nv_dev @ b7643bd built against torch 2.13.0+cu130 (see the release notes for the recipe).
|
||||
flash-mla = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
@@ -53,8 +53,8 @@ describe_tag() {
|
||||
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
local dir="$root/deps/verifiers"
|
||||
standard_git_version() {
|
||||
local dir="$1"
|
||||
local desc tag distance
|
||||
|
||||
[ -d "$dir" ] || return 1
|
||||
@@ -64,6 +64,14 @@ verifiers_git_version() {
|
||||
next_patch_dev_version "$tag" "$distance"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
standard_git_version "$root/deps/verifiers"
|
||||
}
|
||||
|
||||
pydantic_config_git_version() {
|
||||
standard_git_version "$root/deps/pydantic-config"
|
||||
}
|
||||
|
||||
renderers_git_version() {
|
||||
local dir="$root/deps/renderers"
|
||||
local desc tag distance version
|
||||
@@ -111,22 +119,27 @@ resolve_version() {
|
||||
|
||||
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
|
||||
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
|
||||
pydantic_config_version="$(resolve_version prime-pydantic-config PYDANTIC_CONFIG_PRETEND_VERSION pydantic_config_git_version)"
|
||||
|
||||
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
|
||||
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
|
||||
printf 'Resolved pydantic-config pretend version: %s\n' "$pydantic_config_version" >&2
|
||||
|
||||
case "$mode" in
|
||||
shell)
|
||||
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
|
||||
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
|
||||
printf "export PYDANTIC_CONFIG_PRETEND_VERSION='%s'\n" "$pydantic_config_version"
|
||||
;;
|
||||
github-output)
|
||||
printf 'verifiers=%s\n' "$verifiers_version"
|
||||
printf 'renderers=%s\n' "$renderers_version"
|
||||
printf 'pydantic_config=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
env)
|
||||
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
|
||||
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
|
||||
printf 'PYDANTIC_CONFIG_PRETEND_VERSION=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown output mode: %s\n' "$mode" >&2
|
||||
|
||||
@@ -113,8 +113,7 @@ HEAVY_PINS_PY
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
|
||||
--group mamba-ssm )
|
||||
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def editable_paths(root: Path) -> list[Path]:
|
||||
lock = tomllib.loads((root / "uv.lock").read_text())
|
||||
paths = set()
|
||||
for package in lock["package"]:
|
||||
source = package["source"]
|
||||
if "directory" in source:
|
||||
raise ValueError(f"Non-editable local package: {package['name']}")
|
||||
if "editable" not in source:
|
||||
continue
|
||||
path = (root / source["editable"]).resolve()
|
||||
if not path.is_relative_to(root):
|
||||
raise ValueError(f"Editable package outside the application: {path}")
|
||||
paths.add(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def set_fallback_version(pyproject: Path, version: str) -> None:
|
||||
if not re.fullmatch(r"[0-9][A-Za-z0-9.+-]*", version):
|
||||
raise ValueError(f"Invalid package version: {version!r}")
|
||||
content, count = re.subn(
|
||||
r'(?m)^fallback-version = "[^"]*"$', f'fallback-version = "{version}"', pyproject.read_text()
|
||||
)
|
||||
if count != 1:
|
||||
raise ValueError(f"Expected one fallback-version in {pyproject}")
|
||||
pyproject.write_text(content)
|
||||
|
||||
|
||||
def copy_installation_artifacts(venv: Path, baseline: set[Path], output: Path) -> None:
|
||||
# The runtime supplies the interpreter and third-party environment.
|
||||
for directory in (venv / "bin", venv / "lib/python3.12/site-packages"):
|
||||
for path in directory.iterdir():
|
||||
relative = path.relative_to(venv)
|
||||
if relative in baseline:
|
||||
continue
|
||||
target = output / ".venv" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.is_dir():
|
||||
shutil.copytree(path, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
else:
|
||||
shutil.copy2(path, target)
|
||||
|
||||
|
||||
def application_layer(root: Path, output: Path) -> None:
|
||||
if output.is_relative_to(root):
|
||||
raise ValueError("The output directory must be outside the application")
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
venv = root / ".venv"
|
||||
if venv.exists() or venv.is_symlink():
|
||||
raise FileExistsError(venv)
|
||||
versions = {
|
||||
"deps/verifiers": "VERIFIERS_PRETEND_VERSION",
|
||||
"deps/renderers": "RENDERERS_PRETEND_VERSION",
|
||||
"deps/pydantic-config": "PYDANTIC_CONFIG_PRETEND_VERSION",
|
||||
}
|
||||
for path, variable in versions.items():
|
||||
set_fallback_version(root / path / "pyproject.toml", os.environ[variable])
|
||||
|
||||
subprocess.run(["uv", "venv", "--python", "/usr/bin/python3.12", str(venv)], check=True)
|
||||
baseline = {path.relative_to(venv) for path in venv.rglob("*")}
|
||||
command = ["uv", "pip", "install", "--python", str(venv / "bin/python"), "--no-deps"]
|
||||
for path in editable_paths(root):
|
||||
command.extend(["--editable", str(path)])
|
||||
subprocess.run(command, check=True, cwd=root)
|
||||
|
||||
shutil.copytree(root, output, ignore=shutil.ignore_patterns(".venv", ".git", "__pycache__", "*.pyc"))
|
||||
copy_installation_artifacts(venv, baseline, output)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build a source and editable-package Docker layer")
|
||||
parser.add_argument("root", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
application_layer(args.root.resolve(), args.output.resolve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def dependency_fingerprint(root: Path) -> str:
|
||||
inputs = [root / path for path in ("Dockerfile.cuda", ".dockerignore", "uv.lock", "scripts/docker_dependencies.py")]
|
||||
for directory, children, files in os.walk(root):
|
||||
children[:] = [name for name in children if name not in {".git", ".venv", "outputs"}]
|
||||
if "pyproject.toml" in files:
|
||||
inputs.append(Path(directory) / "pyproject.toml")
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(inputs):
|
||||
name = path.relative_to(root).as_posix().encode()
|
||||
content = path.read_bytes()
|
||||
digest.update(len(name).to_bytes(8, "big"))
|
||||
digest.update(name)
|
||||
digest.update(len(content).to_bytes(8, "big"))
|
||||
digest.update(content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def registry_digest(image: str) -> str | None:
|
||||
registry, _, reference = image.partition("/")
|
||||
if registry != "ghcr.io":
|
||||
raise ValueError("Dependency images must use ghcr.io")
|
||||
repository, separator, tag = reference.rpartition(":")
|
||||
if not separator or not repository or not tag:
|
||||
raise ValueError("Expected ghcr.io/<owner>/<image>:<tag>")
|
||||
|
||||
query = urlencode({"service": registry, "scope": f"repository:{repository}:pull"})
|
||||
headers = {}
|
||||
if token := os.environ.get("GH_TOKEN"):
|
||||
credentials = f"{os.environ['GITHUB_ACTOR']}:{token}".encode()
|
||||
headers["Authorization"] = f"Basic {base64.b64encode(credentials).decode()}"
|
||||
request = Request(f"https://{registry}/token?{query}", headers=headers)
|
||||
with urlopen(request, timeout=30) as response:
|
||||
token = json.load(response)["token"]
|
||||
request = Request(
|
||||
f"https://{registry}/v2/{repository}/manifests/{tag}",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json",
|
||||
},
|
||||
method="HEAD",
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=30) as response:
|
||||
digest = response.headers["Docker-Content-Digest"]
|
||||
if not digest or not digest.startswith("sha256:"):
|
||||
raise ValueError(f"Missing or invalid image digest for {image}")
|
||||
return digest
|
||||
except HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Fingerprint and resolve Docker dependency images")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
fingerprint = commands.add_parser("fingerprint")
|
||||
fingerprint.add_argument("root", type=Path)
|
||||
resolve = commands.add_parser("resolve")
|
||||
resolve.add_argument("image")
|
||||
args = parser.parse_args()
|
||||
if args.command == "fingerprint":
|
||||
print(dependency_fingerprint(args.root.resolve()))
|
||||
else:
|
||||
print(registry_digest(args.image) or "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -4,7 +4,7 @@
|
||||
const $ = (sel) => document.querySelector(sel);
|
||||
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c]));
|
||||
const api = async (path) => {
|
||||
const res = await fetch(path);
|
||||
const res = await fetch(path.replace(/^\//, ""));
|
||||
if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
|
||||
return res.json();
|
||||
};
|
||||
@@ -6441,7 +6441,7 @@ function showViewToast(cmd) {
|
||||
}
|
||||
|
||||
function connectViewEvents() {
|
||||
const source = new EventSource("/api/view/events");
|
||||
const source = new EventSource("api/view/events");
|
||||
source.onmessage = (e) => {
|
||||
let cmd;
|
||||
try {
|
||||
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
|
||||
"scroll",
|
||||
(e) => {
|
||||
if (!e.target.matches?.("#replay-output") || !replay) return;
|
||||
// top and bottom coincide when the output fits; keep the mode Home/End chose
|
||||
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
|
||||
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
|
||||
replay.followOutput = atBottom;
|
||||
$("#replay-top")?.classList.toggle("active", !atBottom);
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>prime-rl dashboard</title>
|
||||
<link rel="icon" href="/static/butterfly-white.svg">
|
||||
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<link rel="icon" href="static/butterfly-white.svg">
|
||||
<link rel="stylesheet" href="static/vendor/uPlot.min.css">
|
||||
<link rel="stylesheet" href="static/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<header id="topbar">
|
||||
<div class="brand">
|
||||
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
|
||||
<img src="static/butterfly-white.svg" alt="Prime Intellect">
|
||||
</div>
|
||||
<select id="run-select" title="run"></select>
|
||||
<div id="compare-wrap" class="dd-wrap">
|
||||
@@ -295,7 +295,7 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script src="/static/vendor/uPlot.iife.min.js"></script>
|
||||
<script src="/static/app.js"></script>
|
||||
<script src="static/vendor/uPlot.iife.min.js"></script>
|
||||
<script src="static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+62
-216
@@ -1,13 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
RL_CONFIG = "rl.json"
|
||||
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
|
||||
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
|
||||
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
|
||||
|
||||
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
|
||||
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
|
||||
|
||||
start_command = sys.argv
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
with ProcessGroup() as processes:
|
||||
if config.inference:
|
||||
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
with open(log_dir / "inference.log", "w") as log_file:
|
||||
inference_process = Popen(
|
||||
inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(inference_process, stop_event, error_queue, "inference"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No [inference] block configured - the policy inference server will not be started here. "
|
||||
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
|
||||
# orchestrator start in parallel.
|
||||
for split, source in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {name} server")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file:
|
||||
env_server_process = Popen(
|
||||
env_server_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(env_server_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events[f"env/{split}/{name}"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
f"{split} env server {name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
orchestrator_cmd,
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["orchestrator"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"orchestrator",
|
||||
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
log_path=log_dir / "orchestrator.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={len(trainer_gpu_ids)}",
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / TRAINER_CONFIG).as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
with open(log_dir / "trainer.log", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["trainer"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.rl.train",
|
||||
config_dir / TRAINER_CONFIG,
|
||||
len(trainer_gpu_ids),
|
||||
log_dir,
|
||||
config.trainer.log.ranks_filter,
|
||||
),
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
# Small delay to avoid busy waiting
|
||||
time.sleep(1)
|
||||
|
||||
# Check if any critical process failed
|
||||
if orchestrator_process.returncode != 0:
|
||||
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", "orchestrator")
|
||||
logger.success("Training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
|
||||
+25
-101
@@ -1,12 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
|
||||
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
# Partition GPUs (inference first, then the trainer) only when the launcher must split
|
||||
# them between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
num_infer_gpus = config.deployment.num_infer_gpus
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
|
||||
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
|
||||
)
|
||||
|
||||
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
|
||||
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
processes.append(process)
|
||||
stop_event = Event()
|
||||
stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
return process
|
||||
|
||||
try:
|
||||
with ProcessGroup() as processes:
|
||||
# Optionally, start the inference server for online evals
|
||||
if config.inference is not None:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
start_process(
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
processes.start(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting online evals")
|
||||
start_process(
|
||||
processes.start(
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_train_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.sft.train",
|
||||
config_path,
|
||||
config.deployment.num_train_gpus,
|
||||
log_dir,
|
||||
config.log.ranks_filter,
|
||||
),
|
||||
env=trainer_env,
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "online-eval" in stop_events:
|
||||
terminal_events.append(stop_events["online-eval"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
logger.error(f"Error: {error_queue[0]}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
break
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
|
||||
logger.success("SFT training finished!")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
|
||||
@@ -18,7 +18,7 @@ import os
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.configs.shared import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
|
||||
@@ -34,10 +34,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import (
|
||||
@@ -49,9 +45,6 @@ from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
@@ -121,6 +114,7 @@ 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,
|
||||
|
||||
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -49,64 +47,6 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
original_post_init = VllmConfig.__post_init__
|
||||
|
||||
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
|
||||
return
|
||||
|
||||
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
|
||||
kv_transfer_config = config.kv_transfer_config
|
||||
return (
|
||||
config.model_config is not None
|
||||
and config.model_config.enable_return_routed_experts
|
||||
and kv_transfer_config is not None
|
||||
and kv_transfer_config.kv_connector == "NixlConnector"
|
||||
and kv_transfer_config.is_kv_transfer_instance
|
||||
)
|
||||
|
||||
def _post_init(config: VllmConfig):
|
||||
if not _is_nixl_routed_experts_pd_config(config):
|
||||
return original_post_init(config)
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
# remains rejected by prime-rl config validation.
|
||||
config.model_config.enable_return_routed_experts = False
|
||||
try:
|
||||
return original_post_init(config)
|
||||
finally:
|
||||
config.model_config.enable_return_routed_experts = True
|
||||
|
||||
_post_init._prime_rl_allows_nixl_routed_experts = True
|
||||
VllmConfig.__post_init__ = _post_init
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
|
||||
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
base_name = module_name.rsplit(".", 1)[-1]
|
||||
# Case for expert lora weights.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
if unexpected_modules:
|
||||
|
||||
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
# vLLM captures sampling masks and routed experts only on the V2 model runner.
|
||||
# setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant — the base model name, which
|
||||
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
|
||||
the base-model match, so requests keep addressing one stable name. If a future
|
||||
vLLM rejects registering an adapter under a served model name, fall back to a
|
||||
distinct constant adapter name set once at startup.) vLLM's native loader
|
||||
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
|
||||
that makes the worker re-read the new weights during ``add_lora``, reusing the
|
||||
existing ``lora_int_id``.
|
||||
changes per policy version; the name is constant — the model name every client
|
||||
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
|
||||
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
|
||||
we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
|
||||
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
|
||||
@@ -17,10 +17,6 @@ else:
|
||||
class FileSystemWeightUpdateWorker(Worker):
|
||||
"""vLLM worker extension for updating weights in-place using shared filesystem."""
|
||||
|
||||
def init_broadcaster(self) -> None:
|
||||
"""Initialize the broadcaster."""
|
||||
...
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
@@ -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
|
||||
@@ -55,9 +55,8 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# 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().
|
||||
@@ -76,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, ClassVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType, 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.configs.algorithm import AlgoConfig, FrozenModelConfig
|
||||
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
|
||||
@@ -50,9 +26,8 @@ class Algorithm:
|
||||
annotated traces into transport samples only after admission.
|
||||
"""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
def __init__(self, config: AlgoConfig, clients: InferenceClient):
|
||||
self.action_loss_type = config.action_loss_type
|
||||
self.clients = clients
|
||||
self.connected: InferenceClient | None = None
|
||||
|
||||
@@ -74,7 +49,3 @@ class Algorithm:
|
||||
"""Run rollout-local scoring when the episode has trainable traces."""
|
||||
if any(True for _ in iter_trainable_traces([episode])):
|
||||
await self.score_episode(episode)
|
||||
|
||||
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
|
||||
"""Run group-relative scoring over the native episodes."""
|
||||
await self.score_group(episodes)
|
||||
|
||||
@@ -6,7 +6,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages, trainable_nodes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
@@ -20,6 +20,8 @@ class GRPOAlgorithm(Algorithm):
|
||||
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.length_penalty = config.length_penalty
|
||||
self.length_weighted_baseline = config.length_weighted_baseline
|
||||
self.loss_aggregation = config.loss_aggregation
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
import torch # only the trainer-side extras ship torch; an eval process never scores a group
|
||||
@@ -28,7 +30,7 @@ class GRPOAlgorithm(Algorithm):
|
||||
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
|
||||
length_penalty = self.length_penalty
|
||||
if length_penalty is None:
|
||||
advantages = rewards - rewards.mean()
|
||||
shaped_rewards = rewards
|
||||
else:
|
||||
output = torch.tensor([trace.num_output_tokens for trace in traces], dtype=rewards.dtype)
|
||||
total = torch.tensor([trace.num_total_tokens for trace in traces], dtype=rewards.dtype)
|
||||
@@ -41,6 +43,19 @@ class GRPOAlgorithm(Algorithm):
|
||||
)
|
||||
penalty = rewards.mean() * penalty_frac
|
||||
shaped_rewards = rewards - penalty
|
||||
advantages = shaped_rewards - shaped_rewards.mean()
|
||||
baseline = shaped_rewards.mean()
|
||||
if self.length_weighted_baseline:
|
||||
lengths = torch.tensor(
|
||||
[sum(sum(node.mask) for node in trainable_nodes(trace)) for trace in traces], dtype=rewards.dtype
|
||||
)
|
||||
baseline = (lengths * shaped_rewards).sum() / lengths.sum()
|
||||
advantages = shaped_rewards - baseline
|
||||
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
|
||||
assign_advantages(trace, advantage)
|
||||
nodes = [node for trace in traces for node in trainable_nodes(trace)]
|
||||
if self.loss_aggregation == "prompt" and nodes:
|
||||
# rl weight 1/T_q per token: each group's weights sum to 1, and the trainer divides the
|
||||
# rl loss by the sum of rl weights, i.e. the number of groups.
|
||||
weight = 1.0 / sum(sum(node.mask) for node in nodes)
|
||||
for node in nodes:
|
||||
node.loss_weights = {**(node.loss_weights or {}), "rl": [weight if m else 0.0 for m in node.mask]}
|
||||
|
||||
@@ -24,8 +24,6 @@ class OPDAlgorithm(Algorithm):
|
||||
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
|
||||
advantage stream; ``group_size`` only fans out sampling."""
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.teacher = config.teacher
|
||||
|
||||
@@ -31,8 +31,6 @@ class OPSDAlgorithm(Algorithm):
|
||||
multimodal prompts and any number of turns. No scalar advantage is
|
||||
assigned."""
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.demo_key = config.demo_key
|
||||
|
||||
@@ -8,10 +8,15 @@ from prime_rl.configs.algorithm import ActionLossType
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
|
||||
def trainable_nodes(trace: vf.Trace) -> list[vf.MessageNode]:
|
||||
"""Nodes with sampled (mask-True) tokens on the trace's trainable branches, in graph order."""
|
||||
on_trainable_branch = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
|
||||
return [node for node in trace.nodes if id(node) in on_trainable_branch and any(node.mask)]
|
||||
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
"""Assign credit in compact sampled-token order across trainable graph paths."""
|
||||
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
|
||||
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
|
||||
nodes = trainable_nodes(trace)
|
||||
for node in nodes:
|
||||
if len(node.mask) != len(node.token_ids):
|
||||
raise ValueError(
|
||||
|
||||
@@ -10,5 +10,3 @@ class SFTDistillAlgorithm(Algorithm):
|
||||
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
|
||||
every sampled token. A curriculum can reject results using reward or any
|
||||
other finalized rollout data."""
|
||||
|
||||
action_loss_type = "ce"
|
||||
|
||||
@@ -5,8 +5,11 @@ from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
@@ -693,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.
|
||||
"""
|
||||
@@ -858,3 +860,32 @@ def prepare_batch(
|
||||
batches_per_gpu[worker_idx].extend(worker_batches)
|
||||
|
||||
return batches_per_gpu
|
||||
|
||||
|
||||
class BatchPacker:
|
||||
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
|
||||
|
||||
def __init__(self, config: OrchestratorConfig):
|
||||
self.seq_len = config.seq_len
|
||||
self.num_train_workers = config.num_train_workers
|
||||
self.pad_to_multiple_of = config.pad_to_multiple_of
|
||||
try:
|
||||
model_config = AutoConfig.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
|
||||
)
|
||||
except Exception as e:
|
||||
get_logger().warning(
|
||||
f"Could not load model config for {config.model.name} ({e}) - "
|
||||
"packing balances by token count instead of estimated FLOPs"
|
||||
)
|
||||
model_config = None
|
||||
self.bin_cost = build_bin_cost(model_config)
|
||||
|
||||
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
|
||||
return prepare_batch(
|
||||
rollouts=samples,
|
||||
seq_len=self.seq_len,
|
||||
num_train_workers=self.num_train_workers,
|
||||
bin_cost=self.bin_cost,
|
||||
pad_to_multiple_of=self.pad_to_multiple_of,
|
||||
)
|
||||
@@ -55,19 +55,16 @@ class CheckpointManager:
|
||||
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
|
||||
get_logger().debug(f"Loading checkpoint from {state_file}")
|
||||
start = time.perf_counter()
|
||||
if self.config.skip_progress:
|
||||
get_logger().info("Skipping progress and train source loading from checkpoint")
|
||||
else:
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
saved: Progress = state["progress"]
|
||||
for key, value in asdict(saved).items():
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name in state["train_source"]["envs"]:
|
||||
if name in train_source.curricula:
|
||||
get_logger().info(f"Resumed curriculum state for env {name}")
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
saved: Progress = state["progress"]
|
||||
for key, value in asdict(saved).items():
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name in state["train_source"]["envs"]:
|
||||
if name in train_source.curricula:
|
||||
get_logger().info(f"Resumed curriculum state for env {name}")
|
||||
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
@@ -12,40 +11,20 @@ from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI
|
||||
from renderers import RendererConfig
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
|
||||
from verifiers.v1.clients.base import build_async_openai
|
||||
from verifiers.v1.configs.client import (
|
||||
BaseClientConfig,
|
||||
EvalClientConfig,
|
||||
TrainClientConfig,
|
||||
resolve_api_key,
|
||||
resolve_headers,
|
||||
)
|
||||
|
||||
from prime_rl.configs.eval import PRIME_INFERENCE_URL
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def resolve_api_key(api_key_var: str) -> str:
|
||||
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
|
||||
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
|
||||
api_key = os.environ.get(api_key_var)
|
||||
if not api_key and api_key_var == "PRIME_API_KEY":
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
api_key = PrimeConfig().api_key
|
||||
return api_key or "EMPTY"
|
||||
|
||||
|
||||
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
"""The static headers plus those read from the environment. A Prime Inference client
|
||||
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
|
||||
like the verifiers client: a team's internal models are served only under it."""
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
|
||||
headers["X-Prime-Team-ID"] = team_id
|
||||
return headers
|
||||
|
||||
|
||||
class PrefillScorer:
|
||||
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
|
||||
a single OpenAI client from the pool's train client config."""
|
||||
@@ -55,14 +34,8 @@ class PrefillScorer:
|
||||
|
||||
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
|
||||
if self._client is None:
|
||||
# Build the OpenAI client straight from the config fields — works for any
|
||||
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
|
||||
# for these chat-completions teacher configs.
|
||||
self._client = AsyncOpenAI(
|
||||
base_url=config.base_url,
|
||||
api_key=resolve_api_key(config.api_key_var),
|
||||
default_headers=config.headers or None,
|
||||
)
|
||||
# Prefill scoring uses the SDK even when generation uses the eval relay.
|
||||
self._client = build_async_openai(config)
|
||||
return await prefill_logprobs(self._client, model, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -256,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",
|
||||
@@ -274,10 +262,7 @@ def setup_client(
|
||||
"renderer": renderer_config,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
}
|
||||
headers = resolve_headers(client_config)
|
||||
return config_cls(
|
||||
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
|
||||
)
|
||||
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -290,8 +275,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
|
||||
|
||||
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
|
||||
headers = resolve_headers(client_config)
|
||||
api_key = resolve_api_key(client_config.api_key_var)
|
||||
config = client_config.model_copy(update={"base_url": base_url})
|
||||
headers = resolve_headers(config)
|
||||
api_key = resolve_api_key(config)
|
||||
if api_key != "EMPTY":
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
@@ -324,7 +310,9 @@ async def maybe_check_has_model(
|
||||
f"{result.text[:300]}"
|
||||
)
|
||||
models = body["data"]
|
||||
if not any(model["id"] == model_name for model in models):
|
||||
# A LoRA server lists the model name only once the adapter is loaded; until then
|
||||
# the base model (served as ``<model>-base``) carries it as its ``root``.
|
||||
if not any(model_name in (model["id"], model.get("root")) for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ class ConcurrencyController:
|
||||
|
||||
# ── inbound hooks ────────────────────────────────────────────────────────
|
||||
|
||||
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
|
||||
def record_episode(self, tokens: int) -> None:
|
||||
"""One completed unit (from the dispatcher). Advances the turnover
|
||||
clock and, while the last poll was green, grows the cap — so growth
|
||||
is paced by the pipeline itself at any concurrency scale."""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -143,9 +143,11 @@ class Dispatcher:
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
on_episode_complete: Callable[[str, str, int, float], None] | None = 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
|
||||
@@ -157,7 +159,7 @@ class Dispatcher:
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.run_id = run_id
|
||||
self.run_name = run_name
|
||||
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
|
||||
# Called with ``total_tokens`` per completed episode
|
||||
self.on_episode_complete = on_episode_complete
|
||||
|
||||
# Starting value of the dynamic cap (the concurrency controller moves
|
||||
@@ -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,12 +679,16 @@ 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 self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(
|
||||
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
|
||||
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)
|
||||
|
||||
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
|
||||
@@ -724,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
|
||||
|
||||
@@ -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,38 @@ 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())
|
||||
self.uses_live_policy = config.algo.sampling.source == "policy"
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
if not self.uses_live_policy:
|
||||
# Logprobs only feed importance ratios on policy-sampled tokens; frozen endpoints may reject the knob.
|
||||
self.sampling_args.pop("logprobs", None)
|
||||
# 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.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):
|
||||
@@ -218,9 +232,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 +251,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
|
||||
|
||||
@@ -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
|
||||
@@ -38,6 +38,7 @@ from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.batch import BatchPacker
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
@@ -47,11 +48,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
@@ -78,12 +74,8 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir, resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
# Wall-clock budget for post-training cleanup; force-exit if graceful
|
||||
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
|
||||
@@ -250,8 +242,7 @@ class Orchestrator:
|
||||
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
|
||||
# themselves are restored below, once the envs are loaded.
|
||||
# trainer. The curricula themselves are restored below, once the envs are loaded.
|
||||
if self.resume_step is not None:
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming from step {self.resume_step}")
|
||||
@@ -291,16 +282,12 @@ 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()
|
||||
# A LoRA run's adapter is registered under the base model name: the
|
||||
# single adapter shadows it (vLLM resolves lora_requests before the
|
||||
# base-model match), so requests keep addressing one stable name.
|
||||
# A LoRA run's adapter is registered under the model name clients send;
|
||||
# the inference server serves the base model as ``<model>-base``.
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
@@ -372,7 +359,6 @@ class Orchestrator:
|
||||
train_envs=self.train_envs,
|
||||
progress=self.progress,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
on_result=self.train_source.on_result,
|
||||
)
|
||||
|
||||
@@ -814,7 +800,7 @@ class Orchestrator:
|
||||
inflight_by_env = self.dispatcher.inflight_by_env
|
||||
inflight_train = self.dispatcher.inflight_train_count
|
||||
inflight_eval = self.dispatcher.inflight_eval_count
|
||||
train_batch, train_target, _train_unit = self.train_sink.batch_progress()
|
||||
train_batch, train_target = self.train_sink.batch_progress()
|
||||
train_buffered = self.train_sink.buffered_count()
|
||||
train_batch_by_env = self.train_sink.pending_batch_by_env()
|
||||
eval_batches = self.eval_sink.batch_progress() if self.eval_sink is not None else []
|
||||
@@ -1035,11 +1021,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()
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class BatchPacker:
|
||||
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
|
||||
|
||||
def __init__(self, config: OrchestratorConfig):
|
||||
self.seq_len = config.seq_len
|
||||
self.num_train_workers = config.num_train_workers
|
||||
self.pad_to_multiple_of = config.pad_to_multiple_of
|
||||
try:
|
||||
model_config = AutoConfig.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
|
||||
)
|
||||
except Exception as e:
|
||||
get_logger().warning(
|
||||
f"Could not load model config for {config.model.name} ({e}) - "
|
||||
"packing balances by token count instead of estimated FLOPs"
|
||||
)
|
||||
model_config = None
|
||||
self.bin_cost = build_bin_cost(model_config)
|
||||
|
||||
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
|
||||
return prepare_batch(
|
||||
rollouts=samples,
|
||||
seq_len=self.seq_len,
|
||||
num_train_workers=self.num_train_workers,
|
||||
bin_cost=self.bin_cost,
|
||||
pad_to_multiple_of=self.pad_to_multiple_of,
|
||||
)
|
||||
@@ -1,115 +0,0 @@
|
||||
from typing import Any, Optional, TypedDict, Union
|
||||
|
||||
import openai.types.chat
|
||||
from openai.types.chat.chat_completion import ChatCompletion, Choice
|
||||
from openai.types.chat.chat_completion_assistant_message_param import (
|
||||
Audio,
|
||||
ContentArrayOfContentPart,
|
||||
)
|
||||
from openai.types.chat.chat_completion_content_part_param import ChatCompletionContentPartParam
|
||||
from openai.types.chat.chat_completion_content_part_text_param import ChatCompletionContentPartTextParam
|
||||
from openai.types.chat.chat_completion_developer_message_param import ChatCompletionDeveloperMessageParam
|
||||
from openai.types.chat.chat_completion_function_message_param import ChatCompletionFunctionMessageParam
|
||||
from openai.types.chat.chat_completion_message import FunctionCall
|
||||
from openai.types.chat.chat_completion_message_tool_call_union_param import ChatCompletionMessageToolCallUnionParam
|
||||
from openai.types.chat.chat_completion_system_message_param import ChatCompletionSystemMessageParam
|
||||
from openai.types.chat.chat_completion_user_message_param import ChatCompletionUserMessageParam
|
||||
from typing_extensions import Literal, Required
|
||||
|
||||
|
||||
def monkey_patch_oai_iterable_types():
|
||||
"""
|
||||
This monkey patch is necessary to avoid Pydantic validating fields using
|
||||
typing.Iterable (e.g. in multimodal or tool call messages) lazily which
|
||||
leads to tokenization errors, for more info see
|
||||
https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
|
||||
"""
|
||||
|
||||
class ModdedChatCompletionDeveloperMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["developer"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionSystemMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["system"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionUserMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartParam]]]
|
||||
role: Required[Literal["user"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionAssistantMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
role: Required[Literal["assistant"]]
|
||||
audio: Optional[Audio]
|
||||
content: Union[str, list[ContentArrayOfContentPart], None]
|
||||
function_call: Optional[FunctionCall]
|
||||
name: str
|
||||
refusal: Optional[str]
|
||||
tool_calls: list[ChatCompletionMessageToolCallUnionParam]
|
||||
|
||||
class ModdedChatCompletionToolMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["tool"]]
|
||||
tool_call_id: Required[str]
|
||||
|
||||
# Patch OAI types
|
||||
openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam = (
|
||||
ModdedChatCompletionDeveloperMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam = (
|
||||
ModdedChatCompletionSystemMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam = (
|
||||
ModdedChatCompletionUserMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam = (
|
||||
ModdedChatCompletionAssistantMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam = (
|
||||
ModdedChatCompletionToolMessageParam
|
||||
)
|
||||
|
||||
openai.types.chat.chat_completion_message_param.ChatCompletionMessageParam = Union[
|
||||
ChatCompletionDeveloperMessageParam,
|
||||
ChatCompletionSystemMessageParam,
|
||||
ChatCompletionUserMessageParam,
|
||||
ModdedChatCompletionAssistantMessageParam,
|
||||
ModdedChatCompletionToolMessageParam,
|
||||
ChatCompletionFunctionMessageParam,
|
||||
]
|
||||
|
||||
|
||||
def monkey_patch_chat_completion_logprobs():
|
||||
"""
|
||||
At large batch sizes and context, constructing OAI's Pydantic model
|
||||
ChatCompletion with logprobs is causing heavy CPU overhead (~200ms per
|
||||
object at 32K context, which translates to >10min overhead at 4K batch
|
||||
size). This function monkey-patches the OAI type and verifiers'
|
||||
post-processing utils to avoid validating the complex logprobs field.
|
||||
"""
|
||||
|
||||
class ChoiceAny(Choice):
|
||||
"""Same as openai.types.chat.chat_completion.Choice, but without type validation for logprobs field."""
|
||||
|
||||
logprobs: Optional[Any] = None
|
||||
|
||||
class ModdedChatCompletion(ChatCompletion):
|
||||
"""Same as openai.types.chat.chat_completion.ChatCompletion, but using ChoiceAny instead of Choice."""
|
||||
|
||||
choices: list[ChoiceAny] # type: ignore
|
||||
|
||||
# Patch OAI types
|
||||
openai.types.chat.chat_completion.Choice = ChoiceAny
|
||||
openai.types.chat.chat_completion.ChatCompletion = ModdedChatCompletion
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user