Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5ed9fb7e4 | ||
|
|
b4a41d3f2c | ||
|
|
d7339fcf25 | ||
|
|
c394c2e1bd | ||
|
|
0d372c1fd6 | ||
|
|
9f4eef81a3 | ||
|
|
1d9ab255eb | ||
|
|
eff12f2483 | ||
|
|
e0886c152d | ||
|
|
9ef21a64f1 | ||
|
|
1e7c6888b6 | ||
|
|
815d1c0cad | ||
|
|
28bb83bea7 | ||
|
|
534888b77d | ||
|
|
43b4e2bd13 | ||
|
|
550beb6f43 | ||
|
|
bad80b1a30 | ||
|
|
aa3a6522b4 | ||
|
|
3f0c2e3b5a | ||
|
|
6b0d9e504b | ||
|
|
751a235af8 | ||
|
|
daa72a91d8 | ||
|
|
dad79d1ce8 | ||
|
|
dd2dd5461b | ||
|
|
cea63f9ef3 | ||
|
|
6a360c3029 | ||
|
|
04a61d3b75 | ||
|
|
26b3131d27 | ||
|
|
ef9dea1781 | ||
|
|
6c7b1ef375 | ||
|
|
608c75c0af | ||
|
|
b28714289a | ||
|
|
903baaaa01 | ||
|
|
ae170acda1 | ||
|
|
c84068cf9e | ||
|
|
7ad1bb9123 | ||
|
|
5990b1b9ba | ||
|
|
ffb845c13c | ||
|
|
421198cb93 | ||
|
|
e3fdadedc5 | ||
|
|
84e7312f33 | ||
|
|
fe325ac460 | ||
|
|
0f22eeb862 | ||
|
|
1fbf0b47a4 | ||
|
|
799ac26258 | ||
|
|
d5b38216a5 | ||
|
|
f87ebcc239 | ||
|
|
866c3e1438 | ||
|
|
c176840626 | ||
|
|
bb0c103f08 | ||
|
|
3fc28ddfb3 | ||
|
|
eaad03b9df | ||
|
|
70117046ac | ||
|
|
b2c6fe9aec | ||
|
|
66e1c2cb07 | ||
|
|
26af0c49e6 | ||
|
|
fc12ef2c66 | ||
|
|
95734aa1dd | ||
|
|
0c58f007bc | ||
|
|
d09bf96dbe | ||
|
|
05967ffcd2 | ||
|
|
21a4a32450 | ||
|
|
a070beecbd | ||
|
|
7da7c4d108 | ||
|
|
9e3be00b39 | ||
|
|
ef66401434 |
@@ -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"
|
||||
@@ -87,6 +87,9 @@ jobs:
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
Beautiful is better than ugly.
|
||||
@@ -42,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
|
||||
## Skills
|
||||
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
|
||||
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
|
||||
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
+40
-26
@@ -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 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 \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,9 +132,9 @@ 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 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 \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
@@ -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,14 @@ 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
|
||||
|
||||
# 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/
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -203,24 +198,43 @@ RUN apt-get update && apt-get install -y \
|
||||
libibverbs1 \
|
||||
ibverbs-providers \
|
||||
librdmacm1 \
|
||||
libhwloc15 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& 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
|
||||
# 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. Run directly in this stage (not a separate one COPY'd in after):
|
||||
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
|
||||
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
|
||||
# actually links against -- copying only /opt/amazon out of an isolated
|
||||
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
|
||||
# with whatever older rdma-core this image's own apt install pulled in and
|
||||
# fails to load (symbol version mismatch on libefa.so.1). --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.
|
||||
ARG EFA_INSTALLER_VERSION=1.47.0
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
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/*
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
|
||||
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
|
||||
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
|
||||
|
||||
|
||||
@@ -204,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
|
||||
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
|
||||
## Docs
|
||||
|
||||
@@ -215,7 +212,8 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
|
||||
|
||||
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
|
||||
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
|
||||
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
|
||||
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
|
||||
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
|
||||
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
|
||||
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
|
||||
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
|
||||
|
||||
+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()
|
||||
@@ -23,6 +23,7 @@ import torch
|
||||
from pydantic import Field
|
||||
|
||||
from prime_rl.utils.config import BaseConfig, cli
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
MAX_LORAS = 4
|
||||
|
||||
@@ -70,11 +71,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 +156,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")
|
||||
|
||||
@@ -214,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
|
||||
|
||||
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
|
||||
merge the lines per step, drop the first (warmup) step, and compute
|
||||
mean/std/min/max per metric like the old --bench JSON export did.
|
||||
mean/std/min/max per metric like the old --bench JSON export did. Rows
|
||||
keyed by wall time rather than step (``step: null``) are not per-step and
|
||||
are skipped.
|
||||
"""
|
||||
per_step: dict[int, dict] = {}
|
||||
with open(metrics_path) as f:
|
||||
for line in f:
|
||||
row = json.loads(line)
|
||||
per_step.setdefault(row["step"], {}).update(row)
|
||||
if row.get("step") is not None:
|
||||
per_step.setdefault(row["step"], {}).update(row)
|
||||
|
||||
steps = sorted(per_step)[1:] # Exclude first warmup step
|
||||
columns = {
|
||||
@@ -262,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
|
||||
return
|
||||
|
||||
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
|
||||
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
|
||||
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
|
||||
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
|
||||
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
|
||||
+12
-5
@@ -6,13 +6,20 @@ Configurations for running prime-rl.
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source). Not
|
||||
guaranteed functional or up to date.
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source), and
|
||||
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
|
||||
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
|
||||
Not guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run eval @ configs/debug/eval/<shape>.toml
|
||||
```
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
|
||||
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
|
||||
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
|
||||
#
|
||||
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
|
||||
#
|
||||
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
|
||||
# confirm a coherent response before trusting the model for a real run.
|
||||
#
|
||||
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
|
||||
|
||||
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
|
||||
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
|
||||
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
|
||||
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
|
||||
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
|
||||
use_deep_gemm = true
|
||||
|
||||
[server]
|
||||
port = 8000
|
||||
|
||||
[vllm]
|
||||
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 8192
|
||||
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
|
||||
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
|
||||
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
|
||||
# recipe sets it on every vendor and every architecture.
|
||||
kv_cache_dtype = "fp8"
|
||||
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
|
||||
# the fp8 KV cache with this block size.
|
||||
block_size = 256
|
||||
@@ -0,0 +1,62 @@
|
||||
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
|
||||
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
|
||||
# node, and so no weight broadcast. Tested on 8xH200.
|
||||
#
|
||||
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
|
||||
#
|
||||
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
|
||||
#
|
||||
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
|
||||
# conversion cache, which takes far longer than the 3600s default.
|
||||
#
|
||||
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
|
||||
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
|
||||
# already the default here.
|
||||
#
|
||||
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
|
||||
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
|
||||
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
|
||||
|
||||
dist_timeout_seconds = 14400
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
impl = "custom"
|
||||
ep = 8
|
||||
|
||||
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
|
||||
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
|
||||
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
|
||||
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
|
||||
# nodes against the same weights and conversion cache this config trains on.
|
||||
[model.moe.dispatch]
|
||||
type = "torch"
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
seq_len = 2048
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
|
||||
[monitors.wandb]
|
||||
project = "deepseek-v4-flash"
|
||||
name = "deepseek-v4-flash-sft"
|
||||
|
||||
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "ds-v4-sft"
|
||||
partition = "all"
|
||||
+2
-4
@@ -22,8 +22,6 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -89,7 +87,7 @@ truncate_history_thinking = false
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -99,7 +97,7 @@ interval = 20
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
|
||||
# Prime Inference — the eval path end to end without a GPU or sandbox.
|
||||
num_examples = 4
|
||||
dashboard = false
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -0,0 +1,16 @@
|
||||
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
|
||||
# completion per rollout) against Prime Inference. The math tasksets forbid the
|
||||
# agent any network, and only the sandboxed runtimes enforce that policy, so the
|
||||
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
|
||||
# Competition math needs room to reason, so the completion budget is generous.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/aime2026.toml
|
||||
|
||||
group_size = 16
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime26"
|
||||
env.agent.harness.id = "null"
|
||||
@@ -0,0 +1,20 @@
|
||||
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
|
||||
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
|
||||
# a ten-minute budget, against Prime Inference on the default model. One env server
|
||||
# per source; the sources share the taskset, so each carries its own name.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-env.toml
|
||||
|
||||
num_examples = 16
|
||||
|
||||
[[source]]
|
||||
name = "tb2-bash"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 600
|
||||
|
||||
[[source]]
|
||||
name = "tb2-rlm"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.timeout.rollout = 600
|
||||
@@ -0,0 +1,12 @@
|
||||
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
|
||||
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
|
||||
# each, against Prime Inference on the default model.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-turn.toml
|
||||
|
||||
num_examples = 16
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,23 @@
|
||||
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
|
||||
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
|
||||
# episodes are restored from the trace stream and only the owed rollouts run.
|
||||
# Resuming a finished run restores everything and exits.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
|
||||
# <Ctrl-C partway>
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[concurrency]
|
||||
min_inflight = 2
|
||||
max_inflight = 2
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -0,0 +1,15 @@
|
||||
# Single env, single turn: gsm8k with the null harness (one chat completion per
|
||||
# task, no sandbox) against Prime Inference.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/single-turn.toml
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
|
||||
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/tb2.toml
|
||||
|
||||
group_size = 4
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.agent.retries.max_retries = 2
|
||||
env.agent.retries.include = ["ProviderError", "SandboxError"]
|
||||
@@ -1,6 +1,6 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
|
||||
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 26dafdc958...1f1e050ab0
Vendored
+1
-1
Submodule deps/prime-kernels updated: 2ceaf9eccb...3fb83eb7aa
Vendored
+1
-1
Submodule deps/renderers updated: cb82439137...f91c3e7061
Vendored
+1
-1
Submodule deps/verifiers updated: b2e4e81577...5a69fb4d25
+73
-11
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
|
||||
|
||||
- [Custom Modeling](#custom-modeling)
|
||||
- [Expert Parallelism Backends](#expert-parallelism-backends)
|
||||
- [Runtime Fusions](#runtime-fusions)
|
||||
- [Multimodal Training](#multimodal-training)
|
||||
- [Supported Families](#supported-families)
|
||||
- [Enabling VLM Mode](#enabling-vlm-mode)
|
||||
@@ -33,36 +34,97 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
|
||||
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
|
||||
| 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` | ❌ | ✅ |
|
||||
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
|
||||
| DeepSeek V4 | `deepseek-ai/DeepSeek-V4-Flash-0731` | ✅ | ✅ |
|
||||
|
||||
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.
|
||||
|
||||
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
|
||||
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
|
||||
|
||||
### 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"
|
||||
```
|
||||
|
||||
All MoE compute backends accept `apply_to`:
|
||||
|
||||
- `"all"` (default) applies the backend to all expert groups.
|
||||
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
|
||||
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
|
||||
|
||||
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
|
||||
|
||||
For example, this selects routed experts in Qwen3's first four model layers:
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.compute]
|
||||
type = "mxfp8"
|
||||
apply_to = [0, 1, 2, 3]
|
||||
```
|
||||
|
||||
Backend shape checks and token alignment apply only to the selected compute path.
|
||||
|
||||
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### 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.)
|
||||
|
||||
### Runtime Fusions
|
||||
|
||||
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
|
||||
|
||||
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
|
||||
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
|
||||
|
||||
```toml
|
||||
[trainer.model.fusions]
|
||||
enabled = ["gate_up", "qkv"] # [] disables
|
||||
```
|
||||
|
||||
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
|
||||
|
||||
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
|
||||
|
||||
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
|
||||
|
||||
## Multimodal Training
|
||||
|
||||
### Supported Families
|
||||
@@ -141,7 +203,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.
|
||||
|
||||
+48
-27
@@ -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)
|
||||
@@ -184,47 +184,66 @@ $$
|
||||
\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 optionally [IcePop](#icepop-loss) 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]`.
|
||||
|
||||
### IcePop Loss
|
||||
|
||||
IcePop is an opt-in RL loss that drops tokens whose trainer-to-inference
|
||||
importance ratio falls outside a fixed acceptance band, introduced to stabilize
|
||||
MoE RL in [Every Step Evolves: Scaling Reinforcement Learning for Trillion-Scale
|
||||
Mixture-of-Experts Reasoning Models](https://arxiv.org/abs/2510.18855). Accepted
|
||||
tokens retain the importance-weighted policy-gradient term, and there is no
|
||||
separate KL penalty:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\frac{1}{N}\sum_t
|
||||
\mathbb{1}\!\left(\alpha \le \frac{\pi(y_t)}{\mu(y_t)} \le \beta\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}.
|
||||
$$
|
||||
|
||||
Enable it explicitly:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "icepop"
|
||||
ratio_low = 0.2
|
||||
ratio_high = 5.0
|
||||
```
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `ratio_low` | 0.2 | Lower accepted trainer-to-inference probability ratio. |
|
||||
| `ratio_high` | 5.0 | Upper accepted trainer-to-inference probability ratio. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. |
|
||||
|
||||
### Custom Loss
|
||||
|
||||
@@ -424,7 +443,9 @@ demo_key = "demonstration"
|
||||
|
||||
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
|
||||
|
||||
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
|
||||
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
|
||||
|
||||
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
|
||||
|
||||
## Curricula
|
||||
|
||||
@@ -436,7 +457,7 @@ Three small implementations are included:
|
||||
|
||||
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
|
||||
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
|
||||
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
|
||||
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
|
||||
|
||||
```toml
|
||||
[orchestrator.train.source.curriculum.sampler]
|
||||
|
||||
+12
-6
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -171,7 +171,7 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
|
||||
|
||||
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
|
||||
|
||||
@@ -226,8 +226,8 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
|
||||
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
|
||||
|
||||
@@ -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/resolved/
|
||||
ls /tmp/reverse-dry/check/configs/latest/resolved/
|
||||
# rl.json trainer.json orchestrator.json inference.json
|
||||
```
|
||||
|
||||
Each per-process JSON 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/resolved/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.
|
||||
|
||||
+3
-3
@@ -141,12 +141,12 @@ In the PR that adds the new model, you also need to provide a table covering the
|
||||
|
||||
## Adding a Custom VLM Implementation
|
||||
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in `models/qwen3_5/` is the reference. The pieces, in dependency order:
|
||||
|
||||
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# Eval
|
||||
|
||||
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Launch](#launch)
|
||||
- [Configuration](#configuration)
|
||||
- [Resume](#resume)
|
||||
- [Monitors](#monitors)
|
||||
- [File](#file)
|
||||
- [Prime](#prime)
|
||||
- [Metrics](#metrics)
|
||||
|
||||
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
|
||||
|
||||
## Launch
|
||||
|
||||
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B
|
||||
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
|
||||
```
|
||||
|
||||
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
|
||||
|
||||
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
|
||||
|
||||
## Configuration
|
||||
|
||||
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[concurrency] # adaptive against a local vLLM deployment
|
||||
min_inflight = 8
|
||||
max_inflight = 256
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
|
||||
## Resume
|
||||
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
|
||||
|
||||
```bash
|
||||
uv run eval @ eval.toml --run.name my-eval
|
||||
# <interrupted>
|
||||
uv run eval @ eval.toml --run.name my-eval --resume
|
||||
```
|
||||
|
||||
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
|
||||
|
||||
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
|
||||
## Monitors
|
||||
|
||||
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
|
||||
|
||||
### File
|
||||
|
||||
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
|
||||
|
||||
The dashboard's metrics tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red.
|
||||
|
||||
### Prime
|
||||
|
||||
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
|
||||
```
|
||||
|
||||
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
|
||||
|
||||
## Metrics
|
||||
|
||||
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|
||||
|
||||
| Metric | Reading |
|
||||
|---|---|
|
||||
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
|
||||
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
|
||||
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
|
||||
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
|
||||
|
||||
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
|
||||
+17
-1
@@ -285,7 +285,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -298,3 +298,19 @@ enable_return_routed_experts = true
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
|
||||
### Sampling Replay
|
||||
|
||||
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
|
||||
|
||||
```toml
|
||||
[orchestrator.train.sampling]
|
||||
top_p = 0.95
|
||||
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
|
||||
```
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"overview",
|
||||
"configuration",
|
||||
"training",
|
||||
"eval",
|
||||
"inference",
|
||||
"scaling",
|
||||
"algorithms",
|
||||
|
||||
+36
-11
@@ -99,17 +99,20 @@ 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
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all, is rejected at setup.
|
||||
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
@@ -127,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
|
||||
|
||||
@@ -217,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
|
||||
```
|
||||
|
||||
@@ -225,11 +232,29 @@ gpus_per_node = 8
|
||||
|
||||
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
|
||||
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
|
||||
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:
|
||||
@@ -252,4 +277,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
uv run trainer @ train.toml --data.fake --max-steps 4
|
||||
```
|
||||
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
|
||||
+29
-17
@@ -1,6 +1,6 @@
|
||||
# Training
|
||||
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
|
||||
|
||||
@@ -37,7 +37,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -58,6 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| Knob | What it does |
|
||||
|---|---|
|
||||
| `orchestrator.batch_size` | Tasks per trainer step. |
|
||||
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
|
||||
| `orchestrator.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
@@ -81,7 +83,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `--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 configs to `<run_dir>/configs/resolved/`, 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 +127,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):
|
||||
@@ -133,7 +135,9 @@ Pulled from the console logs and mirrored to W&B.
|
||||
| Source | Metric | Reading |
|
||||
|---|---|---|
|
||||
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
|
||||
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
|
||||
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
|
||||
|
||||
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
|
||||
|
||||
## SFT Trainer
|
||||
|
||||
@@ -198,17 +202,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 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 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 online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (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 online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
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 + online evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -217,7 +221,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 online-eval 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`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -313,6 +317,13 @@ The exported directory loads directly into `uv run inference --vllm.model <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`):
|
||||
@@ -321,6 +332,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
|
||||
├── eval.log # `uv run eval` process, or the SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -331,25 +343,25 @@ 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,eval,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
|
||||
```
|
||||
|
||||
### Dashboard
|
||||
|
||||
`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.
|
||||
`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 the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. 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.
|
||||
|
||||
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
|
||||
|
||||
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
|
||||
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --monitors.wandb # default project, random name
|
||||
@@ -376,9 +388,9 @@ Or set it in TOML:
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
|
||||
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
|
||||
|
||||
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
|
||||
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
|
||||
|
||||
## Rules of Thumb
|
||||
|
||||
|
||||
+33
-12
@@ -2,16 +2,37 @@
|
||||
|
||||
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
|
||||
|
||||
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
|
||||
optional SFT warmup → RL → eval), each with its own README:
|
||||
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- `alphabet-sort` — multi-turn, user simulator, LoRA
|
||||
- `wiki-search` — multi-turn tool calling, LoRA
|
||||
- `wordle` — multi-turn (~6-turn games)
|
||||
- `hendrycks-sanity` — single-turn math, long-running
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
`intellect-3.1` (swe).
|
||||
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
|
||||
|
||||
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
## advanced/ — frontier models, multi-node
|
||||
|
||||
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
|
||||
|
||||
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.2/`](advanced/glm-5.2/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
## basic/ — 1 to 8 GPUs
|
||||
|
||||
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
|
||||
|
||||
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
|
||||
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
|
||||
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
|
||||
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
|
||||
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
|
||||
|
||||
## extra/ — beyond the core loop
|
||||
|
||||
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
|
||||
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
|
||||
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# GLM-4.5-Air
|
||||
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0).
|
||||
|
||||
| Config | Trains on | Evals on | Topology |
|
||||
|---|---|---|---|
|
||||
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run (`<run_name>` from the launch) and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -25,8 +25,6 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -100,7 +98,7 @@ name = "openseeker"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "openseeker"
|
||||
|
||||
@@ -124,7 +122,7 @@ name = "redsearcher"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
@@ -154,7 +152,7 @@ num_examples = 500 # full set is 1266; cap eval at 500
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "browsecomp"
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
|
||||
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
|
||||
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
|
||||
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
|
||||
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe
|
||||
# model, which supports routed_experts. Optimizer state is checkpointed so runs can resume.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
|
||||
# group's own max before the GRPO baseline subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
|
||||
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
|
||||
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
|
||||
# Concurrency is fully default: the controller derives its start from the measured KV budget and
|
||||
# adapts from there.
|
||||
|
||||
@@ -31,16 +32,14 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 3
|
||||
num_infer_replicas = 4
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -65,9 +64,6 @@ impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
@@ -76,11 +72,8 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
@@ -130,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -26,8 +26,6 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -96,7 +94,7 @@ num_turns_weight = 0.1
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.taskset.id = "tmax"
|
||||
|
||||
@@ -123,7 +121,7 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
@@ -144,7 +142,7 @@ env.taskset.id = "swebench-verified"
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.harness.compaction.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`swe.toml`](swe.toml) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
|
||||
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` (llm-d variant) accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in — it ships with prime-rl's dependencies:
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
|
||||
- `WANDB_API_KEY` — both RL configs log to W&B (`[monitors.wandb]`).
|
||||
|
||||
### Install llm-d (llmd variants only)
|
||||
|
||||
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
|
||||
- `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
|
||||
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
# GLM-5.1 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
|
||||
|
||||
# GLM-5 base plane — compose your train source onto it
|
||||
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.toml
|
||||
```
|
||||
|
||||
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
|
||||
|
||||
```bash
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
```
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint and resume
|
||||
|
||||
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
@@ -84,7 +84,6 @@ partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
enable_token_export = true
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
@@ -97,6 +96,9 @@ ep = 8
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "deepgemm_fp8"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Qwen3-30B-A3B
|
||||
|
||||
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
|
||||
|
||||
| Config | Trains on | Evals on | Runtime | Topology |
|
||||
|---|---|---|---|---|
|
||||
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
|
||||
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
|
||||
|
||||
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, log the `prime` CLI in (it ships with prime-rl's dependencies):
|
||||
|
||||
```bash
|
||||
uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
|
||||
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
|
||||
|
||||
```bash
|
||||
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
|
||||
```
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
|
||||
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math
|
||||
```
|
||||
|
||||
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -39,14 +39,7 @@ uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
|
||||
Evaluate the base model:
|
||||
```bash
|
||||
# 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 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 768 \
|
||||
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
```
|
||||
|
||||
We got an **average reward of ~0.26** across 20×3 rollouts. The model achieves **0% perfect attempts** (no rollouts score 1.0) and **0% perfect examples** (no examples have all 3 rollouts at 1.0). The model shows high variance and struggles on most examples, with the high similarity power (8) heavily penalizing even small errors, and the scores aren't different for most attempts.
|
||||
@@ -113,14 +106,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
|
||||
|
||||
```bash
|
||||
# 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 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 768 \
|
||||
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/alphabet-sort/eval.toml -m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
```
|
||||
|
||||
Way better! Our model now gets an **average reward of ~0.81** with **73% perfect attempts** (44/60 rollouts score 1.0) and **65% perfect examples** (13/20 examples have all 3 rollouts at 1.0).
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Evaluate a model on alphabet-sort against a local inference server
|
||||
# (`uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507`).
|
||||
# Override the model with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -27,7 +27,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
|
||||
```bash
|
||||
# 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
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
```
|
||||
|
||||
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
|
||||
@@ -94,7 +94,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
|
||||
```bash
|
||||
# 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
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
```
|
||||
|
||||
Way better! Now we get an **average reward of ~0.8**.
|
||||
@@ -197,10 +197,9 @@ kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval reverse-text --harness.id null \
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL \
|
||||
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
--client.base-url $INFERENCE_URL
|
||||
```
|
||||
|
||||
### Clean Up
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on reverse-text against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-0.6B`). Override the model
|
||||
# with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-0.6B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -21,6 +21,19 @@ env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
num_examples = 256
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
|
||||
@@ -77,13 +77,7 @@ Evaluate the base model:
|
||||
|
||||
```bash
|
||||
# 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 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 512 \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
```
|
||||
|
||||
## RL Training
|
||||
@@ -116,13 +110,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
|
||||
|
||||
```bash
|
||||
# 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 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 512 \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/wiki-search/eval.toml -m <user>/Qwen3-4B-Instruct-WikiSearch-RL
|
||||
```
|
||||
|
||||
## Taskset Configuration
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on wiki-search against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes`).
|
||||
# Override the model with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[source]]
|
||||
name = "wiki-search"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
|
||||
|
||||
```bash
|
||||
# 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
|
||||
uv run eval @ examples/basic/wordle/eval.toml
|
||||
```
|
||||
|
||||
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
|
||||
@@ -97,7 +97,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
|
||||
```bash
|
||||
# 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
|
||||
uv run eval @ examples/basic/wordle/eval.toml -m PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
```
|
||||
|
||||
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on wordle against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-1.7B`). Override the model
|
||||
# with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/wordle/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-1.7B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[source]]
|
||||
name = "wordle"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
@@ -1,32 +0,0 @@
|
||||
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
|
||||
# against DeepSeek V4 Flash on Prime Inference.
|
||||
#
|
||||
# export PRIME_API_KEY=<your Prime Inference key>
|
||||
# uv run evals @ examples/evals/swe.toml
|
||||
#
|
||||
# The tasksets run in prime sandboxes (the default runtime), so the key also
|
||||
# authenticates sandbox creation. External API endpoints expose no vLLM
|
||||
# /metrics, so adaptive concurrency has no load signal - the band must be
|
||||
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
|
||||
|
||||
model = "deepseek/deepseek-v4-flash"
|
||||
|
||||
[eval.client]
|
||||
base_url = "https://api.pinference.ai/api/v1"
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[eval.concurrency]
|
||||
min_inflight = 32
|
||||
max_inflight = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[[eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,73 @@
|
||||
# Dynamo RL
|
||||
|
||||
This example runs five steps of GRPO training on the Hendrycks math environment with `Qwen/Qwen3-0.6B`, one trainer GPU, one external Dynamo inference worker, and NCCL weight transfer.
|
||||
|
||||
Prime-RL does not launch Dynamo from this configuration. Run the frontend, worker, and trainer as separate processes. This example requires two GPUs: GPU 0 for Prime-RL training and GPU 1 for Dynamo inference.
|
||||
|
||||
## Start Dynamo
|
||||
|
||||
Install Dynamo with its vLLM backend and activate its environment. Then start the RL-enabled frontend in the first terminal:
|
||||
|
||||
```bash
|
||||
DYN_HTTP_HOST=127.0.0.1 DYN_ENABLE_RL=true DYN_RL_PORT=8001 python -m dynamo.frontend
|
||||
```
|
||||
|
||||
Start the RL-enabled vLLM worker on GPU 1 in a second terminal:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 DYN_SYSTEM_HOST=127.0.0.1 DYN_SYSTEM_PORT=8081 python -m dynamo.vllm \
|
||||
--model Qwen/Qwen3-0.6B \
|
||||
--enable-rl
|
||||
```
|
||||
|
||||
The `--enable-rl` flag enables worker discovery and the administration routes used for NCCL weight updates. Keep GPU 0 out of `CUDA_VISIBLE_DEVICES` for this process so it remains available to the Prime-RL trainer.
|
||||
|
||||
These commands bind the HTTP, discovery, and worker administration endpoints to loopback. If Prime-RL and Dynamo run on different hosts, expose these endpoints only on a trusted control network; configured client headers are also sent to the discovery endpoint.
|
||||
|
||||
## Endpoint contract
|
||||
|
||||
The default configuration expects:
|
||||
|
||||
- The Dynamo OpenAI-compatible frontend at `http://127.0.0.1:8000/v1`.
|
||||
- The Dynamo RL discovery endpoint at `http://127.0.0.1:8001/v1/rl/workers`.
|
||||
- Exactly one discovered worker for `Qwen/Qwen3-0.6B` with an admin URL and `world_size = 1`.
|
||||
- A vLLM worker with the Prime-RL NCCL weight-update extension enabled.
|
||||
|
||||
Verify both endpoints before starting training:
|
||||
|
||||
```bash
|
||||
curl --fail http://127.0.0.1:8000/v1/models
|
||||
curl --fail http://127.0.0.1:8001/v1/rl/workers
|
||||
```
|
||||
|
||||
## Discovery URL
|
||||
|
||||
The example enables Dynamo with:
|
||||
|
||||
```toml
|
||||
[orchestrator.model.client]
|
||||
base_url = "http://127.0.0.1:8000/v1"
|
||||
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
```
|
||||
|
||||
When `discovery_url` is omitted, Prime-RL removes the path from `base_url` and increments its explicit non-default port by one. Here, `http://127.0.0.1:8000/v1` becomes `http://127.0.0.1:8001`.
|
||||
|
||||
If your Dynamo frontend and discovery service do not use adjacent ports, configure the discovery endpoint explicitly:
|
||||
|
||||
```toml
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
discovery_url = "http://dynamo.example:9000"
|
||||
```
|
||||
|
||||
## Run training
|
||||
|
||||
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/extra/dynamo/rl.toml
|
||||
```
|
||||
|
||||
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
|
||||
@@ -0,0 +1,40 @@
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 32
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator.model.client]
|
||||
base_url = "http://127.0.0.1:8000/v1"
|
||||
|
||||
[orchestrator.model.client.dynamo]
|
||||
enabled = true
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
enable_thinking = false
|
||||
@@ -0,0 +1,22 @@
|
||||
# VLM SFT
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
|
||||
|
||||
## Run it
|
||||
|
||||
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/extra/vlm/sft.toml
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
|
||||
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
|
||||
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
|
||||
@@ -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"
|
||||
@@ -37,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
system = false
|
||||
user = false
|
||||
assistant = true
|
||||
tool = false
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -29,5 +29,8 @@ batch_size = 1
|
||||
micro_batch_size = 1
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.10",
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Algorithm abstraction: sampling and the per-token training signal.
|
||||
|
||||
An algorithm is a named, self-contained config — a discriminated union keyed
|
||||
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
|
||||
on ``type`` (``grpo``, ``max_rl``, ``rae``, ``hierarchical_grpo``, ``opd``,
|
||||
``opsd``, ``sft``, ``echo``, ``debug``).
|
||||
The bundle *is* the algorithm: each variant carries
|
||||
its sampling component and its credit-assignment / loss-routing parameters,
|
||||
and its class defaults are the vetted setting — ``type = "opd"`` with a
|
||||
@@ -364,6 +365,32 @@ class SFTAlgoConfig(BaseAlgoConfig):
|
||||
return self
|
||||
|
||||
|
||||
class DebugAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["debug"] = "debug"
|
||||
"""Debugging algorithm for infra work: every sampled token of every clean
|
||||
trainable trace gets the same constant ``advantage`` (default 1.0),
|
||||
ignoring rewards entirely. Every admitted rollout is trainable and every
|
||||
action token carries gradient signal, so the full RL path (advantage
|
||||
transport, importance ratios, trust region, optimizer, weight update)
|
||||
can be exercised regardless of the reward function. Not a real training
|
||||
signal — a policy pushed by it drifts monotonically."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
advantage: float = Field(1.0, allow_inf_nan=False)
|
||||
"""The constant per-token advantage. Must be nonzero: a zero advantage
|
||||
makes nothing trainable, the exact failure this debug tool exists to
|
||||
rule out."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_nonzero_advantage(self):
|
||||
if self.advantage == 0.0:
|
||||
raise ValueError(
|
||||
"the 'debug' algorithm needs a nonzero advantage — a zero advantage leaves nothing trainable."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
AlgoConfig: TypeAlias = Annotated[
|
||||
GRPOAlgoConfig
|
||||
| EchoAlgoConfig
|
||||
@@ -372,7 +399,8 @@ AlgoConfig: TypeAlias = Annotated[
|
||||
| HierarchicalGRPOAlgoConfig
|
||||
| OPDAlgoConfig
|
||||
| OPSDAlgoConfig
|
||||
| SFTAlgoConfig,
|
||||
| SFTAlgoConfig
|
||||
| DebugAlgoConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""The training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -387,6 +415,8 @@ its class defaults are the vetted setting.
|
||||
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
|
||||
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
|
||||
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
|
||||
- ``debug`` — the same constant advantage on every sampled token, ignoring
|
||||
rewards. Debugging only: for infra work that needs every token trainable.
|
||||
|
||||
A new credit-assignment scheme is a new named algorithm in code (subclass
|
||||
``Algorithm``, register it), not a config that points at an import path.
|
||||
|
||||
@@ -9,8 +9,8 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
|
||||
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
|
||||
set to the source's derived address."""
|
||||
The launchers write one of these per train/eval source they manage, with
|
||||
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
@@ -18,6 +18,11 @@ class EnvServerConfig(BaseConfig):
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
address_file: Path | None = None
|
||||
"""Publish the bound address to this file once serving. Set by the launchers for the
|
||||
servers they spawn, so the address never has to be agreed on up front (``serve.address``
|
||||
unset binds an OS-assigned port)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
|
||||
is an externally managed server; None means the launcher spawns the server and the
|
||||
eval learns its address from the file it publishes."""
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
|
||||
``prime login``) with the concurrency pinned at 128."""
|
||||
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
|
||||
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
|
||||
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
|
||||
let the band adapt to KV usage like the orchestrator's."""
|
||||
|
||||
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (traces, logs,
|
||||
checkpoints) 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. Required to
|
||||
overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Resolve and write the config, then exit without evaluating."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Start (or reuse) the local dashboard daemon and print its URL."""
|
||||
|
||||
resume: bool = False
|
||||
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
|
||||
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
|
||||
sampling and env config must match the interrupted run; ``num_examples`` and
|
||||
``group_size`` may change."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<envs>--<model>--<short-id>``) when unset and
|
||||
default the run directory, W&B run name and platform evaluation name to it."""
|
||||
if self.run.name is None:
|
||||
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source))
|
||||
model = self.model.split("/")[-1]
|
||||
self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
|
||||
self.monitors.wandb.name = self.run.name
|
||||
if self.monitors.prime is not None and self.monitors.prime.name is None:
|
||||
self.monitors.prime.name = self.run.name
|
||||
return self
|
||||
|
||||
|
||||
class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
|
||||
"""The ``[eval]`` block of the ``sft`` entrypoint, and the config of the online-eval
|
||||
process the launcher spawns from it: interval-driven eval sources against the inference
|
||||
server that receives the trainer's weight broadcasts. The process watches the
|
||||
broadcasts directory, moves the inference server onto each broadcast, and runs the
|
||||
due sources against the updated weights. The launcher fills the run-level fields
|
||||
(``model``, ``weight_broadcast``, ``broadcasts_dir``, ``max_steps``, ``resume_step``,
|
||||
``output_dir``, ``log``, ``monitors``) from the resolved SFT config."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""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."""
|
||||
|
||||
model: str | None = None
|
||||
"""Name the inference server serves the model under. The name stays fixed across
|
||||
weight updates (weights are swapped in place), so per-step results are told apart by
|
||||
``eval/{env}/policy_version``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport. None reloads weights from the filesystem broadcasts."""
|
||||
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every eval
|
||||
env, and the process exits after processing it. If None, runs until terminated."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
|
||||
skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.broadcasts_dir is None:
|
||||
self.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
@@ -1,114 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
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, default_output_dir
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
|
||||
(sources, sampling, intervals) with the client of the inference deployment and
|
||||
evals-side knobs."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the inference server evals run against. Auto-wired from the
|
||||
``[inference]`` block when the launcher manages the server."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the eval source at position ``i`` is
|
||||
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
|
||||
keep it instead, without shifting the other sources' ports."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
|
||||
``serve.address`` are externally managed; the evals process spawns an env server at
|
||||
the derived address for every other source."""
|
||||
return {
|
||||
("eval", source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, source in enumerate(self.source)
|
||||
}
|
||||
|
||||
|
||||
class OnlineConfig(BaseConfig):
|
||||
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
|
||||
broadcasts and evaluate each eligible one. Without this block the evals process runs
|
||||
every eval source once against the weights the inference server currently serves,
|
||||
then exits."""
|
||||
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
eval env, and the evals process exits after processing it. If None, the evals process
|
||||
runs until terminated."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
|
||||
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
|
||||
this step."""
|
||||
|
||||
|
||||
class EvalsConfig(BaseConfig):
|
||||
"""``uv run evals``: run the configured evals against a live inference server.
|
||||
Standalone (no ``[online]``), one epoch of every eval source runs against the
|
||||
served weights and the evals process exits. With ``[online]``, the evals process watches a
|
||||
broadcasts directory for new weight broadcasts, updates the inference server through
|
||||
the configured transport, and runs the configured evals against the updated weights.
|
||||
The ``sft`` launcher writes this config; filesystem mode also works standalone against
|
||||
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""Name the inference server serves the model under — the ``model`` field of every
|
||||
eval request and the startup model check. Auto-filled from ``model.name`` by the
|
||||
``sft`` launcher; the name stays fixed across weight updates (weights are
|
||||
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
|
||||
|
||||
eval: EvalsEvalConfig
|
||||
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
|
||||
|
||||
online: OnlineConfig | None = None
|
||||
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
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. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.online is not None and self.online.broadcasts_dir is None:
|
||||
self.online.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_skip_first_step_is_online_only(self):
|
||||
"""``skip_first_step`` gates the base-model eval between checkpoints; a
|
||||
standalone run has only that one epoch, so skipping it would exit
|
||||
successfully without evaluating anything."""
|
||||
if self.online is None and self.eval.skip_first_step:
|
||||
raise ValueError(
|
||||
"eval.skip_first_step only applies to online evals - a standalone run "
|
||||
"would skip its only eval epoch. Remove it or add an [online] block."
|
||||
)
|
||||
return self
|
||||
@@ -220,7 +220,7 @@ class CPUOffloadTier(BaseConfig):
|
||||
|
||||
class DiskOffloadTier(BaseConfig):
|
||||
path: Path
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
|
||||
|
||||
class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
@@ -242,14 +242,14 @@ class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
|
||||
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["native"] = "native"
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
assert self.cpu is not None
|
||||
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
|
||||
if self.disk is not None:
|
||||
extra["spec_name"] = "TieringOffloadingSpec"
|
||||
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
|
||||
extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}]
|
||||
return {
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
@@ -458,11 +458,14 @@ class InferenceConfig(BaseConfig):
|
||||
use_pd_kv_transfer: bool = False
|
||||
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
|
||||
|
||||
enable_return_sampling_mask: bool = False
|
||||
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
|
||||
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""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
|
||||
|
||||
@@ -494,6 +497,20 @@ class InferenceConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_deployment(self):
|
||||
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
|
||||
@@ -607,6 +624,21 @@ 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
|
||||
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
@@ -616,8 +648,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
|
||||
|
||||
|
||||
@@ -25,14 +25,34 @@ class WandbMonitorConfig(BaseConfig):
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
path: Path = Path("metrics.jsonl")
|
||||
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
|
||||
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
|
||||
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
|
||||
|
||||
chunk_bytes: int = 5 * 1024**3
|
||||
"""Size at which a trace stream (the episodes, each producer's annotations) rolls to
|
||||
a new numbered chunk file. A line never spans chunks."""
|
||||
|
||||
compress: bool = True
|
||||
"""Seal full chunks with zstd once the stream rolls past them (the live chunk stays
|
||||
plain text). Sealed chunks use seekable frames: a reader still lands on one line,
|
||||
and ``zstd -dcf stream/* | jq`` reads a whole stream."""
|
||||
|
||||
float_decimals: int | None = 4
|
||||
"""Decimals kept for per-token float streams (logprobs, entropies, advantages) in
|
||||
trace and annotation records; ``None`` keeps every digit. Training reads the wire,
|
||||
not the records, so this only trades record size against overlay precision."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
class PrimeTrainMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class PrimeEvalMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Evaluation name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class MonitorsConfig(BaseConfig):
|
||||
wandb: WandbMonitorConfig | None = None
|
||||
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
|
||||
@@ -41,6 +61,11 @@ class MonitorsConfig(BaseConfig):
|
||||
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
|
||||
|
||||
|
||||
class OrchestratorMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
class TrainMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeTrainMonitorConfig | None = None
|
||||
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
|
||||
|
||||
|
||||
class EvalMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeEvalMonitorConfig | None = None
|
||||
"""Upload every eval source's finished epoch as an evaluation on the Prime Intellect platform. If None, disabled."""
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -9,7 +10,7 @@ from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
GRPOAlgoConfig,
|
||||
)
|
||||
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
@@ -45,6 +46,16 @@ class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
top_p: float = Field(1.0, gt=0, le=1.0)
|
||||
"""Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling
|
||||
distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and
|
||||
rollout distributions stay consistent — see docs/inference.md (Sampling Replay)."""
|
||||
|
||||
top_k: int | None = Field(None, ge=1)
|
||||
"""Top-k sampling for train rollouts. Truncation triggers sampling replay, and
|
||||
a default top-k is injected when only top-p truncates so sampling masks stay
|
||||
bounded — see docs/inference.md (Sampling Replay)."""
|
||||
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
|
||||
|
||||
@@ -53,18 +64,46 @@ class TrainSamplingConfig(BaseConfig):
|
||||
extra_body: dict[str, Any] = {}
|
||||
"""Extra body forwarded with each request to the inference server."""
|
||||
|
||||
def truncates_distribution(self) -> bool:
|
||||
return self.top_p < 1.0 or self.top_k is not None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_no_extra_body_truncation(self):
|
||||
"""Truncating values must come from the typed fields — the replay policy reads
|
||||
them. Disabled values pass so resolved configs (where ``resolve_env_config``
|
||||
stamped the ``top_k = -1`` / ``min_p = 0.0`` sentinels) re-validate cleanly."""
|
||||
smuggled = [
|
||||
key
|
||||
for key, truncates in (
|
||||
("top_p", self.extra_body.get("top_p", 1.0) < 1.0),
|
||||
("top_k", self.extra_body.get("top_k") not in (None, -1, 0)),
|
||||
("min_p", self.extra_body.get("min_p", 0.0) > 0.0),
|
||||
)
|
||||
if truncates
|
||||
]
|
||||
if smuggled:
|
||||
raise ValueError(
|
||||
f"extra_body carries truncating {smuggled}; set them as fields on the train "
|
||||
"sampling config instead (they drive sampling replay)."
|
||||
)
|
||||
return self
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict, omitting None values."""
|
||||
args: dict[str, Any] = {
|
||||
"temperature": self.temperature,
|
||||
"top_p": 1.0,
|
||||
"top_p": self.top_p,
|
||||
"logprobs": True,
|
||||
}
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
|
||||
if self.extra_body:
|
||||
args["extra_body"] = dict(self.extra_body)
|
||||
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
@@ -122,14 +161,11 @@ class EnvConfig(BaseConfig):
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
@@ -230,6 +266,9 @@ class TrainSourceConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
@@ -254,6 +293,10 @@ class EvalSourceConfig(EnvConfig):
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
|
||||
class OnlineEvalSourceConfig(EvalSourceConfig):
|
||||
"""An eval source of a training run: evaluated on a step interval."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
|
||||
|
||||
@@ -265,9 +308,6 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
filter_zero_advantages: bool = True
|
||||
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
@@ -292,7 +332,9 @@ class TrainConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
class EvalSourcesConfig(BaseConfig):
|
||||
"""Eval sources and the group-level defaults they inherit."""
|
||||
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
@@ -305,6 +347,49 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
|
||||
group_size (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
source.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_sources(self):
|
||||
if not self.source:
|
||||
raise ValueError(
|
||||
"At least one eval source is required. Add a source block "
|
||||
"(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [source.resolved_name for source in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class ScheduledEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources evaluated on a step interval next to training."""
|
||||
|
||||
source: list[OnlineEvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources, each with its own step interval."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
@@ -318,43 +403,22 @@ class EvalConfig(BaseConfig):
|
||||
exit where all evals already completed."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
def resolve_env_intervals(self):
|
||||
"""Per-env intervals inherit the group-level interval."""
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
source.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
if "interval" not in source.model_fields_set:
|
||||
source.interval = self.interval
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_sources(self):
|
||||
if not self.source:
|
||||
raise ValueError(
|
||||
"EvalConfig must define at least one source. Either drop the "
|
||||
"[orchestrator.eval] block entirely (to disable eval) or "
|
||||
"add a [[orchestrator.eval.source]] block."
|
||||
)
|
||||
return self
|
||||
@property
|
||||
def intervals(self) -> dict[str, int]:
|
||||
"""Step interval per eval env, by resolved name."""
|
||||
return {source.resolved_name: source.interval for source in self.source}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [source.resolved_name for source in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
|
||||
)
|
||||
return self
|
||||
|
||||
class RLOnlineEvalConfig(ScheduledEvalConfig):
|
||||
"""The ``[orchestrator.eval]`` block: online evals against the orchestrator's
|
||||
inference pool, on the policy the train rollouts see."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
@@ -408,6 +472,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,
|
||||
@@ -439,6 +506,15 @@ class ConcurrencyConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
# Top-k injected on truncated policy sampling that has none, and the hard upper
|
||||
# bound for explicit top-k. vLLM's native sampling-mask capture requires a
|
||||
# per-request top_k > 0 to bound mask sizes, and the trainer pads each micro
|
||||
# batch's masks to the largest sampling mask, so the bound also caps trainer
|
||||
# mask tensors. Large enough that a 0.95-0.99 nucleus rarely reaches it (the
|
||||
# sampling policy is essentially unchanged).
|
||||
TRAIN_TOP_K_BOUND = 512
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -462,7 +538,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
|
||||
client; SFT uses it to backfill tokens for its chat-completions teacher."""
|
||||
|
||||
eval: EvalConfig | None = None
|
||||
eval: RLOnlineEvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
@@ -470,7 +546,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
|
||||
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
@@ -497,12 +573,12 @@ class OrchestratorConfig(BaseConfig):
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
|
||||
constant_trainer_batch_size: bool = True
|
||||
"""Require each batch to reach its effective sample target."""
|
||||
|
||||
token_batch_size: int | None = Field(None, ge=1)
|
||||
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
|
||||
|
||||
@@ -565,6 +641,55 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_cfg.algo.validate_env(env_cfg.env)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def setup_truncated_sampling(self):
|
||||
"""Truncated policy sampling trains with sampling replay (rollout
|
||||
logprobs are renormalized — see docs/inference.md, Sampling Replay).
|
||||
Owned here: every truncating config gets a top-k bound (bounds the sampling
|
||||
masks); opd/opsd is rejected (full-vocab prefill refs would mix
|
||||
normalizations). Frozen-source envs sample externally and are exempt."""
|
||||
policy_samplings = [
|
||||
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
] or ([self.train.sampling] if not self.train.source else [])
|
||||
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
|
||||
if not truncating:
|
||||
return self
|
||||
|
||||
if any(sampling.temperature == 0 for sampling in truncating):
|
||||
raise ValueError(
|
||||
"Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has "
|
||||
"no truncated distribution to replay, and the inference server rejects such requests "
|
||||
"while sampling-mask capture is on."
|
||||
)
|
||||
|
||||
oversized = [sampling.top_k for sampling in truncating if (sampling.top_k or 0) > TRAIN_TOP_K_BOUND]
|
||||
if oversized:
|
||||
raise ValueError(
|
||||
f"Truncated train sampling with top_k = {max(oversized)} exceeds the sampling-replay "
|
||||
f"bound ({TRAIN_TOP_K_BOUND}): the trainer pads each micro batch's masks to the largest "
|
||||
f"sampling mask, so unbounded masks blow up trainer memory. Use top_k <= {TRAIN_TOP_K_BOUND}."
|
||||
)
|
||||
|
||||
unbounded = [sampling for sampling in truncating if sampling.top_k is None]
|
||||
if unbounded:
|
||||
warnings.warn(
|
||||
f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_BOUND} so every sampling mask is "
|
||||
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
|
||||
stacklevel=2,
|
||||
)
|
||||
for sampling in unbounded:
|
||||
sampling.top_k = TRAIN_TOP_K_BOUND
|
||||
|
||||
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
|
||||
if any(algo.type in ("opd", "opsd") for algo in algos):
|
||||
raise ValueError(
|
||||
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
|
||||
"prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the "
|
||||
"ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@property
|
||||
def any_policy_sourced(self) -> bool:
|
||||
"""True when at least one train env samples rollouts from the live policy."""
|
||||
@@ -643,6 +768,23 @@ class OrchestratorConfig(BaseConfig):
|
||||
env.sampling.extra_body.setdefault("return_token_ids", True)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_policy_top_k_consistency(self):
|
||||
"""Require one top-k capture mode across the live policy server."""
|
||||
policy_sources = [
|
||||
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
]
|
||||
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
|
||||
disabled = [env for env in policy_sources if env.sampling.top_k is None]
|
||||
if enabled and disabled:
|
||||
names = ", ".join(env.resolved_name for env in disabled)
|
||||
raise ValueError(
|
||||
"Live-policy train sources cannot mix top_k > 0 and top_k = -1 because "
|
||||
"sampling-mask capture is engine-wide. Set top_k > 0 for these sources: "
|
||||
f"{names}."
|
||||
)
|
||||
return self
|
||||
|
||||
@property
|
||||
def env_sources(self) -> list[tuple[str, EnvConfig]]:
|
||||
"""Every ``(split, source)`` this run pulls from, train first then eval — the
|
||||
@@ -653,15 +795,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
return sources
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
|
||||
the source's own ``serve.address`` when set (an externally managed server), else
|
||||
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
|
||||
``env_sources`` order. The launcher binds env servers at exactly these addresses
|
||||
and the orchestrator connects to them, so both sides agree from the config
|
||||
alone."""
|
||||
return {
|
||||
(split, source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, (split, source) in enumerate(self.env_sources)
|
||||
}
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
|
||||
source's own ``serve.address`` when set (an externally managed server), else None —
|
||||
the launcher spawns the server, which binds an OS-assigned port and publishes it
|
||||
to the source's address file for the orchestrator to pick up."""
|
||||
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
|
||||
|
||||
@@ -7,7 +7,7 @@ from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
@@ -100,9 +100,9 @@ class SharedMonitorsConfig(BaseConfig):
|
||||
"""Shared W&B config. Propagated to trainer and orchestrator."""
|
||||
|
||||
file: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
prime: PrimeTrainMonitorConfig | None = None
|
||||
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
|
||||
|
||||
|
||||
@@ -158,6 +158,9 @@ 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"
|
||||
@@ -490,7 +493,10 @@ 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)
|
||||
@@ -634,6 +640,53 @@ class RLConfig(BaseConfig):
|
||||
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_sampling_mask_capture(self):
|
||||
"""Truncated train sampling needs the inference server to return the sampling
|
||||
masks the trainer replays (OrchestratorConfig guarantees truncating
|
||||
configs are bounded by TRAIN_TOP_K_BOUND). Capture is engine-wide: while it is
|
||||
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
|
||||
so eval sampling against the same server must set both."""
|
||||
policy_samplings = [
|
||||
env.sampling
|
||||
for env in self.orchestrator.train.source
|
||||
if env.algo is not None and env.algo.sampling.source == "policy"
|
||||
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
|
||||
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
|
||||
return self
|
||||
if self.inference is None:
|
||||
warnings.warn(
|
||||
"Truncated train sampling with no managed inference server: set "
|
||||
"`enable_return_sampling_mask = true` on the standalone server's config so it "
|
||||
"returns the sampling masks the trainer replays.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
self.inference.enable_return_sampling_mask = True
|
||||
if self.orchestrator.eval is not None:
|
||||
warnings.warn(
|
||||
"Sampling-mask capture is engine-wide: eval requests without top_k > 0 (from the "
|
||||
"eval sampling config or the model's generation config) or with temperature 0 are "
|
||||
"rejected by the inference server while truncated train sampling is on.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
|
||||
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.evals import EvalsEvalConfig
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -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``."""
|
||||
@@ -204,7 +203,7 @@ class SFTConfig(BaseConfig):
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: EvalsEvalConfig | None = None
|
||||
eval: SFTOnlineEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
@@ -325,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).",
|
||||
@@ -394,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:
|
||||
@@ -426,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
|
||||
|
||||
@@ -438,7 +437,7 @@ class SFTConfig(BaseConfig):
|
||||
"Online evals are configured without an [inference] block - the launcher will not "
|
||||
f"start an inference server. Make sure one is running at eval.client.base_url "
|
||||
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
|
||||
"otherwise the evals process will hang waiting for it. If a router fronts the "
|
||||
"otherwise the online-eval process will hang waiting for it. If a router fronts the "
|
||||
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
|
||||
"(pause/update_weights/resume) must bypass the router.",
|
||||
stacklevel=2,
|
||||
|
||||
@@ -106,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."""
|
||||
|
||||
@@ -159,6 +162,14 @@ class BaseModelConfig(BaseConfig):
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
|
||||
class DynamoConfig(BaseConfig):
|
||||
enabled: bool = True
|
||||
"""Enable Dynamo worker discovery for the inference admin plane."""
|
||||
|
||||
discovery_url: str | None = Field(default=None, min_length=1, max_length=2048)
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
@@ -181,6 +192,9 @@ class ClientConfig(BaseConfig):
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
dynamo: DynamoConfig | None = None
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BeforeValidator, Field, model_validator
|
||||
from pydantic import BeforeValidator, Field, field_validator, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -21,7 +22,6 @@ 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):
|
||||
@@ -31,20 +31,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):
|
||||
@@ -93,6 +86,17 @@ class CompileConfig(BaseConfig):
|
||||
"""Compile transformer blocks with ``fullgraph=True``."""
|
||||
|
||||
|
||||
class FusionsConfig(BaseConfig):
|
||||
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
|
||||
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
|
||||
|
||||
raise_on_fail: bool = False
|
||||
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
|
||||
|
||||
shard_fused_on_dim1: bool = False
|
||||
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
|
||||
|
||||
|
||||
class IndexCacheConfig(BaseConfig):
|
||||
topk_freq: int = Field(1, ge=1)
|
||||
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
|
||||
@@ -123,7 +127,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``."""
|
||||
@@ -151,7 +155,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",
|
||||
@@ -161,21 +165,107 @@ _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 MoEComputeConfigBase(BaseConfig):
|
||||
apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all"
|
||||
"""Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``,
|
||||
or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction
|
||||
of model layers, rounded down. Other expert groups use BF16 compute and transport.
|
||||
"""
|
||||
|
||||
@field_validator("apply_to")
|
||||
@classmethod
|
||||
def validate_apply_to(cls, value: str | list[int]) -> str | list[int]:
|
||||
if isinstance(value, str) and value != "all":
|
||||
if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100:
|
||||
raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices')
|
||||
return value
|
||||
|
||||
def resolve_layers(self, num_layers: int) -> set[int]:
|
||||
if isinstance(self.apply_to, list):
|
||||
invalid = [index for index in self.apply_to if index >= num_layers]
|
||||
if invalid:
|
||||
raise ValueError(
|
||||
f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers"
|
||||
)
|
||||
return set(self.apply_to)
|
||||
count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100)
|
||||
return set(range(count))
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""Run routed-expert grouped GEMMs in bfloat16."""
|
||||
|
||||
type: Literal["bf16"] = "bf16"
|
||||
|
||||
|
||||
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
|
||||
|
||||
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
|
||||
|
||||
|
||||
class MXFP8MoEComputeConfig(MoEComputeConfigBase):
|
||||
"""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."""
|
||||
@@ -189,6 +279,9 @@ class ModelConfig(BaseModelConfig):
|
||||
compile: CompileConfig | None = CompileConfig()
|
||||
"""Compile the model with ``torch.compile``."""
|
||||
|
||||
fusions: FusionsConfig = FusionsConfig()
|
||||
"""Runtime parameter fusions, on by default."""
|
||||
|
||||
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
|
||||
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
|
||||
|
||||
@@ -213,14 +306,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."""
|
||||
@@ -240,12 +327,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
|
||||
@@ -301,12 +382,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):
|
||||
@@ -332,19 +407,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
|
||||
|
||||
|
||||
@@ -492,26 +566,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."""
|
||||
@@ -520,6 +578,25 @@ class IPOLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IcePopLossConfig(BaseConfig):
|
||||
type: Literal["icepop"] = "icepop"
|
||||
|
||||
ratio_low: float = Field(0.2, gt=0)
|
||||
"""Lower accepted trainer-to-inference probability ratio."""
|
||||
|
||||
ratio_high: float = Field(5.0, gt=0)
|
||||
"""Upper accepted trainer-to-inference probability ratio."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ratio_bounds(self):
|
||||
if self.ratio_low > self.ratio_high:
|
||||
raise ValueError("ratio_low must not exceed ratio_high")
|
||||
return self
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -530,7 +607,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -581,6 +658,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,
|
||||
@@ -595,7 +675,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()
|
||||
@@ -649,15 +729,12 @@ class TrainerConfig(BaseConfig):
|
||||
metrics_server: MetricsServerConfig | None = None
|
||||
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
|
||||
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
@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).",
|
||||
@@ -683,16 +760,6 @@ class TrainerConfig(BaseConfig):
|
||||
self.optim.max_norm = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlms_require_bfloat16(self):
|
||||
if self.model.vlm is not None and (
|
||||
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
|
||||
):
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_freeze_incompatible_with_lora(self):
|
||||
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
|
||||
|
||||
@@ -5,6 +5,7 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
|
||||
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
|
||||
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
|
||||
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
|
||||
@@ -25,6 +26,9 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
|
||||
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
|
||||
# V4 reasons inside <think> blocks, but vLLM only splits them out into `reasoning_content`
|
||||
# when this parser is set; the checkpoint ships no chat template, so nothing else supplies it.
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
|
||||
+79
-39
@@ -17,17 +17,20 @@ dependencies = [
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.6.19",
|
||||
"prime-runs[train]>=0.1.1",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"psutil>=7.0.0",
|
||||
"prometheus-client>=0.20.0",
|
||||
"pyzstd>=0.16.2",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"renderers>=0.1.10",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
@@ -40,7 +43,7 @@ sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
evals = "prime_rl.entrypoints.evals:main"
|
||||
eval = "prime_rl.entrypoints.eval:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
dashboard = "prime_rl.entrypoints.dashboard:main"
|
||||
|
||||
@@ -49,32 +52,35 @@ prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
gpu = [
|
||||
"torch>=2.9.0 ; sys_platform == 'linux'",
|
||||
"torch>=2.13.0 ; sys_platform == 'linux'",
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.26.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'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.17.0 ; 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 / cu128 / torch 2.11 / cp312 build and carry
|
||||
dynamo = ["ai-dynamo==1.4.2 ; sys_platform == 'linux'"]
|
||||
# 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 ; sys_platform == 'linux'"]
|
||||
|
||||
@@ -85,12 +91,9 @@ disagg = [
|
||||
"deep-ep ; sys_platform == 'linux'",
|
||||
"deep-gemm ; sys_platform == 'linux'",
|
||||
"nixl ; sys_platform == 'linux'",
|
||||
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
@@ -135,13 +138,19 @@ environments = [
|
||||
"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",
|
||||
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
|
||||
"tilelang==0.1.12",
|
||||
# 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",
|
||||
]
|
||||
|
||||
@@ -178,13 +187,39 @@ 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",
|
||||
]
|
||||
|
||||
# Mirror the upstream Pydantic compatibility correction until the next release.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "ai-dynamo-runtime"
|
||||
version = "1.4.2"
|
||||
requires-dist = [
|
||||
"pydantic>=2.10.6,<=2.13.5",
|
||||
"uvloop>=0.21.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,6 +234,8 @@ flash_attn_3 = false
|
||||
# appear in `uv tree` need to be listed; the resolver ignores entries for
|
||||
# packages it never sees.
|
||||
prime = false
|
||||
prime-runs = false
|
||||
prime-traces = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
@@ -210,7 +247,7 @@ vllm-router = false
|
||||
dion = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
|
||||
@@ -221,53 +258,56 @@ 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", marker = "sys_platform == 'linux'" }]
|
||||
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
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'" }
|
||||
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" }
|
||||
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 = "99e5f7e" }
|
||||
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" }
|
||||
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
mamba-ssm = ["torch>=2.13.0"]
|
||||
|
||||
[tool.uv.extra-build-variables]
|
||||
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]
|
||||
|
||||
@@ -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"
|
||||
@@ -98,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],
|
||||
),
|
||||
@@ -127,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
|
||||
@@ -173,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],
|
||||
|
||||
+9
-13
@@ -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.
|
||||
@@ -59,9 +63,9 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
|
||||
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
|
||||
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
@@ -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 = "icepop"` for ratio masking with `ratio_low = 0.2`, `ratio_high = 5.0`, and `adv_tau = 1.0`; IcePop has no separate KL term. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**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:
|
||||
@@ -80,16 +86,6 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
## Key files
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
|
||||
+20
-94
@@ -5,122 +5,48 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
|
||||
|
||||
# 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.
|
||||
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR`) serves a web UI at `http://localhost:7788`. It only reads run dirs, so it is safe against live runs and installs anywhere: GPU dependencies live behind the `gpu` extra.
|
||||
|
||||
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.
|
||||
What is not obvious from the UI:
|
||||
|
||||
## Isolated mode
|
||||
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
|
||||
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
|
||||
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
|
||||
- For an eval run the metrics tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
|
||||
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
|
||||
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
|
||||
|
||||
`--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.
|
||||
Every dashboard instance serves the dirs it was started with plus every dir in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`). Launchers register their output dir on every start and, in interactive sessions, auto-start a dashboard only when none is live; `--no-dashboard` opts a run out, non-interactive launches never spawn one. `--isolated` serves only the given dirs and ignores the registry.
|
||||
|
||||
## Finding the live dashboard
|
||||
## Finding, stopping, restarting
|
||||
|
||||
The live port can differ from 7788 (a taken port bumps to the next free one),
|
||||
so read the discovery file:
|
||||
The port can differ from 7788 (a taken port bumps to the next free one), so read the discovery file and hand the researcher its `url`; launcher logs also end with a `Dashboard · <url>` banner.
|
||||
|
||||
```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
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<port>"}
|
||||
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # stop; the next launch (or `uv run dashboard`) restarts it
|
||||
```
|
||||
|
||||
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`.
|
||||
Killing a dashboard never affects runs and killing a run never takes the dashboard down. The daemon serves the code of the checkout that started it (`readlink /proc/<pid>/cwd`): after switching branches or worktrees, kill it so the next launch restarts it on the current code. Its log is `~/.cache/prime-rl/dashboard/daemon.log`.
|
||||
|
||||
## Point the open dashboard
|
||||
|
||||
Use `POST /api/view` to show relevant run data in every connected dashboard
|
||||
tab:
|
||||
`POST /api/view` shows run data in every connected tab. `run` is required; the other fields leave unspecified state alone. For trace evidence pass `step`, `kind` and `subset` together and address the episode by its stable `id` (`subset: "effective"` narrows the traces tab to the cohort shipped at that step); `highlight` entries are `{node, quote, reason, field?}`. On `409`, tell the user to open the returned `url`.
|
||||
|
||||
```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"}]
|
||||
}'
|
||||
-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": "the 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.
|
||||
## Reports, only when asked
|
||||
|
||||
## 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:
|
||||
Write a requested report to `<run>/reports/<slug>.md`, then POST `{"run": ..., "tab": "report", "report": "<slug>"}`. Markdown with a frontmatter `title` (rendered as the H1, do not repeat it) and one-line JSON citations:
|
||||
|
||||
```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.
|
||||
A citation needs `step`, `kind`, `subset`, `episode` (the top-level record `id`, never `line` or a `traces[*].id`), an exact short `quote` (case-sensitive, whitespace-insensitive) and a one-sentence `note`; optional `trace`, `branch`, `node`, `field`, `prefix`, `suffix` disambiguate. Cite empirical and diagnostic claims, not routine explanation; one citation per passage. Only HTTP(S) and anchor links render. Before handing over, verify through the API that every citation resolves.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
name: eval
|
||||
description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint, its config and CLI shorthands, run directory, resume, logs and metrics. Use when asked to evaluate a model or checkpoint on an environment, smoke-test an environment, or check on an eval run.
|
||||
---
|
||||
|
||||
# Eval
|
||||
|
||||
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
|
||||
|
||||
## Start an eval
|
||||
|
||||
The user launches runs; hand over the command unless told otherwise. Always cap smokes (`-n`, `-r`).
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 # Prime Inference
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 --env.agent.harness.id bash # pin concurrency; set a field of the env block
|
||||
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1 # a local `uv run inference` server
|
||||
uv run eval @ eval.toml --run.name my-eval # multi-source TOML
|
||||
uv run eval @ eval.toml --run.name my-eval --resume # continue an interrupted run
|
||||
uv run eval @ eval.toml --dry-run # resolve and write the config, exit
|
||||
uv run eval @ eval.toml --monitors.prime # stream each source's epoch to the platform
|
||||
```
|
||||
|
||||
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
|
||||
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
|
||||
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
|
||||
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
|
||||
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
|
||||
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
## Monitor an eval
|
||||
|
||||
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
|
||||
|
||||
```
|
||||
{run_dir}/
|
||||
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
|
||||
├── logs/latest/
|
||||
│ ├── eval.log # the eval process
|
||||
│ └── envs/eval/{name}.log # one log per env server
|
||||
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
|
||||
```
|
||||
|
||||
```bash
|
||||
tail -F {run_dir}/logs/latest/eval.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/eval.log {run_dir}/logs/latest/envs/eval/*.log
|
||||
grep SUCCESS {run_dir}/logs/latest/eval.log # one "Evaluated <env> ... Reward 0.xxxx" line per source
|
||||
uv run python -m prime_rl.monitors.file.traces {run_dir} [<trace_id>] # live rollouts by phase, or one assembled live trace
|
||||
```
|
||||
|
||||
The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · running 3`). A rollout stuck in `boot` for minutes is waiting on its sandbox; one in `running` with a frozen turn count is waiting on a model call or tool.
|
||||
|
||||
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
|
||||
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
|
||||
+17
-6
@@ -59,20 +59,31 @@ See the `kernels` skill.
|
||||
### NemotronH (Mamba SSD kernels)
|
||||
|
||||
```bash
|
||||
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
uv sync --extra gpu
|
||||
```
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
|
||||
|
||||
### 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__)'`.
|
||||
|
||||
@@ -91,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.
|
||||
|
||||
@@ -10,4 +10,4 @@ Two phases — start the run, then watch it.
|
||||
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
|
||||
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
|
||||
|
||||
Both subskills assume the `configs` skill for config-loading mechanics.
|
||||
Both subskills assume the `configs` skill for config-loading mechanics. Standalone evals (`uv run eval`) are the `eval` skill; online evals of a training run are configured in `start-run` and read in `monitor-run`.
|
||||
|
||||
@@ -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/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). The launch TOML is copied verbatim to `{run_dir}/configs/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.
|
||||
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`.
|
||||
|
||||
@@ -48,17 +48,17 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
### Where to find things
|
||||
|
||||
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
|
||||
- `{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}/monitors/file/` — the metrics, and the traces with the annotations about them (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`), the resolved 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.
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
|
||||
files, a rollout trace viewer with per-token overlays (advantage, trainer logprob,
|
||||
entropy, KL mismatch, stable/loss/content masks), 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
|
||||
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
{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)
|
||||
├── eval.log # SFT online-eval process (also the `uv run eval` process — see the `eval` skill)
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -100,10 +100,14 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
|
||||
Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,eval,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
### Live rollouts
|
||||
|
||||
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
|
||||
|
||||
### Metrics
|
||||
|
||||
All metrics print to the console log (and W&B when configured).
|
||||
@@ -135,7 +139,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.
|
||||
@@ -152,6 +156,10 @@ All metrics print to the console log (and W&B when configured).
|
||||
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
|
||||
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
|
||||
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
|
||||
|
||||
`orchestrator.constant_trainer_batch_size` defaults to `true`. It keeps each rollout batch at `orchestrator.batch_size` effective episodes. Set it to `false` for faster collection with variable trainer batch sizes.
|
||||
|
||||
For live vLLM stats, query Prometheus directly:
|
||||
|
||||
```bash
|
||||
@@ -162,27 +170,52 @@ 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}/monitors/file/metrics.jsonl # every metric row, tagged by producer
|
||||
{run_dir}/monitors/file/traces/stream/00000.jsonl.zst # every episode, appended as it arrives: sealed chunks ...
|
||||
{run_dir}/monitors/file/traces/stream/00001.jsonl # ... and the live one, plain text
|
||||
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its chunk and byte offset
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}/00000.jsonl # trace updates: orch ship-time facts, trainer per-token streams
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
|
||||
```
|
||||
|
||||
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
|
||||
`all` gets every completed episode as it arrives — including trace-less failures,
|
||||
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
|
||||
`effective` contains the admitted clean trainable traces grouped into their original episodes
|
||||
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
|
||||
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
|
||||
and `run`. Training-run records discriminate train/eval work and include dispatch
|
||||
step plus an optional live-policy version span. Traces retain their own task,
|
||||
verifiers, agent, and runtime fields.
|
||||
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
|
||||
there when the monitor is off. The traces and everything written about them sit under
|
||||
`traces/`. Each stream is a directory of numbered chunks — the writer rolls to a new
|
||||
chunk at `monitors.file.chunk_bytes` (5 GiB) and, with `monitors.file.compress` (on),
|
||||
seals the full one with zstd in the background; a finished run seals its live chunk
|
||||
too. Sealed chunks use seekable frames, so a seek still costs one frame, and
|
||||
`zstd -dcf` streams them together with the plain live chunk. Every index is named for
|
||||
the stream it indexes and sits beside it. Those indexes are what keep reading a run
|
||||
cheap: a consumer browses them instead of the streams, and seeks by the chunk and
|
||||
offset they carry to read a single episode or its token streams. Both are derived, so
|
||||
deleting them only costs a reader the work of rebuilding what it needs. The stream
|
||||
holds native `vf.Episode` records (training tensors excluded; per-token floats rounded
|
||||
to `monitors.file.float_decimals`, 4 by default), one line per episode in arrival order, whatever kind of work it did —
|
||||
including trace-less failures, curriculum-rejected work, and work that never enters a
|
||||
batch, so it is crash-durable. Each record carries its provenance: `env` (`id` plus the
|
||||
orchestrator's `name`), full `task`, `group` (`id`), and `run`.
|
||||
|
||||
A trace has several steps, so each is stamped as its own event rather than implied by
|
||||
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
|
||||
`info.arrival` (`{step, time}` each) as an episode lands; the ship-time annotation adds
|
||||
`info.effective` and `info.ship` — the orchestrator step whose batch shipped the
|
||||
cohort, or for eval the step that produced the policy it measured. Staleness is
|
||||
`ship.step - dispatch.step`. Only `effective` ties to a step; `all` is the whole stream.
|
||||
|
||||
Everything learned after arrival is an append-only trace update keyed by `trace_id`,
|
||||
one file per producer so each has a single writer: the orchestrator records cohort
|
||||
membership, the scalar advantage and per-branch advantage streams; the trainer records
|
||||
its recomputed per-token logprobs and entropies. Readers fold the updates onto the
|
||||
stream records, newest winning.
|
||||
|
||||
```bash
|
||||
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
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
|
||||
wc -l {run_dir}/monitors/file/traces/stream.index.jsonl
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq '.traces[].rewards'
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq 'select(.ok | not) | {id, env: .env.id, errors}'
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.index.jsonl
|
||||
```
|
||||
|
||||
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}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
---
|
||||
name: start-run
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint. Standalone evals are the `eval` skill.
|
||||
---
|
||||
|
||||
# Start a run
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
@@ -46,6 +46,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
|
||||
- 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'))"`).
|
||||
@@ -69,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
|
||||
|
||||
@@ -93,43 +95,9 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
|
||||
- SLURM: single-node, multi-node, and disaggregated deployments
|
||||
|
||||
## `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.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
uv run evals @ eval.toml
|
||||
```
|
||||
|
||||
Minimal standalone `eval.toml`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
|
||||
[eval.client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
|
||||
min_inflight = 8
|
||||
max_inflight = 128
|
||||
|
||||
[[eval.source]]
|
||||
num_examples = 32 # always cap eval size for smokes
|
||||
group_size = 4
|
||||
env.taskset.id = "aime25"
|
||||
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`.
|
||||
- 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/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.
|
||||
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
|
||||
|
||||
@@ -138,7 +106,8 @@ Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`).
|
||||
| `rl` | Full RL pipeline | Production RL training |
|
||||
| `sft` | Supervised fine-tuning | SFT and hard-distill |
|
||||
| `inference` | vLLM server | Standalone serving / debugging |
|
||||
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
|
||||
|
||||
Standalone evals (`uv run eval`) are covered by the `eval` skill.
|
||||
|
||||
## Key paths
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
|
||||
try:
|
||||
return _original_lazy_load_kernel(kernel_name, mapping)
|
||||
except OfflineModeIsEnabled:
|
||||
# Return None so NemotronH skips hub kernels; prime-rl's
|
||||
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
|
||||
# Return None so callers can use their non-hub implementation.
|
||||
mapping[kernel_name] = None
|
||||
return None
|
||||
|
||||
|
||||
@@ -3,12 +3,18 @@
|
||||
`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. Needs the `dashboard` extra. Every instance also serves
|
||||
http://localhost:7788. The trace viewer includes transcript, synchronized
|
||||
agent timeline, and terminal replay 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:
|
||||
|
||||
@@ -24,6 +30,23 @@ 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.
|
||||
|
||||
**Replay** plays the selected trace branch as a terminal session. Model
|
||||
responses, tool commands, and tool results follow their recorded wall-clock
|
||||
spans, with play/pause, seeking, restart, and speed controls. Providers persist
|
||||
the full model-call span rather than timestamps for individual tokens, so text
|
||||
is revealed evenly across that measured span and the UI labels the token cadence
|
||||
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
|
||||
their relative timing; 1× restores exact wall time, and speeds up to 32× are
|
||||
available. In-flight calls show measured progress and recorded output usage even
|
||||
when the response contains only a tool call. Events from older traces without
|
||||
timing stay in order and are marked untimed. Prompt context committed at response
|
||||
time appears at the linked model call's start rather than creating a false blank
|
||||
delay. **Skip inference** makes every model response immediate while retaining
|
||||
the recorded delays between tool commands and their outputs. Recorded model
|
||||
thinking is visible by default and can be toggled from the controls or with
|
||||
**T** while Replay is open. **Top** (or **Home**) stops following the newest
|
||||
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
|
||||
|
||||
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).
|
||||
|
||||
+1205
-237
File diff suppressed because it is too large
Load Diff
+3642
-344
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,11 @@
|
||||
</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>
|
||||
<div id="platform-wrap" class="dd-wrap" hidden>
|
||||
<a id="platform-link" class="btn platform" target="_blank" rel="noopener">view on platform<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7M9 7h8v8"></path></svg></a>
|
||||
<button id="platform-btn" class="btn dd-btn platform" hidden>view on platform</button>
|
||||
<div class="dd-menu" id="platform-menu" hidden></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="run-overview"></div>
|
||||
@@ -35,6 +40,19 @@
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<div class="controls">
|
||||
<div id="metrics-filter-wrap" class="dd-wrap" hidden>
|
||||
<button id="metrics-filter-btn" class="btn dd-btn" title="filter">
|
||||
<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 class="dd-menu dd-filters" id="metrics-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<label class="dd-row" id="metrics-env-row"><span class="t-label">env</span>
|
||||
<select id="metrics-env"></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="metrics-errors"><span class="dot"></span>include errors</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
@@ -51,10 +69,13 @@
|
||||
<button id="metrics-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="metrics-body"></div>
|
||||
<div id="swarm-tip" hidden></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>
|
||||
@@ -62,53 +83,85 @@
|
||||
<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">
|
||||
<div class="controls" id="trace-bar">
|
||||
<div class="seg" id="trace-mode">
|
||||
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
|
||||
<button data-mode="step" title="the cohort shipped at one step">Step</button>
|
||||
</div>
|
||||
<div id="trace-filter-wrap" class="dd-wrap">
|
||||
<button id="trace-filter-btn" class="btn dd-btn" title="filter">
|
||||
<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
|
||||
<span id="trace-filter-count" class="badge" hidden></span>
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">status</span>
|
||||
<div class="seg toggle-seg" id="trace-status-filter">
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
|
||||
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="trace-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
<button data-kind="eval" class="on">eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="dd-row"><span class="t-label">env</span>
|
||||
<select id="trace-env"><option value="">all envs</option></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<select id="trace-sort" title="sort" data-label="sort">
|
||||
<option value="arrival:desc">arrival ↓</option>
|
||||
<option value="arrival:asc">arrival ↑</option>
|
||||
<option value="group:asc">group</option>
|
||||
<option value="duration:desc">total time ↓</option>
|
||||
<option value="duration:asc">total time ↑</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
</select>
|
||||
<span id="trace-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<button id="trace-clear-bin" class="btn" hidden>clear selection</button>
|
||||
</div>
|
||||
<div class="controls" id="step-bar" hidden>
|
||||
<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 id="trace-chart">
|
||||
<div class="chart-head"><span class="chart-title">Episodes finished</span><span id="trace-chart-sub" class="muted"></span></div>
|
||||
<div id="trace-hist"></div>
|
||||
<div id="hist-tip" hidden></div>
|
||||
</div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<colgroup>
|
||||
<col class="c-line"><col class="c-phase"><col class="c-span"><col class="c-kind"><col class="c-env"><col class="c-group">
|
||||
<col class="c-tok"><col class="c-turns"><col class="c-branches"><col class="c-stop"><col class="c-reward">
|
||||
</colgroup>
|
||||
<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>
|
||||
<th>#</th><th>phase</th><th title="when the rollout was dispatched, when its episode arrived, and how long that took (or has taken so far)">dispatched → arrived</th><th>kind</th><th>env</th><th>group</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>reward</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
@@ -153,44 +206,52 @@
|
||||
<div id="drawer-backdrop" hidden></div>
|
||||
<div id="trace-modal" hidden>
|
||||
<aside id="tm-left">
|
||||
<div class="tm-head tm-stephead">
|
||||
<div class="tm-head tm-stephead" id="tm-stephead">
|
||||
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<span id="tm-step-label"></span>
|
||||
<span id="tm-step-label"></span><span id="tm-live-label" class="muted"></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">
|
||||
<button id="tm-filter-btn" class="btn dd-btn" title="filter">
|
||||
<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 class="dd-menu dd-filters" id="tm-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">status</span>
|
||||
<div class="seg toggle-seg" id="tm-status-filter">
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
|
||||
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="tm-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
<button data-kind="eval" class="on">eval</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="dd-row"><span class="t-label">env</span>
|
||||
<select id="tm-env"><option value="">all envs</option></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
|
||||
</div>
|
||||
</div>
|
||||
<select id="tm-sort" title="sort" data-label="sort">
|
||||
<option value="arrival:desc">arrival ↓</option>
|
||||
<option value="arrival:asc">arrival ↑</option>
|
||||
<option value="group:asc">group</option>
|
||||
<option value="duration:desc">total time ↓</option>
|
||||
<option value="duration:asc">total time ↑</option>
|
||||
<option value="reward:desc">reward ↓</option>
|
||||
<option value="reward:asc">reward ↑</option>
|
||||
<option value="output_tokens:desc">tokens ↓</option>
|
||||
</select>
|
||||
</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 class="tm-head tm-ctlrow" id="tm-mode-row">
|
||||
<div class="seg" id="tm-mode">
|
||||
<button data-mode="stream">Stream</button>
|
||||
<button data-mode="step">Step</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tm-head">
|
||||
@@ -203,17 +264,30 @@
|
||||
<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>
|
||||
<button data-view="replay">Replay</button>
|
||||
<button data-view="semantic">Semantic</button>
|
||||
</div>
|
||||
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
|
||||
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
|
||||
<span id="tm-episode-label"></span>
|
||||
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</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.">
|
||||
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, loss/content mask membership, or the trainer's annotations (entropy, the mismatch between its recomputed logprobs and the sampling ones, and the IPO stable mask).">
|
||||
<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>
|
||||
<option value="entropy">Entropy</option>
|
||||
<option value="mismatch_kl">Mismatch</option>
|
||||
<option value="stable_mask">Stable mask</option>
|
||||
<option value="mask">Loss Mask</option>
|
||||
<option value="is_content">Content Mask</option>
|
||||
</select>
|
||||
<button id="tm-collapse" class="btn">collapse</button>
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
@@ -222,8 +296,18 @@
|
||||
<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 id="tm-evidence-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
<aside id="sg-inspector" hidden>
|
||||
<div class="sg-inspector-head">
|
||||
<span id="sg-inspector-title">Model call</span>
|
||||
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
|
||||
</div>
|
||||
<div id="sg-inspector-body"></div>
|
||||
<button id="sg-open-transcript" class="btn">open in transcript</button>
|
||||
</aside>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
|
||||
@@ -90,6 +90,15 @@ body {
|
||||
#tabs button:hover { color: var(--grey-6); }
|
||||
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
|
||||
#topbar .toggle { margin-left: auto; }
|
||||
#topbar .toggle + .toggle { margin-left: 0; }
|
||||
#platform-wrap { margin-left: 14px; }
|
||||
/* looks like the run and compare pickers; the arrow says it leaves the page */
|
||||
#platform-wrap .platform { display: inline-flex; align-items: center; gap: 8px; text-decoration: none; cursor: pointer; }
|
||||
#platform-wrap .platform:hover { color: var(--accent); border-color: var(--accent); }
|
||||
#platform-wrap .platform.disabled { color: var(--grey-4); border-color: var(--grey-3); cursor: default; }
|
||||
#platform-menu { left: auto; right: 0; min-width: 180px; }
|
||||
#platform-menu .dd-opt { display: block; color: var(--grey-5); text-decoration: none; }
|
||||
#platform-menu .dd-opt:hover { color: var(--grey-6); }
|
||||
|
||||
select, .search, .btn {
|
||||
background: transparent;
|
||||
@@ -135,9 +144,26 @@ select:focus, .search:focus { border-color: var(--grey-6); }
|
||||
.dd-opt:hover { background: var(--grey-2); color: var(--grey-6); }
|
||||
.dd-opt.active { color: var(--accent); }
|
||||
.dd-opt.disabled { color: var(--grey-3); cursor: default; }
|
||||
/* an option with nothing to offer greys out and names its reason */
|
||||
.dd-opt.unavailable { display: flex; justify-content: space-between; gap: 28px; }
|
||||
.dd-opt.unavailable:hover { background: none; color: var(--grey-3); }
|
||||
.dd-why { color: var(--grey-3); }
|
||||
.dd-note {
|
||||
padding: 5px 12px 7px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.dd-btn.unavailable { color: var(--grey-4); }
|
||||
.dd-menu {
|
||||
position: absolute;
|
||||
top: 34px;
|
||||
/* anchor to the trigger's left edge: without it the menu lays out from its
|
||||
static position and runs off the side of the window */
|
||||
left: 0;
|
||||
z-index: 40;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
@@ -319,9 +345,85 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
|
||||
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-fill { height: 100%; background: var(--accent); }
|
||||
/* eval progress: one cell per expected episode */
|
||||
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
|
||||
.ep-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
|
||||
.ep-row { display: flex; align-items: center; gap: 12px; }
|
||||
.ep-row .ep-blocks { flex: 1; }
|
||||
.ep-pct { font-size: 13px; color: var(--grey-6); min-width: 4ch; text-align: right; }
|
||||
.ep-head .name { font-size: 14px; color: var(--grey-6); }
|
||||
.ep-blocks { display: flex; gap: 2px; height: 28px; }
|
||||
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
|
||||
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
|
||||
.ep-cell.done:hover { filter: brightness(1.2); }
|
||||
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
|
||||
|
||||
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
|
||||
#tab-metrics { position: relative; }
|
||||
.swarm-card .chart-head { cursor: default; }
|
||||
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
|
||||
.swarm { display: block; }
|
||||
.swarm .sw-bg { fill: transparent; }
|
||||
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
|
||||
.swarm circle.err { fill: var(--negative); }
|
||||
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
|
||||
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
|
||||
.sw-box rect { fill: var(--hairline-faint); stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-box line { stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-box .median { stroke: var(--grey-4); stroke-width: 1.5; }
|
||||
/* timing pane: breadcrumb, icicle of the zoomed node, per-episode strips, tree legend */
|
||||
/* eval metrics sections: flat, a muted heading each */
|
||||
.eval-sec { margin-bottom: 18px; }
|
||||
.eval-sec-title { text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em; color: var(--grey-4); border-bottom: 1px solid var(--hairline); padding-bottom: 4px; margin-bottom: 10px; }
|
||||
.phase-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
|
||||
.timing-pane .chart-head { cursor: default; }
|
||||
.tm-crumbs { font-size: 12px; color: var(--grey-5); }
|
||||
.tm-crumb.current { color: var(--grey-6); }
|
||||
.tm-legend { display: flex; flex-wrap: wrap; gap: 4px 18px; margin: 4px 0 14px; font-size: 11px; color: var(--grey-5); }
|
||||
.tm-icicle svg { display: block; margin-bottom: 14px; }
|
||||
.tm-seg text { fill: #111; font-size: 10px; pointer-events: none; }
|
||||
.tm-strip-seg { cursor: pointer; }
|
||||
.tm-row-hit { fill: transparent; cursor: pointer; }
|
||||
.tm-line.dim { opacity: 0.3; }
|
||||
.tm-strip-seg.dim { opacity: 0.2; }
|
||||
.tm-strip-seg:hover { filter: brightness(1.25); }
|
||||
.tm-line.err { fill: var(--negative); }
|
||||
.comp-pane [data-part].dim { opacity: 0.2; }
|
||||
.comp-pane .tm-node.dim { opacity: 0.35; }
|
||||
/* the summary is one row whatever the count: the tiles share the width equally */
|
||||
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
|
||||
.sum-tile { cursor: default; padding: 14px 16px; min-height: 96px; display: flex; flex-direction: column; justify-content: center; }
|
||||
.sum-tile .stat-label, .sum-tile .stat-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
|
||||
.sum-tile.rate-warn .stat-value { color: #ffd166; }
|
||||
.sum-tile.rate-bad .stat-value { color: var(--negative); }
|
||||
.tm-note { font-size: 10px; margin-top: 4px; }
|
||||
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
|
||||
.tm-more:hover { color: var(--grey-6); }
|
||||
.tm-strips.scroll { max-height: 560px; overflow-y: auto; }
|
||||
.tm-node { white-space: nowrap; cursor: default; }
|
||||
.tm-node:hover { color: var(--grey-6); }
|
||||
/* constants as chips; counted dot plots for few-valued metrics */
|
||||
.const-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
|
||||
.const-chip { font-size: 12px; color: var(--grey-6); background: var(--grey-2); border: 1px solid var(--hairline); padding: 4px 10px; }
|
||||
.const-chip .k { color: var(--grey-4); font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; margin-right: 8px; }
|
||||
.dp-count { fill: var(--grey-5); font-size: 10px; }
|
||||
#swarm-tip {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 6px 8px;
|
||||
min-width: 160px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
font-size: 11px;
|
||||
}
|
||||
#swarm-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
|
||||
#swarm-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
||||
#swarm-tip .tip-row span:first-child { color: var(--grey-4); }
|
||||
.ep-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
@@ -448,6 +550,34 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
body.resizing { user-select: none; }
|
||||
|
||||
/* ---------------------------------------------------------------- config */
|
||||
#config-command {
|
||||
background: #0b0b0b;
|
||||
border: 1px solid var(--grey-3);
|
||||
color: var(--grey-6);
|
||||
}
|
||||
.config-command-head {
|
||||
min-height: 30px;
|
||||
padding: 4px 6px 4px 12px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
background: var(--grey-2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
#config-command-copy { height: 22px; }
|
||||
#config-command-copy.copied { color: var(--accent); border-color: var(--accent); }
|
||||
#config-command-copy:disabled { opacity: 0.35; cursor: default; }
|
||||
.config-command-body {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 13px 14px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.config-command-prompt { color: var(--accent); user-select: none; }
|
||||
#config-command-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
#config-command.empty #config-command-text { color: var(--grey-4); }
|
||||
#config-view {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
@@ -588,7 +718,7 @@ mark.hit {
|
||||
.sb-cell.eval:hover::after { background: var(--grey-6); }
|
||||
#trace-filter-menu {
|
||||
right: 0;
|
||||
min-width: 240px;
|
||||
min-width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
@@ -598,7 +728,21 @@ mark.hit {
|
||||
|
||||
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
|
||||
#episode-table .vpad td { padding: 0; border: 0; }
|
||||
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
|
||||
/* fixed columns: a poll that swaps rows in or out never reflows the table. The sized
|
||||
columns hold mono text whose width follows the font, not the window, so they are
|
||||
measured in characters; env and stop take what is left, and below the minimum the
|
||||
wrap scrolls sideways instead of crushing them. */
|
||||
#episode-table { width: 100%; min-width: 190ch; border-collapse: collapse; font-size: 11.5px; table-layout: fixed; }
|
||||
#episode-table col.c-line { width: 7.5ch; }
|
||||
#episode-table col.c-phase { width: 11.5ch; }
|
||||
#episode-table col.c-span { width: 50ch; }
|
||||
#episode-table col.c-kind { width: 8.5ch; }
|
||||
#episode-table col.c-group { width: 13.5ch; }
|
||||
#episode-table col.c-tok { width: 25ch; }
|
||||
#episode-table col.c-turns { width: 9ch; }
|
||||
#episode-table col.c-branches { width: 12.5ch; }
|
||||
#episode-table col.c-reward { width: 10.5ch; }
|
||||
#episode-table td, #episode-table th { overflow: hidden; text-overflow: ellipsis; }
|
||||
#episode-table th {
|
||||
text-align: left;
|
||||
font: 400 10px var(--font-mono);
|
||||
@@ -635,6 +779,10 @@ mark.hit {
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr) 320px;
|
||||
}
|
||||
#trace-modal.semantic-view { grid-template-columns: minmax(0, 1fr); }
|
||||
#trace-modal.semantic-view #tm-left,
|
||||
#trace-modal.semantic-view #tm-right { display: none; }
|
||||
#trace-modal.semantic-view #tm-main { grid-column: 1; position: relative; }
|
||||
.tm-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -643,7 +791,25 @@ mark.hit {
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
min-height: 48px;
|
||||
}
|
||||
.tm-tabs-row {
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
#tm-evidence-tabs [data-evidence="task"].active { color: var(--chart-3); }
|
||||
#tm-evidence-tabs [data-evidence="judge"].active { color: #7adfff; }
|
||||
#tm-evidence-tabs { margin-left: auto; }
|
||||
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
|
||||
.tm-semantic-nav { display: flex; align-items: center; gap: 7px; min-width: 0; }
|
||||
#tm-episode-label {
|
||||
max-width: 260px;
|
||||
overflow: hidden;
|
||||
color: var(--grey-5);
|
||||
font-size: 10.5px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
|
||||
#tm-left .search { margin: 10px 14px 6px; }
|
||||
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
|
||||
@@ -686,10 +852,322 @@ mark.hit {
|
||||
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
|
||||
#tm-messages > * { flex-shrink: 0; }
|
||||
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
|
||||
#tm-timeline.semantic-canvas { padding: 0; background: var(--grey-1); }
|
||||
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; }
|
||||
/* episode timeline: lifecycle spans above exact model-call activity */
|
||||
.tl-shell { position: relative; min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.tl-edge-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 14px;
|
||||
min-height: 34px;
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
color: var(--grey-4);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.tl-edge-legend-title { color: var(--grey-5); }
|
||||
.tl-edge-key { color: var(--grey-5); white-space: nowrap; }
|
||||
.tl-edge-key i {
|
||||
display: inline-block;
|
||||
width: 18px;
|
||||
margin-right: 6px;
|
||||
vertical-align: 3px;
|
||||
border-top: 2px solid var(--grey-4);
|
||||
}
|
||||
.tl-edge-key i.subagent-call { border-color: var(--infra); }
|
||||
.tl-edge-key i.subagent-return { border-color: var(--risk); }
|
||||
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
|
||||
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
|
||||
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
|
||||
.tl-head, .tl-lane {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
|
||||
}
|
||||
.tl-head {
|
||||
min-height: 42px;
|
||||
align-items: end;
|
||||
color: var(--grey-4);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
}
|
||||
.tl-head > span { padding: 8px 10px; }
|
||||
.tl-axis { position: relative; align-self: stretch; min-width: 0; }
|
||||
.tl-axis span { position: absolute; bottom: 8px; transform: translateX(-50%); white-space: nowrap; }
|
||||
.tl-axis span:first-child { transform: none; }
|
||||
.tl-axis span:last-child { transform: translateX(-100%); }
|
||||
.tl-lane { min-height: 66px; border-bottom: 1px solid var(--hairline-faint); cursor: pointer; }
|
||||
.tl-lane:last-child { border-bottom: 0; }
|
||||
.tl-lane:hover { background: rgba(255, 255, 255, 0.025); }
|
||||
.tl-label, .tl-time, .tl-outcome { padding: 11px 10px; min-width: 0; }
|
||||
.tl-label { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.tl-tree { color: var(--grey-3); flex-shrink: 0; }
|
||||
.tl-dot { width: 6px; height: 6px; margin-top: 5px; background: var(--chart-2); flex-shrink: 0; }
|
||||
.tl-label-copy { min-width: 0; }
|
||||
.tl-label-name { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
|
||||
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
|
||||
.tl-span { position: absolute; z-index: 2; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
|
||||
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
|
||||
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
|
||||
.tl-span.activity.shared { opacity: 0.28; }
|
||||
.tl-span.untimed { border-left: 3px double var(--grey-6); }
|
||||
.tl-span:hover, .tl-span:focus-visible { opacity: 1; outline: 1px solid var(--grey-6); outline-offset: 1px; }
|
||||
.tl-span.boot, .tl-span.setup { background: var(--grey-4); }
|
||||
.tl-span.agent { background: var(--chart-2); }
|
||||
.tl-span.finalize { background: var(--chart-1); }
|
||||
.tl-span.scoring { background: var(--chart-3); }
|
||||
.tl-span.running { border-right: 2px solid var(--accent); }
|
||||
.tl-time { color: var(--grey-5); font-size: 11px; }
|
||||
.tl-time .muted { display: block; font-size: 9.5px; }
|
||||
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
|
||||
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
z-index: 60;
|
||||
width: min(390px, calc(100vw - 24px));
|
||||
padding: 12px 14px;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
pointer-events: none;
|
||||
}
|
||||
.tl-tooltip-kind { color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.tl-tooltip-title { color: var(--grey-6); font-size: 12px; margin: 3px 0 8px; }
|
||||
.tl-tooltip-snippet { color: var(--grey-5); font-size: 11px; margin-bottom: 9px; white-space: normal; }
|
||||
.tl-tooltip dl { display: grid; grid-template-columns: auto 1fr; gap: 2px 16px; margin: 0; font-size: 10.5px; }
|
||||
.tl-tooltip dt { color: var(--grey-4); }
|
||||
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
|
||||
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
|
||||
|
||||
/* Semantic view: ordinal causal flow down the page. Agent identities occupy
|
||||
reusable concurrency slots, so width reflects peak fan-out rather than the
|
||||
total number of children created over a rollout. */
|
||||
.semantic-canvas > .tl-edge-legend {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 9;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
box-sizing: border-box;
|
||||
background: var(--grey-1);
|
||||
font-size: 11px;
|
||||
}
|
||||
.sg-shell {
|
||||
position: relative;
|
||||
min-width: 100%;
|
||||
overflow: clip;
|
||||
background: var(--grey-1);
|
||||
}
|
||||
.sg-lane-band {
|
||||
position: absolute;
|
||||
inset-block: 0;
|
||||
z-index: 0;
|
||||
border-inline: 1px solid rgba(255, 255, 255, 0.035);
|
||||
background: rgba(255, 255, 255, 0.009);
|
||||
pointer-events: none;
|
||||
}
|
||||
.sg-lane-band.root {
|
||||
border-inline-color: rgba(182, 255, 60, 0.07);
|
||||
background: rgba(182, 255, 60, 0.012);
|
||||
}
|
||||
.sg-edge-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; overflow: visible; }
|
||||
.sg-lifeline {
|
||||
fill: none;
|
||||
stroke: var(--lane-color);
|
||||
stroke-width: 1.5;
|
||||
vector-effect: non-scaling-stroke;
|
||||
opacity: 0.38;
|
||||
}
|
||||
.sg-edge {
|
||||
fill: none;
|
||||
stroke: var(--grey-4);
|
||||
stroke-width: 1.4;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
vector-effect: non-scaling-stroke;
|
||||
opacity: 0.68;
|
||||
}
|
||||
.sg-edge.continuation { opacity: 0.34; }
|
||||
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
|
||||
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
|
||||
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
|
||||
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
|
||||
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
|
||||
#sg-arrow-continuation path { fill: var(--grey-4); }
|
||||
#sg-arrow-subagent-call path { fill: var(--infra); }
|
||||
#sg-arrow-subagent-return path { fill: var(--risk); }
|
||||
#sg-arrow-compaction-attempt path { fill: var(--chart-2); }
|
||||
#sg-arrow-compaction path { fill: var(--chart-2); }
|
||||
#sg-arrow-custom path { fill: var(--accent); }
|
||||
.sg-agent-label {
|
||||
position: absolute;
|
||||
z-index: 6;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
padding: 2px 6px;
|
||||
background: var(--grey-1);
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-agent-label.unlinked {
|
||||
outline: 1px dashed var(--grey-3);
|
||||
}
|
||||
.sg-agent-label.unlinked .sg-agent-name,
|
||||
.sg-agent-label.unlinked .sg-context-name {
|
||||
color: var(--grey-5);
|
||||
}
|
||||
.sg-agent-name,
|
||||
.sg-context-name {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
white-space: nowrap;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.sg-agent-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--grey-6);
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sg-agent-name i { width: 8px; height: 8px; flex: none; }
|
||||
.sg-context-name { color: var(--grey-5); font-size: 10.5px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.sg-agent-label.compacted .sg-context-name { color: var(--chart-2); }
|
||||
.sg-agent-name:hover,
|
||||
.sg-agent-name:focus-visible,
|
||||
.sg-context-name:hover,
|
||||
.sg-context-name:focus-visible { color: var(--accent); outline: none; }
|
||||
.sg-agent-name:focus-visible,
|
||||
.sg-context-name:focus-visible { text-decoration: underline; text-underline-offset: 3px; }
|
||||
.sg-agent-label.side-left { align-items: flex-end; text-align: right; }
|
||||
.sg-agent-label.side-right { align-items: flex-start; text-align: left; }
|
||||
.sg-turn {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.sg-turn-mark {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: var(--turn-mark-width, 44px);
|
||||
height: var(--turn-mark-height, 12px);
|
||||
background: var(--turn-color);
|
||||
transform: translate(-50%, -50%);
|
||||
transition: width 100ms ease, height 100ms ease, background 100ms ease;
|
||||
}
|
||||
.sg-turn-index {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: calc(50% + var(--turn-label-offset, 31px));
|
||||
color: var(--grey-5);
|
||||
font-size: 12.5px;
|
||||
transform: translateY(-50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-turn:hover,
|
||||
.sg-turn:focus-visible { z-index: 4; }
|
||||
.sg-turn:hover .sg-turn-mark,
|
||||
.sg-turn:focus-visible .sg-turn-mark {
|
||||
width: calc(var(--turn-mark-width, 44px) + 6px);
|
||||
height: calc(var(--turn-mark-height, 12px) + 2px);
|
||||
background: var(--accent);
|
||||
}
|
||||
.sg-turn:focus-visible .sg-turn-mark { outline: 1px solid var(--grey-6); outline-offset: 2px; }
|
||||
.sg-turn.compaction-attempt.accepted .sg-turn-mark {
|
||||
outline: 1px solid var(--chart-2);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.sg-turn.compaction-attempt.rejected .sg-turn-mark {
|
||||
border: 1px dashed var(--chart-2);
|
||||
background: var(--grey-1);
|
||||
opacity: 0.72;
|
||||
}
|
||||
.sg-turn.compaction-attempt.rejected .sg-turn-index { color: var(--grey-4); }
|
||||
.sg-turn.compaction-attempt.rejected:hover .sg-turn-mark,
|
||||
.sg-turn.compaction-attempt.rejected:focus-visible .sg-turn-mark {
|
||||
border-color: var(--grey-6);
|
||||
background: var(--grey-2);
|
||||
opacity: 1;
|
||||
}
|
||||
.sg-turn-run {
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
padding: 0 7px;
|
||||
border: 0;
|
||||
border-block: 1px solid color-mix(in srgb, var(--turn-color) 56%, var(--grey-3));
|
||||
background: var(--grey-1);
|
||||
color: var(--grey-5);
|
||||
cursor: pointer;
|
||||
font: 10.5px/1 var(--font-mono);
|
||||
letter-spacing: 0.04em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sg-turn-run.collapsed {
|
||||
box-shadow: 0 0 0 4px var(--grey-1);
|
||||
}
|
||||
.sg-turn-run.expanded {
|
||||
border: 1px dashed color-mix(in srgb, var(--turn-color) 45%, var(--grey-3));
|
||||
color: var(--grey-4);
|
||||
}
|
||||
.sg-turn-run:hover,
|
||||
.sg-turn-run:focus-visible {
|
||||
color: var(--grey-6);
|
||||
outline: none;
|
||||
}
|
||||
.sg-turn-run.collapsed:hover,
|
||||
.sg-turn-run.collapsed:focus-visible { border-block-color: var(--turn-color); }
|
||||
.sg-turn-run:focus-visible { box-shadow: 0 0 0 2px var(--grey-1), 0 0 0 3px var(--turn-color); }
|
||||
|
||||
#sg-inspector {
|
||||
position: absolute;
|
||||
top: 62px;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(330px, calc(100% - 28px));
|
||||
border: 1px solid var(--grey-4);
|
||||
background: rgba(25, 25, 25, 0.98);
|
||||
}
|
||||
.sg-inspector-head { display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-bottom: 1px solid var(--hairline); color: var(--grey-6); font-size: 11px; }
|
||||
.sg-inspector-head button { margin-left: auto; }
|
||||
#sg-inspector-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 13px 14px; }
|
||||
.sg-inspector-section { margin: 13px 0 6px; color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
.sg-inspector-row { display: flex; gap: 12px; padding: 3px 0; font-size: 10.5px; }
|
||||
.sg-inspector-row span { color: var(--grey-4); }
|
||||
.sg-inspector-row strong { margin-left: auto; color: var(--grey-6); font-weight: 400; }
|
||||
.sg-inspector-snippet { color: var(--grey-5); font-size: 10.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
|
||||
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
|
||||
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
@@ -723,6 +1201,14 @@ mark.hit {
|
||||
|
||||
/* numbered collapsible message entries */
|
||||
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
|
||||
details.entry.pending { opacity: 0.55; border-style: dashed; }
|
||||
details.entry.semantic-origin {
|
||||
border-color: var(--accent);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.55);
|
||||
outline-offset: 2px;
|
||||
scroll-margin-block: 80px;
|
||||
}
|
||||
details.entry.semantic-origin > summary { background: rgba(182, 255, 60, 0.08); }
|
||||
details.entry > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -789,11 +1275,85 @@ details.sub .sub-name { font-weight: 500; color: var(--grey-6); }
|
||||
details.sub > .entry-body { border-top: 1px solid var(--hairline); }
|
||||
|
||||
/* tool definitions are model context, but deliberately sit outside numbered messages */
|
||||
details.tool-definitions, details.rendered-transcript {
|
||||
details.tool-definitions, .rendered-transcript {
|
||||
border: 1px solid var(--grey-3);
|
||||
margin-bottom: 12px;
|
||||
background: rgba(183, 166, 250, 0.025);
|
||||
}
|
||||
.task-evidence {
|
||||
border: 1px solid color-mix(in srgb, var(--chart-3) 42%, var(--grey-3));
|
||||
margin-bottom: 12px;
|
||||
background: color-mix(in srgb, var(--chart-3) 3%, transparent);
|
||||
}
|
||||
.task-evidence.standalone,
|
||||
.judging-view .judging-divider { margin-top: 0; }
|
||||
.task-evidence > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
}
|
||||
.task-evidence .context-label { color: var(--chart-3); }
|
||||
.task-evidence[open] > summary { border-bottom: 1px solid var(--hairline); }
|
||||
.task-evidence[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.evidence-fields { display: grid; gap: 8px; padding: 10px 12px 12px; }
|
||||
.evidence-field { min-width: 0; border: 1px solid var(--hairline); background: rgba(0, 0, 0, 0.08); }
|
||||
.evidence-field > header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 5px 9px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
color: var(--chart-3);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.evidence-field > header .icon-btn { margin-left: auto; }
|
||||
.evidence-field > pre,
|
||||
.judge-result > pre {
|
||||
max-height: 360px;
|
||||
margin: 0;
|
||||
overflow: auto;
|
||||
padding: 9px 11px;
|
||||
color: var(--grey-5);
|
||||
font: 400 11px/1.55 var(--font-mono);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.judging-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 20px 0 8px;
|
||||
color: #7adfff;
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.judging-divider::after { content: ""; flex: 1; height: 1px; background: var(--hairline); }
|
||||
.judging-divider > :last-child { order: 2; color: var(--grey-4); }
|
||||
.judge-entry { border-color: color-mix(in srgb, #7adfff 38%, var(--grey-3)); }
|
||||
.judge-entry .entry-role { color: #7adfff; }
|
||||
.judge-call-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; padding: 10px 12px 12px; }
|
||||
.judge-request,
|
||||
.judge-result { min-width: 0; border: 1px solid var(--hairline); }
|
||||
.judge-request > header,
|
||||
.judge-result > header {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
color: #7adfff;
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.judge-result.parsed > header { color: var(--chart-2); }
|
||||
.judge-message { display: grid; grid-template-columns: 72px minmax(0, 1fr); border-bottom: 1px solid var(--hairline-faint); }
|
||||
.judge-message:last-child { border-bottom: 0; }
|
||||
.judge-message > header { display: flex; gap: 8px; padding: 9px 10px; color: var(--grey-4); font-size: 10px; }
|
||||
.judge-message > header strong { color: var(--grey-5); font-weight: 500; text-transform: uppercase; }
|
||||
.judge-message > div { min-width: 0; padding: 9px 11px; border-left: 1px solid var(--hairline); color: var(--grey-5); font-size: 11.5px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
details.tool-definitions > summary, details.rendered-transcript > summary,
|
||||
details.tool-definition > summary {
|
||||
display: flex;
|
||||
@@ -857,6 +1417,78 @@ details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--h
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
/* terminal replay follows the trace's wall clock; message text is revealed
|
||||
across its recorded model-call span because providers do not persist per-token timestamps */
|
||||
.replay-shell {
|
||||
display: flex;
|
||||
flex: 1 1 auto !important;
|
||||
min-height: 420px;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--grey-3);
|
||||
background: #080b07;
|
||||
}
|
||||
.replay-bar, .replay-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 40px;
|
||||
padding: 7px 12px;
|
||||
border-bottom: 1px solid rgba(182, 255, 60, 0.12);
|
||||
background: #0d110c;
|
||||
}
|
||||
.replay-lights { color: var(--grey-3); letter-spacing: 3px; font-size: 8px; }
|
||||
.replay-title { color: var(--grey-6); font-size: 11px; }
|
||||
.replay-bar .chip { margin-left: auto; }
|
||||
.replay-controls .btn { min-width: 48px; }
|
||||
#replay-top, #replay-live { min-width: 52px; }
|
||||
#replay-top.active, #replay-live.active { color: var(--accent); border-color: rgba(182, 255, 60, 0.35); }
|
||||
#replay-restart { min-width: 30px; }
|
||||
#replay-progress { flex: 1; min-width: 80px; accent-color: var(--accent); }
|
||||
#replay-time { color: var(--grey-4); font: 400 10.5px var(--font-mono); white-space: nowrap; }
|
||||
.replay-skip { display: flex; align-items: center; gap: 5px; color: var(--grey-5); font-size: 10.5px; white-space: nowrap; }
|
||||
.replay-skip input { accent-color: var(--accent); }
|
||||
.replay-skip kbd { color: var(--grey-4); font: 400 8.5px var(--font-mono); border: 1px solid var(--grey-3); padding: 1px 3px; }
|
||||
.replay-control-label { color: var(--grey-4); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
|
||||
#replay-speed {
|
||||
border: 1px solid var(--grey-3);
|
||||
background: var(--grey-1);
|
||||
color: var(--grey-5);
|
||||
font: 400 10.5px var(--font-mono);
|
||||
padding: 4px 6px;
|
||||
}
|
||||
.replay-output-pane {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 16px 18px 40px;
|
||||
color: #c8d1c5;
|
||||
font: 400 12px/1.6 var(--font-mono);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.replay-event { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; margin-bottom: 14px; }
|
||||
.replay-event > div > span { display: block; }
|
||||
.replay-stamp { color: #52604e; font-size: 9.5px; padding-top: 2px; }
|
||||
.replay-system { color: #7c8978; }
|
||||
.replay-user { color: #f1f5ef; }
|
||||
.replay-assistant { color: #c8d1c5; }
|
||||
.replay-command { margin-top: 7px; color: var(--accent); }
|
||||
.replay-output { padding-left: 10px; border-left: 1px solid #33432d; color: #9dac98; }
|
||||
.replay-wait, .replay-running { color: #70806c; }
|
||||
.replay-model-wait {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 4px 16px;
|
||||
margin-bottom: 8px;
|
||||
color: #70806c;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
.replay-model-wait > i { grid-column: 1 / -1; height: 2px; overflow: hidden; background: #1c2719; }
|
||||
.replay-model-wait > i > b { display: block; height: 100%; background: var(--accent); }
|
||||
.replay-running { display: flex; align-items: center; gap: 8px; margin: 0 0 14px 76px; }
|
||||
.replay-spinner { width: 7px; height: 7px; border: 1px solid #52604e; border-top-color: var(--accent); border-radius: 50%; animation: replay-spin 0.8s linear infinite; }
|
||||
@keyframes replay-spin { to { transform: rotate(360deg); } }
|
||||
|
||||
.tok { padding: 0 1px; }
|
||||
.tok:hover { outline: 1px solid var(--grey-6); }
|
||||
.tok-tip {
|
||||
@@ -988,3 +1620,83 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
font-size: 12px;
|
||||
}
|
||||
#view-toast .toast-text { color: var(--grey-6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
|
||||
/* filter & sort popover */
|
||||
.dd-filters { min-width: 320px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.dd-sec {
|
||||
text-transform: uppercase;
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--grey-4);
|
||||
border-bottom: 1px solid var(--grey-3);
|
||||
padding-bottom: 3px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
|
||||
.dd-filters .seg button { padding: 0 9px; }
|
||||
/* controls sit right, sized to their content, so the label reads as the row's subject */
|
||||
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
|
||||
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
|
||||
.dd-filters .t-label { white-space: nowrap; }
|
||||
|
||||
/* episodes-finished histogram */
|
||||
#trace-chart { padding: 8px 12px 4px; border-bottom: 1px solid var(--grey-2); }
|
||||
#trace-chart .chart-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 4px; }
|
||||
#trace-chart .chart-title { font-size: 12px; font-weight: 600; }
|
||||
#trace-hist { overflow-x: auto; }
|
||||
#trace-hist svg { display: block; max-width: 100%; }
|
||||
.hbar { fill: var(--accent); opacity: 0.7; cursor: pointer; }
|
||||
.hbar:hover { opacity: 1; }
|
||||
.hbar.on { opacity: 1; fill: #fff; }
|
||||
.hgrid { stroke: var(--grey-3); stroke-width: 1; vector-effect: non-scaling-stroke; }
|
||||
.hax { fill: var(--grey-4); font-size: 10px; }
|
||||
.hval { text-anchor: end; }
|
||||
|
||||
#episode-table td.nowrap { white-space: nowrap; }
|
||||
|
||||
/* kind filter: each side toggles on its own, so both or one can be shown */
|
||||
.toggle-seg button { opacity: 0.4; }
|
||||
.toggle-seg button.on { opacity: 1; color: var(--accent); }
|
||||
.toggle-seg button.absent.on { color: var(--grey-4); }
|
||||
|
||||
/* histogram hover card */
|
||||
#trace-chart { position: relative; }
|
||||
#hist-tip {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 6px 8px;
|
||||
min-width: 150px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
font-size: 11px;
|
||||
}
|
||||
#hist-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
|
||||
#hist-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
||||
#hist-tip .tip-row span:first-child { color: var(--grey-4); }
|
||||
|
||||
/* the label reads as the button's own name, so it takes the button's colour */
|
||||
.dd-select .dd-btn .dd-label { text-transform: uppercase; font-weight: 400; color: inherit; }
|
||||
|
||||
/* rendered tokens: a header row over the sequence, not a disclosure */
|
||||
.rendered-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
padding: 7px 12px;
|
||||
background: var(--grey-2);
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
}
|
||||
|
||||
/* in-flight rollouts share the episode table; the phase badge and a pulsing dot in
|
||||
place of their number set them apart */
|
||||
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
|
||||
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
|
||||
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
|
||||
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
|
||||
#tm-live-label { margin-left: 8px; }
|
||||
#log-comp-menu .file-item.sub { padding-left: 22px; }
|
||||
#episode-table .day { margin-right: 8px; }
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
@@ -17,15 +20,30 @@ def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list
|
||||
set_base_sandbox_labels(sandbox_labels)
|
||||
|
||||
|
||||
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
|
||||
"""Write the bound address once serve_env reports it (it blocks in the server loop
|
||||
afterwards). Atomic, so a waiting client never reads a partial line."""
|
||||
address = addresses.get()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".address.tmp")
|
||||
tmp.write_text(address)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
run_name = os.environ.get("PRL_RUN_NAME")
|
||||
sandbox_labels = [run_name] if run_name else []
|
||||
addresses: queue.SimpleQueue | None = None
|
||||
if config.address_file is not None:
|
||||
addresses = queue.SimpleQueue()
|
||||
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
|
||||
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
|
||||
# setup in this process and in every spawned worker.
|
||||
serve_env(
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
address=config.serve.address,
|
||||
address=config.serve.address or "tcp://127.0.0.1:0",
|
||||
address_queue=addresses,
|
||||
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
|
||||
config_data=env_config_data(config.env),
|
||||
max_concurrent=config.serve.max_concurrent,
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Launcher for ``uv run eval``: one epoch of every configured eval source.
|
||||
|
||||
Defers heavy ML imports until after the config is parsed, so ``eval --help``
|
||||
short-circuits. The implementation lives in ``prime_rl.eval.eval``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import tomllib
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
|
||||
|
||||
USAGE = """\
|
||||
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
|
||||
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
|
||||
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
|
||||
|
||||
Shorthands for a single-source run:
|
||||
<taskset-id> the taskset of the run's only source
|
||||
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash)
|
||||
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
|
||||
"""
|
||||
|
||||
NUMBER = re.compile(r"-?\d+(\.\d+)?")
|
||||
|
||||
|
||||
def set_nested(target: dict[str, Any], keys: list[str], value: Any) -> None:
|
||||
for key in keys[:-1]:
|
||||
target = target.setdefault(key, {})
|
||||
target[keys[-1]] = value
|
||||
|
||||
|
||||
def parse_value(raw: str) -> Any:
|
||||
"""A JSON list/object stays structured; every other value is left to pydantic."""
|
||||
return json.loads(raw) if raw.startswith(("[", "{")) else raw
|
||||
|
||||
|
||||
def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
|
||||
|
||||
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
|
||||
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
|
||||
``--source.0.env...`` cannot address it). ``-c N`` pins the concurrency band.
|
||||
Everything else passes through untouched.
|
||||
"""
|
||||
out: list[str] = []
|
||||
source: dict[str, Any] = {}
|
||||
rest = list(argv)
|
||||
if rest and not rest[0].startswith(("-", "@")):
|
||||
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
|
||||
i = 0
|
||||
while i < len(rest):
|
||||
arg = rest[i]
|
||||
flag, has_value, value = arg.partition("=")
|
||||
if not has_value and (flag.startswith("--env.") or flag == "-c"):
|
||||
if i + 1 >= len(rest) or (rest[i + 1].startswith("-") and not NUMBER.fullmatch(rest[i + 1])):
|
||||
raise SystemExit(f"{flag} needs a value")
|
||||
i += 1
|
||||
value = rest[i]
|
||||
if flag.startswith("--env."):
|
||||
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
|
||||
elif flag == "-c":
|
||||
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
|
||||
else:
|
||||
out.append(arg)
|
||||
i += 1
|
||||
if source:
|
||||
if any(toml_defines_source(path) for path in root_config_files(argv)):
|
||||
raise SystemExit(
|
||||
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
|
||||
"with a config file that defines [[source]] blocks - use one or the other"
|
||||
)
|
||||
out += ["--source", json.dumps([source])]
|
||||
return out
|
||||
|
||||
|
||||
def root_config_files(argv: list[str]) -> list[Path]:
|
||||
"""Root ``@ file`` references (a ``--flag @ file`` is a nested reference)."""
|
||||
return [
|
||||
Path(argv[i + 1])
|
||||
for i, arg in enumerate(argv[:-1])
|
||||
if arg == "@" and (i == 0 or not argv[i - 1].startswith("--"))
|
||||
]
|
||||
|
||||
|
||||
def toml_defines_source(path: Path) -> bool:
|
||||
if path.suffix != ".toml" or not path.is_file():
|
||||
return False
|
||||
with path.open("rb") as f:
|
||||
return "source" in tomllib.load(f)
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Eval")
|
||||
argv = sys.argv[1:]
|
||||
if not argv or any(arg in ("-h", "--help") for arg in argv):
|
||||
print(USAGE)
|
||||
sys.argv = [sys.argv[0], "--help"]
|
||||
cli(EvalConfig)
|
||||
return
|
||||
# The typed parse sees the expanded flags; the launch artifacts keep the command as typed.
|
||||
sys.argv = [sys.argv[0], *expand_shorthands(argv)]
|
||||
config = cli(EvalConfig)
|
||||
sys.argv = [sys.argv[0], *argv]
|
||||
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
prepare_attempt_dirs,
|
||||
validate_run_dir,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
|
||||
# The run identity is runtime-only: $PRL_RUN_ID / $PRL_RUN_NAME are stamped on
|
||||
# every episode and inherited by the env servers.
|
||||
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
|
||||
assert config.run.name is not None # resolved at construction
|
||||
os.environ["PRL_RUN_NAME"] = config.run.name
|
||||
|
||||
clean = config.clean and not os.environ.get("NEVER_CLEAN")
|
||||
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=config.resume, clean=clean)
|
||||
config.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
log_file = log_dir / "eval.log"
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file)
|
||||
logger.info("Starting eval")
|
||||
|
||||
write_launch_artifacts(config_dir, "eval")
|
||||
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
|
||||
# One env server per source without an explicit `serve.address`, like the rl launcher's:
|
||||
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
|
||||
# address file, where the eval picks it up.
|
||||
env_servers = [source for source in config.source if source.serve.address is None]
|
||||
env_names = [source.resolved_name for source in env_servers]
|
||||
if env_servers:
|
||||
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
|
||||
for source in env_servers:
|
||||
components.append(
|
||||
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
|
||||
)
|
||||
if config.dry_run:
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
|
||||
logger.success("Dry run complete. To start the eval, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
from prime_rl.eval.eval import run_eval
|
||||
|
||||
processes: list[Popen] = []
|
||||
for source in env_servers:
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file_handle:
|
||||
processes.append(
|
||||
Popen(
|
||||
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
|
||||
stdout=log_file_handle,
|
||||
stderr=log_file_handle,
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
|
||||
logger.info(format_log_message(log_dir, eval=True, env_names={"eval": env_names}))
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Like the rl/sft launchers, the console stays quiet while the eval runs: results
|
||||
# live in the dashboard and the log file, only errors surface here.
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file, console_level="ERROR")
|
||||
try:
|
||||
asyncio.run(run_eval(config))
|
||||
finally:
|
||||
cleanup_processes(processes)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file).success("Eval finished!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,27 +0,0 @@
|
||||
"""Lightweight launcher for the online evals.
|
||||
|
||||
Defers heavy ML imports until after ``cli()`` parses CLI args, so
|
||||
``evals --help`` short-circuits in ``cli()``. The actual implementation
|
||||
lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import write_launch_toml
|
||||
|
||||
write_launch_toml(config.output_dir, "evals")
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -12,10 +12,10 @@ 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,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -57,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
|
||||
|
||||
@@ -76,6 +76,8 @@ 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,
|
||||
@@ -133,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 = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
|
||||
write_slurm_script(config, config_path, script_path)
|
||||
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)
|
||||
|
||||
|
||||
@@ -20,16 +20,16 @@ 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_config_message,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -52,23 +52,18 @@ INFERENCE_CONFIG = "inference.json"
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
|
||||
"""``(split, source, address)`` for every launcher-managed train/eval source. The
|
||||
launcher runs one env server per source at its deterministic address; the
|
||||
orchestrator connects there. A source with ``serve.address`` set is externally
|
||||
managed — its server runs elsewhere and only the orchestrator connects to it — so
|
||||
the launcher neither writes its TOML nor spawns a server for it."""
|
||||
addresses = config.orchestrator.env_addresses
|
||||
return [
|
||||
(split, source, addresses[(split, source.resolved_name)])
|
||||
for split, source in config.orchestrator.env_sources
|
||||
if source.serve.address is None
|
||||
]
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
|
||||
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
|
||||
runs one env server per source; each binds an OS-assigned port and publishes it to
|
||||
its address file, where the orchestrator picks it up. A source with ``serve.address``
|
||||
set is externally managed — its server runs elsewhere and only the orchestrator
|
||||
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
|
||||
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
|
||||
|
||||
|
||||
def env_server_names(config: RLConfig, split: str) -> list[str]:
|
||||
"""Names of the launcher-managed env servers for one split."""
|
||||
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
|
||||
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
|
||||
|
||||
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
@@ -78,6 +73,19 @@ def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None =
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved per-component configs ``write_subconfigs`` leaves in ``config_dir``."""
|
||||
components: list[tuple[str, Path | str]] = [
|
||||
("Orchestrator", config_dir / ORCHESTRATOR_CONFIG),
|
||||
("Trainer", config_dir / TRAINER_CONFIG),
|
||||
]
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
if env_servers(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -98,21 +106,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
with open(output_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
|
||||
# at the source's deterministic address, where the orchestrator connects. The source's
|
||||
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
|
||||
# orchestrator-side.
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**source_dict.get("serve", {}), "address": address},
|
||||
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# orchestrator picks it up.
|
||||
for split, source in env_servers(config):
|
||||
write_env_server_config(output_dir, split, source, config.orchestrator.log)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -123,15 +121,24 @@ def rl_local(config: RLConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
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}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
orchestrator=True,
|
||||
inference=config.inference is not None,
|
||||
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
@@ -155,7 +162,6 @@ def rl_local(config: RLConfig):
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses. Shared mode is always on for
|
||||
@@ -179,9 +185,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] = []
|
||||
@@ -253,10 +256,10 @@ def rl_local(config: RLConfig):
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start one env server per source. The orchestrator connects to each source's
|
||||
# deterministic address, polling until the server is up, so the servers and the
|
||||
# Start one env server per source. The orchestrator waits for each server's
|
||||
# published address and polls until it answers, so the servers and the
|
||||
# orchestrator start in parallel.
|
||||
for split, source, address in env_servers(config):
|
||||
for split, source in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {name} server")
|
||||
@@ -420,7 +423,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
|
||||
|
||||
@@ -459,10 +462,27 @@ 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),
|
||||
@@ -476,6 +496,7 @@ 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),
|
||||
@@ -510,8 +531,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
**modelexpress_vars,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -519,6 +540,7 @@ 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),
|
||||
@@ -549,8 +571,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
**modelexpress_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -565,13 +587,12 @@ 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)
|
||||
write_launch_toml(config.run_dir, "rl")
|
||||
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"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
@@ -581,12 +602,11 @@ def rl_slurm(config: RLConfig):
|
||||
trainer=True,
|
||||
orchestrator=True,
|
||||
inference=True,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
)
|
||||
else:
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
@@ -597,14 +617,13 @@ def rl_slurm(config: RLConfig):
|
||||
trainer=True,
|
||||
orchestrator=has_infer,
|
||||
inference=has_infer,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
|
||||
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
write_slurm_script(config, config_dir, log_dir, script_path)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
if config.dry_run:
|
||||
@@ -646,6 +665,7 @@ def rl(config: RLConfig):
|
||||
# step is stale. When training from scratch, every existing step directory is
|
||||
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
|
||||
# from a previous run and the orchestrator would see a negative async level.
|
||||
get_logger().info("Starting RL run")
|
||||
resume_step: int | None = None
|
||||
if resuming:
|
||||
if config.resume.dir is not None:
|
||||
|
||||
+143
-209
@@ -8,8 +8,8 @@ from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
@@ -17,18 +17,17 @@ from prime_rl.utils.config import cli, dump_resolved_config, find_package_resour
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
get_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -43,27 +42,19 @@ 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"
|
||||
ONLINE_EVAL_CONFIG = "eval.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
|
||||
"""``(source, address)`` for every launcher-managed eval source. A source with
|
||||
``serve.address`` set is externally managed — the launcher neither writes its
|
||||
config nor spawns a server for it."""
|
||||
def eval_env_servers(config: SFTConfig) -> list[OnlineEvalSourceConfig]:
|
||||
"""Every launcher-managed eval source. A source with ``serve.address`` set is
|
||||
externally managed — the launcher neither writes its config nor spawns a server for it."""
|
||||
if config.eval is None:
|
||||
return []
|
||||
addresses = config.eval.env_addresses
|
||||
return [
|
||||
(source, addresses[("eval", source.resolved_name)])
|
||||
for source in config.eval.source
|
||||
if source.serve.address is None
|
||||
]
|
||||
return [source for source in config.eval.source if source.serve.address is None]
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
@@ -81,28 +72,37 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_evals_config(config: SFTConfig) -> EvalsConfig:
|
||||
"""Derive the evals subconfig from the resolved SFT config. The launcher
|
||||
spawns the env servers itself, so each source's derived address is stamped in,
|
||||
marking it externally managed for the evals process."""
|
||||
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
|
||||
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
|
||||
fields filled from the SFT config. The launcher spawns the env servers itself; the
|
||||
online-eval process finds each one through the address it publishes in the shared
|
||||
config attempt."""
|
||||
assert config.eval is not None
|
||||
eval_config = config.eval.model_copy(deep=True)
|
||||
addresses = config.eval.env_addresses
|
||||
for source in eval_config.source:
|
||||
source.serve.address = addresses[("eval", source.resolved_name)]
|
||||
return EvalsConfig(
|
||||
run_fields = dict(
|
||||
model=config.model.name,
|
||||
eval=eval_config,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
online=OnlineConfig(
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
),
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
output_dir=config.run_dir,
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=config.monitors,
|
||||
)
|
||||
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
|
||||
|
||||
|
||||
def sft_config_components(config: SFTConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved configs a launch leaves in ``config_dir``: the SFT config and, with
|
||||
online evals, the inference, online-eval and env-server configs."""
|
||||
components: list[tuple[str, Path | str]] = [("SFT", config_dir / SFT_CONFIG)]
|
||||
if config.eval is not None:
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
|
||||
if eval_env_servers(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
@@ -113,7 +113,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
|
||||
|
||||
|
||||
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
|
||||
"""Write the inference, evals, and env-server configs for online evals."""
|
||||
"""Write the inference, online-eval, and env-server configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
@@ -126,32 +126,30 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
with open(config_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
with open(config_dir / EVALS_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
|
||||
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
|
||||
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
|
||||
# binds at the source's deterministic address, where the evals process connects.
|
||||
for source, address in eval_env_servers(config):
|
||||
env_dir = config_dir / ENVS_DIR / "eval"
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**(source_dict.get("serve") or {}), "address": address},
|
||||
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# online-eval process picks it up.
|
||||
for source in eval_env_servers(config):
|
||||
write_env_server_config(config_dir, "eval", source, config.log)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, 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 = {
|
||||
@@ -164,29 +162,62 @@ 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,
|
||||
"online_eval_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
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)
|
||||
@@ -194,172 +225,66 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
|
||||
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,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_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)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if 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 online-eval 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"]
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
script_path = launcher_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:
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
eval_script_path = launcher_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]
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, 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,
|
||||
eval=online_eval,
|
||||
inference=online_eval,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
if 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
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
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}")
|
||||
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(log_message)
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
|
||||
@@ -369,24 +294,30 @@ 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)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
if config.eval is not None:
|
||||
write_eval_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
eval=config.eval is not None,
|
||||
inference=config.inference is not None,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# 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.
|
||||
infer_gpu_ids: list[int] = []
|
||||
@@ -403,17 +334,17 @@ def sft_local(config: SFTConfig):
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
|
||||
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.eval is not None:
|
||||
# The trainer creates the run; the evals process (which drains its final evals
|
||||
# after the trainer exits) finalizes it.
|
||||
# The trainer creates the run; the online-eval process (which drains its final
|
||||
# evals after the trainer exits) finalizes it.
|
||||
wandb_shared_env = {
|
||||
"WANDB_SHARED_MODE": "1",
|
||||
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
|
||||
"WANDB_SHARED_PRIMARY": "trainer",
|
||||
"WANDB_SHARED_FINISHER": "evals",
|
||||
"WANDB_SHARED_FINISHER": "online-eval",
|
||||
"WANDB_PROGRAM": "uv run sft",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
@@ -462,9 +393,9 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
|
||||
# Start one env server per eval source. The evals process connects to each source's
|
||||
# deterministic address, polling until the server is up.
|
||||
for source, address in eval_env_servers(config):
|
||||
# Start one env server per eval source. The online-eval process waits for each
|
||||
# server's published address and polls until it answers.
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
@@ -475,19 +406,22 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evals")
|
||||
logger.info("Starting online evals")
|
||||
start_process(
|
||||
"evals",
|
||||
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
"WANDB_SHARED_LABEL": "online-eval",
|
||||
},
|
||||
log_path=log_dir / "evals.log",
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
@@ -526,11 +460,11 @@ def sft_local(config: SFTConfig):
|
||||
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.
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "evals" in stop_events:
|
||||
terminal_events.append(stop_events["evals"])
|
||||
if "online-eval" in stop_events:
|
||||
terminal_events.append(stop_events["online-eval"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
@@ -568,12 +502,12 @@ def sft_local(config: SFTConfig):
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the evals process would replay stale broadcasts (and then skip the
|
||||
Without this the online-eval process would replay stale broadcasts (and then skip the
|
||||
re-trained ones at the same steps), and the append-only trace files would mix two
|
||||
policies' rollouts under one step."""
|
||||
logger = setup_logger(config.log.level or "info")
|
||||
if os.environ.get("NEVER_CLEAN"):
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the online-eval process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Evals: one epoch of every configured eval source against the weights the inference
|
||||
server currently serves.
|
||||
|
||||
Every episode streams through the monitors as it arrives; a finished epoch also goes to
|
||||
the platform when ``monitors.prime`` is set. An interrupted run resumes with
|
||||
``--resume`` from its trace stream: the landed episodes rejoin the epoch and only the
|
||||
rollouts still owed run (``prime_rl.eval.resume``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.eval import resume
|
||||
from prime_rl.eval.runner import EvalRunner
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
class Eval:
|
||||
def __init__(self, config: EvalConfig) -> None:
|
||||
self.config = config
|
||||
self.runner = EvalRunner(config, run_dir=config.run_dir)
|
||||
|
||||
async def run(self) -> None:
|
||||
config = self.config
|
||||
landed: list[dict] = []
|
||||
if config.resume:
|
||||
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
|
||||
resume.check_config(resume.previous_config(config.run_dir), dump_resolved_config(config))
|
||||
landed = resume.take_landed(config.run_dir)
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="eval",
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.run_dir,
|
||||
run_config=config,
|
||||
eval_env_names=[source.resolved_name for source in config.source],
|
||||
overview_flavor="eval",
|
||||
)
|
||||
resume.stamp_config(config.run_dir, dump_resolved_config(config))
|
||||
await self.runner.setup()
|
||||
restored: list = []
|
||||
if config.resume:
|
||||
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
|
||||
self.runner.eval_source.restore(owed, groups)
|
||||
get_logger().info(
|
||||
f"Resuming from the trace stream: {len(restored)} episodes restored, "
|
||||
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
|
||||
)
|
||||
|
||||
await self.runner.start()
|
||||
fired = self.runner.eval_source.trigger(0)
|
||||
await self.runner.run_epoch(fired, 0, restored=restored)
|
||||
await self.runner.drain()
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_eval(config: EvalConfig) -> None:
|
||||
evaluation = Eval(config)
|
||||
try:
|
||||
await evaluation.run()
|
||||
# Finalize only on a clean exit — a crashed run must not mark itself completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evaluation.runner.stop()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user