Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f87ebcc239 | ||
|
|
866c3e1438 | ||
|
|
c176840626 | ||
|
|
bb0c103f08 | ||
|
|
3fc28ddfb3 | ||
|
|
eaad03b9df | ||
|
|
70117046ac | ||
|
|
b2c6fe9aec | ||
|
|
66e1c2cb07 | ||
|
|
26af0c49e6 | ||
|
|
fc12ef2c66 | ||
|
|
95734aa1dd | ||
|
|
0c58f007bc | ||
|
|
d09bf96dbe | ||
|
|
05967ffcd2 | ||
|
|
21a4a32450 | ||
|
|
a070beecbd | ||
|
|
7da7c4d108 | ||
|
|
9e3be00b39 | ||
|
|
ef66401434 | ||
|
|
be5855cfe3 | ||
|
|
43365ec52f | ||
|
|
ab5de8fff4 | ||
|
|
97d32d947f | ||
|
|
6b3364d1a8 | ||
|
|
544bd6205a | ||
|
|
3460245d63 | ||
|
|
3758321f08 | ||
|
|
01dc127b1a | ||
|
|
663b53bbc2 | ||
|
|
f96a46f090 | ||
|
|
01994b8168 | ||
|
|
e6b5e4de5d | ||
|
|
a5853ce9ab | ||
|
|
38582b2bf1 | ||
|
|
a266325605 | ||
|
|
b9de4a0f7a | ||
|
|
75663f0d4c | ||
|
|
a975cab86d | ||
|
|
9aa5f1f2c8 | ||
|
|
c09bb0b30c | ||
|
|
3e93371dad | ||
|
|
f53e4d9c63 | ||
|
|
cabbd132eb | ||
|
|
947a02aafc | ||
|
|
f615de9383 | ||
|
|
1093f9b914 | ||
|
|
67ab1d6667 | ||
|
|
04e796d21b | ||
|
|
9f29e5388e | ||
|
|
822db2902c |
@@ -170,7 +170,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync
|
||||
run: uv sync --all-extras
|
||||
- name: Download all benchmark artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
name: Build Kernels
|
||||
|
||||
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
|
||||
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
|
||||
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
|
||||
# skill).
|
||||
#
|
||||
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
|
||||
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
|
||||
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
|
||||
#
|
||||
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
|
||||
required: false
|
||||
type: string
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Release tag to attach the wheels to. The release may still be a draft."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the caller's ref."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
env:
|
||||
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
|
||||
# the job container image below must be edited alongside it (no env context there).
|
||||
CUDA_TAG: cu128
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build wheel (${{ matrix.arch }})
|
||||
# Uploading the wheels to a release needs write; on workflow_call the caller
|
||||
# must grant it too (tag-and-release.yaml does).
|
||||
permissions:
|
||||
contents: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: image-builder
|
||||
arch: x86_64
|
||||
- runner: image-builder-arm-2204
|
||||
arch: aarch64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
|
||||
steps:
|
||||
- name: Install build tooling
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
|
||||
- name: Init the kernels submodule
|
||||
run: |
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
git submodule update --init -- deps/prime-kernels
|
||||
|
||||
- name: Install uv
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
|
||||
uv --version
|
||||
|
||||
# The wheel only imports under the exact torch it was compiled against, so build
|
||||
# against the torch prime-rl resolves rather than whatever is newest today.
|
||||
- name: Create build environment
|
||||
env:
|
||||
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
|
||||
run: |
|
||||
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
|
||||
if [ -z "$TORCH_PIN" ]; then
|
||||
echo "Could not read torch's version from uv.lock" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Building against torch==$TORCH_PIN"
|
||||
uv venv --python 3.12 /tmp/build-env
|
||||
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
|
||||
|
||||
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
|
||||
# the wheel carries both in its local version.
|
||||
- name: Stamp ABI into the version
|
||||
run: |
|
||||
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
|
||||
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
|
||||
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
|
||||
grep '^version' deps/prime-kernels/pyproject.toml
|
||||
|
||||
- name: Build wheel
|
||||
env:
|
||||
VIRTUAL_ENV: /tmp/build-env
|
||||
CUDA_HOME: /usr/local/cuda
|
||||
PRIME_KERNELS_REQUIRE: "1"
|
||||
MAX_JOBS: "8"
|
||||
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
|
||||
|
||||
- name: Inspect wheel
|
||||
run: |
|
||||
ls -lh dist/
|
||||
/tmp/build-env/bin/python - <<'PY'
|
||||
import pathlib, zipfile
|
||||
wheel = next(pathlib.Path("dist").glob("*.whl"))
|
||||
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
|
||||
assert extensions, f"{wheel.name} contains no compiled kernels"
|
||||
print(wheel.name, *extensions, sep="\n ")
|
||||
PY
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: prime-kernels-${{ matrix.arch }}
|
||||
path: dist/*.whl
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Attach to release
|
||||
if: inputs.release_tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
# gh must not resolve the repo from the checkout: inside the container the
|
||||
# workspace is owned by another uid, which git rejects as dubious ownership.
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
gh release upload "$TAG" dist/*.whl --clobber
|
||||
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
|
||||
WHEEL=$(basename dist/*.whl)
|
||||
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
|
||||
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --extra flash-attn --all-packages --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -113,21 +113,8 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Wheels are attached while the release is still a draft, so it is never published without
|
||||
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
|
||||
# resolves to a wheel-less release would fall back to compiling CUDA from source.
|
||||
kernels-from-auto-tag:
|
||||
needs: auto-tag-on-main
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
|
||||
release-from-auto-tag:
|
||||
needs: [auto-tag-on-main, kernels-from-auto-tag]
|
||||
needs: auto-tag-on-main
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -219,17 +206,8 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
kernels-from-tag:
|
||||
needs: resolve-release
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.resolve-release.outputs.tag }}
|
||||
ref: ${{ needs.resolve-release.outputs.tag }}
|
||||
|
||||
publish-release:
|
||||
needs: [resolve-release, kernels-from-tag]
|
||||
needs: resolve-release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
## Running code
|
||||
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
+44
-24
@@ -6,7 +6,7 @@
|
||||
|
||||
# Every pyproject.toml + uv.lock, so the dependency sync below caches
|
||||
# independently of source edits.
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
|
||||
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
|
||||
RUN mkdir -p /manifests \
|
||||
@@ -15,7 +15,7 @@ RUN mkdir -p /manifests \
|
||||
&& cp uv.lock /manifests/
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# mount here: .git would bust the cache every commit.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,7 +132,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --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", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
@@ -150,8 +150,8 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
|
||||
fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
@@ -161,19 +161,42 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
|
||||
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
|
||||
FROM builder AS cuda-trim
|
||||
RUN find /usr/local/cuda-12.8/targets/*/lib \
|
||||
RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
|
||||
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
|
||||
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
|
||||
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# CUDA 13 runtime libs source
|
||||
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
|
||||
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
|
||||
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
|
||||
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
|
||||
# installed as one version-matched unit via AWS's official installer
|
||||
# rather than picking versions by hand. Do not substitute a host-mounted
|
||||
# copy of these libraries instead of building them in -- symbol-version
|
||||
# mismatches between a host's rdma-core and a container's can silently
|
||||
# break the NCCL plugin. --skip-kmod: containers share the host kernel and
|
||||
# must never build/load a kernel module themselves; the EFA driver is
|
||||
# expected to already be present on the host. --skip-limit-conf: ulimits
|
||||
# config doesn't apply inside a build. Same base OS as the runtime stage
|
||||
# below for glibc/rdma-core ABI compatibility.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS efa-installer
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ARG EFA_INSTALLER_VERSION=1.47.0
|
||||
# One RUN: efa_installer.sh apt-get installs its own deps (pciutils,
|
||||
# libnl-3-200, tcl, ...) internally, so the package index has to survive
|
||||
# until after it runs. Purging /var/lib/apt/lists/* only at the very end
|
||||
# (not between the curl/tar deps and the installer invocation) keeps that
|
||||
# available.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl ca-certificates tar gzip \
|
||||
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
|
||||
-o /tmp/aws-efa-installer.tar.gz \
|
||||
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
|
||||
&& cd /tmp/aws-efa-installer \
|
||||
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
|
||||
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -207,20 +230,12 @@ RUN apt-get update && apt-get install -y \
|
||||
&& apt-get clean autoclean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
|
||||
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
|
||||
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH="/usr/local/cuda/bin:${PATH}"
|
||||
|
||||
# CUDA 13 runtime libs for deep-gemm
|
||||
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
|
||||
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
|
||||
&& ldconfig \
|
||||
&& ldconfig -p | grep -q libcudart.so.13 \
|
||||
&& ldconfig -p | grep -q libnvrtc.so.13
|
||||
|
||||
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
|
||||
@@ -252,6 +267,11 @@ 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
|
||||
|
||||
# EFA userspace stack from the dedicated stage above. Not added to
|
||||
# LD_LIBRARY_PATH here -- deployment configs opt into that only where
|
||||
# EFA is actually available, so this is inert everywhere else.
|
||||
COPY --from=efa-installer /opt/amazon /opt/amazon
|
||||
|
||||
# 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
|
||||
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:50:40+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:35:31.543870+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
"time_taken": 295.5118532651104
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 20.802552047875178,
|
||||
"std": 0.16199364988631793,
|
||||
"min": 20.664358307416567,
|
||||
"max": 20.98082222151257
|
||||
"mean": 16.701924322664684,
|
||||
"std": 0.0999595293790186,
|
||||
"min": 16.586575698092034,
|
||||
"max": 16.763194274056005
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2484.411208996455,
|
||||
"std": 19.346608946709658,
|
||||
"min": 2467.9069802355616,
|
||||
"max": 2505.7016937694384
|
||||
"mean": 1994.6806480062144,
|
||||
"std": 11.937986005933869,
|
||||
"min": 1980.9047701633856,
|
||||
"max": 2001.998007610024
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 52.79691480938345,
|
||||
"std": 0.4071756223542672,
|
||||
"min": 52.35017399210483,
|
||||
"max": 53.14720633160323
|
||||
"mean": 65.74198961785685,
|
||||
"std": 0.3962098986964774,
|
||||
"min": 65.49867434287444,
|
||||
"max": 66.19917749473825
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 11.728515625,
|
||||
"pct": 24.742767157118376
|
||||
"gib": 11.591145833333334,
|
||||
"pct": 24.45296844104
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:55:54+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:28:40.728120+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
"time_taken": 317.33935201819986
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.217465998339005,
|
||||
"std": 0.02905058130694137,
|
||||
"min": 17.19503698271855,
|
||||
"max": 17.250282374540514
|
||||
"mean": 15.880248465863398,
|
||||
"std": 0.005915779562921215,
|
||||
"min": 15.873443653590638,
|
||||
"max": 15.884167926432548
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 8225.003435798719,
|
||||
"std": 13.877833769765575,
|
||||
"min": 8214.288808538377,
|
||||
"max": 8240.68023789224
|
||||
"mean": 7586.197539502296,
|
||||
"std": 2.826043462792163,
|
||||
"min": 7582.946793757898,
|
||||
"max": 7588.069915881657
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.90305413212627,
|
||||
"std": 0.11015530079183487,
|
||||
"min": 63.77801387012005,
|
||||
"max": 63.985770548693836
|
||||
"mean": 69.21047159920757,
|
||||
"std": 0.022114607283211834,
|
||||
"min": 69.19065106380731,
|
||||
"max": 69.234325167723
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 6.298828125,
|
||||
"pct": 13.288163877053583
|
||||
"gib": 8.55078125,
|
||||
"pct": 18.038939985655993
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
|
||||
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
|
||||
|
||||
Forward and backward are timed separately, because only the forward is a kernel — the
|
||||
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
|
||||
grouped-mm reference. A speedup on the forward can be spent again on the backward.
|
||||
|
||||
uv run benchmarks/scripts/bench_fused_moe.py
|
||||
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
|
||||
|
||||
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
|
||||
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
|
||||
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
|
||||
parser.add_argument("--num-experts", type=int, default=64)
|
||||
parser.add_argument("--top-k", type=int, default=8)
|
||||
parser.add_argument("--iters", type=int, default=20)
|
||||
parser.add_argument("--warmup", type=int, default=5)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
|
||||
torch.manual_seed(0)
|
||||
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
|
||||
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
|
||||
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
|
||||
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
|
||||
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
|
||||
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
|
||||
|
||||
|
||||
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
|
||||
x, w1, w2, w3, selected, top_scores = inputs
|
||||
if mode == "grouped_mm":
|
||||
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
|
||||
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
|
||||
|
||||
|
||||
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
|
||||
"""Median forward ms, median backward ms, peak MiB."""
|
||||
forward_ms, backward_ms = [], []
|
||||
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
|
||||
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
|
||||
for i in range(args.warmup + args.iters):
|
||||
for tensor in inputs[:4] + (inputs[5],):
|
||||
tensor.grad = None
|
||||
torch.cuda.synchronize()
|
||||
|
||||
start.record()
|
||||
out = run_forward(mode, inputs, args.num_experts)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
forward_ms.append(start.elapsed_time(end))
|
||||
|
||||
start.record()
|
||||
out.backward(grad_out)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
backward_ms.append(start.elapsed_time(end))
|
||||
|
||||
median = lambda values: sorted(values)[len(values) // 2]
|
||||
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
if not torch.cuda.is_available():
|
||||
raise SystemExit("no CUDA device")
|
||||
kernel = _load_fused_moe_kernel()
|
||||
for mxfp8 in (False, True):
|
||||
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
|
||||
if reason is not None:
|
||||
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
|
||||
|
||||
inputs = make_inputs(args)
|
||||
print(
|
||||
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
|
||||
f"experts={args.num_experts} top_k={args.top_k} "
|
||||
f"({args.iters} iters, {args.warmup} warmup, median)\n"
|
||||
)
|
||||
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
|
||||
|
||||
baseline = None
|
||||
for mode in MODES:
|
||||
forward, backward, peak = time_mode(mode, inputs, args)
|
||||
total = forward + backward
|
||||
baseline = baseline or total
|
||||
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -70,11 +70,6 @@ class BenchmarkConfig(BaseConfig):
|
||||
Field(description="Activation checkpointing type"),
|
||||
] = "Recompute"
|
||||
|
||||
selective_targets: Annotated[
|
||||
list[str] | None,
|
||||
Field(description="Selective activation checkpoint targets when ac=Selective"),
|
||||
] = None
|
||||
|
||||
attention: Annotated[
|
||||
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
|
||||
Field(description="Attention implementation"),
|
||||
@@ -160,8 +155,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
|
||||
cmd.append("--model.ac")
|
||||
elif config.ac == "Selective":
|
||||
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
|
||||
if config.selective_targets:
|
||||
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
|
||||
elif config.ac == "Offload":
|
||||
cmd.append("--model.ac-offloading")
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ group_size = 16
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -20,7 +20,6 @@ group_size = 16
|
||||
max_inflight = 128
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: b30aad3637...1f1e050ab0
Vendored
+1
-1
Submodule deps/prime-kernels updated: 2ceaf9eccb...3fb83eb7aa
Vendored
+1
-1
Submodule deps/renderers updated: 2846a3dcd2...9b47901de1
Vendored
+1
-1
Submodule deps/verifiers updated: a60a606ecc...e2103d6fb4
+29
-10
@@ -35,31 +35,50 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
|
||||
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
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.
|
||||
|
||||
### Low-precision training
|
||||
|
||||
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
|
||||
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
|
||||
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
|
||||
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
|
||||
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
|
||||
|
||||
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
|
||||
|
||||
- `type = "bf16"` (default)
|
||||
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
|
||||
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
|
||||
|
||||
```toml
|
||||
[trainer.model.quantization]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
enable_a2a = true
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "mxfp8"
|
||||
```
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
|
||||
|
||||
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
|
||||
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
|
||||
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
|
||||
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
|
||||
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "deepep"
|
||||
num_sms = 20
|
||||
token_chunk_size = 4096
|
||||
```
|
||||
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
@@ -141,7 +160,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c '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
|
||||
```
|
||||
|
||||
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
|
||||
|
||||
+15
-26
@@ -13,7 +13,7 @@ This page covers the math and the configurable algorithmic components: the algor
|
||||
- [Async / Off-Policy Training](#async--off-policy-training)
|
||||
- [Loss](#loss)
|
||||
- [Loss Components](#loss-components)
|
||||
- [Default RL Loss](#default-rl-loss)
|
||||
- [IPO Loss](#ipo-loss)
|
||||
- [Custom Loss](#custom-loss)
|
||||
- [Advantage](#advantage)
|
||||
- [Default Advantage](#default-advantage)
|
||||
@@ -159,7 +159,7 @@ Algorithms operate on native verifier artifacts and annotate their message graph
|
||||
|
||||
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
|
||||
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
|
||||
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.algo.advantage`.
|
||||
|
||||
## Async / Off-Policy Training
|
||||
|
||||
@@ -184,47 +184,36 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `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.
|
||||
|
||||
### Default RL Loss
|
||||
### IPO Loss
|
||||
|
||||
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
|
||||
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$:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
|
||||
\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].
|
||||
$$
|
||||
|
||||
where the policy-gradient term is
|
||||
$\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.
|
||||
|
||||
$$
|
||||
\mathcal{J}_{\text{PG}}(\theta)
|
||||
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t}
|
||||
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
|
||||
$$
|
||||
|
||||
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
|
||||
|
||||
$$
|
||||
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
|
||||
$$
|
||||
|
||||
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
|
||||
|
||||
The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
The knobs under `[trainer.loss]` are:
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `eps` | 0.1 | 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` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
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]`.
|
||||
|
||||
### Custom Loss
|
||||
|
||||
|
||||
@@ -247,8 +247,14 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/check/configs/
|
||||
ls /tmp/reverse-dry/check/configs/latest/resolved/
|
||||
# rl.json trainer.json orchestrator.json inference.json
|
||||
```
|
||||
|
||||
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
|
||||
Each per-process JSON contains the final, validated configuration that the run
|
||||
uses. This is also what each standalone process reads. For example, the trainer
|
||||
reads `configs/latest/resolved/trainer.json`.
|
||||
|
||||
`configs/latest/command.txt` records the shell-safe launch command and its CLI
|
||||
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
|
||||
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
|
||||
|
||||
+1
-9
@@ -191,15 +191,7 @@ Both backends support the 2 most important things:
|
||||
|
||||
### Routing policies
|
||||
The 2 policies you might want to configure are:
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - this works by hashing a request header to determine where to route the request to. You can configure what to hash by setting
|
||||
`orchestrator.model.client.extra_headers_from_state` to the header the `router` expects to be set.
|
||||
|
||||
We set it to a sensible default, that works with all verifiers environments.
|
||||
|
||||
```toml
|
||||
[orchestrator.model.client.extra_headers_from_state]
|
||||
X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique trajectory_id and router expects X-Session-ID
|
||||
```
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
|
||||
|
||||
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
|
||||
|
||||
|
||||
+41
-13
@@ -43,19 +43,20 @@ uv run rl @ rl.toml \
|
||||
|
||||
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
|
||||
|
||||
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
|
||||
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
|
||||
|
||||
```bash
|
||||
# session 1, GPUs 0–1, default port 8000
|
||||
bash scripts/tmux.sh -s exp1 -o outputs/exp1
|
||||
# shell 1, GPUs 0–1, default port 8000
|
||||
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
|
||||
|
||||
# session 2, GPUs 2–3, port 8001
|
||||
bash scripts/tmux.sh -s exp2 -o outputs/exp2
|
||||
# shell 2, GPUs 2–3, port 8001
|
||||
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
|
||||
--inference.server.port 8001 \
|
||||
--orchestrator.model.client.base-url http://localhost:8001/v1 \
|
||||
--run.name exp2
|
||||
|
||||
# watch both side by side
|
||||
uv run dashboard outputs
|
||||
```
|
||||
|
||||
#### SFT and Torchrun
|
||||
@@ -98,11 +99,14 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
ep_comm_backend = "torch" # or "deepep"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "bf16"
|
||||
```
|
||||
|
||||
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
|
||||
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
@@ -126,15 +130,18 @@ cp_style = "ulysses" # "ring"
|
||||
| `trainer.model.ac.mode = "selective"` | medium | small |
|
||||
| `trainer.model.ac_offloading` | extra | a bit more |
|
||||
|
||||
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
|
||||
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
|
||||
```
|
||||
|
||||
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
|
||||
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
|
||||
|
||||
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
|
||||
|
||||
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
@@ -193,9 +200,11 @@ Launch:
|
||||
|
||||
```bash
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
|
||||
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
|
||||
```
|
||||
|
||||
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
|
||||
|
||||
### `[deployment]` Block
|
||||
|
||||
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
|
||||
@@ -214,7 +223,8 @@ SFT multi-node:
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_nodes = 2
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1 # required only for online evals
|
||||
gpus_per_node = 8
|
||||
```
|
||||
|
||||
@@ -227,6 +237,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### NIXL weight broadcast
|
||||
|
||||
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
|
||||
|
||||
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
|
||||
|
||||
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
|
||||
|
||||
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
+38
-22
@@ -77,11 +77,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
|
||||
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
|
||||
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
|
||||
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
|
||||
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<run_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
|
||||
|
||||
### Algorithms
|
||||
|
||||
@@ -125,7 +125,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
|
||||
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
|
||||
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
|
||||
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
|
||||
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
|
||||
|
||||
**Performance** (trainer + orchestrator step independently):
|
||||
@@ -198,17 +198,17 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
#### Multi-Node Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evals)
|
||||
num_train_nodes = 2 # trainer nodes
|
||||
num_infer_nodes = 1 # inference pool + evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -217,7 +217,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -263,8 +263,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
|
||||
|
||||
| Process | What's saved | Where |
|
||||
|---|---|---|
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
|
||||
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
|
||||
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
|
||||
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
|
||||
|
||||
### Enabling Checkpoints
|
||||
@@ -297,8 +297,29 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
|
||||
--resume.dir outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
### Exporting Checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
|
||||
|
||||
```bash
|
||||
# single process (1 GPU)
|
||||
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
|
||||
# multi-rank for faster gathers and models that don't fit one GPU
|
||||
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
|
||||
```
|
||||
|
||||
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
|
||||
|
||||
## Observability
|
||||
|
||||
### Config Files
|
||||
|
||||
Each launch writes its command, input TOML, and resolved JSON files to
|
||||
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
|
||||
`command.txt` uses shell-safe quoting.
|
||||
`configs/latest` points to the current attempt.
|
||||
|
||||
### Log Files
|
||||
|
||||
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
@@ -307,6 +328,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── evals.log # SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -317,27 +339,21 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
### Console Output
|
||||
### Dashboard
|
||||
|
||||
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from `metrics.jsonl`), the resolved configs, a rollout trace viewer with a per-token advantage/logprob view, merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh -o outputs/my-run
|
||||
# then in the Launcher window:
|
||||
uv run rl @ ... --run.name my-run
|
||||
```
|
||||
|
||||
Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_name>`) to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
### Weights & Biases
|
||||
|
||||
|
||||
@@ -97,6 +97,9 @@ ep = 8
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "deepgemm_fp8"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -12,9 +12,10 @@ The taskset is included through the Verifiers workspace. After syncing the repos
|
||||
uv run python -c "import alphabet_sort"
|
||||
```
|
||||
|
||||
Start the tmux session:
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
## Task
|
||||
@@ -31,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
|
||||
|
||||
Start the inference server:
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
@@ -91,7 +92,7 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
|
||||
|
||||
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/alphabet-sort/rl.toml \
|
||||
--run.name rl \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -106,12 +107,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
|
||||
|
||||
Let's see how our final RL checkpoint performs on the eval set.
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
|
||||
@@ -12,21 +12,21 @@ The `reverse-text` taskset is included through the Verifiers workspace. After sy
|
||||
uv run python -c "import reverse_text"
|
||||
```
|
||||
|
||||
First, let's start a `tmux` session which we will use throughout the experiment.
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` environment.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -41,7 +41,7 @@ We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/Prime
|
||||
To train on a single GPU, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run sft @ examples/basic/reverse-text/sft.toml \
|
||||
--run.name sft \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -51,7 +51,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml \
|
||||
To train on multiple GPUs, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run torchrun \
|
||||
--local-ranks-filter 0 \
|
||||
--nproc-per-node ... \
|
||||
@@ -71,7 +71,7 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
|
||||
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
@@ -88,12 +88,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`
|
||||
Let's see how our final RL checkpoints perform on the `reverse-text` environment.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
|
||||
@@ -25,10 +25,10 @@ Set up the credentials for the configured reference judge:
|
||||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
Start the tmux session:
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
## Task
|
||||
@@ -69,14 +69,14 @@ Key configuration highlights:
|
||||
Start the inference server:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
Evaluate the base model:
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
@@ -91,7 +91,7 @@ uv run eval wiki-search --harness.id null \
|
||||
Train with the unified config file:
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/wiki-search/rl.toml \
|
||||
--run.name rl \
|
||||
--monitors.wandb.project your-project-name \
|
||||
@@ -110,12 +110,12 @@ This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
|
||||
Evaluate your trained model:
|
||||
|
||||
```bash
|
||||
# In the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
|
||||
```
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
|
||||
@@ -37,7 +37,6 @@ group_size = 16
|
||||
initial_inflight = 1024
|
||||
|
||||
[orchestrator.model.lora]
|
||||
name = "qwen3-4b-wiki-search"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -12,23 +12,23 @@ The taskset is included through the Verifiers workspace. After syncing the repos
|
||||
uv run python -c "import wordle"
|
||||
```
|
||||
|
||||
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
|
||||
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh
|
||||
uv run dashboard
|
||||
```
|
||||
|
||||
Before training, we want to get a baseline score and test how well `Qwen3-1.7B` does out-of-the-box in the `wordle` environment so that we quantify our training effect. To do so, first start a local inference server to serve `Qwen3-1.7B`.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model Qwen/Qwen3-1.7B
|
||||
```
|
||||
|
||||
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
@@ -43,7 +43,7 @@ We will fine-tune `PrimeIntellect/Qwen3-1.7B` ([HF](https://huggingface.co/Prime
|
||||
To train on a single GPU, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run sft @ examples/basic/wordle/sft.toml \
|
||||
--run.name sft \
|
||||
--monitors.wandb.project ... \
|
||||
@@ -53,7 +53,7 @@ uv run sft @ examples/basic/wordle/sft.toml \
|
||||
To train on multiple GPUs, run
|
||||
|
||||
```bash
|
||||
# In the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run torchrun \
|
||||
--local-ranks-filter 0 \
|
||||
--nproc-per-node ... \
|
||||
@@ -74,7 +74,7 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
|
||||
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run rl @ examples/basic/wordle/rl.toml \
|
||||
--model.name ... \
|
||||
--run.name rl \
|
||||
@@ -91,12 +91,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](http
|
||||
Let's see how our final RL checkpoint performs on the eval set.
|
||||
|
||||
```bash
|
||||
# Run this in the `Inference` pane
|
||||
# Run this in the inference terminal
|
||||
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run this in the `Trainer` pane
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
```
|
||||
|
||||
|
||||
@@ -23,11 +23,8 @@ rank = 32
|
||||
alpha = 32
|
||||
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
|
||||
|
||||
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
|
||||
# raises CheckpointError; selective AC excluding routed_experts avoids that.
|
||||
[model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj", "linear_attn"]
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
|
||||
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.9",
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import SerializeAsAny, model_validator
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
@@ -20,8 +20,8 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
|
||||
@@ -6,7 +6,7 @@ from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
|
||||
Disable to finish every triggered eval epoch before loading later weights. The trainer can
|
||||
idle while it waits for slow evals."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
@@ -86,9 +91,9 @@ class EvalsConfig(BaseConfig):
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals."""
|
||||
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from pydantic import ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
|
||||
from prime_rl.utils.config import find_package_resource
|
||||
from prime_rl.utils.config import default_output_dir, find_package_resource
|
||||
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
@@ -111,14 +111,9 @@ class VllmConfig(BaseConfig):
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA."""
|
||||
|
||||
max_loras: int = 8
|
||||
"""Maximum number of LoRAs."""
|
||||
|
||||
# TODO: The default value is very high because our areal impl for lora isn't ideal
|
||||
# We add a lora with the same name instead of changing weights inplace
|
||||
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
|
||||
max_cpu_loras: int = 100
|
||||
"""Maximum number of LoRAs on CPU."""
|
||||
max_loras: int = 1
|
||||
"""Maximum number of concurrently served LoRAs. prime-rl serves one adapter and reloads
|
||||
it in place every policy version (same name, same lora_int_id), so one slot suffices."""
|
||||
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Rounded up to the nearest value vLLM accepts."""
|
||||
@@ -467,7 +462,7 @@ class InferenceConfig(BaseConfig):
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
|
||||
|
||||
# Launcher-only fields
|
||||
|
||||
@@ -476,8 +471,8 @@ class InferenceConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory for SLURM logs and generated scripts."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
@@ -612,6 +607,18 @@ class InferenceConfig(BaseConfig):
|
||||
if not hasattr(namespace, "logprobs_mode"):
|
||||
namespace.logprobs_mode = "processed_logprobs"
|
||||
|
||||
# Always surface cached prompt tokens in `usage` — the router's
|
||||
# cache-discount billing counters parse them off /inference/v1/generate.
|
||||
if "enable_prompt_tokens_details" not in extra_fields:
|
||||
namespace.enable_prompt_tokens_details = True
|
||||
|
||||
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
|
||||
# `moe_router_dtype` off the HF config to pick the router logits dtype.
|
||||
if self.enable_fp32_router_logits:
|
||||
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
|
||||
hf_overrides.setdefault("moe_router_dtype", "float32")
|
||||
namespace.hf_overrides = hf_overrides
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
@@ -621,8 +628,6 @@ class InferenceConfig(BaseConfig):
|
||||
additional_config = getattr(namespace, "additional_config", None) or {}
|
||||
if self.enable_fp32_lm_head:
|
||||
additional_config["fp32_lm_head"] = True
|
||||
if self.enable_fp32_router_logits:
|
||||
additional_config["fp32_router_logits"] = True
|
||||
if additional_config:
|
||||
namespace.additional_config = additional_config
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
HeartbeatConfig,
|
||||
@@ -21,13 +22,10 @@ from prime_rl.configs.shared import (
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
|
||||
|
||||
rank: int | None = Field(None, ge=1)
|
||||
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
|
||||
|
||||
@@ -376,20 +374,17 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseConfig):
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseConfig):
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Weight transfer timeout in seconds."""
|
||||
|
||||
inference_world_size: int = Field(1, ge=1)
|
||||
"""Total inference workers across all servers."""
|
||||
|
||||
@@ -413,6 +408,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
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,
|
||||
@@ -496,8 +494,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
@@ -543,12 +541,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_prime_monitor_name(self):
|
||||
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
|
||||
|
||||
@@ -41,7 +41,7 @@ from prime_rl.configs.trainer import (
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
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,
|
||||
@@ -136,7 +136,7 @@ class SharedInMemoryWeightBroadcastConfig(BaseConfig):
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for in-memory weight transfer."""
|
||||
"""Timeout in seconds for the broadcast handshake and transfer."""
|
||||
|
||||
|
||||
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
@@ -158,10 +158,16 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
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,
|
||||
@@ -240,8 +246,8 @@ class RLConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
@@ -296,6 +302,10 @@ class RLConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. If None, runs locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -460,8 +470,9 @@ class RLConfig(BaseConfig):
|
||||
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
"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 = (
|
||||
@@ -482,14 +493,21 @@ class RLConfig(BaseConfig):
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(session_id=self.weight_broadcast.session_id)
|
||||
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()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
|
||||
timeout=self.weight_broadcast.timeout
|
||||
)
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
@@ -568,11 +586,6 @@ class RLConfig(BaseConfig):
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
self.inference.vllm.enable_lora = True
|
||||
self.inference.vllm.max_lora_rank = self.trainer.model.lora.rank
|
||||
|
||||
@@ -33,7 +33,7 @@ from prime_rl.configs.trainer import (
|
||||
WeightBroadcastConfig,
|
||||
validate_scheduler,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseConfig):
|
||||
@@ -175,9 +175,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
|
||||
from the trainer job. The eval job can outlive the trainer job while it evaluates
|
||||
the final weight broadcast."""
|
||||
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
|
||||
one SLURM allocation with the trainer nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
@@ -233,8 +232,8 @@ class SFTConfig(BaseConfig):
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
@@ -285,6 +284,10 @@ class SFTConfig(BaseConfig):
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Make sure a local dashboard daemon serves this run's output dir (started on
|
||||
demand in interactive sessions; an already-running daemon's URL is logged)."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
@@ -321,7 +324,7 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
@@ -390,18 +393,18 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
|
||||
|
||||
if self.deployment.type == "multi_node":
|
||||
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
|
||||
# inference pool (one engine per DP rank behind a router) plus the evals process.
|
||||
# Dedicated nodes in the SFT allocation run the inference pool, router,
|
||||
# env servers, and evals process.
|
||||
if self.inference is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an [inference] block - the launcher submits "
|
||||
"a dedicated SLURM job running the inference pool and the evals process."
|
||||
"Multi-node online evals require an [inference] block - dedicated nodes in the "
|
||||
"SFT allocation run the inference pool and evals process."
|
||||
)
|
||||
if self.deployment.num_infer_nodes < 1:
|
||||
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
|
||||
if self.inference.router is None:
|
||||
raise ValueError(
|
||||
"Multi-node online evals require an inference router - the eval job starts one "
|
||||
"Multi-node online evals require an inference router - the launcher starts one "
|
||||
"router in front of the per-rank engines. Remove inference.router = 'None'."
|
||||
)
|
||||
if self.inference.vllm.model != self.model.name:
|
||||
@@ -422,10 +425,10 @@ class SFTConfig(BaseConfig):
|
||||
if self.max_steps is None:
|
||||
warnings.warn(
|
||||
"Online evals without max_steps: the evals process never sees a final checkpoint, "
|
||||
"so the eval SLURM job holds its allocation until its walltime.",
|
||||
"so the SFT SLURM job holds its allocation until its walltime.",
|
||||
stacklevel=2,
|
||||
)
|
||||
# The client is wired at runtime by the eval sbatch script (the router and
|
||||
# The client is wired at runtime by the SFT sbatch script (the router and
|
||||
# per-rank admin URLs are only known once SLURM assigns hosts).
|
||||
return self
|
||||
|
||||
|
||||
@@ -37,6 +37,12 @@ EnvVars: TypeAlias = Annotated[dict[str, str], AfterValidator(reject_protected_e
|
||||
"""A per-component `env_vars` mapping, validated to not clobber `PROTECTED_ENV_VARS`."""
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseConfig):
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
|
||||
fails the run when no consumer acknowledges an offered version in time."""
|
||||
|
||||
|
||||
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."""
|
||||
@@ -100,6 +106,9 @@ class SlurmConfig(BaseConfig):
|
||||
pre_run_command: str | None = None
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
launch_modelexpress: bool = True
|
||||
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
|
||||
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
@@ -169,9 +178,6 @@ class ClientConfig(BaseConfig):
|
||||
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"}``."""
|
||||
|
||||
extra_headers_from_state: dict[str, str] = {}
|
||||
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
|
||||
|
||||
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``."""
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from pydantic import BeforeValidator, Field, model_validator
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
EnvVars,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
@@ -15,12 +16,11 @@ from prime_rl.configs.shared import (
|
||||
TransportConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
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"]
|
||||
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
@@ -30,20 +30,13 @@ class GCConfig(BaseConfig):
|
||||
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
mode: Literal["full", "selective"] = "full"
|
||||
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
|
||||
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
|
||||
|
||||
freq: int = Field(1, ge=1)
|
||||
"""Apply activation checkpointing to every N layers."""
|
||||
|
||||
targets: list[str] = ["norm"]
|
||||
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_selective_targets(self):
|
||||
self.targets = list(dict.fromkeys(self.targets))
|
||||
if self.mode == "selective" and not self.targets:
|
||||
raise ValueError("Selective activation checkpointing requires at least one target.")
|
||||
return self
|
||||
targets: list[str] | None = None
|
||||
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
@@ -122,7 +115,7 @@ class LoRAConfig(BaseConfig):
|
||||
"fc1_latent_proj",
|
||||
"fc2_latent_proj",
|
||||
]
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
|
||||
modules_to_save: list[str] = []
|
||||
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
|
||||
@@ -150,7 +143,7 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
# in BF16 on the trainer while inference quantized it to FP8, causing
|
||||
# hidden-state drift before the MoE router.
|
||||
r"mlp\.gate\.",
|
||||
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"in_proj_a",
|
||||
@@ -160,21 +153,80 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
|
||||
class FP8Config(BaseConfig):
|
||||
type: Literal["fp8"] = "fp8"
|
||||
enable_grouped_gemm: bool = True
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from DeepGEMM FP8 replacement."""
|
||||
|
||||
|
||||
class MXFP8Config(BaseConfig):
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
enable_grouped_gemm: bool = True
|
||||
enable_a2a: bool = True
|
||||
"""MXFP8 recipe for dense linear modules."""
|
||||
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from torchao MXFP8 replacement."""
|
||||
|
||||
|
||||
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs in bfloat16."""
|
||||
|
||||
type: Literal["bf16"] = "bf16"
|
||||
|
||||
|
||||
class DeepGemmFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
|
||||
|
||||
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
|
||||
|
||||
|
||||
class MXFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
|
||||
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
"""MXFP8 expert-compute recipe."""
|
||||
|
||||
|
||||
MoEComputeConfig: TypeAlias = Annotated[
|
||||
BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class TorchMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with torch all-to-all collectives."""
|
||||
|
||||
type: Literal["torch"] = "torch"
|
||||
transport: Literal["bf16", "mxfp8"] = "bf16"
|
||||
"""Wire format for routed activations and their reverse-path gradients."""
|
||||
|
||||
|
||||
class DeepEPMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with DeepEP."""
|
||||
|
||||
type: Literal["deepep"] = "deepep"
|
||||
num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated to DeepEP communication kernels."""
|
||||
|
||||
token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Optional chunk size used to pipeline dispatch with local expert compute."""
|
||||
|
||||
|
||||
MoEDispatchConfig: TypeAlias = Annotated[
|
||||
TorchMoEDispatchConfig | DeepEPMoEDispatchConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class MoERuntimeConfig(BaseConfig):
|
||||
"""Independent routed-expert compute and token-dispatch choices."""
|
||||
|
||||
compute: MoEComputeConfig = BF16MoEComputeConfig()
|
||||
dispatch: MoEDispatchConfig = TorchMoEDispatchConfig()
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
@@ -212,14 +264,8 @@ class ModelConfig(BaseModelConfig):
|
||||
ep: int | Literal["auto"] = "auto"
|
||||
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
|
||||
|
||||
ep_comm_backend: EPCommBackend = "torch"
|
||||
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
|
||||
|
||||
deepep_num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
|
||||
|
||||
deepep_token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
|
||||
moe: MoERuntimeConfig = MoERuntimeConfig()
|
||||
"""Routed-expert compute and token-dispatch runtime."""
|
||||
|
||||
cp: int = 1
|
||||
"""Context parallelism degree. 1 disables CP."""
|
||||
@@ -239,12 +285,6 @@ class ModelConfig(BaseModelConfig):
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) 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. 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."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
moe_fused_kernel: bool = False
|
||||
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
@@ -300,12 +340,6 @@ class ModelConfig(BaseModelConfig):
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def selective_ac_only_with_custom_impl(self):
|
||||
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
|
||||
@@ -331,19 +365,18 @@ class ModelConfig(BaseModelConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
def validate_moe_runtime(self):
|
||||
if self.ep == 1:
|
||||
return self
|
||||
|
||||
if isinstance(self.ep, int) and self.ep <= 1:
|
||||
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def mxfp8_only_with_torch_ep_backend(self):
|
||||
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
|
||||
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
|
||||
compute = self.moe.compute
|
||||
dispatch = self.moe.dispatch
|
||||
if isinstance(dispatch, DeepEPMoEDispatchConfig):
|
||||
if isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
|
||||
elif dispatch.transport == "mxfp8":
|
||||
if not isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -491,26 +524,10 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the optimizer state from checkpoint."""
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
eps: float = Field(0.1, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
@@ -529,7 +546,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -545,10 +562,6 @@ class DataLoaderConfig(BaseConfig):
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
|
||||
class BaseWeightBroadcastConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
@@ -560,9 +573,6 @@ class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Weight transfer timeout in seconds."""
|
||||
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: int = 1
|
||||
"""Number of inference workers."""
|
||||
@@ -587,6 +597,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
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,
|
||||
@@ -601,7 +614,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
loss: LossConfig = IPOLossConfig()
|
||||
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
@@ -625,8 +638,8 @@ class TrainerConfig(BaseConfig):
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
matmul_precision: Literal["highest", "high", "medium"] = "high"
|
||||
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
|
||||
@@ -663,7 +676,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
@@ -733,7 +746,15 @@ class TrainerConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
raise ValueError("In-memory weight broadcast does not support LoRA yet.")
|
||||
raise ValueError(
|
||||
"LoRA requires weight_broadcast.type = 'filesystem': vLLM loads adapters only from a "
|
||||
"PEFT-shaped directory on disk - in-memory transports have no disk artifact to load from."
|
||||
)
|
||||
if self.model.lora is not None and self.model.lora.modules_to_save and self.data.fake is None:
|
||||
raise ValueError(
|
||||
"model.lora.modules_to_save cannot be served: the weight broadcast ships only the "
|
||||
"adapter tensors, so fully-trained modules would silently diverge from inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -6,6 +7,11 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def default_output_dir() -> Path:
|
||||
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
|
||||
|
||||
|
||||
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a resolved config for a machine-written JSON artifact.
|
||||
|
||||
|
||||
+91
-56
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -13,38 +13,25 @@ dependencies = [
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.26.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.19",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"psutil>=7.0.0",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.3.1.dev59",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
"nvidia-ml-py>=12.575.51",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"renderers[multimodal]>=0.1.11",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
"torchao>=0.17.0",
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -55,43 +42,66 @@ trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
evals = "prime_rl.entrypoints.evals:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
dashboard = "prime_rl.entrypoints.dashboard:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
|
||||
gpu = [
|
||||
"torch>=2.13.0 ; sys_platform == 'linux'",
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.28.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'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.18.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
dashboard = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn>=0.30",
|
||||
]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
|
||||
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
|
||||
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
|
||||
# trainer/model.py).
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
|
||||
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
"flash-attn-4 ; sys_platform == 'linux'",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
"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'",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
"kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
# 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 = [
|
||||
"prime-kernels",
|
||||
"prime-kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
all = [
|
||||
"prime-rl[gpu]",
|
||||
"prime-rl[flash-attn]",
|
||||
"prime-rl[disagg]",
|
||||
"prime-rl[quack]",
|
||||
@@ -101,12 +111,13 @@ all = [
|
||||
|
||||
[dependency-groups]
|
||||
mamba-ssm = [
|
||||
"mamba-ssm>=2.3.0",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
"pre-commit>=4.2.0",
|
||||
"playwright>=1.49",
|
||||
"pytest>=8.4.1",
|
||||
"pytest-asyncio>=0.23",
|
||||
"ruff>=0.12.1",
|
||||
@@ -123,14 +134,19 @@ no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"sys_platform == 'linux' and platform_machine == 'aarch64'",
|
||||
"sys_platform == 'darwin' and platform_machine == 'arm64'",
|
||||
]
|
||||
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
|
||||
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
# 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.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.6.2",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"torch>=2.13.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
@@ -167,13 +183,30 @@ version = "0.3.0"
|
||||
requires-dist = [
|
||||
"grpcio>=1.66.2",
|
||||
"huggingface_hub>=0.20.0",
|
||||
"nixl[cu12]",
|
||||
"nixl",
|
||||
"numpy>=1.24.0",
|
||||
"protobuf>=5.27.0,<7.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
# NIXL publishes its CUDA 12 package as a base dependency even when the
|
||||
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nixl"
|
||||
version = "0.10.1"
|
||||
requires-dist = ["nixl-cu13==0.10.1"]
|
||||
|
||||
# CUTLASS DSL has the same CUDA 12 default. vLLM requests its CUDA 13 extra,
|
||||
# so resolve that variant without installing both runtime packages.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
requires-dist = [
|
||||
"nvidia-cutlass-dsl-libs-base==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
@@ -199,7 +232,7 @@ vllm-router = false
|
||||
dion = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
|
||||
@@ -210,36 +243,38 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchvision = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchaudio = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ 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'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ 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-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ 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'" },
|
||||
]
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
@@ -250,13 +285,13 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
name = "pytorch-cu130"
|
||||
url = "https://download.pytorch.org/whl/cu130"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
name = "pytorch-cu130-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu130"
|
||||
explicit = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
|
||||
@@ -53,16 +53,10 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# Mirror the image's uv sync extras — explicit instead
|
||||
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
|
||||
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra gpt-oss \
|
||||
--group mamba-ssm )
|
||||
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
|
||||
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
|
||||
# lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
cd "$DEST"
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
|
||||
|
||||
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
|
||||
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
|
||||
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
|
||||
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
|
||||
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
|
||||
(one training sample is built per branch).
|
||||
|
||||
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
|
||||
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
|
||||
condition and a complete conversation, so it stays; its reward may be partial/zero, which
|
||||
`--min-reward` handles.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
|
||||
[-o OUT_DIR] [--push HF_REPO_ID]
|
||||
|
||||
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
|
||||
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
|
||||
(PrimeIntellect-ai/verifiers#1963).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from datasets import Dataset
|
||||
from verifiers.v1 import Trace, WireTrace
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def sft_rows(trace: Trace) -> list[dict]:
|
||||
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
|
||||
dicts plus the trace's advertised tools, JSON-encoded."""
|
||||
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
|
||||
return [
|
||||
{
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"tools": tools,
|
||||
}
|
||||
for branch in trace.branches
|
||||
if branch.messages
|
||||
]
|
||||
|
||||
|
||||
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
|
||||
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
|
||||
if trace.stop_condition == "error":
|
||||
return False
|
||||
if drop_truncated and trace.is_truncated:
|
||||
return False
|
||||
return min_reward is None or trace.reward >= min_reward
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
|
||||
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
|
||||
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
|
||||
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
|
||||
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
|
||||
args = parser.parse_args()
|
||||
|
||||
traces_path = args.run_dir / "traces.jsonl"
|
||||
if not traces_path.exists():
|
||||
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
|
||||
|
||||
total, rows = 0, []
|
||||
with traces_path.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
total += 1
|
||||
trace = WireTrace.model_validate(json.loads(line))
|
||||
if keep(trace, args.min_reward, args.drop_truncated):
|
||||
rows.extend(sft_rows(trace))
|
||||
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
|
||||
if not rows:
|
||||
raise SystemExit("export-sft: no rows to export after selection")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if args.push:
|
||||
dataset.push_to_hub(args.push)
|
||||
print(f"export-sft: pushed to {args.push}")
|
||||
return
|
||||
out = args.output_dir or args.run_dir / "sft"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(out / "train.parquet"))
|
||||
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
|
||||
#
|
||||
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
|
||||
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
|
||||
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
|
||||
# and is what `pyproject.toml` consumes by default; this script is for
|
||||
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
|
||||
#
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh # build + install in-place
|
||||
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: d30fc36)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
|
||||
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if already installed at the right version
|
||||
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
|
||||
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
|
||||
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
|
||||
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Auto-detect CUDA version
|
||||
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
|
||||
if [ -z "$CUDA_VERSION" ]; then
|
||||
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CUDA_MAJOR="${CUDA_VERSION%%.*}"
|
||||
CUDA_MINOR="${CUDA_VERSION#*.}"
|
||||
CUDA_MINOR="${CUDA_MINOR%%.*}"
|
||||
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
|
||||
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " Building DeepGEMM (${SHORT_REF})"
|
||||
echo " CUDA: ${CUDA_VERSION}"
|
||||
echo "================================================================"
|
||||
|
||||
TMPDIR=$(mktemp -d)
|
||||
cleanup() { rm -rf "$TMPDIR"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
|
||||
cd "$TMPDIR/DeepGEMM"
|
||||
git checkout "$DEEPGEMM_GIT_REF"
|
||||
git submodule update --init --recursive
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
if [ -n "$WHEEL_DIR" ]; then
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Wheel built:"
|
||||
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
|
||||
else
|
||||
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " DeepGEMM build complete"
|
||||
echo "================================================================"
|
||||
@@ -1,170 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install DeepEP kernels for expert-parallel disaggregated inference.
|
||||
#
|
||||
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
|
||||
# Required for disaggregated prefill/decode deployments with expert parallelism.
|
||||
#
|
||||
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
|
||||
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
|
||||
# - For multi-node: IBGDA driver configured (see --configure-drivers)
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_ep_kernels.sh
|
||||
#
|
||||
# Options:
|
||||
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
|
||||
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
|
||||
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
|
||||
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPEP_COMMIT_HASH="73b6ea4"
|
||||
NVSHMEM_VER="3.3.24"
|
||||
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
|
||||
CONFIGURE_DRIVERS=0
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--workspace) WORKSPACE="$2"; shift 2 ;;
|
||||
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
|
||||
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
|
||||
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if DeepEP is already installed
|
||||
if python -c "import deep_ep" 2>/dev/null; then
|
||||
echo "DeepEP already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
|
||||
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
|
||||
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
|
||||
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
|
||||
|
||||
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
|
||||
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
|
||||
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
|
||||
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
|
||||
exit 1
|
||||
fi
|
||||
export CUDA_HOME
|
||||
|
||||
# Verify versions actually match
|
||||
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
|
||||
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
|
||||
|
||||
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
|
||||
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
|
||||
case "$GPU_NAME" in
|
||||
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
|
||||
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
|
||||
*)
|
||||
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
|
||||
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
|
||||
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
export TORCH_CUDA_ARCH_LIST
|
||||
|
||||
echo "================================================================"
|
||||
echo " Installing DeepEP kernels"
|
||||
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
|
||||
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
|
||||
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
|
||||
echo " NVSHMEM: ${NVSHMEM_VER}"
|
||||
echo " Workspace: ${WORKSPACE}"
|
||||
echo "================================================================"
|
||||
|
||||
mkdir -p "$WORKSPACE"
|
||||
|
||||
# ── Step 1: Install build deps ────────────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Installing build dependencies ---"
|
||||
cd "$REPO_ROOT"
|
||||
uv pip install cmake ninja
|
||||
|
||||
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
|
||||
|
||||
ARCH=$(uname -m)
|
||||
case "${ARCH,,}" in
|
||||
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
|
||||
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
|
||||
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
NVSHMEM_DIR="$WORKSPACE/nvshmem"
|
||||
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
|
||||
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
|
||||
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
|
||||
|
||||
echo "Downloading ${NVSHMEM_URL}"
|
||||
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
|
||||
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
|
||||
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
|
||||
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
|
||||
else
|
||||
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
|
||||
fi
|
||||
|
||||
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
|
||||
export NVSHMEM_DIR
|
||||
|
||||
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
|
||||
|
||||
DEEPEP_DIR="$WORKSPACE/DeepEP"
|
||||
if [ ! -d "$DEEPEP_DIR/.git" ]; then
|
||||
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
|
||||
fi
|
||||
|
||||
cd "$DEEPEP_DIR"
|
||||
git fetch origin
|
||||
git checkout "$DEEPEP_COMMIT_HASH"
|
||||
|
||||
WHEEL_DIR="$REPO_ROOT/deps"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
|
||||
echo ""
|
||||
echo "--- DeepEP wheel built at: $WHEEL ---"
|
||||
|
||||
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
|
||||
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
|
||||
echo ""
|
||||
echo "--- Configuring IBGDA drivers (requires sudo) ---"
|
||||
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
|
||||
if command -v update-initramfs &> /dev/null; then
|
||||
sudo update-initramfs -u
|
||||
elif command -v dracut &> /dev/null; then
|
||||
sudo dracut --force
|
||||
else
|
||||
echo "No supported initramfs update tool found." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo ""
|
||||
echo "IBGDA configured. Please REBOOT the system to apply changes."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "================================================================"
|
||||
echo " DeepEP installation complete"
|
||||
echo " NVSHMEM: ${NVSHMEM_DIR}"
|
||||
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
|
||||
echo "================================================================"
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the ModelExpress metadata server and Redis backend used by SLURM RL jobs.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
MODELEXPRESS_REPOSITORY="https://github.com/ai-dynamo/modelexpress.git"
|
||||
MODELEXPRESS_REF="v0.3.0"
|
||||
REDIS_VERSION="7.4.2"
|
||||
REDIS_SHA256="4ddebbf09061cbb589011786febdb34f29767dd7f89dbe712d2b68e808af6a1f"
|
||||
|
||||
if [[ $# -gt 0 ]]; then
|
||||
echo "This installer does not accept arguments" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BIN_DIR="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
mkdir -p "$BIN_DIR"
|
||||
|
||||
if [[ -x "$BIN_DIR/modelexpress-server" ]] \
|
||||
&& "$BIN_DIR/modelexpress-server" --version 2>/dev/null | grep -q "${MODELEXPRESS_REF#v}"; then
|
||||
echo "modelexpress-server $MODELEXPRESS_REF already installed at $BIN_DIR"
|
||||
else
|
||||
command -v cargo >/dev/null || {
|
||||
echo "cargo not found; install Rust 1.90 or newer before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
command -v protoc >/dev/null || {
|
||||
echo "protoc not found; install Protocol Buffers before running this script" >&2
|
||||
exit 1
|
||||
}
|
||||
BUILD_DIR=$(mktemp -d)
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT
|
||||
git clone --depth 1 --branch "$MODELEXPRESS_REF" "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
|
||||
(
|
||||
cd "$BUILD_DIR/modelexpress"
|
||||
cargo build --release --bin modelexpress-server
|
||||
)
|
||||
cp "$BUILD_DIR/modelexpress/target/release/modelexpress-server" "$BIN_DIR/"
|
||||
fi
|
||||
|
||||
if [[ -x "$BIN_DIR/redis-server" ]] \
|
||||
&& "$BIN_DIR/redis-server" --version | grep -q "v=$REDIS_VERSION"; then
|
||||
echo "redis-server $REDIS_VERSION already installed at $BIN_DIR"
|
||||
else
|
||||
BUILD_DIR="${BUILD_DIR:-$(mktemp -d)}"
|
||||
trap 'rm -rf "$BUILD_DIR"' EXIT
|
||||
REDIS_ARCHIVE="$BUILD_DIR/redis-${REDIS_VERSION}.tar.gz"
|
||||
curl --fail --location --silent --show-error \
|
||||
--output "$REDIS_ARCHIVE" \
|
||||
"https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz"
|
||||
echo "$REDIS_SHA256 $REDIS_ARCHIVE" | sha256sum --check
|
||||
tar -xzf "$REDIS_ARCHIVE" -C "$BUILD_DIR"
|
||||
make -C "$BUILD_DIR/redis-${REDIS_VERSION}" -j redis-server MALLOC=libc
|
||||
cp "$BUILD_DIR/redis-${REDIS_VERSION}/src/redis-server" "$BIN_DIR/"
|
||||
fi
|
||||
|
||||
echo "Installed ModelExpress server dependencies in $BIN_DIR"
|
||||
+2
-3
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
|
||||
tc.num_attention_heads = 4
|
||||
tc.num_key_value_heads = 2
|
||||
tc.head_dim = 64
|
||||
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
|
||||
tc.rope_parameters["mrope_section"] = [3, 3, 2]
|
||||
tc.moe_intermediate_size = 128
|
||||
tc.shared_expert_intermediate_size = 128
|
||||
tc.num_experts = 4
|
||||
@@ -96,7 +98,6 @@ ARCH_PRESETS = {
|
||||
first_k_dense_replace=1,
|
||||
norm_topk_prob=True,
|
||||
use_qk_norm=False,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=151329,
|
||||
eos_token_id=[151329, 151336, 151338],
|
||||
),
|
||||
@@ -125,7 +126,6 @@ ARCH_PRESETS = {
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
use_grouped_mm=False,
|
||||
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
|
||||
),
|
||||
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
|
||||
@@ -171,7 +171,6 @@ ARCH_PRESETS = {
|
||||
num_experts_per_tok=4,
|
||||
mlp_layer_types=["dense"] + ["sparse"] * 11,
|
||||
moe_routed_scaling_factor=2.5,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=9,
|
||||
bos_token_id=2,
|
||||
eos_token_id=[2, 24],
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
SESSION_NAME="prime-rl"
|
||||
OUTPUT_DIR="outputs"
|
||||
AGENT="claude"
|
||||
|
||||
# Optional CLI parsing
|
||||
# Supports:
|
||||
# -s|--session-name NAME
|
||||
# -o|--output-dir DIR
|
||||
# -a|--agent AGENT (claude|codex, default: claude)
|
||||
# Positional: [SESSION_NAME [OUTPUT_DIR]]
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-s|--session-name)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --session-name requires a value" >&2
|
||||
exit 1
|
||||
fi
|
||||
SESSION_NAME="$2"
|
||||
shift 2
|
||||
;;
|
||||
-o|--output-dir)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --output-dir requires a value" >&2
|
||||
exit 1
|
||||
fi
|
||||
OUTPUT_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-a|--agent)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --agent requires a value (claude|codex)" >&2
|
||||
exit 1
|
||||
fi
|
||||
AGENT="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
|
||||
echo " -a, --agent claude|codex (default: claude)" >&2
|
||||
exit 0
|
||||
;;
|
||||
--)
|
||||
shift
|
||||
break
|
||||
;;
|
||||
*)
|
||||
POSITIONAL+=("$1")
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ ${#POSITIONAL[@]} -ge 1 ]]; then
|
||||
SESSION_NAME="${POSITIONAL[0]}"
|
||||
fi
|
||||
if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
|
||||
OUTPUT_DIR="${POSITIONAL[1]}"
|
||||
fi
|
||||
|
||||
LOG_DIR="${OUTPUT_DIR}/logs/latest"
|
||||
|
||||
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
|
||||
echo "Attaching to tmux session: $SESSION_NAME"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
fi
|
||||
|
||||
echo "Creating new tmux session: $SESSION_NAME"
|
||||
|
||||
# Window 0: Launcher - empty shell
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "Launcher"
|
||||
|
||||
# Window 1: Logs - 4 vertical panes
|
||||
tmux new-window -t "$SESSION_NAME" -n "Logs"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.0"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.1"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.2"
|
||||
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Envs"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.3" -T "Inference"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.0" \
|
||||
"tail -F ${LOG_DIR}/trainer.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
|
||||
|
||||
# Window 2: SUCCESS - grep SUCCESS on orch and trainer logs (two stacked panes)
|
||||
tmux new-window -t "$SESSION_NAME" -n "SUCCESS"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:SUCCESS.0"
|
||||
tmux select-layout -t "$SESSION_NAME:SUCCESS" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:SUCCESS.0" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:SUCCESS.1" -T "Trainer"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:SUCCESS.0" "tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:SUCCESS.1" "tail -F ${LOG_DIR}/trainer.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
|
||||
|
||||
# Window 3: Agent (claude code or codex) with log context
|
||||
tmux new-window -t "$SESSION_NAME" -n "Agent"
|
||||
|
||||
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
|
||||
Trainer: ${LOG_DIR}/trainer.log
|
||||
All nodes: ${LOG_DIR}/trainer/node_*.log
|
||||
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
|
||||
Orchestrator: ${LOG_DIR}/orchestrator.log
|
||||
Inference: ${LOG_DIR}/inference.log
|
||||
Envs: ${LOG_DIR}/envs/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*.log
|
||||
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
|
||||
Help the user monitor and debug this run."
|
||||
|
||||
case "$AGENT" in
|
||||
claude)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
codex)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"codex --yolo \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
*)
|
||||
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Pane title styling
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
|
||||
|
||||
# Focus launcher window and attach
|
||||
tmux select-window -t "$SESSION_NAME:Launcher"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
@@ -17,7 +17,7 @@ uv run rl --model @ model.toml --data @ data.toml # nes
|
||||
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
|
||||
```
|
||||
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
|
||||
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base. `output_dir` has one extra fallback: CLI > config files > `$PRL_OUTPUT_DIR` > `"outputs"`.
|
||||
|
||||
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
|
||||
|
||||
@@ -25,9 +25,13 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
|
||||
|
||||
```bash
|
||||
uv run rl --help # all fields and defaults
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
|
||||
```
|
||||
|
||||
Each attempt also writes `configs/attempt_<n>/command.txt`. It records the
|
||||
shell-safe launch command, including CLI overrides. `configs/latest` points to
|
||||
the current attempt.
|
||||
|
||||
## Validators
|
||||
|
||||
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
|
||||
@@ -69,6 +73,8 @@ 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.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 = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.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.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). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.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`.
|
||||
|
||||
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
name: dashboard
|
||||
description: Find, start, use, and stop the local run dashboard for metrics, configs, traces, logs, and reports. Use when asked for its URL, to watch or inspect a run, to control the open dashboard, or to create a cited dashboard report explicitly requested by the user.
|
||||
---
|
||||
|
||||
# Run dashboard
|
||||
|
||||
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
|
||||
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
|
||||
dirs — safe against live runs — and installs anywhere (cluster head node,
|
||||
laptop against a mounted outputs dir): GPU dependencies live behind the
|
||||
`gpu` extra.
|
||||
|
||||
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch. The Config
|
||||
view shows a copyable launch command above the launch TOML or resolved JSON.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
start and, in interactive sessions, auto-start a dashboard only when none is
|
||||
live — an already-running one absorbs the new dir automatically, whatever port
|
||||
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
|
||||
register their dir but never spawn.
|
||||
|
||||
## Isolated mode
|
||||
|
||||
`--isolated` serves only the given dirs: no registry read or write, no
|
||||
discovery claim, and launchers ignore the instance. Use it for focused views
|
||||
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
|
||||
|
||||
## Finding the live dashboard
|
||||
|
||||
The live port can differ from 7788 (a taken port bumps to the next free one),
|
||||
so read the discovery file:
|
||||
|
||||
```bash
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
|
||||
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
|
||||
ps aux | grep PRL::Dashboard # process title
|
||||
```
|
||||
|
||||
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
|
||||
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
|
||||
to `~/.cache/prime-rl/dashboard/daemon.log`.
|
||||
|
||||
## Stopping / restarting
|
||||
|
||||
```bash
|
||||
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
|
||||
pkill -f PRL::Dashboard # every dashboard on the host
|
||||
```
|
||||
|
||||
A clean exit releases `daemon.json`; a stale file from a dead process is taken
|
||||
over by the next start. Killing a dashboard never affects runs (it only reads),
|
||||
and killing a run never takes the dashboard down (it runs in its own session).
|
||||
Restart by launching any run, or directly: `uv run dashboard`.
|
||||
|
||||
## Point the open dashboard
|
||||
|
||||
Use `POST /api/view` to show relevant run data in every connected dashboard
|
||||
tab:
|
||||
|
||||
```bash
|
||||
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
|
||||
-H 'content-type: application/json' -d '{
|
||||
"run": "demo-rl", "tab": "traces",
|
||||
"step": 0, "kind": "train", "subset": "effective",
|
||||
"episode": "ep-s00-reverse-text-0",
|
||||
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
|
||||
}'
|
||||
```
|
||||
|
||||
`run` is required; other fields are optional and leave unspecified UI state
|
||||
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
|
||||
address the episode by stable `id`. Use optional `trace` and `branch` indices
|
||||
for multi-agent traces and `highlight` entries shaped as `{node, quote,
|
||||
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
|
||||
command applies when the tab connects.
|
||||
|
||||
## Write a report only when asked
|
||||
|
||||
Create a report only when the user explicitly asks for one. Otherwise answer
|
||||
normally; use `/api/view` when showing trace evidence would help.
|
||||
|
||||
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
|
||||
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
|
||||
`title` and one-line JSON citation definitions:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Why does reward dip at step 4?
|
||||
---
|
||||
|
||||
The dip is provider errors, not policy regression [^err].
|
||||
|
||||
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
|
||||
```
|
||||
|
||||
The frontmatter `title` is rendered as the report H1; do not repeat it with a
|
||||
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
|
||||
links. Relative Markdown links render as literal text, so identify local source
|
||||
files with inline code paths or link to a supported HTTP endpoint.
|
||||
|
||||
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
|
||||
Use the top-level rollout record `id` returned by the dashboard episode-list
|
||||
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
|
||||
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
|
||||
`note` to 1–2 sentences explaining why the quote supports the claim.
|
||||
|
||||
Cite major empirical, comparative, and diagnostic conclusions, but not routine
|
||||
explanation. Use exact trace citations for trajectory-level claims. For
|
||||
aggregate statistics, identify the run and source file; do not imply that one
|
||||
example trajectory proves the aggregate.
|
||||
|
||||
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
|
||||
distinct passages, such as a comparison or corroboration. Use one citation
|
||||
when one passage is sufficient.
|
||||
|
||||
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
|
||||
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
|
||||
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
|
||||
Ambiguous or mismatched citations remain broken and do not navigate.
|
||||
|
||||
Use Markdown; raw HTML is escaped.
|
||||
|
||||
Before handoff, reload the report and verify through the dashboard API that
|
||||
every referenced citation resolves uniquely to its episode, node, and quote.
|
||||
Confirm zero broken citations, one rendered title, and no unsupported relative
|
||||
links.
|
||||
+18
-5
@@ -22,13 +22,15 @@ git submodule update --init --recursive
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
uv sync # core only
|
||||
uv sync # slim
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
|
||||
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
|
||||
uv sync --package prime-rl --package gsm8k # core + just one env
|
||||
```
|
||||
|
||||
`uv sync --group dev` installs the `pre-commit` package but leaves the git hook inert until it's wired up — run `uv run pre-commit install` once per clone (see `README.md`'s Development section).
|
||||
|
||||
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
@@ -64,13 +66,24 @@ Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
The `disagg` extra installs the prebuilt DeepEP wheel pinned in `[tool.uv.sources]`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_ep_kernels.sh
|
||||
uv sync --extra disagg
|
||||
```
|
||||
|
||||
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
|
||||
The prime-kernels repository owns source builds for DeepEP, DeepGEMM, and TorchAO. Use
|
||||
its scripts when a local rebuild is required:
|
||||
|
||||
```bash
|
||||
git submodule update --init deps/prime-kernels
|
||||
bash deps/prime-kernels/scripts/install_ep_kernels.sh --wheel-dir /tmp/prime-kernels-wheels
|
||||
uv pip install --reinstall --no-deps /tmp/prime-kernels-wheels/deep_ep-*.whl
|
||||
```
|
||||
|
||||
The build needs a CUDA toolkit whose version matches torch. Set
|
||||
`TORCH_CUDA_ARCH_LIST` when the build host has no GPU or when the wheel must support
|
||||
more than the local GPU architecture.
|
||||
|
||||
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
|
||||
|
||||
@@ -89,4 +102,4 @@ Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, s
|
||||
- `pyproject.toml` — dependencies, extras, dependency groups
|
||||
- `uv.lock` — pinned lockfile (refresh with `uv sync --all-extras`)
|
||||
- `scripts/install.sh` — bootstrap installer
|
||||
- `scripts/install_ep_kernels.sh` — DeepEP build script
|
||||
- `deps/prime-kernels/scripts/` — native wheel build scripts
|
||||
|
||||
+48
-50
@@ -10,13 +10,13 @@ CUDA kernels live in their own monorepo,
|
||||
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
|
||||
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
|
||||
package: one folder per kernel, holding the
|
||||
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
|
||||
kernel's Python surface and, for compiled kernels, its C++/CUDA sources under `csrc/`, all declared in the single
|
||||
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
|
||||
is initialized.
|
||||
|
||||
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
|
||||
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
|
||||
compiled extensions to it.
|
||||
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit for local
|
||||
source builds and a prime-kernels release for installs. prime-kernels builds and publishes
|
||||
its own wheels. prime-rl stays a pure-Python wheel; never add compiled extensions to it.
|
||||
|
||||
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
|
||||
already covers it — prime-rl lints none of it.
|
||||
@@ -38,15 +38,18 @@ it once at startup rather than failing a run halfway through. `unavailable_reaso
|
||||
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
|
||||
wants; `is_available` is just that call compared to `None`.
|
||||
|
||||
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
|
||||
tcgen05, reached through `model.moe_fused_kernel=true`.
|
||||
`flash_moe` is a compiled fused MoE forward kernel (bf16 + mxfp8) on Blackwell
|
||||
tcgen05. Its trainer integration is dormant. `mxfp8_moe` is a Python-only registered
|
||||
kernel package for MXFP8 grouped GEMM and torch EP transport on SM100; it owns the
|
||||
MoE-specific torchao-derived orchestration and exports explicit BF16 boundaries instead
|
||||
of tensor-subclass interception.
|
||||
|
||||
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
|
||||
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
|
||||
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
|
||||
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
|
||||
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
|
||||
a change in both repos.
|
||||
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`. When the trainer integration
|
||||
is restored, call this once during setup so an unsupported model fails before training rather
|
||||
than mid-step. Never hardcode a `128` on this side: then every requirement change is a change
|
||||
in both repos.
|
||||
|
||||
## Building locally
|
||||
|
||||
@@ -72,14 +75,15 @@ The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels
|
||||
|
||||
1. Commit the sources under `prime_kernels/<name>/csrc/`.
|
||||
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
|
||||
`arch`, `cxx-std`; paths are relative to the kernel folder.
|
||||
`arch`, `cxx-std`; paths are relative to the kernel folder. A vendored Python kernel
|
||||
uses `python-only = true`, may declare import checks in `requires`, and omits compiled
|
||||
extension fields.
|
||||
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
|
||||
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
|
||||
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
|
||||
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
|
||||
used in training also needs `torch.library.register_autograd`, since a schema carries
|
||||
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
|
||||
of its own.)
|
||||
no backward. `flash_moe` is forward only and currently has no trainer integration.
|
||||
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
|
||||
|
||||
Rules the build assumes:
|
||||
@@ -112,69 +116,63 @@ Then, in order:
|
||||
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
|
||||
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
|
||||
numbers, not a build error, and prime-rl's call sites have to absorb it.
|
||||
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
|
||||
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
|
||||
forward and its hand-written backward against the grouped-mm expert path; it is
|
||||
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
|
||||
on a machine the kernel was built for.
|
||||
- Rebuild and re-run the kernel repository's numerical coverage plus every PrimeRL runtime
|
||||
path that calls the changed kernel; the ABI is not checked for you.
|
||||
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
|
||||
new code only reaches users once a release rebuilds the wheels and the pin below moves.
|
||||
|
||||
## Prebuilt wheels
|
||||
|
||||
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
|
||||
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
|
||||
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
|
||||
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
|
||||
The [prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels) repository owns
|
||||
`build_kernels.yaml`. It builds `prime-kernels`, `deep-ep`, `deep-gemm`, and `torchao` for
|
||||
x86_64 and aarch64. It publishes the wheels as prime-kernels release assets.
|
||||
|
||||
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
|
||||
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
|
||||
bumps would build no wheels.
|
||||
|
||||
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
|
||||
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
|
||||
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
|
||||
Run that workflow in prime-kernels for each torch or CUDA bump:
|
||||
|
||||
```bash
|
||||
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
|
||||
gh workflow run build_kernels.yaml \
|
||||
--repo PrimeIntellect-ai/prime-kernels \
|
||||
-f release_tag=vX.Y.Z
|
||||
```
|
||||
|
||||
The wheel version carries the ABI it was built against, e.g.
|
||||
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
|
||||
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
|
||||
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
|
||||
`prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl`. It imports only under
|
||||
that exact torch and CUDA ABI. prime-kernels CI controls the build dependency pins.
|
||||
|
||||
### Pinning installs at the prebuilt wheels
|
||||
|
||||
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
|
||||
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
|
||||
the extra may take, since a sync must never compile:
|
||||
`[tool.uv.sources]`. deep-ep, deep-gemm, torchao, and vLLM use the same pattern. A sync must
|
||||
never compile these packages:
|
||||
|
||||
```toml
|
||||
[tool.uv.sources]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/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/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
```
|
||||
|
||||
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
|
||||
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
|
||||
its job summary. Then `uv lock`.
|
||||
The wheels are prime-kernels release assets. Get the exact names before you move all pins:
|
||||
|
||||
The pin necessarily trails by one release: a release's own assets do not exist until that
|
||||
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
|
||||
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
|
||||
pin whose torch no longer matches the lock fails at import, not at install.
|
||||
```bash
|
||||
gh release view vX.Y.Z \
|
||||
--repo PrimeIntellect-ai/prime-kernels \
|
||||
--json assets
|
||||
```
|
||||
|
||||
Then run `uv lock`.
|
||||
|
||||
Move the pin when a kernel, torch, or CUDA pin changes. A stale pin ships stale kernels. A
|
||||
torch ABI mismatch fails at import, not at install.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
|
||||
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
|
||||
wheel imports only under the torch it was compiled against.
|
||||
- Keep the torch floor in prime-kernels aligned with prime-rl. The wheel imports only under
|
||||
the torch version it was compiled against.
|
||||
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
|
||||
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
|
||||
metadata and does not.
|
||||
- A fresh clone without the submodule still installs and trains — only the source build needs
|
||||
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
|
||||
published with kernels silently skipped.
|
||||
- A fresh prime-rl clone without the submodule still installs and trains. Only a local source
|
||||
build needs it. prime-kernels CI sets `PRIME_KERNELS_REQUIRE=1`, so a release cannot omit
|
||||
kernels silently.
|
||||
|
||||
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
|
||||
|
||||
### On launch
|
||||
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/` (start with `rl.json`). The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
1. Find the run dir and read the resolved configs at `{run_dir}/configs/latest/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). Read the launch command from `{run_dir}/configs/latest/command.txt`. The launch TOML is copied verbatim to `{run_dir}/configs/latest/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
|
||||
2. Confirm all processes are alive and the run is making progress.
|
||||
3. Write the initial summary into `{run_dir}/STATUS.md`.
|
||||
|
||||
@@ -40,14 +40,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
|
||||
|
||||
**Never** run kill or launch commands from your own shell. Dispatch them to the tmux **Launcher** window so the researcher sees what was executed:
|
||||
|
||||
```bash
|
||||
SESSION=$(tmux display-message -p '#S')
|
||||
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
|
||||
```
|
||||
|
||||
After a restart, verify all processes are back up and progress resumed before the next check-in.
|
||||
**Never** run kill or launch commands yourself. Hand the researcher the exact command and let them run it; after a restart, verify all processes are back up and progress resumed before the next check-in.
|
||||
|
||||
---
|
||||
|
||||
@@ -55,10 +48,33 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
|
||||
### Where to find things
|
||||
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
|
||||
- `{run_dir}/configs/latest/` — the current attempt's command, launch TOML, and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
|
||||
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
|
||||
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
|
||||
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
|
||||
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
|
||||
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
|
||||
component logs. It only reads the run dirs — safe to run against a live run.
|
||||
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
|
||||
free one, so several dashboards run side by side without coordination. GPU deps live
|
||||
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
|
||||
without the training stack (e.g. on a head node).
|
||||
|
||||
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
|
||||
live one absorbs each new run's output dir automatically — see the `dashboard` skill
|
||||
for discovery, kill/restart commands, and `--isolated`. The short version: the live
|
||||
port can differ from 7788 (a taken port bumps), so read the discovery file:
|
||||
|
||||
```bash
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
|
||||
ps aux | grep PRL::Dashboard # the daemon's process title
|
||||
```
|
||||
|
||||
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -66,7 +82,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
|
||||
├── evals.log # SFT online-eval evals stdout
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -77,6 +93,8 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
|
||||
Scan for problems:
|
||||
@@ -117,7 +135,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
|--------|-------------|
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
|
||||
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
|
||||
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
|
||||
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
|
||||
| `optim/grad_norm` | spikes may precede divergence |
|
||||
|
||||
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
|
||||
@@ -144,8 +162,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
### Episodes
|
||||
|
||||
```
|
||||
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
|
||||
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
@@ -164,7 +182,7 @@ jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
@@ -180,13 +198,13 @@ A few warnings are normal. Escalate when errors are persistent, growing, or hit
|
||||
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
|
||||
|
||||
```
|
||||
PRIME-RL::Launcher
|
||||
├── PRIME-RL::Inference (vLLM server, GPU 0)
|
||||
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
PRL::Launcher
|
||||
├── PRL::Inference (vLLM server, GPU 0)
|
||||
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── PRL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── torchrun
|
||||
│ └── PRIME-RL::Trainer (GPU 1+)
|
||||
│ └── PRL::Trainer (GPU 1+)
|
||||
└── tail trainer.log
|
||||
```
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs and `command.txt` under `configs/attempt_<n>/`. `configs/latest` points to the current attempt. The command uses shell-safe quoting.
|
||||
|
||||
## Run directories
|
||||
|
||||
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
|
||||
@@ -43,6 +45,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
|
||||
- NIXL on SLURM: install NIXL and ModelExpress with the provided scripts. The job starts ModelExpress and Redis unless `slurm.launch_modelexpress = false`.
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
|
||||
@@ -66,6 +70,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
|
||||
- SLURM: single- and multi-node
|
||||
- Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes.
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
@@ -92,7 +97,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
@@ -119,11 +124,15 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
|
||||
## Summary
|
||||
|
||||
| Command | Purpose | Typical use |
|
||||
@@ -139,3 +148,11 @@ env.agent.runtime.type = "subprocess"
|
||||
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
|
||||
- `configs/debug/` — minimal debug configs
|
||||
- `examples/` — full example configs (e.g. `reverse-text/`)
|
||||
|
||||
## Dashboard
|
||||
|
||||
Interactive launches auto-start one shared dashboard daemon per user (process title
|
||||
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
|
||||
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
|
||||
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
|
||||
opts a run out.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
http://localhost:7788. The trace viewer includes transcript and synchronized
|
||||
agent timeline views; timeline activities open the corresponding transcript
|
||||
call. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
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.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
|
||||
```bash
|
||||
uv sync --extra dashboard && uv run dashboard [output_dir ...]
|
||||
```
|
||||
|
||||
The trace viewer's **Messages** mode keeps structured `message.content` and
|
||||
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
|
||||
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
|
||||
it never reconstructs a chat template. The recorded IDs remain the source of
|
||||
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
|
||||
are unavailable. Text, advantage, logprob, mask, and content signals apply to
|
||||
both views; Rendered with Text uses the exact full-sequence decode.
|
||||
|
||||
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
|
||||
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
|
||||
runs after every integration test).
|
||||
Executable
+1611
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,254 @@
|
||||
<!-- This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests. -->
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<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">
|
||||
</head>
|
||||
<body>
|
||||
<header id="topbar">
|
||||
<div class="brand">
|
||||
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
|
||||
</div>
|
||||
<select id="run-select" title="run"></select>
|
||||
<div id="compare-wrap" class="dd-wrap">
|
||||
<button id="compare-btn" class="btn dd-btn">compare</button>
|
||||
<div id="compare-menu" class="dd-menu" hidden></div>
|
||||
</div>
|
||||
<nav id="tabs">
|
||||
<button data-tab="config">Config</button>
|
||||
<button data-tab="metrics" class="active">Metrics</button>
|
||||
<button data-tab="traces">Traces</button>
|
||||
<button data-tab="report">Report</button>
|
||||
<button data-tab="logs">Logs</button>
|
||||
</nav>
|
||||
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
|
||||
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
|
||||
</header>
|
||||
|
||||
<div id="run-overview"></div>
|
||||
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<div class="controls">
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
</div>
|
||||
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
|
||||
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
|
||||
<span id="metrics-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="all-layout" hidden>
|
||||
<button data-layout="flat">Flat</button>
|
||||
<button data-layout="nested">Nested</button>
|
||||
</div>
|
||||
<button id="metrics-collapse" class="btn">collapse</button>
|
||||
<button id="metrics-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="metrics-body"></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
<select id="config-attempt-select"></select>
|
||||
<div class="seg" id="config-format">
|
||||
<button data-fmt="toml">TOML</button>
|
||||
<button data-fmt="json">JSON</button>
|
||||
</div>
|
||||
<input id="config-search" class="search" type="search" placeholder="regex search, e.g. lora|lr">
|
||||
<span id="config-hits" class="muted"></span>
|
||||
</div>
|
||||
<div id="config-command">
|
||||
<div class="config-command-head">
|
||||
<span class="t-label">command</span>
|
||||
<button id="config-command-copy" class="btn" type="button">copy</button>
|
||||
</div>
|
||||
<div class="config-command-body">
|
||||
<span class="config-command-prompt" aria-hidden="true">$</span>
|
||||
<code id="config-command-text"></code>
|
||||
</div>
|
||||
</div>
|
||||
<pre id="config-view"></pre>
|
||||
</section>
|
||||
|
||||
<section id="tab-traces" hidden>
|
||||
<div class="controls" id="step-bar">
|
||||
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<div id="step-blocks"></div>
|
||||
<button id="step-next" class="btn tm-nav" title="next step">›</button>
|
||||
<span id="step-label" class="t-label"></span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="trace-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="trace-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="trace-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="trace-kind">
|
||||
<button data-kind="train" class="active">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
<div class="seg" id="trace-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective" class="active">Effective</button>
|
||||
</div>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<thead><tr>
|
||||
<th>#</th><th>env</th><th>group</th><th>reward</th><th>adv</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="tab-report" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">report</label>
|
||||
<select id="report-select"></select>
|
||||
<span id="report-verify" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<span id="report-status" class="muted"></span>
|
||||
</div>
|
||||
<div id="report-wrap"><article id="report-body"></article></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-logs" hidden>
|
||||
<div class="controls">
|
||||
<label class="t-label">attempt</label>
|
||||
<select id="attempt-select"></select>
|
||||
<div id="log-comp-wrap" class="dd-wrap">
|
||||
<button id="log-comp-btn" class="btn dd-btn">components</button>
|
||||
<div id="log-comp-menu" class="dd-menu" hidden></div>
|
||||
</div>
|
||||
<div class="seg" id="log-view">
|
||||
<button data-view="merge" class="active">Merge</button>
|
||||
<button data-view="split">Split</button>
|
||||
</div>
|
||||
<div class="stepper" id="log-level" title="minimum log level">
|
||||
<button id="log-level-down" title="more verbose">‹</button>
|
||||
<span id="log-level-label">all</span>
|
||||
<button id="log-level-up" title="less verbose">›</button>
|
||||
</div>
|
||||
<input id="log-search" class="search" type="search" placeholder="regex filter, e.g. ERROR|WARN">
|
||||
<button id="log-older" class="btn">load older</button>
|
||||
</div>
|
||||
<div id="log-panes"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div id="drawer-backdrop" hidden></div>
|
||||
<div id="trace-modal" hidden>
|
||||
<aside id="tm-left">
|
||||
<div class="tm-head tm-stephead">
|
||||
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<span id="tm-step-label"></span>
|
||||
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow">
|
||||
<div id="tm-filter-wrap" class="dd-wrap">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter & sort">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div id="tm-filter-menu" class="dd-menu" hidden>
|
||||
<label class="t-label">env</label>
|
||||
<select id="tm-env"><option value="">all envs</option></select>
|
||||
<label class="t-label">sort</label>
|
||||
<select id="tm-sort">
|
||||
<option value="line:asc">order: arrival</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="advantage:desc">advantage ↓</option>
|
||||
<option value="advantage:asc">advantage ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
<option value="group:asc">group</option>
|
||||
</select>
|
||||
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-kind-row">
|
||||
<div class="seg" id="tm-kind">
|
||||
<button data-kind="train">Train</button>
|
||||
<button data-kind="eval">Eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow" id="tm-subset-row">
|
||||
<div class="seg" id="tm-subset">
|
||||
<button data-subset="all">All</button>
|
||||
<button data-subset="effective">Effective</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head">
|
||||
<span class="t-label">episodes</span>
|
||||
<span id="tm-count" class="badge"></span>
|
||||
</div>
|
||||
<div id="tm-list"></div>
|
||||
</aside>
|
||||
<section id="tm-main">
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
<button data-mode="rendered">Rendered</button>
|
||||
</div>
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, log probability, training mask, or message-content membership.">
|
||||
<option value="">Text</option>
|
||||
<option value="advantage">Advantage</option>
|
||||
<option value="logprob">Logprob</option>
|
||||
<option value="mask">Mask</option>
|
||||
<option value="is_content">Content</option>
|
||||
</select>
|
||||
<button id="tm-collapse" class="btn">collapse</button>
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
<button id="drawer-close" class="btn">✕</button>
|
||||
</div>
|
||||
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
|
||||
<div id="tm-trace-tabs" class="seg" hidden></div>
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
<div id="tm-meta"></div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<script src="/static/vendor/uPlot.iife.min.js"></script>
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Launcher-side dashboard auto-start.
|
||||
|
||||
Every launcher registers its output dir in a shared registry and makes sure one
|
||||
dashboard is running: every dashboard instance serves its own dirs plus the
|
||||
registry (re-read live), so each new run shows up on one URL - one dashboard
|
||||
per host per user. If a live daemon already exists, its URL is reused instead
|
||||
of starting another. Discovery goes through
|
||||
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
|
||||
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
|
||||
|
||||
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
|
||||
without the extra (then it registers the dir and points at the missing extra
|
||||
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
|
||||
to the actual server.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.utils.pathing import CACHE_DIR
|
||||
|
||||
STATE_DIR = CACHE_DIR / "dashboard"
|
||||
DAEMON_FILE = STATE_DIR / "daemon.json"
|
||||
DIRS_FILE = STATE_DIR / "dirs.json"
|
||||
DAEMON_LOG = STATE_DIR / "daemon.log"
|
||||
SPAWN_TIMEOUT_S = 10.0
|
||||
|
||||
|
||||
@contextmanager
|
||||
def registry_lock():
|
||||
"""Serialize read-modify-write cycles on the shared registry files: concurrent
|
||||
launchers (or dashboard starts) must not drop each other's entries."""
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with open(STATE_DIR / ".lock", "w") as lock_file:
|
||||
fcntl.flock(lock_file, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def register_output_dir(output_dir: Path) -> None:
|
||||
"""Add the dir to the daemon's registry (idempotent, atomic)."""
|
||||
with registry_lock():
|
||||
try:
|
||||
dirs = json.loads(DIRS_FILE.read_text())
|
||||
except (OSError, ValueError):
|
||||
dirs = []
|
||||
entry = str(output_dir.resolve())
|
||||
if entry in dirs:
|
||||
return
|
||||
dirs.append(entry)
|
||||
tmp = DIRS_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(dirs))
|
||||
tmp.replace(DIRS_FILE)
|
||||
|
||||
|
||||
def find_daemon(timeout: float = 1.0) -> dict | None:
|
||||
"""The live daemon's record ({pid, url, ...}), or None."""
|
||||
try:
|
||||
info = json.loads(DAEMON_FILE.read_text())
|
||||
os.kill(info["pid"], 0)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
try:
|
||||
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
|
||||
return info
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def ensure_dashboard(output_dir: Path, logger) -> str | None:
|
||||
"""Register the run's output dir and make sure one dashboard daemon serves it.
|
||||
|
||||
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
|
||||
daemon could be found or started (missing extra, non-interactive session, or
|
||||
startup failure).
|
||||
"""
|
||||
# The dir may not exist yet on a first run: create it up front, because the
|
||||
# daemon only serves registered dirs that exist (and refuses to start with none).
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
register_output_dir(output_dir)
|
||||
daemon = find_daemon()
|
||||
if daemon is not None:
|
||||
return daemon["url"]
|
||||
if not sys.stdout.isatty():
|
||||
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
|
||||
return None
|
||||
# The console script exists even without the extra, so check the actual imports.
|
||||
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
|
||||
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
|
||||
return None
|
||||
binary = shutil.which("dashboard")
|
||||
if binary is None:
|
||||
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
|
||||
return None
|
||||
with open(DAEMON_LOG, "ab") as log_file:
|
||||
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
|
||||
deadline = time.monotonic() + SPAWN_TIMEOUT_S
|
||||
while time.monotonic() < deadline:
|
||||
daemon = find_daemon()
|
||||
if daemon is not None:
|
||||
return daemon["url"]
|
||||
if process.poll() is not None:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
|
||||
return None
|
||||
|
||||
|
||||
def log_dashboard_url(logger, url: str | None) -> None:
|
||||
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
|
||||
if url is None:
|
||||
return
|
||||
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.dashboard.server import main as server_main
|
||||
|
||||
server_main()
|
||||
@@ -6,15 +6,25 @@ lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
|
||||
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
os.environ["PRL_LOG_DIR"] = str(log_dir)
|
||||
write_launch_artifacts(config_dir, "evals")
|
||||
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
@@ -10,7 +10,13 @@ from typing import Any
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
|
||||
from prime_rl.utils.pathing import (
|
||||
format_log_message,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
@@ -51,7 +57,7 @@ def write_config(
|
||||
return config_path
|
||||
|
||||
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -70,7 +76,10 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.output_dir,
|
||||
launcher_log_dir=get_launcher_log_dir(config.output_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
@@ -116,6 +125,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
script = template.render(**template_vars)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -125,17 +135,17 @@ def inference_slurm(config: InferenceConfig):
|
||||
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
write_launch_artifacts(config_dir, "inference")
|
||||
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
|
||||
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_dir = latest_log_dir(config.output_dir)
|
||||
num_nodes = getattr(config.deployment, "num_nodes", 1)
|
||||
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
|
||||
|
||||
|
||||
@@ -14,18 +14,20 @@ from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
latest_log_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -119,7 +121,8 @@ def rl_local(config: RLConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "rl")
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
@@ -127,6 +130,8 @@ def rl_local(config: RLConfig):
|
||||
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
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
|
||||
@@ -172,9 +177,6 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
@@ -252,7 +254,7 @@ def rl_local(config: RLConfig):
|
||||
for split, source, address 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 {split} env server {name} at {address}")
|
||||
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)
|
||||
@@ -282,7 +284,7 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
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(
|
||||
@@ -365,17 +367,12 @@ def rl_local(config: RLConfig):
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
|
||||
# Check for errors from monitor threads
|
||||
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
|
||||
# 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}")
|
||||
@@ -418,7 +415,7 @@ def rl_local(config: RLConfig):
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -457,11 +454,30 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
|
||||
nixl_broadcast = (
|
||||
config.weight_broadcast
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nixl"
|
||||
else None
|
||||
)
|
||||
launch_modelexpress = nixl_broadcast is not None and config.slurm.launch_modelexpress
|
||||
modelexpress_vars = {
|
||||
"use_nixl_broadcast": nixl_broadcast is not None,
|
||||
"launch_modelexpress": launch_modelexpress,
|
||||
"modelexpress_host": nixl_broadcast.host if nixl_broadcast is not None else "",
|
||||
"modelexpress_port": nixl_broadcast.port if nixl_broadcast is not None else 0,
|
||||
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
|
||||
}
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
**modelexpress_vars,
|
||||
config_path=config_dir / RL_CONFIG,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
|
||||
@@ -472,7 +488,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=True,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
|
||||
nodes_per_infer_replica=infer_deploy.num_nodes,
|
||||
@@ -506,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -513,7 +533,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
is_disaggregated=False,
|
||||
run_name=config.run.name,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
@@ -543,9 +566,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
@@ -556,8 +581,8 @@ def rl_slurm(config: RLConfig):
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
log_dir = latest_log_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "rl")
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
@@ -593,14 +618,16 @@ def rl_slurm(config: RLConfig):
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = config.run_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
@@ -608,6 +635,7 @@ def rl_slurm(config: RLConfig):
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
def rl(config: RLConfig):
|
||||
|
||||
+89
-144
@@ -12,19 +12,20 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -39,8 +40,6 @@ from prime_rl.utils.process import (
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
@@ -140,14 +139,20 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
@@ -160,190 +165,130 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
online_eval = config.eval is not None
|
||||
eval_vars = {}
|
||||
if online_eval:
|
||||
assert config.inference is not None
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
eval_vars = {
|
||||
"router": config.inference.router,
|
||||
"router_port": config.inference.server.port,
|
||||
"backend_port": config.inference.backend_port,
|
||||
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"evals_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
|
||||
"""Write the SLURM script for the decoupled online-eval job (inference pool +
|
||||
env servers + evals) to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
assert config.deployment.type == "multi_node"
|
||||
assert config.inference is not None
|
||||
|
||||
# The eval template is bundled next to the trainer templates; a custom
|
||||
# slurm.template_path directory takes precedence so both can be overridden.
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(EVAL_TEMPLATE)
|
||||
|
||||
inference_env_vars = {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
}
|
||||
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir,
|
||||
output_dir=config.run_dir,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.router,
|
||||
router_port=config.inference.server.port,
|
||||
backend_port=config.inference.backend_port,
|
||||
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
|
||||
inference_env_vars=inference_env_vars,
|
||||
evals_env_vars=evals_env_vars,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTConfig):
|
||||
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
|
||||
trainer and the eval deployment (inference pool + evals) are two independent
|
||||
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
|
||||
directory so the eval deployment can join its NCCL weight-broadcast group."""
|
||||
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evals processes log to a single shared W&B run across both jobs,
|
||||
# keyed by the launcher's run id.
|
||||
# Trainer and evals processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
script_path = config.run_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
# The trainer job is submitted first and the eval job depends on it having started:
|
||||
# the trainer creates the shared W&B run, and the evals process's joiner init only
|
||||
# retries for a bounded window — starting the evals process while the trainer job pends
|
||||
# would crash it at wandb init.
|
||||
script_paths = [script_path]
|
||||
if decoupled_eval:
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = config.run_dir / EVAL_SBATCH
|
||||
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
|
||||
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
|
||||
script_paths = [script_path, eval_script_path]
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=latest_log_dir(config.run_dir),
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
evals=online_eval,
|
||||
inference=online_eval,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The eval job logs at stable (non-attempt) paths under the run dir.
|
||||
log_message += "\n" + format_log_message(
|
||||
log_dir=get_log_dir(config.run_dir),
|
||||
evals=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
submitted_job_ids: list[str] = []
|
||||
for path in script_paths:
|
||||
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
|
||||
# (e.g. multi-cluster sbatch appends "on cluster <name>").
|
||||
cmd = ["sbatch", "--parsable"]
|
||||
if submitted_job_ids:
|
||||
# Hold the eval job until the trainer job has started (not finished).
|
||||
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
|
||||
cmd.append(str(path))
|
||||
logger.info(f"Submitting: {' '.join(cmd)}")
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
for job_id in submitted_job_ids:
|
||||
logger.warning(f"Cancelling already-submitted job {job_id}")
|
||||
subprocess.run(["scancel", job_id], capture_output=True, text=True)
|
||||
sys.exit(1)
|
||||
job_id = result.stdout.strip().split(";")[0]
|
||||
submitted_job_ids.append(job_id)
|
||||
logger.success(f"Submitted batch job {job_id}")
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
logger.success(log_message)
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
def sft_local(config: SFTConfig):
|
||||
@@ -352,7 +297,8 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
@@ -365,7 +311,7 @@ def sft_local(config: SFTConfig):
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
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.
|
||||
@@ -446,7 +392,7 @@ def sft_local(config: SFTConfig):
|
||||
# deterministic address, polling until the server is up.
|
||||
for source, address in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting eval env server {name} at {address}")
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
@@ -455,7 +401,7 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evals process")
|
||||
logger.info("Starting evals")
|
||||
start_process(
|
||||
"evals",
|
||||
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
|
||||
@@ -464,6 +410,9 @@ def sft_local(config: SFTConfig):
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
@@ -503,12 +452,8 @@ def sft_local(config: SFTConfig):
|
||||
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")
|
||||
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the evals process, which drains its final evals after
|
||||
# the trainer's last checkpoint) while surfacing any process failure.
|
||||
|
||||
+197
-126
@@ -2,17 +2,20 @@
|
||||
|
||||
Standalone (no ``[online]``), it runs one epoch of every configured eval
|
||||
source against the weights the inference server currently serves, then exits.
|
||||
With ``[online]``, it watches a broadcasts directory for new weight
|
||||
broadcasts — the trainer writes ``broadcasts/step_{n}`` with a ``STABLE``
|
||||
marker on completion — tells the inference server to receive each eligible
|
||||
broadcast, and runs the configured evals against the updated weights,
|
||||
sequentially per broadcast so every epoch measures exactly one policy version.
|
||||
With ``[online]``, it watches a broadcasts directory for offered weight
|
||||
broadcasts through a ``WeightReceiver`` (announced by their
|
||||
``.sender_ready`` marker), moves the inference server onto each of them, and
|
||||
runs the configured evals against the updated weights, sequentially per
|
||||
broadcast so every epoch measures exactly one policy version. Every offered
|
||||
broadcast must be received, even when no eval is due — the trainer blocks
|
||||
inside the handshake until the receiver acknowledges.
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
|
||||
are version-pinned measurements, so an overload cut only blocks admission and
|
||||
the in-flight pool drains through natural completions.
|
||||
are version-pinned measurements. By default, a newer online checkpoint cancels
|
||||
unfinished episodes from the prior version; callers can disable this when they need
|
||||
every epoch to drain.
|
||||
|
||||
Env servers: sources without an explicit ``serve.address`` get an env server
|
||||
spawned by the evals process at their derived address; sources with one are
|
||||
@@ -26,27 +29,31 @@ import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.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 EvalBatch, Policy
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
|
||||
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -56,15 +63,19 @@ monkey_patch_chat_completion_logprobs()
|
||||
# How often to re-scan the broadcasts directory for new weight broadcasts.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
# Served model name for adapter broadcasts of LoRA runs. Reloading the same name
|
||||
# with fresh weights each step is supported (the server forces an in-place
|
||||
# reload, see /load_lora_adapter).
|
||||
LORA_NAME = "eval-adapter"
|
||||
# Budget for the trainer's startup broadcast: it is always coming, but only
|
||||
# after the trainer has finished loading the model.
|
||||
STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
self.config = config
|
||||
self.log_dir = log_dir or (
|
||||
Path(os.environ["PRL_LOG_DIR"])
|
||||
if "PRL_LOG_DIR" in os.environ
|
||||
else create_attempt_log_dir(config.output_dir)
|
||||
)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
@@ -76,12 +87,21 @@ class Evals:
|
||||
self.env_server_procs: list[Popen] = []
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
# Assigned in setup(); None-initialized so stop() can tear down a
|
||||
# partially completed setup with plain attribute checks.
|
||||
self.clients: InferenceClient | None = None
|
||||
self.admin_clients: AdminClients | None = None
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
|
||||
async def setup(self) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="evals",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
@@ -95,7 +115,8 @@ class Evals:
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
|
||||
self.pool = InferencePool(config.eval.client, model_name=config.model)
|
||||
self.clients = InferenceClient(config.eval.client, model_name=config.model)
|
||||
self.admin_clients = AdminClients(config.eval.client)
|
||||
|
||||
self.spawn_env_servers()
|
||||
|
||||
@@ -105,20 +126,23 @@ class Evals:
|
||||
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.pool.wait_for_ready(config.model)
|
||||
await self.admin_clients.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
weight_broadcast = config.weight_broadcast
|
||||
if weight_broadcast is not None and weight_broadcast.type == "nccl":
|
||||
self.receiver: WeightReceiver | None = None
|
||||
if config.online is not None:
|
||||
assert config.online.broadcasts_dir is not None
|
||||
# A hand-written online config may omit the transport; broadcasts
|
||||
# are then plain filesystem checkpoints.
|
||||
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
await init_nccl_broadcast(
|
||||
self.pool.admin_clients,
|
||||
weight_broadcast.host,
|
||||
weight_broadcast.port,
|
||||
weight_broadcast.timeout,
|
||||
inference_world_size=weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=weight_broadcast.quantize_in_weight_transfer,
|
||||
self.receiver = setup_weight_receiver(
|
||||
config.online.broadcasts_dir,
|
||||
weight_broadcast,
|
||||
admin_clients=self.admin_clients.clients,
|
||||
model_name=config.model,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
@@ -134,7 +158,7 @@ class Evals:
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=None,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.pool,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
@@ -152,11 +176,10 @@ class Evals:
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor.
|
||||
# metrics fan out to every registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.pool.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
|
||||
@@ -166,7 +189,7 @@ class Evals:
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.eval.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
@@ -193,7 +216,7 @@ class Evals:
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = self.log_dir / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
@@ -242,65 +265,55 @@ class Evals:
|
||||
assert config.online is not None
|
||||
online = config.online
|
||||
|
||||
# Rendezvous with the trainer's startup broadcast (v0 fresh, the
|
||||
# checkpoint step on resume) — always, for every transport: an
|
||||
# in-memory trainer blocks inside its startup broadcast until this
|
||||
# receive, and for filesystem it guarantees the served weights match
|
||||
# the trainer's incoming policy.
|
||||
assert self.receiver is not None
|
||||
startup_step = online.resume_step or 0
|
||||
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
|
||||
self.policy.version = startup_step
|
||||
|
||||
if online.resume_step is None:
|
||||
# Base-model eval: the inference server starts with the untrained weights,
|
||||
# so no reload is needed. The first trigger fires every env (policy v0)
|
||||
# unless ``skip_first_step``.
|
||||
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
|
||||
await self.maybe_run_evals(step=0)
|
||||
elif config.eval.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals). The trainer rebroadcasts the resumed policy on startup, but only
|
||||
# after loading the model — wait for that broadcast instead of checking
|
||||
# once. A newer stable broadcast means the resume step's was already
|
||||
# cleaned away (only the newest is kept) and can never reappear. The
|
||||
# evals); the startup rendezvous above already loaded its weights. The
|
||||
# final broadcast force-fires every env, exactly like the watch loop below.
|
||||
assert online.broadcasts_dir is not None and online.resume_step is not None
|
||||
while True:
|
||||
if (get_step_path(online.broadcasts_dir, online.resume_step) / "STABLE").exists():
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
|
||||
break
|
||||
newer_stable = any(
|
||||
step > online.resume_step and (get_step_path(online.broadcasts_dir, step) / "STABLE").exists()
|
||||
for step in get_all_ckpt_steps(online.broadcasts_dir)
|
||||
)
|
||||
if newer_stable:
|
||||
get_logger().warning(
|
||||
f"Broadcast for resume step {online.resume_step} was cleaned before it could be "
|
||||
"re-evaluated (broadcast cleaning outpaced the evals process) - skipping the retrigger"
|
||||
)
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, force=is_final)
|
||||
|
||||
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
|
||||
while True:
|
||||
assert online.broadcasts_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.broadcasts_dir)
|
||||
stable = {step: (get_step_path(online.broadcasts_dir, step) / "STABLE").exists() for step in steps}
|
||||
newest_stable = max((step for step in steps if stable[step]), default=None)
|
||||
published = {step: self.receiver.is_published(step) for step in steps}
|
||||
newest_published = max((step for step in steps if published[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
|
||||
# (the trainer keeps only the newest broadcast) can delete a step before
|
||||
# this scan sees it, and a vanished step would otherwise be skipped
|
||||
# without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in stable:
|
||||
if step not in published:
|
||||
get_logger().warning(
|
||||
f"Weight broadcast for eval step {step} was deleted before it could be "
|
||||
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not stable[step]:
|
||||
if not published[step]:
|
||||
# The trainer writes broadcasts in ascending order, so a marker-less
|
||||
# step below a stable one is an abandoned partial write (e.g. a crash
|
||||
# mid-save), not one in progress — skip it instead of wedging on it.
|
||||
if newest_stable is None or newest_stable < step:
|
||||
# step below a published one is an abandoned partial write (e.g. a
|
||||
# crash mid-save), not one in progress — skip it instead of wedging.
|
||||
if newest_published is None or newest_published < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight broadcast step {step} has no STABLE marker but newer stable "
|
||||
"broadcasts exist - treating it as abandoned and skipping its evals"
|
||||
f"Weight broadcast step {step} is not marked published but newer "
|
||||
"broadcasts are - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
@@ -310,33 +323,59 @@ class Evals:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest stable broadcast that are missing from the
|
||||
broadcasts dir — the trainer wrote them (it broadcasts at every due step), so
|
||||
their absence means broadcast cleaning removed them before they were
|
||||
def next_published_step(self, step: int) -> int | None:
|
||||
"""Return the first newer checkpoint offered by the trainer."""
|
||||
assert self.config.online is not None
|
||||
assert self.config.online.broadcasts_dir is not None
|
||||
assert self.receiver is not None
|
||||
return next(
|
||||
(
|
||||
candidate
|
||||
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
|
||||
if candidate > step and self.receiver.is_published(candidate)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest published broadcast that are missing from
|
||||
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
|
||||
so their absence means broadcast cleaning removed them before they were
|
||||
evaluated."""
|
||||
if newest_stable is None:
|
||||
if newest_published is None:
|
||||
return set()
|
||||
due = {
|
||||
step
|
||||
for interval in self.eval_source.intervals.values()
|
||||
for step in range(interval, newest_stable + 1, interval)
|
||||
for step in range(interval, newest_published + 1, interval)
|
||||
}
|
||||
return due - set(steps)
|
||||
|
||||
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due."""
|
||||
reloading the inference weights first. No-op when no env is due — except
|
||||
that a live transport's broadcast must always be received (the trainer
|
||||
is blocked inside it), eval or no eval."""
|
||||
if reload_weights:
|
||||
assert self.config.online is not None and self.config.online.broadcasts_dir is not None
|
||||
broadcast_dir = get_step_path(self.config.online.broadcasts_dir, step)
|
||||
if not (broadcast_dir / "STABLE").exists():
|
||||
get_logger().warning(f"No stable weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
assert self.receiver is not None
|
||||
broadcast_dir = self.receiver.step_dir(step)
|
||||
if not self.receiver.is_published(step):
|
||||
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
fired = self.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
|
||||
if reload_weights:
|
||||
# Every offered version must be received: the trainer blocks inside
|
||||
# the handshake, so a failed receive fails the run loudly.
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
await self.dispatcher.on_version_pending(step)
|
||||
await self.receiver.receive(step)
|
||||
self.policy.version = step
|
||||
await self.dispatcher.on_new_version(step)
|
||||
|
||||
if not fired:
|
||||
return
|
||||
|
||||
@@ -348,59 +387,88 @@ class Evals:
|
||||
for env_name in fired
|
||||
)
|
||||
|
||||
if reload_weights:
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
# LoRA runs broadcast the raw adapter; load it under a fixed adapter name
|
||||
# and serve the evals against that name (mirrors WeightWatcher).
|
||||
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
|
||||
try:
|
||||
await self.pool.update_weights(broadcast_dir, lora_name=lora_name, step=step)
|
||||
except Exception as exc:
|
||||
# Skip this step instead of killing the run; drain the queued examples
|
||||
# so they don't leak into a later epoch with the wrong step.
|
||||
while self.eval_source.next_task() is not None:
|
||||
pass
|
||||
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
|
||||
return
|
||||
if lora_name is not None:
|
||||
self.pool.update_model_name(lora_name)
|
||||
self.policy.model_name = lora_name
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
self.policy.version = step
|
||||
if not reload_weights:
|
||||
self.policy.version = step
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
await self.consume_epoch(fired)
|
||||
await self.consume_epoch(fired, step)
|
||||
|
||||
async def consume_epoch(self, fired: list[str]) -> None:
|
||||
"""Consume dispatcher episodes until every fired env's epoch finalizes,
|
||||
routing them through the sink and monitors."""
|
||||
# An env with no examples emits no episodes, so its epoch can never finalize.
|
||||
async def consume_epoch(self, fired: list[str], step: int) -> None:
|
||||
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
superseding_step: int | None = None
|
||||
online = self.config.online
|
||||
|
||||
while pending:
|
||||
episode = await self.dispatcher.out_q.get()
|
||||
step = eval_work(episode).step
|
||||
await monitors.log([episode], step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(episode)
|
||||
if (
|
||||
cancellation_task is None
|
||||
and online is not None
|
||||
and self.config.eval.cancel_on_new_checkpoint
|
||||
and (superseding_step := self.next_published_step(step)) is not None
|
||||
):
|
||||
get_logger().warning(
|
||||
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
|
||||
)
|
||||
cancellation_task = asyncio.create_task(
|
||||
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
|
||||
)
|
||||
|
||||
try:
|
||||
if online is not None and self.config.eval.cancel_on_new_checkpoint:
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
|
||||
else:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
except asyncio.TimeoutError:
|
||||
if cancellation_task is not None and cancellation_task.done():
|
||||
cancellation_task.result()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
item_step = eval_work(item).step
|
||||
await monitors.log([item], item_step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
|
||||
f"advancing to checkpoint {superseding_step}"
|
||||
)
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
@@ -408,6 +476,13 @@ class Evals:
|
||||
eff, full = effective.metrics, episodes.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
@@ -438,24 +513,22 @@ class Evals:
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
|
||||
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
|
||||
if periodic_logger is not None:
|
||||
await periodic_logger.stop()
|
||||
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
|
||||
if inference_metrics is not None:
|
||||
await inference_metrics.stop()
|
||||
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
|
||||
if dispatcher is not None:
|
||||
await dispatcher.stop()
|
||||
pool: InferencePool | None = getattr(self, "pool", None)
|
||||
if pool is not None:
|
||||
await pool.stop()
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
if self.inference_metrics is not None:
|
||||
await self.inference_metrics.stop()
|
||||
if self.dispatcher is not None:
|
||||
await self.dispatcher.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_clients is not None:
|
||||
await self.admin_clients.aclose()
|
||||
cleanup_processes(self.env_server_procs)
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig) -> None:
|
||||
evals = Evals(config)
|
||||
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
evals = Evals(config, log_dir)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
@@ -465,11 +538,9 @@ async def run_evals(config: EvalsConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.entrypoints.evals import main as entrypoint_main
|
||||
|
||||
set_proc_title("Evals")
|
||||
asyncio.run(run_evals(cli(EvalsConfig)))
|
||||
entrypoint_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -207,7 +207,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -233,8 +232,11 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if envs.VLLM_USE_V2_MODEL_RUNNER:
|
||||
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"The V2 model runner does not support routed experts capture - "
|
||||
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
@@ -609,32 +611,6 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_harmony_stop_token_propagation():
|
||||
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
|
||||
|
||||
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
|
||||
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
|
||||
ignores them, using only self.stop_token_ids (which defaults to []).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/22519
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
|
||||
|
||||
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
|
||||
|
||||
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
|
||||
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
|
||||
# Merge harmony stop tokens from default_sampling_params
|
||||
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
|
||||
if default_stop_ids:
|
||||
existing = set(params.stop_token_ids or [])
|
||||
merged = list(existing | set(default_stop_ids))
|
||||
params.stop_token_ids = merged
|
||||
return params
|
||||
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
@@ -717,45 +693,6 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ 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")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
|
||||
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
|
||||
# stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
# Router replay needs the V1 GPU model runner: V2 silently never captures
|
||||
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
|
||||
# setdefault so it stays overridable.
|
||||
if config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "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
|
||||
|
||||
@@ -20,17 +20,13 @@ 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_harmony_stop_token_propagation,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.28 — 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.
|
||||
@@ -92,10 +88,14 @@ 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, see orchestrator.lora_name).
|
||||
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 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``.
|
||||
|
||||
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
|
||||
|
||||
@@ -3,22 +3,20 @@
|
||||
vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
|
||||
defaulting. We subclass it for the bits still missing from the upstream handler:
|
||||
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
|
||||
defaulting and ``usage`` reporting. We subclass it for the bits still missing
|
||||
from the upstream handler:
|
||||
|
||||
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
|
||||
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
|
||||
now does this too; we keep the equivalent path for the DP-replicated
|
||||
inference servers prime-RL runs.
|
||||
1. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
|
||||
objects (the form the PD router can merge and the renderers parse) instead
|
||||
of upstream's single ``.npy`` base64 string.
|
||||
|
||||
2. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
|
||||
source fork.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
|
||||
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
|
||||
``get_max_tokens``); we keep an equivalent guard so callers that omit
|
||||
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
|
||||
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
|
||||
parses ``request.kv_transfer_params`` but never threads it into the engine,
|
||||
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
|
||||
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
|
||||
cut — drop the bridge once we pin a release that includes it.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
routed_experts: dict[str, Any] | None = None
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact
|
||||
# ``{data, shape, start, dtype}`` object the PD router merges and the
|
||||
# renderers parse.
|
||||
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=choices,
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
|
||||
instance, which means an unset ``max_tokens`` is indistinguishable from
|
||||
an explicit ``max_tokens=16`` once the request reaches the handler —
|
||||
both surface as ``sampling_params.max_tokens == 16``. We re-read the
|
||||
cached body to recover that distinction. When we can't (no raw_request,
|
||||
non-JSON body, or read error), pessimistically assume the client did
|
||||
set it so we never clobber an explicit value.
|
||||
"""
|
||||
if raw_request is None:
|
||||
return True
|
||||
try:
|
||||
body = await raw_request.json()
|
||||
except Exception:
|
||||
return True
|
||||
if not isinstance(body, dict):
|
||||
return True
|
||||
sp = body.get("sampling_params")
|
||||
return isinstance(sp, dict) and "max_tokens" in sp
|
||||
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
|
||||
|
||||
Computed lazily because ``custom_init_app_state`` swaps in this
|
||||
subclass via ``object.__new__`` + ``__dict__.update`` (so our
|
||||
``__init__`` never runs).
|
||||
"""
|
||||
diff = self.model_config.get_diff_sampling_param()
|
||||
mc = self.model_config
|
||||
override = (
|
||||
diff.get("max_tokens")
|
||||
if mc.generation_config not in ("auto", "vllm")
|
||||
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
|
||||
# in case a downstream caller ever sets the attribute to ``None``
|
||||
# (``getattr``'s default only fires when the attribute is missing,
|
||||
# not when it exists with a ``None`` value).
|
||||
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
|
||||
)
|
||||
return diff, override
|
||||
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
|
||||
|
||||
async def serve_tokens(
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
# (c) dispatch to our overridden response builder so ``routed_experts``
|
||||
# makes it into the JSON.
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
return error_check_ret
|
||||
|
||||
if self.engine_client.errored:
|
||||
raise self.engine_client.dead_error
|
||||
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
model_name = self.models.model_name(lora_request)
|
||||
|
||||
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
|
||||
request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = request_metadata
|
||||
|
||||
# Build the engine input — features-aware (MM) or text-only fallback.
|
||||
# Identical to upstream so we keep tracking it.
|
||||
if features := request.features:
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
PlaceholderRange,
|
||||
)
|
||||
|
||||
mm_placeholders = {
|
||||
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
|
||||
for modality, ranges in features.mm_placeholders.items()
|
||||
}
|
||||
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
|
||||
if features.kwargs_data is not None:
|
||||
for modality, items in features.kwargs_data.items():
|
||||
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
|
||||
else:
|
||||
for modality, hashes in features.mm_hashes.items():
|
||||
mm_kwargs[modality] = [None] * len(hashes)
|
||||
engine_input = mm_input(
|
||||
prompt_token_ids=request.token_ids,
|
||||
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
|
||||
mm_hashes=features.mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
cache_salt=request.cache_salt,
|
||||
)
|
||||
else:
|
||||
(engine_input,) = await self.online_renderer.preprocess_completion(
|
||||
request,
|
||||
prompt_input=request.token_ids,
|
||||
prompt_embeds=None,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
|
||||
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
|
||||
# engine's KV connector picks the params up.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Upstream parses ``request.kv_transfer_params`` but never threads it
|
||||
# into the engine, so decode receives an empty NIXL handshake and
|
||||
# re-prefills the prompt locally (~100x slower under concurrency).
|
||||
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
|
||||
# connector picks the params up. Fixed upstream by vllm#42644 (merged
|
||||
# after 0.28.0) — drop once we pin a release that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = sampling_params.extra_args or {}
|
||||
extra = request.sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
request.sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
|
||||
# ``ServingTokens`` now does this too; kept here so callers that omit
|
||||
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
|
||||
# default.
|
||||
if not await _client_set_max_tokens(raw_request):
|
||||
diff_sp, override = self._max_tokens_defaults
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
max_model_len=self.model_config.max_model_len,
|
||||
max_tokens=None,
|
||||
input_length=len(request.token_ids),
|
||||
default_sampling_params=diff_sp,
|
||||
override_max_tokens=override,
|
||||
)
|
||||
|
||||
if self.force_no_detokenize:
|
||||
sampling_params.detokenize = False
|
||||
if request.stream:
|
||||
sampling_params.output_kind = RequestOutputKind.DELTA
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
engine_input,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
result_generator = self.engine_client.generate(
|
||||
engine_input,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=self._get_data_parallel_rank(raw_request),
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
# Streaming path: defer to upstream — prime-RL's renderer client
|
||||
# only consumes the full response, so adding routed_experts to the
|
||||
# streaming choice schema is unnecessary churn.
|
||||
return self.serve_tokens_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
return await self.serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
return await super().serve_tokens(request, raw_request)
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
start = request.sampling_params.routed_experts_prompt_start
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=start,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -3,7 +3,6 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
@@ -21,6 +20,3 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -51,7 +51,7 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
|
||||
# Split concatenated tensor back into individual tensors
|
||||
offset = 0
|
||||
for key, shape, numel in tensor_info_list:
|
||||
tensor = concatenated[offset : offset + numel].view(shape).clone()
|
||||
tensor = concatenated[offset : offset + numel].view(shape)
|
||||
offset += numel
|
||||
try:
|
||||
yield key, tensor
|
||||
|
||||
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
MemDesc,
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
PreparedRead,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
@@ -44,7 +48,6 @@ else:
|
||||
Worker = object
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nixl")
|
||||
_BUFFER_POLL_INTERVAL = 0.01
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
|
||||
class WeightTransferGroup:
|
||||
name: str
|
||||
layers: list[LayerWeightTransferPlan]
|
||||
pulls: list[tuple[Any, Any, list[int]]]
|
||||
pulls: list[PreparedRead]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferPlan:
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor]
|
||||
receive_buffer_count: int
|
||||
trainer_peers: list[NixlPeer]
|
||||
groups: list[WeightTransferGroup]
|
||||
|
||||
|
||||
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=server_url),
|
||||
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
session_id=session_id,
|
||||
worker_id=f"inference-{global_rank}",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.weight_transfer_timeout = timeout
|
||||
self.weight_transfer_plan: WeightTransferPlan | None = None
|
||||
logger.info(
|
||||
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
trainer_ref = self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=None,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)[0]
|
||||
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
|
||||
copies = self.trace_weight_loads(table)
|
||||
plan = self.build_transfer_plan(table, copies)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(table.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=self.model_express.client,
|
||||
role="inference",
|
||||
rank=self.model_express.rank,
|
||||
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
# Join the current generation directly. Publishing a transient READY
|
||||
# before the first pull would let the trainer mistake initialization
|
||||
# for a completed acknowledgement.
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.weight_transfer_plan = plan
|
||||
self.group_generations = [0] * len(plan.groups)
|
||||
logger.info(
|
||||
"Initialized NIXL transfer plan on rank %d with %d groups",
|
||||
self.model_express.rank,
|
||||
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
copies,
|
||||
replay_plans,
|
||||
)
|
||||
receive_buffer_count = self.choose_receive_buffer_count(
|
||||
receive_buffer_elements,
|
||||
table.staging_buffer_count,
|
||||
)
|
||||
receive_buffer_count = table.staging_buffer_count
|
||||
receive_arenas = self.allocate_receive_arenas(
|
||||
receive_buffer_elements,
|
||||
receive_buffer_count,
|
||||
)
|
||||
peers: list[NixlPeer] = []
|
||||
for agent in table.agents:
|
||||
peer = self.nixl_agent.add_remote_agent(agent.metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
peers.append(peer)
|
||||
groups = self.build_transfer_groups(
|
||||
table,
|
||||
copies,
|
||||
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements,
|
||||
receive_arenas,
|
||||
receive_buffer_count,
|
||||
peers,
|
||||
)
|
||||
return WeightTransferPlan(
|
||||
receive_arenas=receive_arenas,
|
||||
receive_buffer_count=receive_buffer_count,
|
||||
trainer_peers=peers,
|
||||
groups=groups,
|
||||
)
|
||||
|
||||
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
|
||||
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
|
||||
def choose_receive_buffer_count(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
staging_buffer_count: int,
|
||||
) -> int:
|
||||
receive_buffer_bytes = max(
|
||||
1,
|
||||
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
|
||||
)
|
||||
allocated_bytes = torch.cuda.memory_allocated(self.device)
|
||||
peak_growth_bytes = max(
|
||||
0,
|
||||
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
|
||||
)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(self.device)
|
||||
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
return size_cuda_buffers(
|
||||
receive_buffer_bytes,
|
||||
max_receive_buffers,
|
||||
self.device,
|
||||
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
|
||||
)
|
||||
|
||||
def allocate_receive_arenas(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor],
|
||||
receive_buffer_count: int,
|
||||
peers: list[NixlPeer],
|
||||
) -> list[WeightTransferGroup]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
)
|
||||
|
||||
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
|
||||
peer_names: dict[int, str] = {}
|
||||
transfer_groups: list[WeightTransferGroup] = []
|
||||
|
||||
for group_index, group in enumerate(table.groups):
|
||||
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
persistent_plans_by_layer,
|
||||
),
|
||||
pulls=self.prepare_group_pulls(
|
||||
table,
|
||||
local_descs,
|
||||
remote_descs,
|
||||
peer_names,
|
||||
peers,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def prepare_group_pulls(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
local_descs: dict[int, list[MemDesc]],
|
||||
remote_descs: dict[int, list[MemDesc]],
|
||||
peer_names: dict[int, str],
|
||||
) -> list[tuple[Any, Any, list[int]]]:
|
||||
pulls: list[tuple[Any, Any, list[int]]] = []
|
||||
for agent_index, remote in sorted(remote_descs.items()):
|
||||
peer_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
self.nixl_agent.make_connection(peer_name)
|
||||
peer_names[agent_index] = peer_name
|
||||
peers: list[NixlPeer],
|
||||
) -> list[PreparedRead]:
|
||||
pulls: list[PreparedRead] = []
|
||||
agent_indices = sorted(remote_descs)
|
||||
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
|
||||
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
|
||||
for agent_index in agent_indices:
|
||||
remote = remote_descs[agent_index]
|
||||
peer = peers[agent_index]
|
||||
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
|
||||
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
|
||||
pulls.append(
|
||||
self.nixl_agent.prepare_read(
|
||||
local_prepared,
|
||||
list(range(len(remote))),
|
||||
remote_prepared,
|
||||
)
|
||||
)
|
||||
return pulls
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
|
||||
del weight_dir
|
||||
plan = self.initialize_transfer()
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
self.apply_transfer_plan(plan)
|
||||
update_mla_absorbed_weights(self.raw_model)
|
||||
torch.cuda.synchronize(self.device)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
logger.info(
|
||||
"Applied NIXL policy update on rank %d in %.2fs",
|
||||
self.model_express.rank,
|
||||
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def pull_group(group_index: int) -> WeightTransferGroup:
|
||||
transfer_group = plan.groups[group_index]
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
plan.trainer_peers,
|
||||
notification,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
|
||||
for local, remote, indices in transfer_group.pulls:
|
||||
handle = self.nixl_agent.post_read(local, indices, remote)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.post_read(read, notification)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.wait(
|
||||
handle,
|
||||
read,
|
||||
context=f"weight pull for {transfer_group.name}",
|
||||
timeout=self.weight_transfer_timeout,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
return transfer_group
|
||||
|
||||
def acknowledge_group(group_index: int) -> None:
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.group_generations[group_index] += 1
|
||||
return transfer_group
|
||||
|
||||
def prefetch_group(group_index: int) -> WeightTransferGroup:
|
||||
torch.cuda.set_device(self.device)
|
||||
transfer_group = pull_group(group_index)
|
||||
acknowledge_group(group_index)
|
||||
return transfer_group
|
||||
return pull_group(group_index)
|
||||
|
||||
def replay_group(transfer_group: WeightTransferGroup) -> None:
|
||||
for layer_plan in transfer_group.layers:
|
||||
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
replay_group(transfer_group)
|
||||
torch.cuda.synchronize(self.device)
|
||||
|
||||
if not pipelined:
|
||||
acknowledge_group(group_index)
|
||||
finally:
|
||||
cancelled.set()
|
||||
if executor is not None:
|
||||
|
||||
@@ -9,6 +9,7 @@ down training.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
|
||||
@@ -18,7 +19,7 @@ from prime_rl.monitors.file import FileMonitor
|
||||
from prime_rl.monitors.prime import PrimeMonitor
|
||||
from prime_rl.monitors.wandb import WandbMonitor
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
@@ -44,6 +45,7 @@ async def setup(
|
||||
file: FileMonitorConfig | None = None,
|
||||
*,
|
||||
output_dir: Path,
|
||||
producer: str | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
train_env_names: list[str] | None = None,
|
||||
eval_env_names: list[str] | None = None,
|
||||
@@ -60,12 +62,13 @@ async def setup(
|
||||
if rank != 0:
|
||||
return
|
||||
|
||||
monitors: list[tuple[Monitor, dict[str, Any]]] = []
|
||||
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
|
||||
if prime is not None:
|
||||
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
|
||||
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
|
||||
if wandb is not None:
|
||||
monitors.append(
|
||||
(
|
||||
"wandb",
|
||||
WandbMonitor(wandb),
|
||||
dict(
|
||||
output_dir=output_dir,
|
||||
@@ -77,11 +80,17 @@ async def setup(
|
||||
)
|
||||
)
|
||||
if file is not None:
|
||||
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
|
||||
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir, producer=producer)))
|
||||
if not monitors:
|
||||
return
|
||||
|
||||
for monitor, init_kwargs in monitors:
|
||||
get_logger().info(f"Initializing monitors ({', '.join(name for name, _, _ in monitors)})")
|
||||
t0 = time.perf_counter()
|
||||
for name, monitor, init_kwargs in monitors:
|
||||
get_logger().info(f"Initializing {name} monitor ({monitor.config})")
|
||||
await monitor.init(**init_kwargs)
|
||||
MONITORS.append(monitor)
|
||||
get_logger().debug(f"Initialized monitors in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
def get(monitor_cls: type[Monitor]) -> Monitor | None:
|
||||
@@ -91,7 +100,7 @@ def get(monitor_cls: type[Monitor]) -> Monitor | None:
|
||||
|
||||
|
||||
@overload
|
||||
async def log(data: dict[str, Any], step: int) -> None: ...
|
||||
async def log(data: dict[str, Any], step: int | None) -> None: ...
|
||||
|
||||
|
||||
@overload
|
||||
@@ -100,7 +109,7 @@ async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset
|
||||
|
||||
async def log(
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
step: int | None,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
|
||||
@@ -24,7 +24,7 @@ class Monitor(ABC):
|
||||
"""Initialize run. Overrides name their own kwargs."""
|
||||
|
||||
@overload
|
||||
async def log(self, data: dict[str, Any], step: int) -> None: ...
|
||||
async def log(self, data: dict[str, Any], step: int | None) -> None: ...
|
||||
|
||||
@overload
|
||||
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
|
||||
@@ -32,7 +32,7 @@ class Monitor(ABC):
|
||||
async def log(
|
||||
self,
|
||||
data: dict[str, Any] | vf.Episode | list[vf.Episode],
|
||||
step: int,
|
||||
step: int | None,
|
||||
kind: Kind = "train",
|
||||
subset: Subset = "effective",
|
||||
) -> None:
|
||||
@@ -41,11 +41,13 @@ class Monitor(ABC):
|
||||
await self.log_metrics(data, step=step)
|
||||
else:
|
||||
episodes = data if isinstance(data, list) else [data]
|
||||
assert step is not None
|
||||
await self.log_episodes(episodes, step=step, kind=kind, subset=subset)
|
||||
|
||||
@abstractmethod
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
"""Log scalar metrics."""
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""Log scalar metrics. ``step=None`` logs a time-keyed row (e.g. inference
|
||||
metrics, which are sampled on wall time rather than the training step)."""
|
||||
|
||||
@abstractmethod
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -22,15 +22,18 @@ class FileMonitor(Monitor):
|
||||
config: FileMonitorConfig
|
||||
file: TextIO
|
||||
|
||||
async def init(self, output_dir: Path) -> None:
|
||||
async def init(self, output_dir: Path, producer: str | None = None) -> None:
|
||||
self.output_dir = output_dir
|
||||
self.producer = producer
|
||||
self.path = output_dir / self.config.path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
|
||||
sampled on wall time rather than the training step)."""
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(
|
||||
@@ -38,6 +41,8 @@ class FileMonitor(Monitor):
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
if self.producer is not None:
|
||||
row["producer"] = self.producer
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -5,6 +5,7 @@ import atexit
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Coroutine
|
||||
|
||||
@@ -87,10 +88,13 @@ class PrimeMonitor(Monitor):
|
||||
)
|
||||
await self.run.create(name=self.config.name, **run_fields)
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# every monitor stamps its own wall time; without it, step=None rows
|
||||
# (e.g. inference metrics) reach the platform with no time anchor
|
||||
metrics["_timestamp"] = time.time()
|
||||
self.run.submit("metrics upload", self.run.log_metrics(metrics))
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
|
||||
@@ -16,6 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.wandb.overview import ensure_overview_view
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import format_time
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
@@ -41,6 +42,9 @@ class WandbMonitor(Monitor):
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
# W&B advertises Weave on every init when it sees openai/verifiers imported.
|
||||
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
|
||||
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
# requires a server connection and can't work offline.
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
|
||||
@@ -63,7 +67,7 @@ class WandbMonitor(Monitor):
|
||||
x_primary=primary,
|
||||
x_update_finish_state=finisher,
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
|
||||
self.logger.debug(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
|
||||
is_online = True
|
||||
else:
|
||||
run_id = None
|
||||
@@ -112,6 +116,9 @@ class WandbMonitor(Monitor):
|
||||
self.wandb = init_wandb(max_retries)
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
# key prefixes that arrived via step=None (wall-time rows); their time axis
|
||||
# is defined lazily on first sight in log_metrics
|
||||
self._time_prefixes: set[str] = set()
|
||||
|
||||
# Provision the curated "overview" saved view once per project (the run's primary process
|
||||
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
|
||||
@@ -130,16 +137,28 @@ class WandbMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to create W&B overview view - {e}")
|
||||
|
||||
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
|
||||
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
wandb.log({**metrics, "step": step})
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# every log carries the monitor's own wall-time stamp
|
||||
if step is None:
|
||||
# time-keyed rows chart against wall time; whichever key prefixes show
|
||||
# up this way get their time axis defined on first sight
|
||||
for prefix in {key.split("/")[0] for key in metrics}:
|
||||
if prefix not in self._time_prefixes:
|
||||
self._time_prefixes.add(prefix)
|
||||
wandb.define_metric(f"{prefix}/*", step_metric="_timestamp")
|
||||
wandb.log({**metrics, "_timestamp": time.time()})
|
||||
else:
|
||||
wandb.log({**metrics, "step": step, "_timestamp": time.time()})
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
pass
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
|
||||
t0 = time.perf_counter()
|
||||
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
|
||||
# not land the run state - without this, even clean runs decay to "crashed".
|
||||
await asyncio.to_thread(wandb.finish, exit_code=0)
|
||||
self.logger.debug(f"Finalized W&B run in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"""Curated "overview" W&B saved view.
|
||||
|
||||
The dashboard mirrors these sections in `prime_rl/dashboard/static/app.js`
|
||||
(buildSections + the *_METRICS/INFERENCE_PANELS constants) — keep the two in
|
||||
sync when editing panels here.
|
||||
|
||||
prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
|
||||
few that matter. These build a named saved view grouping the important metrics into sections, so a
|
||||
new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
|
||||
@@ -138,6 +142,7 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
|
||||
+ [f"eval/{env_pattern}/all/cancelled/mean"]
|
||||
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
|
||||
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
|
||||
)
|
||||
|
||||
@@ -22,7 +22,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
|
||||
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
|
||||
@@ -35,7 +35,7 @@ from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.algorithm import AlgoConfig
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
|
||||
# each config class's defaults are its vetted parameterization.
|
||||
@@ -51,7 +51,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
}
|
||||
|
||||
|
||||
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
@@ -59,7 +59,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
return cls(config, policy_pool)
|
||||
return cls(config, clients)
|
||||
|
||||
|
||||
__all__ = [
|
||||
@@ -73,7 +73,7 @@ __all__ = [
|
||||
"RAEAlgorithm",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
"connect_frozen_pool",
|
||||
"connect_frozen_client",
|
||||
"assign_advantages",
|
||||
"stamp_loss_routing",
|
||||
]
|
||||
|
||||
@@ -12,24 +12,24 @@ from prime_rl.utils.logger import get_logger
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
async def connect_frozen_pool(
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferencePool:
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
pool = InferencePool(
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
pool = InferencePool(config, model_name=config.name)
|
||||
await pool.wait_for_ready(config.name)
|
||||
return pool
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
|
||||
|
||||
def iter_trainable_traces(episodes: list[vf.Episode]):
|
||||
@@ -52,18 +52,17 @@ class Algorithm:
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
|
||||
self.policy_pool = policy_pool
|
||||
self.connected_pools: list[InferencePool] = []
|
||||
def __init__(self, config: AlgoConfig, clients: InferenceClient):
|
||||
self.clients = clients
|
||||
self.connected: InferenceClient | None = None
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect resources owned by the algorithm."""
|
||||
|
||||
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
|
||||
"""Connect and track a frozen model pool owned by this algorithm."""
|
||||
pool = await connect_frozen_pool(reference)
|
||||
self.connected_pools.append(pool)
|
||||
return pool
|
||||
async def connect(self, reference: FrozenModelConfig) -> InferenceClient:
|
||||
"""Connect and track the frozen model pool owned by this algorithm."""
|
||||
self.connected = await connect_frozen_client(reference)
|
||||
return self.connected
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
"""Assign rollout-local annotations to one finalized episode."""
|
||||
|
||||
@@ -11,7 +11,7 @@ from prime_rl.utils.utils import import_object
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class EchoAlgorithm(GRPOAlgorithm):
|
||||
@@ -22,8 +22,8 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
mask and its denominator. An optional user filter narrows the selection
|
||||
per rollout (e.g. dropping tool-output warnings)."""
|
||||
|
||||
def __init__(self, config: EchoAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: EchoAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.role_weights = {
|
||||
role: role_config.alpha
|
||||
for role in ("system", "user", "assistant", "tool")
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GRPOAlgorithm(Algorithm):
|
||||
@@ -18,8 +18,8 @@ class GRPOAlgorithm(Algorithm):
|
||||
policy per example; credit = reward minus the group mean (optionally
|
||||
length-shaped); action tokens feed the ``rl`` loss."""
|
||||
|
||||
def __init__(self, config: GRPOAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.length_penalty = config.length_penalty
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
@@ -26,8 +26,8 @@ class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
within one episode. Other roles are compared across the full rollout group.
|
||||
A comparison group with one trace produces zero advantage."""
|
||||
|
||||
def __init__(self, config: HierarchicalGRPOAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: HierarchicalGRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.episode_agents = set(config.episode_agents)
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
|
||||
@@ -11,7 +11,7 @@ from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class OPDAlgorithm(Algorithm):
|
||||
@@ -26,20 +26,20 @@ class OPDAlgorithm(Algorithm):
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.teacher = config.teacher
|
||||
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
|
||||
self.teacher_clients: InferenceClient | None = None # frozen teacher endpoint, connected in setup()
|
||||
|
||||
async def setup(self) -> None:
|
||||
self.teacher_pool = await self.connect(self.teacher)
|
||||
self.teacher_clients = await self.connect(self.teacher)
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
|
||||
teacher = self.teacher_clients
|
||||
assert teacher is not None, "teacher not connected — Algorithm.setup() must run first"
|
||||
branches = [
|
||||
branch for _, trace in iter_trainable_traces([episode]) for branch, _ in iter_trainable_branches(trace)
|
||||
]
|
||||
scores = await asyncio.gather(*(pool.score(branch.token_ids) for branch in branches))
|
||||
scores = await asyncio.gather(*(teacher.score(branch.token_ids) for branch in branches))
|
||||
for branch, logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, logprobs)
|
||||
|
||||
@@ -14,7 +14,7 @@ from prime_rl.orchestrator.utils import episode_env_name
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class OPSDAlgorithm(Algorithm):
|
||||
@@ -33,8 +33,8 @@ class OPSDAlgorithm(Algorithm):
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPSDAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.demo_key = config.demo_key
|
||||
self.template = config.template
|
||||
self.renderer_config = config.renderer
|
||||
@@ -42,7 +42,7 @@ class OPSDAlgorithm(Algorithm):
|
||||
# Self-distillation: the teacher *is* the live policy. Scoring against
|
||||
# the shared policy pool tracks its current weights, model name, and
|
||||
# endpoint churn for free.
|
||||
self.teacher_pool = self.policy_pool
|
||||
self.teacher_clients = self.clients
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Build opsd's own hint-block renderer from config — it is not handed
|
||||
@@ -51,7 +51,7 @@ class OPSDAlgorithm(Algorithm):
|
||||
identically to the policy's own prompts."""
|
||||
from renderers.base import create_renderer, load_tokenizer
|
||||
|
||||
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
|
||||
self.renderer = create_renderer(load_tokenizer(self.clients.model_name), self.renderer_config)
|
||||
|
||||
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
|
||||
demonstration = trace.info.get(self.demo_key)
|
||||
@@ -66,13 +66,13 @@ class OPSDAlgorithm(Algorithm):
|
||||
return demonstration
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
teacher = self.teacher_clients
|
||||
renderer = self.renderer
|
||||
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
|
||||
for _, trace in iter_trainable_traces([episode]):
|
||||
hint = self.template.format(demonstration=self._demonstration(episode, trace))
|
||||
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
|
||||
branches = [branch for branch, _ in iter_trainable_branches(trace)]
|
||||
scores = await asyncio.gather(*(pool.score(hint_block + branch.token_ids) for branch in branches))
|
||||
scores = await asyncio.gather(*(teacher.score(hint_block + branch.token_ids) for branch in branches))
|
||||
for branch, full_logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class RAEAlgorithm(Algorithm):
|
||||
@@ -31,8 +31,8 @@ class RAEAlgorithm(Algorithm):
|
||||
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
|
||||
traces per agent."""
|
||||
|
||||
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: RAEAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.decay = config.decay
|
||||
self.baselines: dict[str, float] = defaultdict(float)
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
@@ -40,8 +41,9 @@ class PrefillScorer:
|
||||
await self._client.close()
|
||||
|
||||
|
||||
class InferencePool:
|
||||
"""Inference pool with a single data-plane endpoint and one admin client per server."""
|
||||
class InferenceClient:
|
||||
"""Data-plane clients for one inference endpoint (the router of the policy
|
||||
deployment, or an external API for frozen models)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -59,7 +61,31 @@ class InferencePool:
|
||||
renderer_model_name=renderer_model_name,
|
||||
)
|
||||
self.eval_client = setup_client(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
self._scorer = PrefillScorer()
|
||||
self.model_name = model_name
|
||||
|
||||
async def score(self, token_ids: list[int]) -> list[float]:
|
||||
"""Prefill-score ``token_ids`` under this endpoint's model (one logprob
|
||||
per token, 0.0 for the leading token)."""
|
||||
return await self._scorer.score(self.train_client, self.model_name, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self._scorer.aclose()
|
||||
|
||||
|
||||
class AdminClients:
|
||||
"""Admin plane of the policy inference deployment: one httpx client per
|
||||
engine process. The router serves no admin routes (pause/resume,
|
||||
update_weights, init_broadcaster, load_lora_adapter live on the engines),
|
||||
so these clients bypass it via ``admin_base_url``.
|
||||
|
||||
The client order is load-bearing: ``admin_base_url`` order must match the
|
||||
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
|
||||
``init_nixl_broadcast`` and the metrics collector's role list index into
|
||||
it."""
|
||||
|
||||
def __init__(self, client_config: ClientConfig):
|
||||
self.clients = setup_admin_clients(client_config)
|
||||
# When admin URLs bypass a router, also health-check the client-facing
|
||||
# (router) endpoint - it only starts serving once its workers are healthy.
|
||||
self._router_clients = (
|
||||
@@ -69,33 +95,32 @@ class InferencePool:
|
||||
)
|
||||
self._skip_model_check = client_config.skip_model_check
|
||||
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
|
||||
self._scorer = PrefillScorer()
|
||||
self.model_name = model_name
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
return self._admin_clients
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
|
||||
await check_health(
|
||||
self._admin_clients + self._router_clients,
|
||||
timeout=timeout if timeout is not None else self._wait_for_ready_timeout,
|
||||
async def wait_for_ready(self, model_name: str) -> None:
|
||||
# The engines are waited on even when a router fronts them: the llm-d
|
||||
# router (Envoy) 404s /health, which check_health treats as "no health
|
||||
# route", so the router alone is not a readiness signal. The router
|
||||
# owns the info-level waiting log; the per-engine waits log at debug.
|
||||
await asyncio.gather(
|
||||
check_health(self.clients, timeout=self._wait_for_ready_timeout, quiet=bool(self._router_clients)),
|
||||
check_health(self._router_clients, timeout=self._wait_for_ready_timeout),
|
||||
)
|
||||
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
|
||||
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
|
||||
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
|
||||
async def aclose(self) -> None:
|
||||
for client in self.clients + self._router_clients:
|
||||
await client.aclose()
|
||||
|
||||
async def score(self, token_ids: list[int]) -> list[float]:
|
||||
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
|
||||
token, 0.0 for the leading token). Delegates to the shared scorer."""
|
||||
return await self._scorer.score(self.train_client, self.model_name, token_ids)
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self._scorer.aclose()
|
||||
async def check_inference_ready(client_config: ClientConfig, model_name: str) -> None:
|
||||
"""One-shot readiness check of an inference endpoint (health + model
|
||||
listing) with transient clients — for frozen endpoints that never need a
|
||||
persistent admin plane."""
|
||||
admin = AdminClients(client_config)
|
||||
try:
|
||||
await admin.wait_for_ready(model_name)
|
||||
finally:
|
||||
await admin.aclose()
|
||||
|
||||
|
||||
def setup_client(
|
||||
@@ -172,13 +197,20 @@ async def maybe_check_has_model(
|
||||
|
||||
|
||||
async def check_health(
|
||||
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
|
||||
admin_clients: list[AsyncClient],
|
||||
interval: int = 1,
|
||||
log_interval: int = 30,
|
||||
timeout: int = 1800,
|
||||
quiet: bool = False,
|
||||
) -> None:
|
||||
"""Wait until every client's /health responds. With ``quiet``, the periodic
|
||||
waiting lines log at debug instead of info - used for engines fronted by a
|
||||
router, so startup logs one waiting line instead of one per engine."""
|
||||
logger = get_logger()
|
||||
|
||||
async def _check_health(admin_client: AsyncClient) -> None:
|
||||
wait_time = 0
|
||||
logger.debug("Starting pinging /health to check health")
|
||||
logger.debug("Pinging /health until the inference server is ready")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
response = await admin_client.get("/health")
|
||||
@@ -190,9 +222,9 @@ async def check_health(
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
f"Inference server was not reached after {wait_time} seconds (Error: {e}) on {admin_client.base_url}"
|
||||
)
|
||||
log = logger.debug if quiet else logger.info
|
||||
log(f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)")
|
||||
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
msg = f"Inference server is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
|
||||
@@ -202,9 +234,6 @@ async def check_health(
|
||||
await asyncio.gather(*[_check_health(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def _is_retryable_admin_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
@@ -253,7 +282,7 @@ async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMI
|
||||
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
|
||||
"""Pause all inference engines, waiting for in-flight requests to drain."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Updating policy in-flight to v{step}")
|
||||
logger.debug(f"Pausing inference engines to update weights to policy v{step}")
|
||||
await asyncio.gather(
|
||||
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
|
||||
)
|
||||
@@ -274,50 +303,39 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
|
||||
async def update_weights(
|
||||
admin_clients: list[AsyncClient],
|
||||
weight_dir: Path | None,
|
||||
lora_name: str | None = None,
|
||||
step: int = 0,
|
||||
on_paused: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
"""Update weights on static inference servers.
|
||||
|
||||
Pauses all engines first to drain in-flight requests, then performs the
|
||||
weight update, then resumes. This ensures all DP workers are idle and can
|
||||
participate in the collective weight transfer.
|
||||
participate in the collective weight transfer. ``on_paused`` runs between
|
||||
the pause and the update RPC — the NCCL receiver signals the trainer there.
|
||||
|
||||
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
|
||||
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
|
||||
``orchestrator/envs.py``), so KV computed under old weights is never reused.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
|
||||
|
||||
if lora_name is not None and weight_dir is not None:
|
||||
await load_lora_adapter(admin_clients, lora_name, weight_dir)
|
||||
else:
|
||||
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
|
||||
await _pause_engines(admin_clients, step=step)
|
||||
|
||||
try:
|
||||
# Create ready marker before servers enter receive path (used by NCCL broadcast)
|
||||
if weight_dir is not None:
|
||||
nccl_ready_file = weight_dir / NCCL_READY_MARKER
|
||||
nccl_ready_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
nccl_ready_file.touch()
|
||||
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
|
||||
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in admin_clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(admin_clients)
|
||||
await _pause_engines(admin_clients, step=step)
|
||||
try:
|
||||
if on_paused is not None:
|
||||
on_paused()
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in admin_clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(admin_clients)
|
||||
|
||||
|
||||
def _is_retryable_lora_error(exception: BaseException) -> bool:
|
||||
@@ -375,25 +393,12 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
|
||||
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
async def unload_lora_adapter(admin_clients: list[AsyncClient], lora_name: str) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to unload a LoRA adapter."""
|
||||
logger = get_logger()
|
||||
|
||||
async def _unload_lora_adapter(admin_client: AsyncClient) -> None:
|
||||
logger.debug(f"Sending request to unload LoRA adapter {lora_name}")
|
||||
await admin_client.post("/v1/unload_lora_adapter", json={"lora_name": lora_name})
|
||||
# TODO: The first one can fail, but subsequent ones should succeed.
|
||||
# response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_unload_lora_adapter(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
async def init_nccl_broadcast(
|
||||
admin_clients: list[AsyncClient],
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int | None = None,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
"""Initialize NCCL broadcast on all inference servers.
|
||||
@@ -404,12 +409,6 @@ async def init_nccl_broadcast(
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
if inference_world_size is None:
|
||||
inference_world_size = len(admin_clients)
|
||||
logger.warning(
|
||||
f"inference_world_size not provided, defaulting to {inference_world_size} (one GPU per admin client)"
|
||||
)
|
||||
|
||||
gpus_per_server = inference_world_size // len(admin_clients)
|
||||
|
||||
logger.info(
|
||||
@@ -6,10 +6,10 @@
|
||||
burst-capped so a raised (or drained) cap never lands all its prefills at
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once — as a native episode, or covered by its group's
|
||||
single ``GroupCancellation`` message when the group is dropped. Failures
|
||||
remain episode errors; sinks decide drop / partial-train policy.
|
||||
- Every dispatched attempt reaches ``out_q`` exactly once: as the native
|
||||
episode returned by the environment, as a ``DispatchFailure`` when no
|
||||
episode was produced, or under the group's ``GroupCancellation`` when the
|
||||
orchestrator abandons it.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight episodes of the opposite kind drain
|
||||
@@ -18,7 +18,7 @@
|
||||
the weight update) drops train groups already past ``max_off_policy_steps`` — a
|
||||
compute-saving early cancel; the sink's queue sweep is what guarantees the
|
||||
bound. Eval episodes are measurements for the policy version they started
|
||||
with, so they are allowed to finish even if training advances. Train
|
||||
with. Online evals may explicitly cancel them when a newer checkpoint is ready. Train
|
||||
episodes sampled from a frozen model never go stale — their generation
|
||||
source doesn't change with policy updates.
|
||||
"""
|
||||
@@ -38,11 +38,13 @@ from typing import Literal
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
CancelReason,
|
||||
DispatchFailure,
|
||||
DispatchResult,
|
||||
GroupCancellation,
|
||||
GroupState,
|
||||
@@ -53,7 +55,6 @@ from prime_rl.orchestrator.types import (
|
||||
)
|
||||
from prime_rl.orchestrator.utils import min_fresh_version
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -121,15 +122,6 @@ class DispatcherMetrics:
|
||||
return keys
|
||||
|
||||
|
||||
def _trace_task(task: vf.Task) -> vf.TraceTask:
|
||||
return vf.TraceTask(
|
||||
type=type(task).__name__,
|
||||
data=task.data,
|
||||
key=task.key,
|
||||
hash=task.hash,
|
||||
)
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
actual = (episode.task.key, episode.task.hash)
|
||||
@@ -151,7 +143,7 @@ class Dispatcher:
|
||||
eval_envs: EvalEnvs | None,
|
||||
train_source: TrainSource | None,
|
||||
eval_source: EvalSource | None,
|
||||
policy_pool: InferencePool,
|
||||
policy_clients: InferenceClient,
|
||||
policy: Policy,
|
||||
progress: Progress | None,
|
||||
initial_max_inflight: int,
|
||||
@@ -168,7 +160,7 @@ class Dispatcher:
|
||||
self.eval_envs = eval_envs
|
||||
# Train rollouts go to the env's generation source; eval always
|
||||
# evaluates the policy.
|
||||
self.policy_pool = policy_pool
|
||||
self.policy_clients = policy_clients
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
@@ -202,7 +194,8 @@ class Dispatcher:
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
# in-flight work). One entry per episode — the sinks count episodes,
|
||||
# never loose traces — plus one ``GroupCancellation`` per dropped group.
|
||||
# never loose traces — plus terminal dispatcher events for attempts
|
||||
# that produced no episode.
|
||||
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
|
||||
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
@@ -217,18 +210,20 @@ class Dispatcher:
|
||||
# *why* — the orchestrator toggles this based on step / policy lead.
|
||||
self.dispatch_allowed = asyncio.Event()
|
||||
self.dispatch_allowed.set()
|
||||
self.policy_update_pending = False
|
||||
self.scheduling_lock = asyncio.Lock()
|
||||
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferenceClient, str, bool]:
|
||||
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.pool, self.policy.model_name, True
|
||||
return source.pool, source.pool.model_name, False
|
||||
return source.clients, self.policy.model_name, True
|
||||
return source.clients, source.clients.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -353,7 +348,7 @@ class Dispatcher:
|
||||
timeout=0.5, # wake periodically to re-check fill (mode flips)
|
||||
)
|
||||
for task in done:
|
||||
await self.handle_completed_episode(task)
|
||||
await self.handle_completed_request(task)
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
|
||||
@@ -378,6 +373,12 @@ class Dispatcher:
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
self.policy_update_pending = True
|
||||
# Wait for a scheduling call that started before the pending update.
|
||||
# No rollout can cross the inference weight swap after this barrier.
|
||||
async with self.scheduling_lock:
|
||||
pass
|
||||
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return
|
||||
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
|
||||
@@ -399,7 +400,8 @@ class Dispatcher:
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
"""Resume rollout scheduling after inference applies the new policy."""
|
||||
self.policy_update_pending = False
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
@@ -408,28 +410,33 @@ class Dispatcher:
|
||||
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
|
||||
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
|
||||
while True:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.available_permits <= 0 or self.admission_budget() <= 0:
|
||||
return
|
||||
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
async with self.scheduling_lock:
|
||||
if self.policy_update_pending:
|
||||
return
|
||||
if self.mode == DispatcherMode.PREFER_EVAL:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
self.switch_mode(DispatcherMode.PREFER_TRAIN, reason="the eval queue drained")
|
||||
continue
|
||||
scheduled = await self.try_schedule("eval")
|
||||
if not scheduled:
|
||||
return
|
||||
else: # PREFER_TRAIN — respects the orchestrator's dispatch gate
|
||||
if not self.dispatch_allowed.is_set():
|
||||
return
|
||||
scheduled = await self.try_schedule("train")
|
||||
if not scheduled:
|
||||
return
|
||||
|
||||
def switch_mode(self, new_mode: DispatcherMode, *, reason: str) -> None:
|
||||
if new_mode == self.mode:
|
||||
@@ -500,14 +507,12 @@ class Dispatcher:
|
||||
# goes through the eval client (chat-completions) so eval scores stay
|
||||
# comparable.
|
||||
if group.kind == "eval":
|
||||
pool, model_name = self.policy_pool, self.policy.model_name
|
||||
clients, model_name = self.policy_clients, self.policy.model_name
|
||||
live_sourced = True
|
||||
else:
|
||||
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
clients, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
|
||||
if group.pinned_client is None:
|
||||
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
|
||||
client = group.pinned_client
|
||||
client = clients.eval_client if group.kind == "eval" else clients.train_client
|
||||
|
||||
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
|
||||
if env_collection is None:
|
||||
@@ -560,34 +565,40 @@ class Dispatcher:
|
||||
if refund_admission:
|
||||
self.admissions_in_window = max(0, self.admissions_in_window - 1)
|
||||
|
||||
async def handle_completed_episode(self, task: asyncio.Task) -> None:
|
||||
"""Emit every dispatched episode exactly once to ``out_q``."""
|
||||
async def handle_completed_request(self, task: asyncio.Task) -> None:
|
||||
"""Emit the terminal result of one dispatched environment request."""
|
||||
meta = self.inflight.pop(task, None)
|
||||
if meta is None:
|
||||
return # already handled by drop_group / cancel_inflight_episodes
|
||||
self.release(refund_admission=True)
|
||||
group = self.groups.get(meta.group_id)
|
||||
|
||||
is_synth_exception = False
|
||||
try:
|
||||
episode: vf.WireEpisode = task.result()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Episode task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[
|
||||
vf.Error(
|
||||
get_logger().warning(f"Environment request failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
policy_version = self.complete_group_member(meta, group)
|
||||
await self.out_q.put(
|
||||
DispatchFailure(
|
||||
kind=meta.kind,
|
||||
env_name=meta.env_name,
|
||||
group_id=str(meta.group_id),
|
||||
step=meta.step,
|
||||
policy_version=policy_version,
|
||||
task_type=type(meta.task).__name__,
|
||||
task_key=meta.task.key,
|
||||
task_hash=meta.task.hash,
|
||||
error=vf.Error(
|
||||
type=type(exc).__name__,
|
||||
message=str(exc),
|
||||
traceback="".join(traceback.format_exception(exc)),
|
||||
)
|
||||
],
|
||||
),
|
||||
)
|
||||
)
|
||||
is_synth_exception = True
|
||||
return
|
||||
|
||||
if not episode.traces and episode.ok:
|
||||
episode.ok = False
|
||||
@@ -603,19 +614,29 @@ class Dispatcher:
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if trace.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and trace.last_error is not None:
|
||||
if trace.last_error is not None:
|
||||
get_logger().warning(
|
||||
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{trace.last_error.type}: {trace.last_error.message}"
|
||||
)
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
|
||||
if self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(
|
||||
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
|
||||
)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
|
||||
"""Advance group accounting and return the attempt's pinned policy version."""
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
return policy_version
|
||||
|
||||
async def emit_episode(
|
||||
self,
|
||||
meta: InflightEpisode,
|
||||
@@ -624,12 +645,7 @@ class Dispatcher:
|
||||
) -> None:
|
||||
"""Stamp one completed episode with its dispatch provenance and emit it."""
|
||||
_validate_episode_task(episode, meta.task)
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
policy_version = self.complete_group_member(meta, group)
|
||||
|
||||
episode.env.name = meta.env_name
|
||||
episode.group = vf.GroupInfo(id=str(meta.group_id))
|
||||
@@ -656,7 +672,7 @@ class Dispatcher:
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
# the dropped tasks are no longer reachable from ``self.inflight``,
|
||||
# so ``handle_completed_episode``'s existing None-guard makes the
|
||||
# so ``handle_completed_request``'s existing None-guard makes the
|
||||
# subsequent async emit phase race-free.
|
||||
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
|
||||
for task, meta in list(self.inflight.items()):
|
||||
@@ -678,7 +694,7 @@ class Dispatcher:
|
||||
env_name = group.env_name if group is not None else claimed[-1][1].env_name
|
||||
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
|
||||
get_logger().debug(
|
||||
f"drop {kind} | group={str(group_id)[:8]} env={env_name} reason={reason} | "
|
||||
f"Dropped {kind} group | group={str(group_id)[:8]} env={env_name} reason={reason} | "
|
||||
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
|
||||
)
|
||||
await self.out_q.put(
|
||||
@@ -686,6 +702,7 @@ class Dispatcher:
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
group_id=str(group_id),
|
||||
step=group.step if group is not None else claimed[-1][1].step,
|
||||
count=cancelled,
|
||||
reason=reason,
|
||||
)
|
||||
@@ -729,6 +746,40 @@ class Dispatcher:
|
||||
await safe_cancel_all(train_tasks)
|
||||
return cancelled
|
||||
|
||||
async def cancel_eval_step(self, step: int) -> int:
|
||||
"""Cancel queued and active eval groups for a superseded checkpoint.
|
||||
|
||||
Scheduling remains paused until ``on_new_version`` runs after the
|
||||
replacement weights are live.
|
||||
"""
|
||||
if self.eval_source is None or self.eval_envs is None:
|
||||
return 0
|
||||
|
||||
self.policy_update_pending = True
|
||||
async with self.scheduling_lock:
|
||||
queued = self.eval_source.cancel_step(step)
|
||||
group_ids = [gid for gid, group in self.groups.items() if group.kind == "eval" and group.step == step]
|
||||
|
||||
cancelled = 0
|
||||
for group_id in group_ids:
|
||||
cancelled += await self.drop_group(group_id, reason="superseded")
|
||||
|
||||
for request in queued:
|
||||
count = self.eval_envs.get(request.env_name).config.group_size
|
||||
cancelled += count
|
||||
self.metrics.record_cancellation(kind="eval", env_name=request.env_name, n=count)
|
||||
await self.out_q.put(
|
||||
GroupCancellation(
|
||||
kind="eval",
|
||||
env_name=request.env_name,
|
||||
group_id=str(uuid.uuid4()),
|
||||
step=request.step,
|
||||
count=count,
|
||||
reason="superseded",
|
||||
)
|
||||
)
|
||||
return cancelled
|
||||
|
||||
# ── metrics ────────────────────────────────────────────────────────────
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
|
||||
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Iterator, Sequence
|
||||
from itertools import islice
|
||||
from typing import Generic, TypeVar
|
||||
@@ -30,7 +31,7 @@ from verifiers.v1.serve import EnvClient
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
# servers concurrently with the orchestrator, and a server imports its env package
|
||||
@@ -68,6 +69,7 @@ class Env:
|
||||
async def start(self) -> None:
|
||||
"""Connect to the env server and load the taskset client-side."""
|
||||
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
|
||||
t0 = time.perf_counter()
|
||||
self._env_client = EnvClient(address=self.address)
|
||||
# The server may still be coming up (the launcher spawns it concurrently with
|
||||
# the orchestrator), so poll until it answers.
|
||||
@@ -82,7 +84,7 @@ class Env:
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks}")
|
||||
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
@@ -177,6 +179,13 @@ class Envs(Generic[EnvT]):
|
||||
async def start(self) -> None:
|
||||
"""Connect to all env servers in parallel — every address is known up front,
|
||||
so there's nothing to serialize on."""
|
||||
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
|
||||
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
|
||||
# `AttributeError: type object 'tqdm' has no attribute '_lock'`. Pre-seed the lock so it
|
||||
# isn't created-and-deleted per call.
|
||||
from datasets.utils import tqdm as hf_tqdm
|
||||
|
||||
hf_tqdm.set_lock(hf_tqdm.get_lock())
|
||||
await asyncio.gather(*(env.start() for env in self))
|
||||
|
||||
|
||||
@@ -190,17 +199,18 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
configs: Sequence[TrainSourceConfig],
|
||||
addresses: dict[tuple[str, str], str],
|
||||
*,
|
||||
policy_pool,
|
||||
clients,
|
||||
renderer_config=None,
|
||||
):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
|
||||
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
GenerationSource(config.algo.sampling, clients, renderer_config),
|
||||
build_algorithm(config.algo, clients),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
from prime_rl.orchestrator.types import EvalBatch
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -19,7 +19,11 @@ class EvalSink:
|
||||
def __init__(self, *, eval_envs: EvalEnvs) -> None:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
|
||||
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -28,12 +32,54 @@ class EvalSink:
|
||||
bkey = (env_name, eval_step)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) >= self.group_size_for(env_name):
|
||||
if self._group_size(group_id) >= self.group_size_for(env_name):
|
||||
self.process_group(group_id)
|
||||
if len(self.pending_batches[bkey]) >= self.batch_size_for(env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def fail(self, failure: DispatchFailure) -> EvalBatch | None:
|
||||
"""Count a request failure toward its group and eval epoch without
|
||||
manufacturing a verifier episode."""
|
||||
if failure.kind != "eval":
|
||||
raise ValueError(f"EvalSink cannot process a {failure.kind} dispatch failure")
|
||||
group_id = failure.group_id
|
||||
bkey = (failure.env_name, failure.step)
|
||||
self.pending_group_failures[group_id].append(failure)
|
||||
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def cancel(self, cancellation: GroupCancellation) -> EvalBatch | None:
|
||||
"""Count a dispatcher-cancelled group toward its superseded eval epoch."""
|
||||
if cancellation.kind != "eval":
|
||||
raise ValueError(f"EvalSink cannot process a {cancellation.kind} group cancellation")
|
||||
group_id = cancellation.group_id
|
||||
bkey = (cancellation.env_name, cancellation.step)
|
||||
self.pending_group_cancellations[group_id] = cancellation
|
||||
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def _group_size(self, group_id: str) -> int:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
return (
|
||||
len(self.pending_groups[group_id])
|
||||
+ len(self.pending_group_failures[group_id])
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
|
||||
def _batch_size(self, key: tuple[str, int]) -> int:
|
||||
return (
|
||||
len(self.pending_batches[key])
|
||||
+ len(self.pending_batch_failures[key])
|
||||
+ self.pending_batch_cancellations[key]
|
||||
)
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
|
||||
@@ -42,15 +88,32 @@ class EvalSink:
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
|
||||
batch_counts = {key: len(runs) for key, runs in self.pending_batches.items()}
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures) | set(self.pending_batch_cancellations)
|
||||
batch_counts = {key: self._batch_size(key) for key in keys}
|
||||
buffered: dict[tuple[str, int], int] = {}
|
||||
for group in self.pending_groups.values():
|
||||
if not group:
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures) | set(self.pending_group_cancellations)
|
||||
for group_id in group_ids:
|
||||
group = self.pending_groups[group_id]
|
||||
failures = self.pending_group_failures[group_id]
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
if not group and not failures and cancellation is None:
|
||||
continue
|
||||
episode = group[0]
|
||||
eval_step = eval_work(episode).step
|
||||
key = (episode_env_name(episode), eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group)
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
buffered[key] = (
|
||||
buffered.get(key, 0)
|
||||
+ len(group)
|
||||
+ len(failures)
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
return [
|
||||
(
|
||||
env_name,
|
||||
@@ -64,12 +127,24 @@ class EvalSink:
|
||||
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and not failures and cancellation is None:
|
||||
return
|
||||
episode = group[0]
|
||||
env_name = episode_env_name(episode)
|
||||
eval_step = eval_work(episode).step
|
||||
self.pending_batches[(env_name, eval_step)].extend(group)
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
self.pending_batches[key].extend(group)
|
||||
self.pending_batch_failures[key].extend(failures)
|
||||
if cancellation is not None:
|
||||
self.pending_batch_cancellations[key] += cancellation.count
|
||||
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for trace in traces if not trace.has_error]
|
||||
@@ -79,15 +154,20 @@ class EvalSink:
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} "
|
||||
f"eval_step={eval_step} | episodes={len(group)} traces={len(traces)} "
|
||||
f"(errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
|
||||
f"cancelled={cancellation.count if cancellation is not None else 0} "
|
||||
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
failures = self.pending_batch_failures.pop(key, [])
|
||||
cancelled = self.pending_batch_cancellations.pop(key, 0)
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
failures=failures,
|
||||
cancelled=cancelled,
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
|
||||
|
||||
The orchestrator pokes ``trigger(step)`` after each ship + once at
|
||||
startup; the dispatcher pulls via ``next_task()`` until
|
||||
The policy watcher calls ``trigger(step)`` after each applied policy,
|
||||
including startup. The dispatcher pulls via ``next_task()`` until
|
||||
``bool(source) == False``. Constructed only when eval is configured."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -37,8 +37,8 @@ class EvalSource:
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
|
||||
# On resume we skip the startup eval; on fresh start the first
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
@@ -71,6 +71,12 @@ class EvalSource:
|
||||
return None
|
||||
return self.queue.popleft()
|
||||
|
||||
def cancel_step(self, step: int) -> list[TaskRequest]:
|
||||
"""Remove and return queued examples for a superseded eval step."""
|
||||
cancelled = [request for request in self.queue if request.step == step]
|
||||
self.queue = deque(request for request in self.queue if request.step != step)
|
||||
return cancelled
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self.queue)
|
||||
|
||||
|
||||
@@ -5,38 +5,36 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
|
||||
from prime_rl.orchestrator.algo import connect_frozen_pool
|
||||
from prime_rl.orchestrator.algo import connect_frozen_client
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference pool.
|
||||
"""One env's generation model and inference clients.
|
||||
|
||||
``pool`` is the pool train rollouts are generated from: the policy pool,
|
||||
swapped for a connected frozen pool in :meth:`setup` when the source is an
|
||||
inline frozen model. A frozen source *generates* rollouts, so its pool uses
|
||||
``clients`` is what train rollouts are generated from: the policy clients,
|
||||
swapped for a connected frozen endpoint in :meth:`setup` when the source is
|
||||
an inline frozen model. A frozen source *generates* rollouts, so it uses
|
||||
the renderer (token-in/out) client (built from ``renderer_config``) — the
|
||||
rollout must carry tokens for training."""
|
||||
|
||||
def __init__(
|
||||
self, config: SamplingConfig, policy_pool: InferencePool, renderer_config: RendererConfig | None = None
|
||||
):
|
||||
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
|
||||
assert config.source is not None, "sampling.source must be resolved by config validation"
|
||||
self.config = config
|
||||
self.pool: InferencePool = policy_pool
|
||||
self.clients: InferenceClient = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
|
||||
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect a client pool to a frozen generation source and wait for
|
||||
"""Connect clients to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected_pools.append(self.pool)
|
||||
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected = self.clients
|
||||
|
||||
@property
|
||||
def uses_live_policy(self) -> bool:
|
||||
|
||||
@@ -7,10 +7,10 @@ from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from statistics import mean, median
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.orchestrator.concurrency import EngineLoadSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -279,7 +279,7 @@ class InferenceMetricsCollector:
|
||||
admin_clients: list[AsyncClient],
|
||||
roles: list[str | None] | None = None,
|
||||
on_load: Callable[[list[EngineLoadSample]], None] | None = None,
|
||||
log_to_wandb: bool = True,
|
||||
log_metrics: bool = True,
|
||||
):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
|
||||
@@ -287,16 +287,13 @@ class InferenceMetricsCollector:
|
||||
self.task: asyncio.Task | None = None
|
||||
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
|
||||
self.on_load = on_load
|
||||
self.log_to_wandb = log_to_wandb
|
||||
self.log_metrics = log_metrics
|
||||
get_logger().info(
|
||||
"Collecting inference metrics from "
|
||||
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
if self.log_to_wandb:
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
|
||||
async def poll_loop():
|
||||
while True:
|
||||
try:
|
||||
@@ -346,7 +343,7 @@ class InferenceMetricsCollector:
|
||||
return
|
||||
|
||||
await asyncio.gather(*[self.fetch_max_model_len(endpoint) for endpoint in self.endpoints])
|
||||
metrics = self.build_metrics(samples) if self.log_to_wandb else {}
|
||||
metrics = self.build_metrics(samples) if self.log_metrics else {}
|
||||
load_samples = [self.build_load_sample(sample) for sample in samples]
|
||||
for sample in samples:
|
||||
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
|
||||
@@ -355,8 +352,10 @@ class InferenceMetricsCollector:
|
||||
self.on_load(load_samples)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
# Time-keyed rows (step=None): inference metrics are sampled on wall
|
||||
# time, not the training step. Fans out to every registered monitor;
|
||||
# each monitor stamps its own timestamp.
|
||||
await monitors.log(metrics, step=None)
|
||||
|
||||
async def fetch_max_model_len(self, endpoint: MetricsEndpoint) -> None:
|
||||
"""Cache the engine's max context length from ``/v1/models`` (set
|
||||
|
||||
@@ -9,11 +9,25 @@ from typing import Any, Literal
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable, scalar_advantage
|
||||
from prime_rl.orchestrator.types import DispatchFailure
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics, episode_env_name, episode_group_id
|
||||
|
||||
Subset = Literal["all", "effective"]
|
||||
|
||||
|
||||
def dispatch_failure_metrics(failures: list[DispatchFailure], *, prefix: str, total_attempts: int) -> dict[str, float]:
|
||||
"""Metrics for requests that failed outside the verifier episode boundary."""
|
||||
if total_attempts == 0:
|
||||
return {}
|
||||
out = {f"{prefix}/dispatch_failure/mean": len(failures) / total_attempts}
|
||||
error_types = [failure.error.type for failure in failures]
|
||||
out |= {
|
||||
f"{prefix}/dispatch_failure/{error_type}": float(error_types.count(error_type))
|
||||
for error_type in sorted(set(error_types))
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TraceRecord:
|
||||
"""A trace joined with its episode and training selection state.
|
||||
@@ -317,8 +331,7 @@ class EpisodeMetrics:
|
||||
def cancelled(self) -> Stat:
|
||||
"""Per-episode pipeline-cancellation rate — same denominator as
|
||||
``has_error``. Read from the id-set, not the trace records, so
|
||||
trace-less episodes (synthetic error episodes inside a voided group)
|
||||
still count."""
|
||||
trace-less episodes still count."""
|
||||
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
|
||||
@@ -26,29 +26,26 @@ import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.orchestrator.ckpt import CheckpointManager
|
||||
from prime_rl.transports.rollouts.base import MicroBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.transports.batch.base import BatchSender
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
@@ -58,6 +55,7 @@ from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
DispatchFailure,
|
||||
EvalBatch,
|
||||
GroupCancellation,
|
||||
Policy,
|
||||
@@ -68,24 +66,19 @@ from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
episode_staleness,
|
||||
eval_work,
|
||||
get_weight_dir,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
setup_policy_inference_pool,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transports.rollouts import setup_micro_batch_sender
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transports.batch import setup_batch_sender
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
resolve_latest_ckpt_step,
|
||||
)
|
||||
from prime_rl.utils.pathing import get_broadcast_dir
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
@@ -124,8 +117,9 @@ class Orchestrator:
|
||||
|
||||
# Always set by ``setup()``
|
||||
tokenizer: PreTrainedTokenizer
|
||||
policy_inference: InferencePool
|
||||
sender: MicroBatchSender | None
|
||||
clients: InferenceClient | None
|
||||
admin_clients: AdminClients | None
|
||||
sender: BatchSender | None
|
||||
packer: BatchPacker
|
||||
train_envs: TrainEnvs
|
||||
train_source: TrainSource
|
||||
@@ -137,14 +131,12 @@ class Orchestrator:
|
||||
periodic_logger: PeriodicLogger
|
||||
|
||||
# Set by ``setup()`` only when relevant config is present
|
||||
renderer: Renderer | None
|
||||
mm_token_type_ids_mapping: dict[int, int] | None
|
||||
heart: Heartbeat | None
|
||||
inference_metrics: InferenceMetricsCollector | None
|
||||
eval_envs: EvalEnvs | None
|
||||
eval_sink: EvalSink | None
|
||||
eval_source: EvalSource | None
|
||||
lora_name: str | None
|
||||
receiver: WeightReceiver
|
||||
resume_step: int | None
|
||||
lag_task: asyncio.Task | None
|
||||
|
||||
@@ -154,8 +146,7 @@ class Orchestrator:
|
||||
# Route the in-process v1 library logging through our handler. The
|
||||
# env server runs in a child process, so its logging is separate.
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
|
||||
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
|
||||
get_logger().info("Starting orchestrator")
|
||||
|
||||
self.progress = Progress()
|
||||
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
|
||||
@@ -171,24 +162,26 @@ class Orchestrator:
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
|
||||
# Pulsed after inference applies a policy so held work can re-check it.
|
||||
self.version_advanced = asyncio.Event()
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.eval_triggered_steps: set[int] = set()
|
||||
self.component_tasks = []
|
||||
|
||||
# Always assigned by ``setup()``; None-initialized so teardown can run
|
||||
# on a partially completed setup with plain attribute checks
|
||||
self.clients = None
|
||||
self.admin_clients = None
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
# config is present
|
||||
self.renderer = None
|
||||
self.mm_token_type_ids_mapping = None
|
||||
self.heart = None
|
||||
self.inference_metrics = None
|
||||
self.eval_envs = None
|
||||
self.eval_sink = None
|
||||
self.eval_source = None
|
||||
self.lora_name = None
|
||||
self.resume_step = None
|
||||
self.lag_task = None
|
||||
self.model_express = None
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -199,25 +192,25 @@ class Orchestrator:
|
||||
set_default_executor()
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
t0 = time.perf_counter()
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
get_logger().debug(f"Initialized tokenizer in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# The one model prime-rl hosts: the live policy. Frozen model
|
||||
# references are external endpoints — each env's Algorithm builds its
|
||||
# own pools in ``setup()`` below.
|
||||
get_logger().info(
|
||||
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
|
||||
get_logger().info(f"Initializing policy inference pool ({config.model})")
|
||||
self.clients = InferenceClient(
|
||||
config.model.client,
|
||||
model_name=config.model.name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
self.renderer, self.policy_inference = await setup_policy_inference_pool(
|
||||
config=config, tokenizer=self.tokenizer
|
||||
)
|
||||
self.mm_token_type_ids_mapping = (
|
||||
getattr(self.renderer, "mm_token_type_id_map", None) if self.renderer is not None else None
|
||||
)
|
||||
if self.mm_token_type_ids_mapping == {}:
|
||||
self.mm_token_type_ids_mapping = None
|
||||
self.admin_clients = AdminClients(config.model.client)
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="orch",
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
@@ -237,25 +230,14 @@ class Orchestrator:
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source,
|
||||
config.env_addresses,
|
||||
policy_pool=self.policy_inference,
|
||||
clients=self.clients,
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
get_logger().debug(
|
||||
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
|
||||
)
|
||||
await self.train_envs.start()
|
||||
get_logger().success("Train environment(s) ready")
|
||||
|
||||
if config.eval is not None:
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
|
||||
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
|
||||
await self.eval_envs.start()
|
||||
get_logger().success("Eval environment(s) ready")
|
||||
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
@@ -266,11 +248,49 @@ class Orchestrator:
|
||||
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
|
||||
|
||||
# Resume below may bump ``policy.version`` and the LoRA model name
|
||||
self.policy.model_name = self.policy_inference.model_name
|
||||
self.policy.model_name = self.clients.model_name
|
||||
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
|
||||
# themselves are restored below, once the envs are loaded.
|
||||
if self.resume_step is not None:
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming from step {self.resume_step}")
|
||||
else:
|
||||
get_logger().info("Starting from scratch")
|
||||
|
||||
# Transports are local setup — initialize them before the env and inference waits.
|
||||
self.packer = BatchPacker(config)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
|
||||
# Wait phase: envs, then inference, then the trainer's startup broadcast —
|
||||
# the last things before the main loop starts.
|
||||
get_logger().info(f"Loading train environments ({', '.join(self.train_envs.names)})")
|
||||
t0 = time.perf_counter()
|
||||
await self.train_envs.start()
|
||||
get_logger().success(f"Train environments ready in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
if self.eval_envs is not None:
|
||||
get_logger().info(f"Loading eval environments ({', '.join(self.eval_envs.names)})")
|
||||
t0 = time.perf_counter()
|
||||
await self.eval_envs.start()
|
||||
get_logger().success(f"Eval environments ready in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
if self.resume_step is not None:
|
||||
resume = self.config.resume
|
||||
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
|
||||
self.progress.step = self.resume_step + 1
|
||||
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
await self.policy_inference.wait_for_ready(config.model.name)
|
||||
get_logger().success("Policy inference pool ready")
|
||||
t0 = time.perf_counter()
|
||||
await self.admin_clients.wait_for_ready(config.model.name)
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
@@ -279,89 +299,27 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif config.weight_broadcast.type == "nixl":
|
||||
await init_nixl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
config.weight_broadcast.inference_world_size,
|
||||
config.weight_broadcast.session_id,
|
||||
)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
session_id=config.weight_broadcast.session_id,
|
||||
worker_id="orchestrator",
|
||||
)
|
||||
self.model_express.publish()
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
self.lora_name = config.model.lora.name if config.model.lora else None
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
|
||||
if self.resume_step is not None:
|
||||
resume = self.config.resume
|
||||
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
self.packer = BatchPacker(config)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
t0 = time.perf_counter()
|
||||
# A LoRA run's adapter is registered under the base model name: the
|
||||
# single adapter shadows it (vLLM resolves lora_requests before the
|
||||
# base-model match), so requests keep addressing one stable name.
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
admin_clients=self.admin_clients.clients,
|
||||
model_name=config.model.name,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, rendezvousing
|
||||
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
|
||||
# scratch).
|
||||
# scratch). The startup broadcast is always coming, so wait for it rather
|
||||
# than failing immediately when it is not there yet.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
check_exists = config.weight_broadcast.type == "filesystem"
|
||||
# The trainer's startup broadcast is always coming, so wait for it
|
||||
# rather than failing immediately when the directory is not there yet.
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
# Complete the startup rendezvous before the watcher begins its next cycle.
|
||||
await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=config.weight_broadcast.timeout,
|
||||
)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
wait_timeout = (config.ckpt.wait_for_weights_timeout if config.ckpt else None) or (
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
)
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -382,7 +340,7 @@ class Orchestrator:
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=self.train_source,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.policy_inference,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=self.progress,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
@@ -399,20 +357,21 @@ class Orchestrator:
|
||||
on_overload=self.dispatcher.cancel_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor (the collector logs
|
||||
# to the global W&B session, which only exists when init succeeded).
|
||||
# metrics fan out to every registered monitor when collection is on.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
|
||||
log_metrics=config.collect_inference_metrics,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
# One awaited scrape so the concurrency controller derives (and logs) its
|
||||
# initial limit before the loop-start line; failures are tolerated.
|
||||
await self.inference_metrics.probe()
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
train_envs=self.train_envs,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
progress=self.progress,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
@@ -421,14 +380,14 @@ class Orchestrator:
|
||||
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
|
||||
self.watcher = WeightWatcher(
|
||||
config,
|
||||
self.receiver,
|
||||
policy=self.policy,
|
||||
inference=self.policy_inference,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.policy.version,
|
||||
model_express=self.model_express,
|
||||
observers=[self.dispatcher],
|
||||
ckpt_step=sync_version,
|
||||
)
|
||||
if self.eval_source is not None:
|
||||
self.watcher.on_update(self.trigger_eval)
|
||||
self.watcher.on_update(self.on_policy_update)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
self.lag_monitor = EventLoopLagMonitor()
|
||||
@@ -455,6 +414,11 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
await self.watcher.sync_startup(sync_version, timeout=wait_timeout)
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -474,14 +438,6 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
|
||||
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
|
||||
# interval-aligned evals at the checkpoint step (e.g. after a crash).
|
||||
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
|
||||
self.maybe_trigger_eval(self.resume_step)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
@@ -511,32 +467,25 @@ class Orchestrator:
|
||||
# first ship).
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
await self.stop()
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
get_logger().success("Orchestrator finished")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
get_logger().warning("Orchestrator cleanup complete (forced)")
|
||||
trim_process_memory()
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
|
||||
nothing samples from v{max_steps}, so it is never sent). An in-memory
|
||||
broadcast is a blocking collective — tearing down the watcher before
|
||||
the rendezvous would strand the trainer inside it."""
|
||||
config = self.config
|
||||
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
|
||||
async def wait_for_version(self, version: int, reason: str) -> None:
|
||||
"""Bounded wait until the watcher has applied v{version}."""
|
||||
if self.policy.version >= version:
|
||||
return
|
||||
final_version = config.max_steps - 1
|
||||
if self.policy.version >= final_version:
|
||||
return
|
||||
get_logger().info(f"Waiting for the trainer's final broadcast (v{final_version}) before shutdown")
|
||||
get_logger().info(f"Waiting for inference to apply policy v{version} {reason}")
|
||||
|
||||
async def wait() -> None:
|
||||
while self.policy.version < final_version:
|
||||
while self.policy.version < version:
|
||||
self.version_advanced.clear()
|
||||
if self.policy.version >= final_version:
|
||||
if self.policy.version >= version:
|
||||
return
|
||||
# A dead watcher can never deliver the broadcast — fail out
|
||||
# instead of idling until the timeout.
|
||||
@@ -546,18 +495,28 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
timeout = self.config.weight_broadcast.timeout
|
||||
try:
|
||||
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
|
||||
await asyncio.wait_for(wait(), timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
get_logger().warning(
|
||||
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
|
||||
"shutting down anyway"
|
||||
)
|
||||
get_logger().warning(f"Inference did not apply policy v{version} within {timeout}s — proceeding anyway")
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last broadcast. Every broadcast is a
|
||||
blocking rendezvous — tearing down the watcher before it would strand
|
||||
the trainer inside the handshake."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
await self.wait_for_version(self.config.max_steps, reason="before shutdown")
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume completed episodes and ``GroupCancellation`` events from the
|
||||
dispatcher and route them to the train / eval sink. The sinks return a
|
||||
finalized batch (or ``None``); we just dispatch on the result."""
|
||||
"""Consume dispatcher results and route them to the train / eval sink.
|
||||
|
||||
Native episodes are persisted as verifier artifacts. Dispatch failures
|
||||
and group cancellations remain internal accounting events.
|
||||
|
||||
The sinks return a finalized batch (or ``None``); we just dispatch on
|
||||
the result."""
|
||||
while not self.stopped.is_set():
|
||||
self._raise_if_component_stopped()
|
||||
if self.draining and self.dispatcher.is_idle:
|
||||
@@ -577,6 +536,17 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
if isinstance(item, DispatchFailure):
|
||||
if item.kind == "eval":
|
||||
assert self.eval_sink is not None
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
else:
|
||||
train_batch = await self.train_sink.fail(item)
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
episode = item
|
||||
|
||||
# Every completed rollout — errored, rejected, or never batched — lands in the
|
||||
@@ -659,16 +629,16 @@ class Orchestrator:
|
||||
f"({n_trainable / effective.num_traces:.1%}) — consider reviewing task difficulty"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
# Ship batch ``step`` only once inference has applied v{step-1-TARGET_LAG}.
|
||||
# Without this, fast envs fill batches from buffered rollouts and the
|
||||
# orchestrator races arbitrarily far ahead of the trainer. Always
|
||||
# satisfiable: the trainer broadcasts every version except v{max_steps},
|
||||
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
|
||||
# last rendezvous after the pipeline drains.
|
||||
# satisfiable: the trainer broadcasts every version, and
|
||||
# ``wait_for_final_broadcast`` keeps the watcher alive through the last
|
||||
# rendezvous after the pipeline drains.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
f"Holding batch {step} until the trainer publishes policy v{required_version} "
|
||||
f"Holding batch {step} until inference applies policy v{required_version} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
hold_start = time.perf_counter()
|
||||
@@ -700,6 +670,20 @@ class Orchestrator:
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
for env_name, env_pool in pool.by_env().items():
|
||||
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
|
||||
total_attempts = len(batch.episodes) + len(batch.failures)
|
||||
metrics |= dispatch_failure_metrics(batch.failures, prefix="train/agg/all", total_attempts=total_attempts)
|
||||
failures_by_env: dict[str, list[DispatchFailure]] = {}
|
||||
for failure in batch.failures:
|
||||
failures_by_env.setdefault(failure.env_name, []).append(failure)
|
||||
episodes_by_env = batch.episodes.by_env()
|
||||
for env_name in set(episodes_by_env) | set(failures_by_env):
|
||||
env_failures = failures_by_env.get(env_name, [])
|
||||
env_attempts = len(episodes_by_env.get(env_name, TrainEpisodes())) + len(env_failures)
|
||||
metrics |= dispatch_failure_metrics(
|
||||
env_failures,
|
||||
prefix=f"train/{env_name}/all",
|
||||
total_attempts=env_attempts,
|
||||
)
|
||||
|
||||
# Progress / timing / env-share accounting (assembled here, not in the metrics
|
||||
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
|
||||
@@ -709,7 +693,9 @@ class Orchestrator:
|
||||
num_input = sum(record.trace.num_input_tokens for record in effective.records)
|
||||
num_output = sum(record.trace.num_output_tokens for record in effective.records)
|
||||
num_rollouts = batch.episodes.num_traces
|
||||
num_unique_examples = len({episode_group_id(episode) for episode in batch.episodes})
|
||||
group_ids = {episode_group_id(episode) for episode in batch.episodes}
|
||||
group_ids.update(failure.group_id for failure in batch.failures)
|
||||
num_unique_examples = len(group_ids)
|
||||
metrics |= {
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/input_tokens": num_input,
|
||||
@@ -756,7 +742,8 @@ class Orchestrator:
|
||||
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
await self.wait_for_version(step, reason="before shutdown")
|
||||
# Drain right after shipping the final batch. Waiting for a further
|
||||
# batch to fill would burn inference on data that can never train —
|
||||
# and with a tight ``max_off_policy_steps`` it never fills at all (the
|
||||
@@ -776,14 +763,18 @@ class Orchestrator:
|
||||
f"train episode(s); any in-flight evals will complete)"
|
||||
)
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
async def trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
fires. No-op when eval is not configured."""
|
||||
if self.eval_source is None:
|
||||
if self.eval_source is None or step in self.eval_triggered_steps:
|
||||
return
|
||||
fired = self.eval_source.trigger(step)
|
||||
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
|
||||
return
|
||||
is_final = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
fired = self.eval_source.trigger(step, force=is_final)
|
||||
if not fired:
|
||||
return
|
||||
self.eval_triggered_steps.add(step)
|
||||
reason = f"eval was triggered at step {step}"
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=reason)
|
||||
now = time.perf_counter()
|
||||
@@ -863,10 +854,9 @@ class Orchestrator:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, not a rollout failure)."""
|
||||
``Error``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window. Over the
|
||||
shipped set they are 0/0/share-of-shipped by construction, so the window is the only scope
|
||||
where they carry signal. A cancellation is a pipeline decision, not a rollout failure."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -909,23 +899,21 @@ class Orchestrator:
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors."""
|
||||
if not batch.episodes:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
|
||||
if not batch.episodes and not batch.failures:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
# The non-errored subset is logged on epoch completion (multiple eval envs share the
|
||||
# step's trace file — each epoch appends its cohort once, and every record carries
|
||||
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
policy_spans = [eval_work(episode).policy for episode in batch.episodes]
|
||||
if any(span is None for span in policy_spans):
|
||||
raise ValueError(f"Eval {batch.env_name} step {batch.step} is missing policy provenance")
|
||||
policy_versions = {span.start for span in policy_spans if span is not None}
|
||||
policy_versions.update(failure.policy_version for failure in batch.failures)
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
get_logger().warning(
|
||||
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
|
||||
)
|
||||
# Episode metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
|
||||
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
|
||||
episodes = batch.episodes
|
||||
@@ -933,6 +921,12 @@ class Orchestrator:
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures)
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
@@ -943,7 +937,7 @@ class Orchestrator:
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Evaluated {batch.env_name} | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
@@ -980,31 +974,23 @@ class Orchestrator:
|
||||
if lead > TARGET_LAG:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
f"Pausing dispatcher until inference applies policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
|
||||
``policy.version`` already carries the new version, so wake a held ship."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.version_advanced.set()
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the weight update completed;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
async def on_policy_update(self, _step: int) -> None:
|
||||
"""Refresh policy-dependent state after inference applies new weights."""
|
||||
self.update_dispatch_gate()
|
||||
self.version_advanced.set()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Bounded best-effort teardown of all components. Has a global
|
||||
@@ -1012,10 +998,13 @@ class Orchestrator:
|
||||
training artifacts are already persisted before this is reached."""
|
||||
|
||||
async def teardown() -> None:
|
||||
get_logger().debug("Closing micro batch sender")
|
||||
self.sender.close()
|
||||
if self.dispatcher is not None:
|
||||
get_logger().debug("Stopping dispatcher")
|
||||
await self.dispatcher.stop()
|
||||
if self.watcher is not None:
|
||||
get_logger().debug("Stopping weight watcher")
|
||||
await self.watcher.stop()
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
@@ -1026,14 +1015,21 @@ class Orchestrator:
|
||||
await safe_cancel(task)
|
||||
self.component_tasks.clear()
|
||||
if self.inference_metrics is not None:
|
||||
get_logger().debug("Stopping inference metrics collector")
|
||||
await self.inference_metrics.stop()
|
||||
if getattr(self, "policy_inference", None) is not None:
|
||||
await self.policy_inference.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_clients is not None:
|
||||
await self.admin_clients.aclose()
|
||||
if self.train_envs is not None:
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
for clients in (env.generation_source.connected, env.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
|
||||
get_logger().info("Stopping orchestrator components")
|
||||
t0 = time.perf_counter()
|
||||
task = asyncio.create_task(teardown())
|
||||
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
|
||||
if pending:
|
||||
@@ -1043,6 +1039,7 @@ class Orchestrator:
|
||||
)
|
||||
os._exit(0)
|
||||
await task
|
||||
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@clean_exit
|
||||
|
||||
@@ -2,7 +2,7 @@ from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user