Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
0164aab72c | ||
|
|
243cfba0fb | ||
|
|
9ff04f56bf | ||
|
|
afe37d1c7a | ||
|
|
ecbf3e657f | ||
|
|
23017482f9 | ||
|
|
37bdd552f6 | ||
|
|
e094f0860f | ||
|
|
93cfa84dcc | ||
|
|
43be755e39 |
+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:
|
||||
|
||||
@@ -75,7 +75,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
|
||||
|
||||
@@ -13,7 +13,7 @@ concurrency:
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
runs-on: vm
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
@@ -61,34 +61,34 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
|
||||
+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 | ✅ | ✅ |
|
||||
@@ -146,7 +144,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -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.
|
||||
|
||||
+3
-8
@@ -2,24 +2,19 @@
|
||||
|
||||
Configurations for running prime-rl.
|
||||
|
||||
- **[`basic/`](basic)** — small, 2-GPU (1 trainer + 1 inference) configs for the core
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source), and
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and
|
||||
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
|
||||
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
|
||||
Not guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run rl @ configs/debug/algo/<algo>.toml
|
||||
uv run sft @ configs/debug/fake/sft.toml
|
||||
uv run eval @ configs/debug/eval/<shape>.toml
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# alphabet-sort (2 GPU)
|
||||
|
||||
Multi-turn task driven by a colocated user simulator, LoRA on `Qwen3-4B`. Dev mirror of
|
||||
[`examples/basic/alphabet-sort`](../../../examples/basic/alphabet-sort).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/alphabet-sort/rl.toml
|
||||
```
|
||||
@@ -1,48 +0,0 @@
|
||||
# Alphabet-sort on 2 GPUs (1 trainer + 1 inference) — a multi-turn task driven by a colocated
|
||||
# user simulator, trained with LoRA on Qwen3-4B. Dev-sized mirror of examples/basic/alphabet-sort.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
alpha = 64
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
@@ -1,9 +0,0 @@
|
||||
# hendrycks-sanity (2 GPU)
|
||||
|
||||
Single-turn math sanity run (reward climbs slowly, meant to run long),
|
||||
`DeepSeek-R1-Distill-Qwen-1.5B`. Dev mirror of
|
||||
[`examples/basic/hendrycks-sanity`](../../../examples/basic/hendrycks-sanity).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/hendrycks-sanity/rl.toml
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
# Hendrycks-math sanity on 2 GPUs (1 trainer + 1 inference) — a single-turn math env meant to
|
||||
# run long (reward climbs slowly). Dev-sized mirror of examples/basic/hendrycks-sanity.
|
||||
|
||||
max_steps = 5000
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 8192
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -1,9 +0,0 @@
|
||||
# reverse-text (2 GPU)
|
||||
|
||||
Smallest end-to-end RL loop — single-turn, `Qwen3-0.6B`. Dev mirror of
|
||||
[`examples/basic/reverse-text`](../../../examples/basic/reverse-text).
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/basic/reverse-text/sft.toml # optional warmup
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
```
|
||||
@@ -1,43 +0,0 @@
|
||||
# Reverse-text on 2 GPUs (1 trainer + 1 inference) — the smallest end-to-end RL loop
|
||||
# (single-turn, 0.6B). Dev-sized mirror of examples/basic/reverse-text.
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# PrimeIntellect Qwen3 fine-tune - select its renderer explicitly (the -SFT
|
||||
# suffix misses the MODEL_RENDERER_MAP exact match).
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -1,38 +0,0 @@
|
||||
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
|
||||
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
|
||||
|
||||
max_steps = 100
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[data]
|
||||
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
|
||||
seq_len = 4096
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
@@ -1,8 +0,0 @@
|
||||
# wiki-search (2 GPU)
|
||||
|
||||
Multi-turn tool calling (search a wiki corpus via native V1 tools), LoRA on `Qwen3-4B`. Dev mirror
|
||||
of [`examples/basic/wiki-search`](../../../examples/basic/wiki-search).
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/wiki-search/rl.toml
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
# Wiki-search on 2 GPUs (1 trainer + 1 inference) — a multi-turn tool-calling task (the model
|
||||
# searches a wiki corpus via MCP tools), trained with LoRA on Qwen3-4B. Dev-sized mirror of
|
||||
# examples/basic/wiki-search.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 4096
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
weight_decay = 0.0
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
dropout = 0.0
|
||||
target_modules = [
|
||||
"q_proj",
|
||||
"k_proj",
|
||||
"v_proj",
|
||||
"o_proj",
|
||||
"gate_proj",
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
]
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference.vllm]
|
||||
tool_call_parser = "hermes"
|
||||
@@ -1,9 +0,0 @@
|
||||
# wordle (2 GPU)
|
||||
|
||||
Multi-turn Wordle (~6-turn games), `Qwen3-1.7B-Wordle-SFT`. Dev mirror of
|
||||
[`examples/basic/wordle`](../../../examples/basic/wordle).
|
||||
|
||||
```bash
|
||||
uv run sft @ configs/basic/wordle/sft.toml # optional warmup
|
||||
uv run rl @ configs/basic/wordle/rl.toml
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
# Wordle on 2 GPUs (1 trainer + 1 inference). The Wordle-SFT model plays a
|
||||
# full ~6-turn game per rollout.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # single inference GPU (no data parallelism)
|
||||
|
||||
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -1,20 +0,0 @@
|
||||
# SFT warmup for wordle on 2 GPUs. Dev-sized mirror of examples/basic/wordle/sft.toml.
|
||||
|
||||
max_steps = 20
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B"
|
||||
|
||||
[data]
|
||||
name = "willcb/V3-wordle"
|
||||
seq_len = 1024
|
||||
batch_size = 64
|
||||
micro_batch_size = 1
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
|
||||
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
|
||||
# SWE-Bench Verified instances. Concurrency is fully default: the controller
|
||||
# derives its start from the measured KV budget and adapts from there — watch
|
||||
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
|
||||
# orchestrator log.
|
||||
#
|
||||
# Inference serves FP8 via online per-tensor quantization of the bf16
|
||||
# checkpoint; weight broadcasts re-quantize through the same path on every
|
||||
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
|
||||
# offload with the stateless sign-SGD optimizer, plus the memory improvements
|
||||
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
|
||||
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
|
||||
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
|
||||
# glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns
|
||||
# coefficients set to 0.1.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "debug-concurrency"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "debug-concurrency"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.train.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
select.limit = 100
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8_per_block"
|
||||
enable_return_routed_experts = true
|
||||
@@ -1,55 +0,0 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.5
|
||||
Vendored
+1
-1
Submodule deps/prime-kernels updated: 3fb83eb7aa...6f481769ca
Vendored
+1
-1
Submodule deps/verifiers updated: 4fd5921071...7ba657f2a4
+4
-12
@@ -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.
|
||||
|
||||
@@ -137,7 +130,7 @@ With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is
|
||||
enabled = ["gate_up", "qkv"] # [] disables
|
||||
```
|
||||
|
||||
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
|
||||
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning and is skipped. Fusions are skipped when LoRA is enabled.
|
||||
|
||||
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+19
-14
@@ -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,19 +188,16 @@ $$
|
||||
- `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
|
||||
|
||||
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
The default RL loss is Importance Policy Optimization (IPO). It is an importance-weighted policy-gradient term. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = \frac{1}{N}\sum_t
|
||||
\left[
|
||||
-\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}
|
||||
+ \tau_{KL}\log^2\!\left(\frac{\pi(y_t)}{\mu(y_t)}\right)
|
||||
\right].
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
|
||||
$$
|
||||
|
||||
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
|
||||
@@ -210,8 +207,7 @@ The knobs under `[trainer.loss]` are:
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. |
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
@@ -221,8 +217,7 @@ IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
|
||||
importance ratio falls outside a fixed acceptance band, introduced to stabilize
|
||||
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
|
||||
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
|
||||
tokens retain the importance-weighted policy-gradient term, and there is no
|
||||
separate KL penalty:
|
||||
tokens retain the importance-weighted policy-gradient term:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
@@ -330,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):
|
||||
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
|
||||
+4
-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). |
|
||||
|
||||
@@ -191,7 +192,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 +281,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:**
|
||||
|
||||
|
||||
@@ -35,4 +35,3 @@ Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -45,7 +45,6 @@ dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
@@ -59,7 +59,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"
|
||||
|
||||
@@ -60,7 +60,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"
|
||||
|
||||
@@ -46,7 +46,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
|
||||
@@ -6,11 +6,11 @@ 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
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ 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).
|
||||
|
||||
@@ -15,3 +15,5 @@ uv run rl @ examples/basic/hendrycks-sanity/rl.toml \
|
||||
--monitors.wandb.project your-project \
|
||||
--monitors.wandb.name your-run
|
||||
```
|
||||
|
||||
To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -9,7 +9,7 @@ In this example, we demonstrate how to train `Qwen3-4B-Instruct-2507` to answer
|
||||
- **LLM judges**: Uses an LLM judge to evaluate answer quality alongside tool execution metrics
|
||||
- **Online difficulty buffer**: Uses difficulty-based sampling to ensure rollouts have strictly non-zero advantages
|
||||
|
||||
> This example runs on 8 GPUs (6 for inference, 2 for training).
|
||||
> This example runs on 8 GPUs (6 for inference, 2 for training). To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128` to the `rl` command.
|
||||
|
||||
## Setup
|
||||
|
||||
|
||||
@@ -82,6 +82,8 @@ uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--monitors.wandb.name ...
|
||||
```
|
||||
|
||||
This config runs on 8 GPUs (6 for inference, 2 for training). To run on 2 GPUs (1 inference, 1 trainer), add `--deployment.num-train-gpus 1 --deployment.num-infer-gpus 1 --orchestrator.batch-size 128`.
|
||||
|
||||
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
|
||||
|
||||
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
|
||||
|
||||
@@ -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,28 @@ 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 = (
|
||||
if "inference_world_size" in self.weight_broadcast.model_fields_set:
|
||||
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
|
||||
update = {}
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
update["inference_world_size"] = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
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(update=update)
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
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 +595,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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -275,6 +276,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 +471,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 +522,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 +624,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):
|
||||
@@ -61,9 +62,6 @@ class OptimizerInBackwardOffloadConfig(BaseConfig):
|
||||
bit-faithful to that path, disable offloading.
|
||||
"""
|
||||
|
||||
cpu_optimizer_backend: Literal["native", "torch"] = "native"
|
||||
"""CPU optimizer implementation used by full offload (AdamW or SignSGD). ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
|
||||
|
||||
numa_bind: bool = True
|
||||
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
|
||||
|
||||
@@ -93,9 +91,6 @@ class FusionsConfig(BaseConfig):
|
||||
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
|
||||
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
|
||||
|
||||
raise_on_fail: bool = False
|
||||
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
|
||||
|
||||
shard_fused_on_dim1: bool = False
|
||||
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
|
||||
|
||||
@@ -320,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."""
|
||||
|
||||
@@ -330,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."""
|
||||
@@ -349,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":
|
||||
@@ -373,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")
|
||||
@@ -398,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:
|
||||
@@ -496,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"
|
||||
|
||||
@@ -540,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):
|
||||
@@ -558,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."""
|
||||
|
||||
@@ -582,9 +530,6 @@ class IPOLossConfig(BaseConfig):
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(0.0, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IcePopLossConfig(BaseConfig):
|
||||
type: Literal["icepop"] = "icepop"
|
||||
@@ -668,48 +613,6 @@ class DataLoaderConfig(BaseConfig):
|
||||
"""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"),
|
||||
]
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -768,9 +671,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."""
|
||||
|
||||
@@ -781,6 +681,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:
|
||||
@@ -861,17 +775,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",
|
||||
@@ -230,6 +229,8 @@ requires-dist = [
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00: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'" },
|
||||
@@ -290,9 +292,11 @@ deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/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.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-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()
|
||||
@@ -75,7 +75,7 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.train.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1` and `adv_tau = 1.0`. Omit the section to use these defaults. Set `type = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.train.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.train.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Each train source inherits the group algorithm: a source `algo` with a different `type` is its own algorithm (`[orchestrator.train.source.algo] type = "opd"`), and params without a `type` keep the group's algorithm with those params changed. prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.train.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.train.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ SLURM launches write generated scripts and coordination files under `<run_dir>/l
|
||||
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
|
||||
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
|
||||
halves the host RAM footprint), and disables gradient clipping. Use a
|
||||
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
|
||||
`[model.full_offload]` table only to disable NUMA binding.
|
||||
|
||||
## `rl` — RL training
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
Opening a trace adds `trace=<id>` to the URL. Bookmarking or reopening that URL
|
||||
restores the selected trace, whether it is still live or has finished.
|
||||
|
||||
The Config and Logs views keep each launch attempt available. The Config view
|
||||
shows a copyable command above the launch TOML or resolved JSON. Both views
|
||||
open at `latest (attempt <n>)` and let you select an earlier attempt.
|
||||
|
||||
@@ -1546,6 +1546,7 @@ def row_filter(
|
||||
kind: str | None = None,
|
||||
env: str | None = None,
|
||||
episode: str | None = None,
|
||||
trace: str | None = None,
|
||||
ok: bool | None = None,
|
||||
start: float | None = None,
|
||||
end: float | None = None,
|
||||
@@ -1563,6 +1564,8 @@ def row_filter(
|
||||
return False
|
||||
if episode is not None and row.get("id") != episode:
|
||||
return False
|
||||
if trace is not None and trace not in row.get("trace_ids", []):
|
||||
return False
|
||||
if ok is not None and bool(row.get("ok")) != ok:
|
||||
return False
|
||||
arrival = row.get("arrival") or 0
|
||||
@@ -1591,6 +1594,7 @@ def list_stream_episodes(
|
||||
kind: str | None = None,
|
||||
env: str | None = None,
|
||||
episode: str | None = None,
|
||||
trace: str | None = None,
|
||||
ok: bool | None = None,
|
||||
sort: str = "arrival",
|
||||
order: str = "desc",
|
||||
@@ -1618,7 +1622,7 @@ def list_stream_episodes(
|
||||
if upto is not None:
|
||||
rows = rows[:upto]
|
||||
envs, kinds = index_facets(run_dir)
|
||||
keep = row_filter(step=step, kind=kind, env=env, episode=episode, ok=ok, start=start, end=end)
|
||||
keep = row_filter(step=step, kind=kind, env=env, episode=episode, trace=trace, ok=ok, start=start, end=end)
|
||||
if sort == "arrival":
|
||||
# the index is already in arrival order: walk it from the right end and stop
|
||||
# once the page is full, so the common view costs a page rather than a run
|
||||
|
||||
@@ -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();
|
||||
};
|
||||
@@ -201,6 +201,7 @@ function applyRunTypeControls() {
|
||||
|
||||
async function selectRun(name, deferTab = false) {
|
||||
if (!name) return;
|
||||
if (!$("#trace-modal").hidden) closeDrawer();
|
||||
state.run = name;
|
||||
state.compare = { runs: [], data: new Map() };
|
||||
$("#run-select").value = name;
|
||||
@@ -366,10 +367,18 @@ function renderOverview() {
|
||||
`</div>`;
|
||||
}
|
||||
|
||||
let renderedHash = location.hash;
|
||||
let initializing = true;
|
||||
|
||||
function updateHash() {
|
||||
const parts = [`run=${encodeURIComponent(state.run || "")}`, `tab=${state.tab}`];
|
||||
if (state.tab === "report" && state.report.file) parts.push(`report=${encodeURIComponent(state.report.file)}`);
|
||||
location.hash = `#${parts.join("&")}`;
|
||||
const trace = currentLive || currentEpisode?.traces?.[currentTraceIdx]?.id;
|
||||
if (trace) parts.push(`trace=${encodeURIComponent(trace)}`);
|
||||
renderedHash = `#${parts.join("&")}`;
|
||||
// Restoring the view on page load must not add navigation history.
|
||||
if (initializing) history.replaceState(null, "", renderedHash);
|
||||
else location.hash = renderedHash;
|
||||
}
|
||||
|
||||
async function activateTab(tab, force = false) {
|
||||
@@ -3433,7 +3442,7 @@ function renderLiveRows() {
|
||||
if ((state.traces.live || []).some((r) => r.trace === currentLive)) openLiveTrace(currentLive, { refresh: true });
|
||||
else {
|
||||
const landed = (state.traces.episodes || []).find((ep) => (ep.trace_ids || []).includes(currentLive));
|
||||
if (landed) openEpisode(landed.line);
|
||||
if (landed) openEpisode(landed.line, { traceId: currentLive });
|
||||
else $("#tm-live-label").textContent = "finished · now in the stream";
|
||||
}
|
||||
}
|
||||
@@ -3467,6 +3476,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
currentLive = traceId;
|
||||
if (!refresh) updateHash();
|
||||
const requestVersion = ++episodeOpenVersion;
|
||||
let episode;
|
||||
try {
|
||||
@@ -3678,6 +3688,7 @@ async function modalStep(delta) {
|
||||
} else {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
updateHash();
|
||||
renderRolloutList();
|
||||
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
@@ -3768,7 +3779,7 @@ async function openEpisode(line, target = {}) {
|
||||
episode._hasTokens = withTokens;
|
||||
episode._hasRendered = withRendered;
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.trace ?? 0;
|
||||
currentTraceIdx = target.traceId ? episode.traces.findIndex((trace) => trace.id === target.traceId) : target.trace ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
currentEvidenceView = target.evidence ?? null;
|
||||
traceView = currentEvidenceView == null ? preferredTraceView : "transcript";
|
||||
@@ -3800,6 +3811,7 @@ function closeDrawer() {
|
||||
$("#sg-inspector").hidden = true;
|
||||
currentLine = null;
|
||||
pendingHighlight = null;
|
||||
updateHash();
|
||||
}
|
||||
|
||||
function traceBranches(trace) {
|
||||
@@ -5796,6 +5808,7 @@ function renderEpisode() {
|
||||
const traces = ep.traces || [];
|
||||
if (currentTraceIdx >= traces.length) currentTraceIdx = 0;
|
||||
const trace = traces[currentTraceIdx];
|
||||
updateHash();
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
// the episode's own errors sit above the agent and branch selectors: they belong to
|
||||
@@ -6428,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 {
|
||||
@@ -6903,9 +6916,11 @@ async function refreshModalList() {
|
||||
async function reopenFirstEpisode() {
|
||||
renderModalStep();
|
||||
const first = filteredRollouts()[0];
|
||||
if (first) return openEpisode(first.line);
|
||||
if (first) return first.live ? openLiveTrace(first.live.trace) : openEpisode(first.line);
|
||||
currentLive = null;
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
updateHash();
|
||||
renderRolloutList();
|
||||
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
@@ -7299,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);
|
||||
@@ -7453,6 +7470,9 @@ setInterval(pollLive, LIVE_POLL_MS);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) pollDashboard();
|
||||
});
|
||||
window.addEventListener("hashchange", () => {
|
||||
if (location.hash !== renderedHash) location.reload();
|
||||
});
|
||||
|
||||
(async function init() {
|
||||
syncSmoothControls();
|
||||
@@ -7484,5 +7504,21 @@ document.addEventListener("visibilitychange", () => {
|
||||
const run = state.runs.find((r) => r.name === wanted)?.name ?? state.runs[0]?.name;
|
||||
if (run) await selectRun(run);
|
||||
else $("#overview-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
const trace = params.get("trace");
|
||||
if (run === wanted && trace) {
|
||||
try {
|
||||
if (!state.traces.loaded) await initTraces();
|
||||
if (state.traces.live.some((row) => row.trace === trace)) await openLiveTrace(trace);
|
||||
else {
|
||||
const data = await api(`/api/runs/${encodeURIComponent(run)}/episodes?trace=${encodeURIComponent(trace)}&limit=1`);
|
||||
const episode = data.episodes[0];
|
||||
if (episode) await openEpisode(episode.line, { traceId: trace });
|
||||
else toastMsg(`trace ${esc(trace)} not found in this run`);
|
||||
}
|
||||
} catch (err) {
|
||||
toastMsg(`could not open trace ${esc(trace)}: ${esc(err.message)}`);
|
||||
}
|
||||
}
|
||||
initializing = false;
|
||||
connectViewEvents();
|
||||
})();
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,26 +1,33 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
"""vLLM general plugin and the single place prime-rl applies its vLLM patches; vLLM runs it once in every process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
vLLM swallows plugin load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from prime_rl.inference.vllm.gpt_oss_weight_loading import patch_gpt_oss_weight_loading
|
||||
from prime_rl.inference.vllm.qwen38_weight_loading import patch_qwen38_weight_loading
|
||||
|
||||
patch_gpt_oss_weight_loading()
|
||||
patch_qwen38_weight_loading()
|
||||
_patch_lora_key_prefix()
|
||||
_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()
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Set by `server()` when the LoRA target modules include no expert layers.
|
||||
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
@@ -40,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.
|
||||
|
||||
@@ -234,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.
|
||||
|
||||
@@ -422,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:
|
||||
@@ -431,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:
|
||||
@@ -574,8 +479,8 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
These patches are only needed when using LoRA with MiniMax M2 but are safe
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them at
|
||||
import time because the worker __init__ runs before the vLLM config is
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them
|
||||
unconditionally because the vLLM plugin runs before the vLLM config is
|
||||
available, so we can't check if LoRA is enabled.
|
||||
|
||||
Problem 1 — Gate dtype mismatch:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from functools import wraps
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def patch_qwen38_weight_loading() -> None:
|
||||
"""Skip nonlocal PLE checkpoint pieces before vLLM buffers parameter loads.
|
||||
|
||||
Remove when vLLM's Qwen4ExpNGramEmbedding.load_weights checks TP overlap
|
||||
before calling the embedding parameter's weight_loader.
|
||||
"""
|
||||
from vllm.models.qwen4_exp.common.ple import compute_ple_shard_overlap
|
||||
from vllm.models.qwen4_exp.nvidia.ngram_embedding import Qwen4ExpNGramEmbedding
|
||||
|
||||
original_load_weights = Qwen4ExpNGramEmbedding.load_weights
|
||||
if getattr(original_load_weights, "_prime_rl_filters_ple_shards", False):
|
||||
return
|
||||
|
||||
@wraps(original_load_weights)
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
embedding = self.ngram_embedding
|
||||
shard_size = (embedding.org_vocab_size + self.split_ngram_parts - 1) // self.split_ngram_parts
|
||||
skipped: set[str] = set()
|
||||
|
||||
def local_weights():
|
||||
for name, weight in weights:
|
||||
match = re.fullmatch(r"ngram_embedding\.shard_(\d+)\.weight", name)
|
||||
if match is not None:
|
||||
shard_index = int(match[1])
|
||||
checkpoint_start = shard_index * shard_size
|
||||
expected_rows = max(0, min(shard_size, embedding.org_vocab_size - checkpoint_start))
|
||||
# Leave malformed shards to the original loader's validation.
|
||||
if shard_index < self.split_ngram_parts and weight.shape == (
|
||||
expected_rows,
|
||||
embedding.embedding_dim,
|
||||
):
|
||||
overlap = compute_ple_shard_overlap(
|
||||
checkpoint_start=checkpoint_start,
|
||||
checkpoint_rows=expected_rows,
|
||||
tp_start=embedding.shard_indices.org_vocab_start_index,
|
||||
tp_end=embedding.shard_indices.org_vocab_end_index,
|
||||
)
|
||||
if overlap is None:
|
||||
skipped.add("ngram_embedding.weight")
|
||||
continue
|
||||
yield name, weight
|
||||
|
||||
loaded = original_load_weights(self, local_weights())
|
||||
return loaded | skipped
|
||||
|
||||
load_weights._prime_rl_filters_ple_shards = True
|
||||
Qwen4ExpNGramEmbedding.load_weights = load_weights
|
||||
@@ -15,32 +15,6 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.30 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
|
||||
|
||||
@@ -88,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,
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
logger.info("PRIME_NO_MOE_LORA=1: disabling LoRA on MoE layers")
|
||||
monkey_patch_no_moe_lora()
|
||||
else:
|
||||
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user