Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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"
|
||||
@@ -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
|
||||
|
||||
+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 gpt-oss --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 gpt-oss --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
|
||||
|
||||
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:50:40+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:35:31.543870+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
"time_taken": 295.5118532651104
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 20.802552047875178,
|
||||
"std": 0.16199364988631793,
|
||||
"min": 20.664358307416567,
|
||||
"max": 20.98082222151257
|
||||
"mean": 16.701924322664684,
|
||||
"std": 0.0999595293790186,
|
||||
"min": 16.586575698092034,
|
||||
"max": 16.763194274056005
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2484.411208996455,
|
||||
"std": 19.346608946709658,
|
||||
"min": 2467.9069802355616,
|
||||
"max": 2505.7016937694384
|
||||
"mean": 1994.6806480062144,
|
||||
"std": 11.937986005933869,
|
||||
"min": 1980.9047701633856,
|
||||
"max": 2001.998007610024
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 52.79691480938345,
|
||||
"std": 0.4071756223542672,
|
||||
"min": 52.35017399210483,
|
||||
"max": 53.14720633160323
|
||||
"mean": 65.74198961785685,
|
||||
"std": 0.3962098986964774,
|
||||
"min": 65.49867434287444,
|
||||
"max": 66.19917749473825
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 11.728515625,
|
||||
"pct": 24.742767157118376
|
||||
"gib": 11.591145833333334,
|
||||
"pct": 24.45296844104
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:55:54+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:28:40.728120+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
"time_taken": 317.33935201819986
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.217465998339005,
|
||||
"std": 0.02905058130694137,
|
||||
"min": 17.19503698271855,
|
||||
"max": 17.250282374540514
|
||||
"mean": 15.880248465863398,
|
||||
"std": 0.005915779562921215,
|
||||
"min": 15.873443653590638,
|
||||
"max": 15.884167926432548
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 8225.003435798719,
|
||||
"std": 13.877833769765575,
|
||||
"min": 8214.288808538377,
|
||||
"max": 8240.68023789224
|
||||
"mean": 7586.197539502296,
|
||||
"std": 2.826043462792163,
|
||||
"min": 7582.946793757898,
|
||||
"max": 7588.069915881657
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.90305413212627,
|
||||
"std": 0.11015530079183487,
|
||||
"min": 63.77801387012005,
|
||||
"max": 63.985770548693836
|
||||
"mean": 69.21047159920757,
|
||||
"std": 0.022114607283211834,
|
||||
"min": 69.19065106380731,
|
||||
"max": 69.234325167723
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 6.298828125,
|
||||
"pct": 13.288163877053583
|
||||
"gib": 8.55078125,
|
||||
"pct": 18.038939985655993
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
|
||||
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
|
||||
|
||||
Forward and backward are timed separately, because only the forward is a kernel — the
|
||||
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
|
||||
grouped-mm reference. A speedup on the forward can be spent again on the backward.
|
||||
|
||||
uv run benchmarks/scripts/bench_fused_moe.py
|
||||
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
|
||||
|
||||
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
|
||||
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
|
||||
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
|
||||
parser.add_argument("--num-experts", type=int, default=64)
|
||||
parser.add_argument("--top-k", type=int, default=8)
|
||||
parser.add_argument("--iters", type=int, default=20)
|
||||
parser.add_argument("--warmup", type=int, default=5)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
|
||||
torch.manual_seed(0)
|
||||
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
|
||||
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
|
||||
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
|
||||
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
|
||||
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
|
||||
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
|
||||
|
||||
|
||||
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
|
||||
x, w1, w2, w3, selected, top_scores = inputs
|
||||
if mode == "grouped_mm":
|
||||
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
|
||||
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
|
||||
|
||||
|
||||
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
|
||||
"""Median forward ms, median backward ms, peak MiB."""
|
||||
forward_ms, backward_ms = [], []
|
||||
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
|
||||
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
|
||||
for i in range(args.warmup + args.iters):
|
||||
for tensor in inputs[:4] + (inputs[5],):
|
||||
tensor.grad = None
|
||||
torch.cuda.synchronize()
|
||||
|
||||
start.record()
|
||||
out = run_forward(mode, inputs, args.num_experts)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
forward_ms.append(start.elapsed_time(end))
|
||||
|
||||
start.record()
|
||||
out.backward(grad_out)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
backward_ms.append(start.elapsed_time(end))
|
||||
|
||||
median = lambda values: sorted(values)[len(values) // 2]
|
||||
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
if not torch.cuda.is_available():
|
||||
raise SystemExit("no CUDA device")
|
||||
kernel = _load_fused_moe_kernel()
|
||||
for mxfp8 in (False, True):
|
||||
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
|
||||
if reason is not None:
|
||||
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
|
||||
|
||||
inputs = make_inputs(args)
|
||||
print(
|
||||
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
|
||||
f"experts={args.num_experts} top_k={args.top_k} "
|
||||
f"({args.iters} iters, {args.warmup} warmup, median)\n"
|
||||
)
|
||||
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
|
||||
|
||||
baseline = None
|
||||
for mode in MODES:
|
||||
forward, backward, peak = time_mode(mode, inputs, args)
|
||||
total = forward + backward
|
||||
baseline = baseline or total
|
||||
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -70,11 +70,6 @@ class BenchmarkConfig(BaseConfig):
|
||||
Field(description="Activation checkpointing type"),
|
||||
] = "Recompute"
|
||||
|
||||
selective_targets: Annotated[
|
||||
list[str] | None,
|
||||
Field(description="Selective activation checkpoint targets when ac=Selective"),
|
||||
] = None
|
||||
|
||||
attention: Annotated[
|
||||
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
|
||||
Field(description="Attention implementation"),
|
||||
@@ -160,8 +155,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
|
||||
cmd.append("--model.ac")
|
||||
elif config.ac == "Selective":
|
||||
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
|
||||
if config.selective_targets:
|
||||
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
|
||||
elif config.ac == "Offload":
|
||||
cmd.append("--model.ac-offloading")
|
||||
|
||||
|
||||
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...3ed6ef7c2c
+29
-10
@@ -35,31 +35,50 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
|
||||
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
|
||||
|
||||
### Low-precision training
|
||||
|
||||
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
|
||||
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
|
||||
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
|
||||
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
|
||||
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
|
||||
|
||||
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
|
||||
|
||||
- `type = "bf16"` (default)
|
||||
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
|
||||
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
|
||||
|
||||
```toml
|
||||
[trainer.model.quantization]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
enable_a2a = true
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "mxfp8"
|
||||
```
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
|
||||
|
||||
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
|
||||
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
|
||||
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
|
||||
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
|
||||
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "deepep"
|
||||
num_sms = 20
|
||||
token_chunk_size = 4096
|
||||
```
|
||||
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
@@ -141,7 +160,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
|
||||
```
|
||||
|
||||
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
|
||||
|
||||
+14
-25
@@ -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,36 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
|
||||
|
||||
### Default RL Loss
|
||||
### IPO Loss
|
||||
|
||||
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
|
||||
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
|
||||
|
||||
$$
|
||||
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
|
||||
\mathcal{L}(\theta) = \frac{1}{N}\sum_t
|
||||
\left[
|
||||
-\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
|
||||
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}
|
||||
+ \tau_{KL}\log^2\!\left(\frac{\pi(y_t)}{\mu(y_t)}\right)
|
||||
\right].
|
||||
$$
|
||||
|
||||
where the policy-gradient term is
|
||||
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
|
||||
|
||||
$$
|
||||
\mathcal{J}_{\text{PG}}(\theta)
|
||||
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t}
|
||||
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
|
||||
$$
|
||||
|
||||
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
|
||||
|
||||
$$
|
||||
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
|
||||
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
|
||||
$$
|
||||
|
||||
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
|
||||
|
||||
The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
The knobs under `[trainer.loss]` are:
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
### Custom Loss
|
||||
|
||||
|
||||
@@ -247,8 +247,14 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
|
||||
Then inspect the resolved config:
|
||||
|
||||
```bash
|
||||
ls /tmp/reverse-dry/check/configs/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.
|
||||
|
||||
+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`.
|
||||
|
||||
+32
-7
@@ -99,11 +99,14 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
ep_comm_backend = "torch" # or "deepep"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "bf16"
|
||||
```
|
||||
|
||||
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
|
||||
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -230,6 +237,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### NIXL weight broadcast
|
||||
|
||||
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
|
||||
|
||||
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
|
||||
|
||||
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
|
||||
|
||||
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
|
||||
|
||||
+18
-10
@@ -81,7 +81,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 +125,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
|
||||
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
|
||||
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
|
||||
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
|
||||
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
|
||||
|
||||
**Performance** (trainer + orchestrator step independently):
|
||||
@@ -198,17 +198,17 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at 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 `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node (Decoupled Trainer and Inference Pool)
|
||||
#### Multi-Node Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer job
|
||||
num_infer_nodes = 1 # eval job (inference pool + evals)
|
||||
num_train_nodes = 2 # trainer nodes
|
||||
num_infer_nodes = 1 # inference pool + evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -217,7 +217,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
|
||||
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -313,6 +313,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 +328,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── evals.log # SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -331,12 +339,12 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
@@ -100,7 +100,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 +124,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 +154,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"
|
||||
|
||||
@@ -96,7 +96,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 +123,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 +144,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"
|
||||
|
||||
@@ -97,6 +97,9 @@ ep = 8
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "deepgemm_fp8"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -89,7 +89,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 +99,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
|
||||
|
||||
|
||||
@@ -23,11 +23,8 @@ rank = 32
|
||||
alpha = 32
|
||||
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
|
||||
|
||||
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
|
||||
# raises CheckpointError; selective AC excluding routed_experts avoids that.
|
||||
[model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj", "linear_attn"]
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
|
||||
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.10",
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
|
||||
@@ -4,7 +4,7 @@ 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.shared import ClientConfig, LogConfig, ResumeConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
|
||||
Disable to finish every triggered eval epoch before loading later weights. The trainer can
|
||||
idle while it waits for slow evals."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
@@ -61,6 +66,13 @@ class OnlineConfig(BaseConfig):
|
||||
this step."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Checkpoint progress for an interruptible standalone eval run."""
|
||||
|
||||
interval: int = Field(1, ge=1)
|
||||
"""Save after the task cursor advances by N completed groups."""
|
||||
|
||||
|
||||
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
|
||||
@@ -90,6 +102,12 @@ class EvalsConfig(BaseConfig):
|
||||
"""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``."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
@@ -112,3 +130,12 @@ class EvalsConfig(BaseConfig):
|
||||
"would skip its only eval epoch. Remove it or add an [online] block."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_checkpointing_is_standalone_only(self):
|
||||
if self.online is not None and (self.ckpt is not None or self.resume is not None):
|
||||
raise ValueError(
|
||||
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
|
||||
"with the trainer's live weight-broadcast lifecycle"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -408,6 +447,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 +481,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
|
||||
@@ -565,6 +616,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 +743,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
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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``."""
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -21,7 +21,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 +30,13 @@ class GCConfig(BaseConfig):
|
||||
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
mode: Literal["full", "selective"] = "full"
|
||||
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
|
||||
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
|
||||
|
||||
freq: int = Field(1, ge=1)
|
||||
"""Apply activation checkpointing to every N layers."""
|
||||
|
||||
targets: list[str] = ["norm"]
|
||||
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_selective_targets(self):
|
||||
self.targets = list(dict.fromkeys(self.targets))
|
||||
if self.mode == "selective" and not self.targets:
|
||||
raise ValueError("Selective activation checkpointing requires at least one target.")
|
||||
return self
|
||||
targets: list[str] | None = None
|
||||
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
@@ -123,7 +115,7 @@ class LoRAConfig(BaseConfig):
|
||||
"fc1_latent_proj",
|
||||
"fc2_latent_proj",
|
||||
]
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
|
||||
modules_to_save: list[str] = []
|
||||
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
|
||||
@@ -151,7 +143,7 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
# in BF16 on the trainer while inference quantized it to FP8, causing
|
||||
# hidden-state drift before the MoE router.
|
||||
r"mlp\.gate\.",
|
||||
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"in_proj_a",
|
||||
@@ -161,21 +153,80 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
|
||||
class FP8Config(BaseConfig):
|
||||
type: Literal["fp8"] = "fp8"
|
||||
enable_grouped_gemm: bool = True
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from DeepGEMM FP8 replacement."""
|
||||
|
||||
|
||||
class MXFP8Config(BaseConfig):
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
enable_grouped_gemm: bool = True
|
||||
enable_a2a: bool = True
|
||||
"""MXFP8 recipe for dense linear modules."""
|
||||
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from torchao MXFP8 replacement."""
|
||||
|
||||
|
||||
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs in bfloat16."""
|
||||
|
||||
type: Literal["bf16"] = "bf16"
|
||||
|
||||
|
||||
class DeepGemmFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
|
||||
|
||||
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
|
||||
|
||||
|
||||
class MXFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
|
||||
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
"""MXFP8 expert-compute recipe."""
|
||||
|
||||
|
||||
MoEComputeConfig: TypeAlias = Annotated[
|
||||
BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class TorchMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with torch all-to-all collectives."""
|
||||
|
||||
type: Literal["torch"] = "torch"
|
||||
transport: Literal["bf16", "mxfp8"] = "bf16"
|
||||
"""Wire format for routed activations and their reverse-path gradients."""
|
||||
|
||||
|
||||
class DeepEPMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with DeepEP."""
|
||||
|
||||
type: Literal["deepep"] = "deepep"
|
||||
num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated to DeepEP communication kernels."""
|
||||
|
||||
token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Optional chunk size used to pipeline dispatch with local expert compute."""
|
||||
|
||||
|
||||
MoEDispatchConfig: TypeAlias = Annotated[
|
||||
TorchMoEDispatchConfig | DeepEPMoEDispatchConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class MoERuntimeConfig(BaseConfig):
|
||||
"""Independent routed-expert compute and token-dispatch choices."""
|
||||
|
||||
compute: MoEComputeConfig = BF16MoEComputeConfig()
|
||||
dispatch: MoEDispatchConfig = TorchMoEDispatchConfig()
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
@@ -213,14 +264,8 @@ class ModelConfig(BaseModelConfig):
|
||||
ep: int | Literal["auto"] = "auto"
|
||||
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
|
||||
|
||||
ep_comm_backend: EPCommBackend = "torch"
|
||||
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
|
||||
|
||||
deepep_num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
|
||||
|
||||
deepep_token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
|
||||
moe: MoERuntimeConfig = MoERuntimeConfig()
|
||||
"""Routed-expert compute and token-dispatch runtime."""
|
||||
|
||||
cp: int = 1
|
||||
"""Context parallelism degree. 1 disables CP."""
|
||||
@@ -240,12 +285,6 @@ class ModelConfig(BaseModelConfig):
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
moe_fused_kernel: bool = False
|
||||
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
@@ -301,12 +340,6 @@ class ModelConfig(BaseModelConfig):
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def selective_ac_only_with_custom_impl(self):
|
||||
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
|
||||
@@ -332,19 +365,18 @@ class ModelConfig(BaseModelConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
def validate_moe_runtime(self):
|
||||
if self.ep == 1:
|
||||
return self
|
||||
|
||||
if isinstance(self.ep, int) and self.ep <= 1:
|
||||
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def mxfp8_only_with_torch_ep_backend(self):
|
||||
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
|
||||
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
|
||||
compute = self.moe.compute
|
||||
dispatch = self.moe.dispatch
|
||||
if isinstance(dispatch, DeepEPMoEDispatchConfig):
|
||||
if isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
|
||||
elif dispatch.transport == "mxfp8":
|
||||
if not isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -492,26 +524,10 @@ class CheckpointConfig(BaseConfig):
|
||||
"""Skip loading the optimizer state from checkpoint."""
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
eps: float = Field(0.1, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
@@ -530,7 +546,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -581,6 +597,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
overlap_transfer_and_replay: bool = False
|
||||
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
@@ -595,7 +614,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
loss: LossConfig = IPOLossConfig()
|
||||
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
|
||||
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
@@ -657,7 +676,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
|
||||
+57
-33
@@ -27,7 +27,7 @@ dependencies = [
|
||||
"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",
|
||||
@@ -49,11 +49,11 @@ 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'",
|
||||
@@ -61,20 +61,21 @@ gpu = [
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; 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
|
||||
# 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,7 +86,7 @@ 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 = [
|
||||
@@ -135,13 +136,17 @@ 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",
|
||||
# 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 +183,30 @@ version = "0.3.0"
|
||||
requires-dist = [
|
||||
"grpcio>=1.66.2",
|
||||
"huggingface_hub>=0.20.0",
|
||||
"nixl[cu12]",
|
||||
"nixl",
|
||||
"numpy>=1.24.0",
|
||||
"protobuf>=5.27.0,<7.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
# NIXL publishes its CUDA 12 package as a base dependency even when the
|
||||
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nixl"
|
||||
version = "0.10.1"
|
||||
requires-dist = ["nixl-cu13==0.10.1"]
|
||||
|
||||
# CUTLASS DSL has the same CUDA 12 default. vLLM requests its CUDA 13 extra,
|
||||
# so resolve that variant without installing both runtime packages.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
requires-dist = [
|
||||
"nvidia-cutlass-dsl-libs-base==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
@@ -210,7 +232,7 @@ vllm-router = false
|
||||
dion = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
|
||||
@@ -221,36 +243,38 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
torch = [{ index = "pytorch-cu128", 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'" }
|
||||
torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
@@ -261,13 +285,13 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
name = "pytorch-cu130"
|
||||
url = "https://download.pytorch.org/whl/cu130"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
name = "pytorch-cu130-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu130"
|
||||
explicit = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -25,9 +25,13 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
|
||||
|
||||
```bash
|
||||
uv run rl --help # all fields and defaults
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
|
||||
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
|
||||
```
|
||||
|
||||
Each attempt also writes `configs/attempt_<n>/command.txt`. It records the
|
||||
shell-safe launch command, including CLI overrides. `configs/latest` points to
|
||||
the current attempt.
|
||||
|
||||
## Validators
|
||||
|
||||
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
|
||||
@@ -69,6 +73,8 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
|
||||
|
||||
@@ -11,6 +11,10 @@ dirs — safe against live runs — and installs anywhere (cluster head node,
|
||||
laptop against a mounted outputs dir): GPU dependencies live behind the
|
||||
`gpu` extra.
|
||||
|
||||
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch. The Config
|
||||
view shows a copyable launch command above the launch TOML or resolved JSON.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
|
||||
+15
-4
@@ -66,13 +66,24 @@ Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
The `disagg` extra installs the prebuilt DeepEP wheel pinned in `[tool.uv.sources]`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_ep_kernels.sh
|
||||
uv sync --extra disagg
|
||||
```
|
||||
|
||||
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
|
||||
The prime-kernels repository owns source builds for DeepEP, DeepGEMM, and TorchAO. Use
|
||||
its scripts when a local rebuild is required:
|
||||
|
||||
```bash
|
||||
git submodule update --init deps/prime-kernels
|
||||
bash deps/prime-kernels/scripts/install_ep_kernels.sh --wheel-dir /tmp/prime-kernels-wheels
|
||||
uv pip install --reinstall --no-deps /tmp/prime-kernels-wheels/deep_ep-*.whl
|
||||
```
|
||||
|
||||
The build needs a CUDA toolkit whose version matches torch. Set
|
||||
`TORCH_CUDA_ARCH_LIST` when the build host has no GPU or when the wheel must support
|
||||
more than the local GPU architecture.
|
||||
|
||||
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,7 +48,7 @@ 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).
|
||||
|
||||
@@ -56,7 +56,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
|
||||
|
||||
`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
|
||||
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
|
||||
files, a rollout trace viewer with a per-token advantage/logprob view, and merged
|
||||
component logs. It only reads the run dirs — safe to run against a live run.
|
||||
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
|
||||
@@ -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)
|
||||
├── evals.log # SFT online-eval evals stdout
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -135,7 +135,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
|--------|-------------|
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
|
||||
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
|
||||
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
|
||||
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
|
||||
| `optim/grad_norm` | spikes may precede divergence |
|
||||
|
||||
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
|
||||
|
||||
@@ -7,7 +7,7 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
|
||||
|
||||
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
|
||||
|
||||
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory.
|
||||
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
|
||||
|
||||
@@ -95,7 +97,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
@@ -120,16 +122,19 @@ group_size = 4
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # optional: make a standalone eval resumable
|
||||
interval = 10 # completed task groups between cursor saves
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/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
|
||||
|
||||
|
||||
@@ -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 and synchronized
|
||||
agent timeline views; timeline activities open the corresponding transcript
|
||||
call. Needs the `dashboard` extra. Every instance also serves
|
||||
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
|
||||
(one dashboard per host per user); `--isolated` serves only the given dirs and
|
||||
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
|
||||
kill/restart commands, and the local view-command/report contract.
|
||||
|
||||
The Config and Logs views keep each launch attempt available. The Config view
|
||||
shows a copyable command above the launch TOML or resolved JSON. Both views
|
||||
open at `latest (attempt <n>)` and let you select an earlier attempt.
|
||||
|
||||
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
|
||||
cluster head node, a laptop against a mounted outputs dir:
|
||||
|
||||
|
||||
@@ -208,10 +208,27 @@ def model_name(config: dict) -> str | None:
|
||||
return model if isinstance(model, str) else (model or {}).get("name")
|
||||
|
||||
|
||||
def resolved_config_dir(run_dir: Path) -> Path:
|
||||
"""Where the resolved JSON dumps live: `configs/resolved/`, or `configs/` on
|
||||
runs from before the launch-TOML split."""
|
||||
def config_attempt_numbers(run_dir: Path) -> list[int]:
|
||||
return [n for n, _ in numbered_dirs(run_dir / "configs", "attempt_")]
|
||||
|
||||
|
||||
def config_attempt_dir(run_dir: Path, attempt: str = "latest") -> tuple[Path, int | None]:
|
||||
"""Return one config attempt root, with a fallback for legacy run layouts."""
|
||||
configs = run_dir / "configs"
|
||||
attempts = config_attempt_numbers(run_dir)
|
||||
if not attempts:
|
||||
return configs, None
|
||||
if attempt == "latest":
|
||||
latest = (configs / "latest").resolve()
|
||||
attempt_num = int(latest.name.removeprefix("attempt_")) if latest.is_dir() else attempts[-1]
|
||||
else:
|
||||
attempt_num = int(attempt)
|
||||
return configs / f"attempt_{attempt_num}", attempt_num
|
||||
|
||||
|
||||
def resolved_config_dir(run_dir: Path, attempt: str = "latest") -> Path:
|
||||
"""Return resolved JSON dumps for one attempt or a legacy run."""
|
||||
configs, _ = config_attempt_dir(run_dir, attempt)
|
||||
resolved = configs / "resolved"
|
||||
return resolved if resolved.is_dir() else configs
|
||||
|
||||
@@ -278,6 +295,7 @@ def run_meta(run_dir: Path) -> dict:
|
||||
"type": run_type,
|
||||
"model": model_name(config),
|
||||
"dataset": (config.get("data") or {}).get("name"),
|
||||
"has_validation": run_type == "sft" and config.get("val") is not None,
|
||||
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
|
||||
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
|
||||
"max_steps": config.get("max_steps"),
|
||||
@@ -365,7 +383,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
|
||||
for path in sorted(attempt_dir.rglob("*.log")):
|
||||
component, label = log_component(path.relative_to(attempt_dir))
|
||||
add(path, component, label)
|
||||
# The evals process writes its env-server logs outside attempt_N (logs/envs/eval/*.log).
|
||||
# Include unscoped env logs from runs created before attempt-scoped eval logging.
|
||||
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
|
||||
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
|
||||
return {"attempt": attempt_num, "attempts": attempts, "files": files}
|
||||
@@ -407,26 +425,29 @@ def config_rank(name: str) -> tuple[int, str]:
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/configs")
|
||||
def list_configs(run: str) -> dict:
|
||||
def list_configs(run: str, attempt: str = "latest") -> dict:
|
||||
"""Two views of a run's config: each launch TOML (verbatim, as the run was
|
||||
started) and one "resolved" document concatenating every resolved JSON dump."""
|
||||
run_dir = get_run_dir(run)
|
||||
configs_dir = run_dir / "configs"
|
||||
configs_dir, attempt_num = config_attempt_dir(run_dir, attempt)
|
||||
files = sorted((p.name for p in configs_dir.glob("*.toml")), key=config_rank) if configs_dir.is_dir() else []
|
||||
if any(resolved_config_dir(run_dir).rglob("*.json")):
|
||||
if any(resolved_config_dir(run_dir, attempt).rglob("*.json")):
|
||||
files.append("resolved")
|
||||
return {"files": files}
|
||||
if (configs_dir / "command.txt").is_file():
|
||||
files.append("command.txt")
|
||||
return {"attempt": attempt_num, "attempts": config_attempt_numbers(run_dir), "files": files}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/config")
|
||||
def read_config(run: str, file: str) -> dict:
|
||||
def read_config(run: str, file: str, attempt: str = "latest") -> dict:
|
||||
run_dir = get_run_dir(run)
|
||||
if file == "resolved":
|
||||
base = resolved_config_dir(run_dir)
|
||||
base = resolved_config_dir(run_dir, attempt)
|
||||
names = sorted((str(p.relative_to(base).with_suffix("")) for p in base.rglob("*.json")), key=config_rank)
|
||||
doc = {name: read_json(base / f"{name}.json") for name in names}
|
||||
return {"file": file, "content": orjson.dumps(doc).decode()}
|
||||
path = safe_child(run_dir / "configs", file, suffix=".toml")
|
||||
configs_dir, _ = config_attempt_dir(run_dir, attempt)
|
||||
path = safe_child(configs_dir, file, suffix=".txt" if file == "command.txt" else ".toml")
|
||||
return {"file": file, "content": path.read_text()}
|
||||
|
||||
|
||||
@@ -781,6 +802,306 @@ def traces_path(run: str, step: int, kind: str, subset: str) -> Path:
|
||||
raise HTTPException(404, "no traces for this step/kind/subset")
|
||||
|
||||
|
||||
def read_episode_record(path: Path, line: int) -> dict:
|
||||
offsets = line_offsets(path)
|
||||
if not 0 <= line < len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
with path.open("rb") as f:
|
||||
f.seek(offsets[line])
|
||||
return orjson.loads(f.readline())
|
||||
|
||||
|
||||
def message_text(message: dict) -> str:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
return "".join(part.get("text", "") if isinstance(part, dict) else str(part) for part in content)
|
||||
return "" if content is None else str(content)
|
||||
|
||||
|
||||
def timeline_status(trace: dict) -> str:
|
||||
if not trace.get("is_completed"):
|
||||
return "running"
|
||||
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
|
||||
return "failed"
|
||||
return "completed"
|
||||
|
||||
|
||||
def timeline_reward(trace: dict) -> float | None:
|
||||
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
|
||||
if not rewards:
|
||||
return None
|
||||
return sum(
|
||||
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
|
||||
for reward in rewards
|
||||
)
|
||||
|
||||
|
||||
def trace_branch_paths(nodes: list[dict]) -> list[list[int]]:
|
||||
"""Return VF-native root-to-leaf branches in leaf-index order."""
|
||||
if not nodes:
|
||||
return []
|
||||
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
|
||||
paths = []
|
||||
for leaf in (index for index in range(len(nodes)) if index not in parents):
|
||||
path = []
|
||||
seen = set()
|
||||
node_index: int | None = leaf
|
||||
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
|
||||
seen.add(node_index)
|
||||
path.append(node_index)
|
||||
node_index = nodes[node_index].get("parent")
|
||||
paths.append(list(reversed(path)))
|
||||
return paths
|
||||
|
||||
|
||||
def token_usage(usage: dict) -> tuple[int | None, int | None, int | None]:
|
||||
prompt_tokens = usage.get("prompt_tokens")
|
||||
output_tokens = usage.get("completion_tokens")
|
||||
if "cached_input_tokens" in usage:
|
||||
return prompt_tokens, usage.get("cached_input_tokens"), output_tokens
|
||||
cached_tokens = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
|
||||
input_tokens = (
|
||||
max(0, prompt_tokens - cached_tokens) if prompt_tokens is not None and cached_tokens else prompt_tokens
|
||||
)
|
||||
return input_tokens, cached_tokens, output_tokens
|
||||
|
||||
|
||||
def activity_spans(
|
||||
trace: dict,
|
||||
node_indexes: set[int],
|
||||
*,
|
||||
include_unlinked: bool = False,
|
||||
shared_node_indexes: set[int] | None = None,
|
||||
) -> list[dict]:
|
||||
nodes = trace.get("nodes") or []
|
||||
spans = []
|
||||
for call_index, call in enumerate(trace.get("calls") or []):
|
||||
node_index = call.get("node")
|
||||
if node_index is None:
|
||||
if not include_unlinked:
|
||||
continue
|
||||
node = {}
|
||||
elif node_index not in node_indexes:
|
||||
continue
|
||||
else:
|
||||
node = nodes[node_index]
|
||||
call_time = call.get("time") or {}
|
||||
started = call_time.get("start")
|
||||
ended = call_time.get("end")
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens, cached_tokens, output_tokens = token_usage(usage)
|
||||
reasoning_tokens = usage.get("reasoning_tokens")
|
||||
if reasoning_tokens is None:
|
||||
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
|
||||
text = " ".join(message_text(node.get("message") or {}).split())
|
||||
spans.append(
|
||||
{
|
||||
"kind": "model_call",
|
||||
"label": f"turn {len(spans) + 1}",
|
||||
"track": "activity",
|
||||
"call_index": call_index,
|
||||
"node_index": node_index,
|
||||
"shared": node_index in shared_node_indexes if shared_node_indexes is not None else False,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": "completed" if ended is not None or trace.get("is_completed") else "running",
|
||||
"snippet": text[:240],
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"cost": usage.get("cost"),
|
||||
}
|
||||
)
|
||||
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
|
||||
|
||||
|
||||
def lifecycle_spans(trace: dict) -> list[dict]:
|
||||
timing = trace.get("timing") or {}
|
||||
spans = []
|
||||
for kind, label in (
|
||||
("boot", "boot"),
|
||||
("setup", "setup"),
|
||||
("agent", "agent"),
|
||||
("finalize", "finalize"),
|
||||
("scoring", "scoring"),
|
||||
):
|
||||
span = timing.get(kind) or {}
|
||||
if not span.get("start"):
|
||||
continue
|
||||
spans.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": span["start"],
|
||||
"ended_at": span.get("end") or None,
|
||||
"status": "completed" if span.get("end") or trace.get("is_completed") else "running",
|
||||
}
|
||||
)
|
||||
return spans
|
||||
|
||||
|
||||
def timeline_lane(
|
||||
trace: dict,
|
||||
trace_index: int,
|
||||
*,
|
||||
label: str,
|
||||
depth: int,
|
||||
branch: bool,
|
||||
lifecycle: list[dict],
|
||||
activities: list[dict],
|
||||
started_at: float | None = None,
|
||||
) -> dict:
|
||||
spans = lifecycle + activities
|
||||
starts = [span["started_at"] for span in spans if span.get("started_at") is not None]
|
||||
ends = [span["ended_at"] for span in spans if span.get("ended_at") is not None]
|
||||
started = started_at if started_at is not None else min(starts or ends, default=None)
|
||||
status = (
|
||||
("completed" if all(span["status"] == "completed" for span in lifecycle + activities) else "running")
|
||||
if branch
|
||||
else timeline_status(trace)
|
||||
)
|
||||
ended = max(ends, default=None) if status != "running" else None
|
||||
agent = trace.get("agent") or {}
|
||||
config = agent.get("config") or {}
|
||||
client = config.get("client") or {}
|
||||
|
||||
def total(field: str) -> int | float | None:
|
||||
values = [span[field] for span in activities if isinstance(span.get(field), (int, float))]
|
||||
return sum(values) if values else None
|
||||
|
||||
input_tokens = total("input_tokens")
|
||||
cached_tokens = total("cached_tokens")
|
||||
output_tokens = total("output_tokens")
|
||||
reasoning_tokens = total("reasoning_tokens")
|
||||
total_input_tokens = input_tokens + (cached_tokens or 0) if input_tokens is not None else None
|
||||
total_tokens = (
|
||||
total_input_tokens + output_tokens if total_input_tokens is not None and output_tokens is not None else None
|
||||
)
|
||||
context_lengths = [
|
||||
(span.get("input_tokens") or 0) + (span.get("cached_tokens") or 0)
|
||||
for span in activities
|
||||
if span.get("input_tokens") is not None
|
||||
]
|
||||
return {
|
||||
"trace_index": trace_index,
|
||||
"label": label,
|
||||
"model": config.get("model") or client.get("renderer_model_name") or "",
|
||||
"depth": depth,
|
||||
"started_at": started,
|
||||
"ended_at": ended,
|
||||
"status": status,
|
||||
"outcome": status if branch else (trace.get("stop_condition") or status),
|
||||
"reward": timeline_reward(trace),
|
||||
"usage": {
|
||||
"model_calls": len(activities),
|
||||
"input_tokens": input_tokens,
|
||||
"cached_tokens": cached_tokens,
|
||||
"total_input_tokens": total_input_tokens,
|
||||
"output_tokens": output_tokens,
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
"max_context_tokens": max(context_lengths, default=None),
|
||||
"total_tokens": total_tokens,
|
||||
"cost": total("cost"),
|
||||
},
|
||||
"spans": spans,
|
||||
}
|
||||
|
||||
|
||||
def project_episode_timeline(episode: dict) -> dict:
|
||||
lane_groups = []
|
||||
for trace_index, trace in enumerate(episode.get("traces") or []):
|
||||
nodes = trace.get("nodes") or []
|
||||
branch_paths = trace_branch_paths(nodes)
|
||||
node_branch_counts: dict[int, int] = {}
|
||||
for path in branch_paths:
|
||||
for node_index in path:
|
||||
node_branch_counts[node_index] = node_branch_counts.get(node_index, 0) + 1
|
||||
role = (trace.get("agent") or {}).get("name") or "agent"
|
||||
parent = timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=role,
|
||||
depth=0,
|
||||
branch=False,
|
||||
lifecycle=lifecycle_spans(trace),
|
||||
activities=activity_spans(trace, set(), include_unlinked=True),
|
||||
started_at=(trace.get("timing") or {}).get("start"),
|
||||
)
|
||||
branches = []
|
||||
for branch_index, path in enumerate(branch_paths):
|
||||
node_indexes = set(path)
|
||||
shared_node_indexes = {node_index for node_index in path if node_branch_counts.get(node_index, 0) > 1}
|
||||
unique_node_indexes = node_indexes - shared_node_indexes
|
||||
activities = activity_spans(
|
||||
trace,
|
||||
node_indexes,
|
||||
shared_node_indexes=shared_node_indexes,
|
||||
)
|
||||
path_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in path
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
unique_timestamps = [
|
||||
nodes[node_index].get("timestamp")
|
||||
for node_index in unique_node_indexes
|
||||
if nodes[node_index].get("timestamp") is not None
|
||||
]
|
||||
activity_starts = [span["started_at"] for span in activities if span["started_at"] is not None]
|
||||
unique_activity_starts = [
|
||||
span["started_at"] for span in activities if not span["shared"] and span["started_at"] is not None
|
||||
]
|
||||
branch_start = min(activity_starts or path_timestamps, default=None)
|
||||
sort_start = min(
|
||||
unique_activity_starts or unique_timestamps or activity_starts or path_timestamps, default=None
|
||||
)
|
||||
branch_end = max(
|
||||
[span["ended_at"] for span in activities if span.get("ended_at") is not None] + path_timestamps,
|
||||
default=None,
|
||||
)
|
||||
branch_completed = bool(trace.get("is_completed"))
|
||||
label = f"branch {branch_index}"
|
||||
branch_lifecycle = (
|
||||
[
|
||||
{
|
||||
"kind": "agent",
|
||||
"label": label,
|
||||
"track": "lifecycle",
|
||||
"started_at": branch_start,
|
||||
"ended_at": branch_end if branch_completed else None,
|
||||
"status": "completed" if branch_completed else "running",
|
||||
"node_index": path[-1],
|
||||
}
|
||||
]
|
||||
if branch_start is not None
|
||||
else []
|
||||
)
|
||||
branches.append(
|
||||
(
|
||||
sort_start,
|
||||
branch_index,
|
||||
timeline_lane(
|
||||
trace,
|
||||
trace_index,
|
||||
label=label,
|
||||
depth=1,
|
||||
branch=True,
|
||||
lifecycle=branch_lifecycle,
|
||||
activities=activities,
|
||||
),
|
||||
)
|
||||
)
|
||||
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
|
||||
lane_groups.append((parent, [lane for _, _, lane in branches]))
|
||||
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
|
||||
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
|
||||
return {"lanes": lanes}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts")
|
||||
def list_rollouts(run: str) -> dict:
|
||||
return {"steps": rollout_steps(get_run_dir(run))}
|
||||
@@ -1147,6 +1468,11 @@ async def view_events() -> "StreamingResponse":
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/rollouts/{step}/{kind}/{subset}/{line}/timeline")
|
||||
def get_episode_timeline(run: str, step: int, kind: str, subset: str, line: int) -> dict:
|
||||
return project_episode_timeline(read_episode_at(traces_path(run, step, kind, subset), line))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
@@ -31,7 +31,10 @@ const state = {
|
||||
paneOrder: prefs.paneOrder ?? {},
|
||||
},
|
||||
compare: { runs: [], data: new Map() },
|
||||
config: { loaded: false, files: [], file: null, fmt: "toml", cache: new Map() },
|
||||
config: {
|
||||
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
|
||||
files: [], file: null, fmt: "toml", commandText: "", cache: new Map(),
|
||||
},
|
||||
logs: {
|
||||
loaded: false, attempt: "latest", attempts: [], files: [], paneFile: {},
|
||||
components: prefs.logComponents ? new Set(prefs.logComponents) : null,
|
||||
@@ -188,8 +191,14 @@ async function selectRun(name, deferTab = false) {
|
||||
evalEtag: null, evalCount: 0, evalCost: null,
|
||||
};
|
||||
if (state.meta?.type === "eval") fetchEvalSeries(); // populates the overview cost early
|
||||
state.config = { loaded: false, files: [], file: null, fmt: state.config.fmt, cache: new Map() };
|
||||
state.logs = { ...state.logs, loaded: false, attempt: "latest", files: [], paneFile: {}, maximized: null, buffers: new Map() };
|
||||
state.config = {
|
||||
loaded: false, attempt: "latest", latestAttempt: null, attempts: [],
|
||||
files: [], file: null, fmt: state.config.fmt, commandText: "", cache: new Map(),
|
||||
};
|
||||
state.logs = {
|
||||
...state.logs, loaded: false, attempt: "latest", latestAttempt: null,
|
||||
files: [], paneFile: {}, maximized: null, buffers: new Map(),
|
||||
};
|
||||
state.traces = {
|
||||
...state.traces,
|
||||
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
|
||||
@@ -567,6 +576,7 @@ function buildSections(meta) {
|
||||
{ regex: `eval/${envPattern}/effective/[^/]+/avg@.*` },
|
||||
{ regex: `eval/${envPattern}/effective/[^/]+/reward/mean`, split: true },
|
||||
{ regex: `eval/${envPattern}/all/[^/]+/reward/mean`, split: true },
|
||||
{ regex: `eval/${envPattern}/all/cancelled/mean` },
|
||||
...COMMON_METRICS.map((m) => ({ regex: `eval/${envPattern}/${m}` })),
|
||||
...COMMON_REGEXES.map((r) => ({ regex: `eval/${envPattern}/${r}` })),
|
||||
],
|
||||
@@ -574,7 +584,10 @@ function buildSections(meta) {
|
||||
const sections = [];
|
||||
const evalEnvs = meta.eval_envs || [];
|
||||
if (meta.type === "sft") {
|
||||
sections.push({ name: "train", panels: SFT_TRAIN_METRICS.map((m) => ({ metric: m })) });
|
||||
const trainMetrics = meta.has_validation
|
||||
? SFT_TRAIN_METRICS
|
||||
: SFT_TRAIN_METRICS.filter((m) => !m.startsWith("val/"));
|
||||
sections.push({ name: "train", panels: trainMetrics.map((m) => ({ metric: m })) });
|
||||
if (evalEnvs.length) sections.push(...evalEnvs.map((e) => evalSection(`eval/${e}`, escRe(e), true)));
|
||||
else sections.push(evalSection("eval", ".*"));
|
||||
sections.push({ name: "stability", panels: SFT_STABILITY_METRICS.map((m) => ({ metric: m })) });
|
||||
@@ -681,6 +694,15 @@ function groupColors(groups) {
|
||||
return groups.length > 1 ? groups.map((_, i) => PALETTE[i % PALETTE.length]) : [SINGLE_SERIES];
|
||||
}
|
||||
|
||||
function singletonPoints(series, color) {
|
||||
return {
|
||||
show: () => series.points.size === 1,
|
||||
size: 6,
|
||||
width: 0,
|
||||
fill: color,
|
||||
};
|
||||
}
|
||||
|
||||
/* flatten groups into uPlot series defs + data columns + tooltip meta */
|
||||
function buildChartLayout(entry, timeAxis) {
|
||||
const groups = panelGroups(entry.series);
|
||||
@@ -705,7 +727,7 @@ function buildChartLayout(entry, timeAxis) {
|
||||
width: 1.25,
|
||||
dash: si > 0 ? [6, 4] : undefined,
|
||||
spanGaps: true,
|
||||
points: { show: false },
|
||||
points: singletonPoints(strand.main, color),
|
||||
});
|
||||
const m = { label: labels[mainIdx] || "value", stat: statOf(strand.main.key) ?? "value", color, dataIdx: cols.length };
|
||||
meta.push(m);
|
||||
@@ -714,7 +736,14 @@ function buildChartLayout(entry, timeAxis) {
|
||||
const bandIdx = {};
|
||||
for (const s of aux) {
|
||||
cols.push({ s, role: "aux" });
|
||||
uSeries.push({ stroke: hexToRgba(color, 0.55), width: 1, dash: [3, 3], spanGaps: true, points: { show: false } });
|
||||
const auxColor = hexToRgba(color, 0.55);
|
||||
uSeries.push({
|
||||
stroke: auxColor,
|
||||
width: 1,
|
||||
dash: [3, 3],
|
||||
spanGaps: true,
|
||||
points: singletonPoints(s, auxColor),
|
||||
});
|
||||
if (s === strand.lo) bandIdx.lo = cols.length;
|
||||
if (s === strand.hi) bandIdx.hi = cols.length;
|
||||
}
|
||||
@@ -1198,19 +1227,23 @@ async function initMetrics() {
|
||||
/* ----------------------------------------------------------------- config */
|
||||
|
||||
|
||||
/* both views are fetched once per run, so the TOML/JSON toggle never waits on
|
||||
the network */
|
||||
/* config artifacts are fetched once per attempt, so format changes never wait
|
||||
on the network */
|
||||
async function fetchConfigText(file) {
|
||||
const cache = state.config.cache;
|
||||
if (cache.has(file)) return cache.get(file);
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}`);
|
||||
const key = `${state.config.attempt}:${file}`;
|
||||
if (cache.has(key)) return cache.get(key);
|
||||
const data = await api(
|
||||
`/api/runs/${encodeURIComponent(state.run)}/config?file=${encodeURIComponent(file)}` +
|
||||
`&attempt=${encodeURIComponent(state.config.attempt)}`
|
||||
);
|
||||
let text = data.content;
|
||||
try {
|
||||
text = JSON.stringify(JSON.parse(text), null, 2);
|
||||
} catch {
|
||||
/* show raw content if not valid JSON */
|
||||
}
|
||||
cache.set(file, text);
|
||||
cache.set(key, text);
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -1325,6 +1358,10 @@ function applyConfigSearch() {
|
||||
} catch {
|
||||
re = new RegExp(escRe(query), "gi");
|
||||
}
|
||||
const test = (line) => {
|
||||
re.lastIndex = 0;
|
||||
return re.test(line);
|
||||
};
|
||||
const noHits = () => {
|
||||
view.innerHTML = emptyState("no hits", "nothing in this config matches the filter");
|
||||
hitsEl.textContent = "no hits";
|
||||
@@ -1337,10 +1374,6 @@ function applyConfigSearch() {
|
||||
// TOML (launch config): a matching line keeps itself (plus its [section]
|
||||
// header for context); a matching [section] header keeps the whole section
|
||||
const lines = (state.config.text ?? "").split("\n");
|
||||
const test = (line) => {
|
||||
re.lastIndex = 0;
|
||||
return re.test(line);
|
||||
};
|
||||
const kept = [];
|
||||
let header = null;
|
||||
let headerKept = false;
|
||||
@@ -1399,10 +1432,12 @@ function applyConfigSearch() {
|
||||
view.querySelector("mark.hit")?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
|
||||
/* TOML = the launch config as it was passed, JSON = the concatenated resolved dumps */
|
||||
/* TOML = launch config, JSON = resolved dumps */
|
||||
function configFileFor(fmt) {
|
||||
const files = state.config.files || [];
|
||||
return fmt === "toml" ? files.find((f) => f.endsWith(".toml")) : files.find((f) => f === "resolved");
|
||||
if (fmt === "toml") return files.find((f) => f.endsWith(".toml"));
|
||||
if (fmt === "json") return files.find((f) => f === "resolved");
|
||||
return files.find((f) => f === "command.txt");
|
||||
}
|
||||
|
||||
function renderConfigFormat() {
|
||||
@@ -1412,21 +1447,55 @@ function renderConfigFormat() {
|
||||
}
|
||||
}
|
||||
|
||||
async function initConfig() {
|
||||
state.config.loaded = true;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/configs`);
|
||||
function renderConfigAttempts() {
|
||||
const config = state.config;
|
||||
const latest = config.latestAttempt == null ? "latest" : `latest (attempt ${config.latestAttempt})`;
|
||||
$("#config-attempt-select").innerHTML =
|
||||
`<option value="latest" ${config.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
|
||||
config.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(config.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
syncDressedSelects();
|
||||
}
|
||||
|
||||
function renderConfigCommand() {
|
||||
const command = state.config.commandText.trimEnd();
|
||||
$("#config-command").classList.toggle("empty", !command);
|
||||
$("#config-command-text").textContent = command || "command unavailable for this attempt";
|
||||
$("#config-command-copy").disabled = !command;
|
||||
}
|
||||
|
||||
async function loadConfigAttempt() {
|
||||
const data = await api(
|
||||
`/api/runs/${encodeURIComponent(state.run)}/configs?attempt=${encodeURIComponent(state.config.attempt)}`
|
||||
);
|
||||
state.config.latestAttempt = state.config.attempt === "latest" ? data.attempt : state.config.latestAttempt;
|
||||
state.config.attempts = data.attempts;
|
||||
state.config.files = data.files;
|
||||
if (!data.files.length) {
|
||||
renderConfigAttempts();
|
||||
const commandFile = configFileFor("command");
|
||||
state.config.commandText = commandFile ? await fetchConfigText(commandFile) : "";
|
||||
renderConfigCommand();
|
||||
if (!configFileFor("toml") && !configFileFor("json")) {
|
||||
renderConfigFormat();
|
||||
$("#config-view").innerHTML = emptyState("no configs", "this run has no configs/ directory");
|
||||
$("#config-view").innerHTML = emptyState("no configs", "this attempt has no config files");
|
||||
return;
|
||||
}
|
||||
if (!configFileFor(state.config.fmt)) state.config.fmt = configFileFor("toml") ? "toml" : "json";
|
||||
if (!configFileFor(state.config.fmt)) {
|
||||
state.config.fmt = ["toml", "json"].find((fmt) => configFileFor(fmt));
|
||||
}
|
||||
state.config.file = configFileFor(state.config.fmt);
|
||||
renderConfigFormat();
|
||||
await loadConfig();
|
||||
const other = configFileFor(state.config.fmt === "toml" ? "json" : "toml");
|
||||
if (other) fetchConfigText(other); // warm the other side of the toggle
|
||||
for (const fmt of ["toml", "json"]) {
|
||||
const file = configFileFor(fmt);
|
||||
if (file && file !== state.config.file) fetchConfigText(file);
|
||||
}
|
||||
}
|
||||
|
||||
async function initConfig() {
|
||||
state.config.loaded = true;
|
||||
await loadConfigAttempt();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- logs */
|
||||
@@ -1559,9 +1628,12 @@ function dressLogPaneSelects() {
|
||||
|
||||
function renderLogPanes() {
|
||||
const logs = state.logs;
|
||||
$("#attempt-select").innerHTML = logs.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
const latest = logs.latestAttempt == null ? "latest" : `latest (attempt ${logs.latestAttempt})`;
|
||||
$("#attempt-select").innerHTML =
|
||||
`<option value="latest" ${logs.attempt === "latest" ? "selected" : ""}>${latest}</option>` +
|
||||
logs.attempts
|
||||
.map((a) => `<option value="${a}" ${String(a) === String(logs.attempt) ? "selected" : ""}>attempt ${a}</option>`)
|
||||
.join("");
|
||||
renderLogCompMenu();
|
||||
const container = $("#log-panes");
|
||||
container.innerHTML = "";
|
||||
@@ -1736,7 +1808,7 @@ async function loadLogfiles() {
|
||||
const logs = state.logs;
|
||||
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/logfiles?attempt=${logs.attempt}`);
|
||||
logs.attempts = data.attempts;
|
||||
logs.attempt = data.attempt;
|
||||
if (logs.attempt === "latest") logs.latestAttempt = data.attempt;
|
||||
logs.files = data.files;
|
||||
renderLogPanes();
|
||||
dressLogPaneSelects();
|
||||
@@ -1962,6 +2034,10 @@ let currentTraceIdx = 0;
|
||||
let currentBranchIdx = 0;
|
||||
let episodeOpenVersion = 0;
|
||||
let episodeEnrichmentVersion = 0;
|
||||
let currentTimeline = null;
|
||||
let traceView = prefs.traceView === "timeline" ? "timeline" : "transcript";
|
||||
let pendingTimelineNode = null;
|
||||
let pendingTimelineCall = null;
|
||||
|
||||
const COPY_SVG =
|
||||
`<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">` +
|
||||
@@ -2075,6 +2151,20 @@ function fetchEpisode(line, withTokens, withRendered = false) {
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}${qs}`);
|
||||
}
|
||||
|
||||
function fetchEpisodeTimeline(line) {
|
||||
const traces = state.traces;
|
||||
return api(`/api/runs/${encodeURIComponent(state.run)}/rollouts/${traces.step}/${traces.kind}/${traces.subset}/${line}/timeline`);
|
||||
}
|
||||
|
||||
async function ensureTimeline() {
|
||||
if (currentTimeline || currentLine == null) return;
|
||||
const line = currentLine;
|
||||
const requestVersion = episodeOpenVersion;
|
||||
const timeline = await fetchEpisodeTimeline(line);
|
||||
if (line !== currentLine || requestVersion !== episodeOpenVersion) return;
|
||||
currentTimeline = timeline;
|
||||
}
|
||||
|
||||
/* token strings multiply the payload of a big episode, so they are fetched only
|
||||
for token signals or the rendered-token view — the plain view ships the raw record */
|
||||
async function ensureTokens() {
|
||||
@@ -2103,7 +2193,11 @@ async function openEpisode(line, target = {}) {
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
$("#tm-timeline").innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
$("#tm-meta").innerHTML = "";
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
const withTokens = !!$("#token-signal").value;
|
||||
const withRendered = state.traces.viewMode === "rendered";
|
||||
const episode = await fetchEpisode(line, withTokens, withRendered);
|
||||
@@ -2113,6 +2207,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = episode;
|
||||
currentTraceIdx = target.trace ?? 0;
|
||||
currentBranchIdx = target.branch ?? 0;
|
||||
if (traceView === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
await ensureTokens();
|
||||
if (line === currentLine && requestVersion === episodeOpenVersion) renderEpisode();
|
||||
@@ -2125,6 +2220,9 @@ function closeDrawer() {
|
||||
$("#drawer-backdrop").hidden = true;
|
||||
$("#tm-back").hidden = true;
|
||||
currentEpisode = null;
|
||||
currentTimeline = null;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
currentLine = null;
|
||||
pendingHighlight = null;
|
||||
}
|
||||
@@ -2367,6 +2465,22 @@ function errorBannersHtml(errors) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
if (cached == null) {
|
||||
cached = usage.prompt_tokens_details?.cached_tokens;
|
||||
if (input != null && cached) input = Math.max(0, input - cached);
|
||||
}
|
||||
return {
|
||||
input,
|
||||
cached,
|
||||
output: usage.completion_tokens,
|
||||
reasoning: usage.reasoning_tokens ?? usage.completion_tokens_details?.reasoning_tokens,
|
||||
cost: usage.cost,
|
||||
};
|
||||
}
|
||||
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
@@ -2387,7 +2501,22 @@ function renderMessages(ep, trace, branches) {
|
||||
let maxAbsAdv = 0;
|
||||
for (const node of trace.nodes || [])
|
||||
for (const a of node.advantages || []) maxAbsAdv = Math.max(maxAbsAdv, Math.abs(a));
|
||||
const callsByNode = new Map((trace.calls || []).map((c) => [c.node, c]));
|
||||
const indexedCalls = (trace.calls || []).map((call, index) => ({ call, index }));
|
||||
const callsByNode = new Map();
|
||||
for (const item of indexedCalls) {
|
||||
const calls = callsByNode.get(item.call.node) || [];
|
||||
calls.push(item);
|
||||
callsByNode.set(item.call.node, calls);
|
||||
}
|
||||
const callChipHtml = ({ call, index }) => {
|
||||
const fields = [`call ${index + 1}`];
|
||||
if (call.finish_reason) fields.push(call.finish_reason);
|
||||
const { input, cached, output } = normalizedCallUsage(call.usage);
|
||||
if (input != null) fields.push(`${fmtCompact(input)} in`);
|
||||
if (cached != null) fields.push(`${fmtCompact(cached)} cache`);
|
||||
if (output != null) fields.push(`${fmtCompact(output)} out`);
|
||||
return `<span class="chip" data-call-index="${index}">${esc(fields.join(" · "))}</span>`;
|
||||
};
|
||||
// agent highlights (sticky until the next view command or drawer close)
|
||||
const hl =
|
||||
pendingHighlight &&
|
||||
@@ -2407,14 +2536,12 @@ function renderMessages(ep, trace, branches) {
|
||||
const entryHtml = (idx, i) => {
|
||||
const node = trace.nodes[idx];
|
||||
const role = node.message?.role ?? "?";
|
||||
const call = callsByNode.get(idx);
|
||||
const marks = hlByNode.get(idx) || [];
|
||||
const chips = [];
|
||||
if (concatenated && node.parent != null && node.parent !== idx - 1) chips.push(`↳ branches from ${node.parent + 1}`);
|
||||
if (node.sampled) chips.push("sampled");
|
||||
if (call?.finish_reason) chips.push(call.finish_reason);
|
||||
if (call?.usage) chips.push(`${call.usage.prompt_tokens ?? "?"}→${call.usage.completion_tokens ?? "?"} tok`);
|
||||
else if (node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const nodeCalls = callsByNode.get(idx) || [];
|
||||
if (!nodeCalls.length && node.token_ids?.length) chips.push(`${node.token_ids.length} tok`);
|
||||
const text = messageText(node.message);
|
||||
const contentMarks = marks.filter((h) => !h.field || h.field === "content");
|
||||
const contentMarked = contentMarks.some((h) => h.quote && findQuote(text, h.quote, h.prefix, h.suffix));
|
||||
@@ -2431,11 +2558,12 @@ function renderMessages(ep, trace, branches) {
|
||||
if (reasoning) subs.push(reasoningBlock(reasoning, reasoningMarks));
|
||||
const toolCalls = (node.message?.tool_calls || []).map(toolCallHtml);
|
||||
const messageHtml =
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<details class="entry ${esc(role)}${marked ? " hl-entry" : ""}" data-node="${idx}"${role === "system" && !marked ? "" : " open"}>` +
|
||||
`<summary><span class="entry-num">${String(i + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">${esc(role)}</span>` +
|
||||
`<span class="entry-preview">${preview(text, 180)}</span>` +
|
||||
chips.map((c) => `<span class="chip">${esc(c)}</span>`).join("") +
|
||||
nodeCalls.map(callChipHtml).join("") +
|
||||
`<button class="icon-btn" data-copy="${idx}" title="copy message">${COPY_SVG}</button>` +
|
||||
`<span class="entry-chev">›</span></summary>` +
|
||||
subs.join("") +
|
||||
@@ -2449,11 +2577,23 @@ function renderMessages(ep, trace, branches) {
|
||||
// first chunk forces enough entries into the DOM to scroll to
|
||||
const CHUNK = 30;
|
||||
const lastMark = Math.max(-1, ...[...hlByNode.keys()].map((n) => path.indexOf(n)));
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3));
|
||||
const targetPosition = pendingTimelineNode == null ? -1 : path.indexOf(pendingTimelineNode);
|
||||
let rendered = Math.min(path.length, Math.max(CHUNK, lastMark + 3, targetPosition + 1));
|
||||
const unlinkedCallsHtml = indexedCalls
|
||||
.filter(({ call }) => !Number.isInteger(call.node) || call.node < 0 || call.node >= (trace.nodes || []).length)
|
||||
.map(
|
||||
(item) =>
|
||||
`<details class="entry model-call" data-call-index="${item.index}" open>` +
|
||||
`<summary><span class="entry-num">C${String(item.index + 1).padStart(2, "0")}</span>` +
|
||||
`<span class="entry-role">model call</span><span class="entry-preview">${esc(item.call.model || "unlinked call")}</span>` +
|
||||
`${callChipHtml(item)}<span class="entry-chev">›</span></summary></details>`,
|
||||
)
|
||||
.join("");
|
||||
container.innerHTML =
|
||||
(systemPosition === -1 ? toolsHtml : "") +
|
||||
path.slice(0, rendered).map(entryHtml).join("") +
|
||||
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
|
||||
unlinkedCallsHtml +
|
||||
errorsHtml;
|
||||
if (hl && !hl.scrolled) {
|
||||
const first = container.querySelector(".hl-entry");
|
||||
@@ -2537,28 +2677,35 @@ function renderMeta(ep, trace, branches) {
|
||||
parts.push(metaRow("branches", branches.length));
|
||||
parts.push(metaRow("tool calls", nodes.reduce((acc, n) => acc + (n.message?.tool_calls?.length || 0), 0)));
|
||||
|
||||
const usage = { input: 0, output: 0, reasoning: 0, cached: 0 };
|
||||
let hasUsage = false;
|
||||
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
|
||||
const addUsage = (field, value) => {
|
||||
if (value != null) usage[field] = (usage[field] ?? 0) + value;
|
||||
};
|
||||
for (const call of trace.calls || []) {
|
||||
const u = call.usage || {};
|
||||
if (u.prompt_tokens != null || u.completion_tokens != null) hasUsage = true;
|
||||
usage.input += u.prompt_tokens ?? 0;
|
||||
usage.output += u.completion_tokens ?? 0;
|
||||
usage.reasoning += u.completion_tokens_details?.reasoning_tokens ?? 0;
|
||||
usage.cached += u.prompt_tokens_details?.cached_tokens ?? 0;
|
||||
const current = normalizedCallUsage(call.usage);
|
||||
addUsage("input", current.input);
|
||||
addUsage("cached", current.cached);
|
||||
addUsage("output", current.output);
|
||||
addUsage("reasoning", current.reasoning);
|
||||
addUsage("cost", current.cost);
|
||||
if (current.input != null) {
|
||||
const context = current.input + (current.cached ?? 0);
|
||||
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
|
||||
}
|
||||
}
|
||||
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
|
||||
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
|
||||
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
|
||||
if (hasUsage) {
|
||||
parts.push(`<div class="meta-sec">usage</div>`);
|
||||
parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.cached) parts.push(metaRow("cached tokens", fmtCompact(usage.cached)));
|
||||
// API-priced runs report per-call cost; local deployments usually don't
|
||||
const traceCost = (t) => (t.calls || []).reduce((acc, c) => acc + (c.usage?.cost ?? 0), 0);
|
||||
const allTraces = ep.traces || [];
|
||||
if (allTraces.some((t) => (t.calls || []).some((c) => c.usage?.cost != null)))
|
||||
parts.push(metaRow("cost", fmtCost(allTraces.reduce((acc, t) => acc + traceCost(t), 0))));
|
||||
parts.push(metaRow("total tokens", fmtCompact(usage.input + usage.output)));
|
||||
if (usage.input != null) parts.push(metaRow("input tokens", fmtCompact(usage.input)));
|
||||
if (usage.cached != null) parts.push(metaRow("cached input", fmtCompact(usage.cached)));
|
||||
if (totalInput != null) parts.push(metaRow("total input", fmtCompact(totalInput)));
|
||||
if (usage.output != null) parts.push(metaRow("output tokens", fmtCompact(usage.output)));
|
||||
if (usage.reasoning != null) parts.push(metaRow("reasoning tokens", fmtCompact(usage.reasoning)));
|
||||
if (usage.maxContext != null) parts.push(metaRow("max context length", fmtCompact(usage.maxContext)));
|
||||
if (usage.cost != null) parts.push(metaRow("cost", fmtCost(usage.cost)));
|
||||
if (totalTokens != null) parts.push(metaRow("total tokens", fmtCompact(totalTokens)));
|
||||
}
|
||||
|
||||
parts.push(`<div class="meta-sec">state</div>`);
|
||||
@@ -2598,6 +2745,122 @@ function renderMeta(ep, trace, branches) {
|
||||
$("#tm-meta").innerHTML = parts.join("");
|
||||
}
|
||||
|
||||
function timelineClock(ts) {
|
||||
if (ts == null) return "—";
|
||||
return new Date(ts * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
}
|
||||
|
||||
function timelineTipAttr(payload) {
|
||||
return ` data-timeline-tip="${esc(JSON.stringify(payload))}"`;
|
||||
}
|
||||
|
||||
function appendTimelineUsage(rows, usage, aggregate = false) {
|
||||
if (!usage) return;
|
||||
if (aggregate && usage.model_calls != null) rows.push(["model calls", fmtNum(usage.model_calls)]);
|
||||
if (usage.input_tokens != null) rows.push(["input tokens", fmtCompact(usage.input_tokens)]);
|
||||
if (usage.cached_tokens != null) rows.push(["cached input", fmtCompact(usage.cached_tokens)]);
|
||||
if (usage.total_input_tokens != null) rows.push(["total input", fmtCompact(usage.total_input_tokens)]);
|
||||
if (usage.output_tokens != null) rows.push(["output tokens", fmtCompact(usage.output_tokens)]);
|
||||
if (usage.reasoning_tokens != null) rows.push(["reasoning tokens", fmtCompact(usage.reasoning_tokens)]);
|
||||
if (usage.max_context_tokens != null) rows.push(["max context length", fmtCompact(usage.max_context_tokens)]);
|
||||
if (usage.total_tokens != null) rows.push(["total tokens", fmtCompact(usage.total_tokens)]);
|
||||
if (usage.cost != null) rows.push(["cost", fmtCost(usage.cost)]);
|
||||
}
|
||||
|
||||
function timelineSpanHtml(lane, span, start, total) {
|
||||
const partial = span.started_at == null || span.ended_at == null;
|
||||
const left = span.started_at == null ? 0 : Math.max(0, Math.min(100, ((span.started_at - start) / total) * 100));
|
||||
const width = partial ? 0.35 : Math.max(0.35, Math.min(100 - left, ((span.ended_at - span.started_at) / total) * 100));
|
||||
const rows = [
|
||||
["start", span.started_at == null ? "unknown" : timelineClock(span.started_at)],
|
||||
["end", span.ended_at == null ? (span.status === "running" ? "open" : "unknown") : timelineClock(span.ended_at)],
|
||||
["duration", partial ? "—" : fmtDuration(span.ended_at - span.started_at)],
|
||||
];
|
||||
if (span.track === "activity") {
|
||||
if (span.shared) rows.push(["branch role", "shared prefix"]);
|
||||
const totalInput = span.input_tokens == null ? null : span.input_tokens + (span.cached_tokens || 0);
|
||||
appendTimelineUsage(rows, {
|
||||
input_tokens: span.input_tokens,
|
||||
cached_tokens: span.cached_tokens,
|
||||
total_input_tokens: totalInput,
|
||||
output_tokens: span.output_tokens,
|
||||
reasoning_tokens: span.reasoning_tokens,
|
||||
max_context_tokens: totalInput,
|
||||
total_tokens: totalInput == null || span.output_tokens == null ? null : totalInput + span.output_tokens,
|
||||
cost: span.cost,
|
||||
});
|
||||
} else {
|
||||
appendTimelineUsage(rows, lane.usage, true);
|
||||
}
|
||||
const tip = timelineTipAttr({
|
||||
kind: span.track === "activity" ? "activity" : "lifecycle",
|
||||
title: `${lane.label} — ${span.label}`,
|
||||
snippet: span.snippet || "",
|
||||
rows,
|
||||
hint: span.track === "activity" ? "Click to open this call in the transcript." : "Click to open this trace transcript.",
|
||||
});
|
||||
const node = span.node_index == null ? "" : ` data-tl-node="${span.node_index}"`;
|
||||
const call = span.call_index == null ? "" : ` data-tl-call="${span.call_index}"`;
|
||||
return (
|
||||
`<button class="tl-span ${esc(span.track)} ${esc(span.kind)} ${span.shared ? "shared" : ""} ${span.status === "running" ? "running" : ""} ${partial ? "untimed" : ""}"` +
|
||||
` style="left:${left.toFixed(3)}%;width:${width.toFixed(3)}%" data-tl-trace="${lane.trace_index}"${node}${call}${tip}></button>`
|
||||
);
|
||||
}
|
||||
|
||||
function timelineLaneHtml(lane, start, total) {
|
||||
const grids = [25, 50, 75].map((left) => `<i class="tl-gridline" style="left:${left}%"></i>`).join("");
|
||||
const spans = (lane.spans || []).map((span) => timelineSpanHtml(lane, span, start, total)).join("");
|
||||
const duration = lane.started_at == null || lane.ended_at == null ? "—" : fmtDuration(lane.ended_at - lane.started_at);
|
||||
const ended = lane.ended_at == null ? (lane.status === "running" ? "open" : "unknown") : timelineClock(lane.ended_at);
|
||||
const model = lane.model
|
||||
? `<div class="tl-label-meta" title="${esc(lane.model)}">${esc(lane.model)}</div>`
|
||||
: "";
|
||||
return (
|
||||
`<div class="tl-lane" data-tl-trace="${lane.trace_index}">` +
|
||||
`<div class="tl-label" style="padding-left:${10 + (lane.depth || 0) * 18}px">` +
|
||||
`${lane.depth ? '<span class="tl-tree">└</span>' : ""}<span class="tl-dot" style="background:${PALETTE[lane.trace_index % PALETTE.length]}"></span>` +
|
||||
`<span class="tl-label-copy"><div class="tl-label-name" title="${esc(lane.label)}">${esc(lane.label)}</div>` +
|
||||
`${model}</span></div>` +
|
||||
`<div class="tl-track">${grids}${spans}</div>` +
|
||||
`<div class="tl-time"><span>${duration}</span><span class="muted">${ended}</span></div>` +
|
||||
`<div class="tl-outcome"><span class="tl-state ${esc(lane.status)}">${esc(lane.outcome || lane.status)}</span>` +
|
||||
`${lane.reward == null ? "" : `<span class="tl-reward">reward ${fmtReward(lane.reward)}</span>`}</div></div>`
|
||||
);
|
||||
}
|
||||
|
||||
function renderTimeline() {
|
||||
const target = $("#tm-timeline");
|
||||
const timeline = currentTimeline;
|
||||
if (!timeline) {
|
||||
target.innerHTML = `<div class="chart-empty">loading timeline…</div>`;
|
||||
return;
|
||||
}
|
||||
if (!(timeline.lanes || []).length) {
|
||||
target.innerHTML = emptyState("no timeline", "this episode carries no agent traces");
|
||||
return;
|
||||
}
|
||||
const starts = timeline.lanes.map((lane) => lane.started_at).filter((value) => value != null);
|
||||
const ends = timeline.lanes.map((lane) => lane.ended_at ?? lane.started_at).filter((value) => value != null);
|
||||
const start = starts.length ? Math.min(...starts) : 0;
|
||||
const end = ends.length ? Math.max(...ends) : start + 1;
|
||||
const total = Math.max(1, end - start);
|
||||
const axis = [0, 0.25, 0.5, 0.75, 1]
|
||||
.map((fraction) => `<span style="left:${fraction * 100}%">${fraction ? fmtDuration(total * fraction) : "0"}</span>`)
|
||||
.join("");
|
||||
target.innerHTML =
|
||||
`<div class="tl-shell"><div class="tl-head"><span>branches</span><div class="tl-axis">${axis}</div><span>duration / end</span><span>state / outcome</span></div>` +
|
||||
timeline.lanes.map((lane) => timelineLaneHtml(lane, start, total)).join("") +
|
||||
`</div>`;
|
||||
}
|
||||
|
||||
async function setTraceView(view) {
|
||||
traceView = view;
|
||||
setActive("#tm-view", "view", view);
|
||||
if (view === "timeline") await ensureTimeline();
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
}
|
||||
|
||||
function renderEpisode() {
|
||||
const ep = currentEpisode;
|
||||
if (!ep) return;
|
||||
@@ -2608,14 +2871,10 @@ function renderEpisode() {
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
// multi-agent episodes: label each trace by its agent name (seat), index only
|
||||
// as a tiebreak when names repeat or are missing
|
||||
const names = traces.map((t) => t.agent?.name);
|
||||
const label = (i) => (names[i] && names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : `${names[i] ?? "trace"} ${i}`);
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((_, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(label(i))}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -2627,10 +2886,18 @@ function renderEpisode() {
|
||||
.join("") +
|
||||
`<button data-branch="-1" class="${currentBranchIdx === -1 ? "active" : ""}" title="all branches concatenated top to bottom">all</button>`
|
||||
: "";
|
||||
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
|
||||
setActive("#trace-view-mode", "mode", state.traces.viewMode);
|
||||
renderRolloutList();
|
||||
renderMessages(ep, trace, branches);
|
||||
const timeline = traceView === "timeline";
|
||||
$("#tm-tabs-row").hidden = timeline || (traceTabs.hidden && branchTabs.hidden);
|
||||
$("#tm-messages").hidden = timeline;
|
||||
$("#tm-timeline").hidden = !timeline;
|
||||
$("#token-signal").closest(".dd-select").hidden = timeline;
|
||||
$("#tm-collapse").hidden = timeline;
|
||||
$("#tm-expand").hidden = timeline;
|
||||
setActive("#tm-view", "view", traceView);
|
||||
if (timeline) renderTimeline();
|
||||
else renderMessages(ep, trace, branches);
|
||||
renderMeta(ep, trace, branches);
|
||||
}
|
||||
|
||||
@@ -3318,6 +3585,10 @@ $("#config-format").addEventListener("click", (e) => {
|
||||
renderConfigFormat();
|
||||
loadConfig();
|
||||
});
|
||||
$("#config-command-copy").addEventListener("click", (e) => {
|
||||
const command = state.config.commandText.trimEnd();
|
||||
if (command) copyText(command, e.currentTarget);
|
||||
});
|
||||
$("#config-search").addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
@@ -3421,6 +3692,11 @@ $("#attempt-select").addEventListener("change", async (e) => {
|
||||
await loadLogfiles();
|
||||
await pollLogs();
|
||||
});
|
||||
$("#config-attempt-select").addEventListener("change", async (e) => {
|
||||
state.config.attempt = e.target.value;
|
||||
state.config.file = null;
|
||||
await loadConfigAttempt();
|
||||
});
|
||||
$("#log-panes").addEventListener("change", async (e) => {
|
||||
const select = e.target.closest(".lp-file");
|
||||
if (!select) return;
|
||||
@@ -3654,6 +3930,75 @@ $("#trace-view-mode").addEventListener("click", async (e) => {
|
||||
renderEpisode();
|
||||
savePrefs();
|
||||
});
|
||||
$("#tm-view").addEventListener("click", (e) => {
|
||||
const button = e.target.closest("[data-view]");
|
||||
if (button && button.dataset.view !== traceView) setTraceView(button.dataset.view);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("click", async (e) => {
|
||||
const target = e.target.closest("[data-tl-trace]");
|
||||
if (!target) return;
|
||||
e.stopPropagation();
|
||||
currentTraceIdx = +target.dataset.tlTrace;
|
||||
const node = target.dataset.tlNode == null ? null : +target.dataset.tlNode;
|
||||
const call = target.dataset.tlCall == null ? null : +target.dataset.tlCall;
|
||||
if (node != null) {
|
||||
const trace = currentEpisode?.traces?.[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
const branch = branches.findIndex((path) => path.includes(node));
|
||||
currentBranchIdx = branch >= 0 ? branch : -1;
|
||||
pendingTimelineNode = node;
|
||||
pendingTimelineCall = call;
|
||||
state.traces.viewMode = "messages";
|
||||
} else {
|
||||
currentBranchIdx = 0;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = call;
|
||||
if (call != null) state.traces.viewMode = "messages";
|
||||
}
|
||||
await setTraceView("transcript");
|
||||
requestAnimationFrame(() => {
|
||||
const entry =
|
||||
pendingTimelineCall == null
|
||||
? pendingTimelineNode == null
|
||||
? null
|
||||
: $(`#tm-messages [data-node="${pendingTimelineNode}"]`)
|
||||
: $(`#tm-messages [data-call-index="${pendingTimelineCall}"]`);
|
||||
entry?.scrollIntoView({ block: "center" });
|
||||
const details = entry?.closest("details");
|
||||
if (details) details.open = true;
|
||||
pendingTimelineNode = null;
|
||||
pendingTimelineCall = null;
|
||||
});
|
||||
});
|
||||
const timelineTip = document.createElement("div");
|
||||
timelineTip.className = "tl-tooltip";
|
||||
timelineTip.hidden = true;
|
||||
document.body.appendChild(timelineTip);
|
||||
function moveTimelineTip(e) {
|
||||
const gap = 12;
|
||||
const left = Math.min(e.clientX + gap, window.innerWidth - timelineTip.offsetWidth - 8);
|
||||
const top = Math.min(e.clientY + gap, window.innerHeight - timelineTip.offsetHeight - 8);
|
||||
timelineTip.style.left = `${Math.max(8, left)}px`;
|
||||
timelineTip.style.top = `${Math.max(8, top)}px`;
|
||||
}
|
||||
$("#tm-timeline").addEventListener("mouseover", (e) => {
|
||||
const target = e.target.closest("[data-timeline-tip]");
|
||||
if (!target) return;
|
||||
const payload = JSON.parse(target.dataset.timelineTip);
|
||||
timelineTip.innerHTML =
|
||||
`<div class="tl-tooltip-kind">${esc(payload.kind)}</div><div class="tl-tooltip-title">${esc(payload.title)}</div>` +
|
||||
`${payload.snippet ? `<div class="tl-tooltip-snippet">${esc(payload.snippet)}</div>` : ""}` +
|
||||
`<dl>${payload.rows.map(([key, value]) => `<dt>${esc(key)}</dt><dd>${esc(value)}</dd>`).join("")}</dl>` +
|
||||
`<div class="tl-tooltip-hint">${esc(payload.hint)}</div>`;
|
||||
timelineTip.hidden = false;
|
||||
moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mousemove", (e) => {
|
||||
if (!timelineTip.hidden) moveTimelineTip(e);
|
||||
});
|
||||
$("#tm-timeline").addEventListener("mouseout", (e) => {
|
||||
if (e.target.closest("[data-timeline-tip]") && !e.relatedTarget?.closest?.("[data-timeline-tip]")) timelineTip.hidden = true;
|
||||
});
|
||||
$("#tm-trace-tabs").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-trace]");
|
||||
if (btn) { currentTraceIdx = +btn.dataset.trace; currentBranchIdx = 0; renderEpisode(); }
|
||||
@@ -3734,6 +4079,7 @@ function savePrefs() {
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceSort: `${state.traces.sort}:${state.traces.order}`,
|
||||
traceViewMode: state.traces.viewMode,
|
||||
traceView,
|
||||
logView: state.logs.view,
|
||||
logComponents: state.logs.components ? [...state.logs.components] : null,
|
||||
logLevel: state.logs.level,
|
||||
@@ -3800,7 +4146,7 @@ document.addEventListener("visibilitychange", () => {
|
||||
$("#config-search").value = prefs.configSearch ?? "";
|
||||
$("#token-signal").value = prefs.tokenSignal === "rendered" ? "" : (prefs.tokenSignal ?? "");
|
||||
$("#follow-toggle").checked = state.follow;
|
||||
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal", "#report-select"])
|
||||
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
dressSelect($(sel));
|
||||
syncTraceFilterControls();
|
||||
setActive("#metrics-mode", "mode", state.metrics.mode);
|
||||
|
||||
@@ -55,6 +55,8 @@
|
||||
|
||||
<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,6 +64,16 @@
|
||||
<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>
|
||||
|
||||
@@ -203,6 +215,10 @@
|
||||
<div class="tm-head">
|
||||
<span class="tm-title">Trace Viewer</span>
|
||||
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
|
||||
<div class="seg" id="tm-view">
|
||||
<button data-view="transcript" class="active">Transcript</button>
|
||||
<button data-view="timeline">Timeline</button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="trace-view-mode">
|
||||
<button data-mode="messages" class="active">Messages</button>
|
||||
@@ -224,6 +240,7 @@
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
</div>
|
||||
<div id="tm-messages"></div>
|
||||
<div id="tm-timeline" hidden></div>
|
||||
</section>
|
||||
<aside id="tm-right">
|
||||
<div class="tm-head"><span class="tm-title">Overview</span></div>
|
||||
|
||||
@@ -448,6 +448,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;
|
||||
@@ -643,6 +671,12 @@ 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-title { font-size: 12px; font-weight: 500; color: var(--grey-6); 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; }
|
||||
@@ -686,9 +720,78 @@ 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-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
|
||||
#tm-meta { padding: 12px 14px; }
|
||||
|
||||
/* episode timeline: lifecycle spans above exact model-call activity */
|
||||
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
|
||||
.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; 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, .tl-reward { 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-reward { color: var(--chart-3); }
|
||||
.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; }
|
||||
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
|
||||
@@ -6,18 +6,25 @@ lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import write_launch_toml
|
||||
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
|
||||
|
||||
write_launch_toml(config.output_dir, "evals")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
os.environ["PRL_LOG_DIR"] = str(log_dir)
|
||||
write_launch_artifacts(config_dir, "evals")
|
||||
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
@@ -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,14 @@ from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
create_attempt_log_dir,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_config_dir,
|
||||
get_launcher_dir,
|
||||
get_launcher_log_dir,
|
||||
latest_log_dir,
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_launch_toml,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -123,8 +121,8 @@ 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}")
|
||||
|
||||
@@ -179,9 +177,6 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
|
||||
log_dir = create_attempt_log_dir(config.run_dir)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
@@ -420,7 +415,7 @@ def rl_local(config: RLConfig):
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
@@ -459,10 +454,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 +488,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),
|
||||
@@ -512,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -519,6 +533,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),
|
||||
@@ -551,6 +566,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
**modelexpress_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -565,9 +581,8 @@ def rl_slurm(config: RLConfig):
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
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"})
|
||||
@@ -604,7 +619,7 @@ def rl_slurm(config: RLConfig):
|
||||
)
|
||||
|
||||
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:
|
||||
|
||||
+72
-143
@@ -17,18 +17,15 @@ 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_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_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -43,8 +40,6 @@ from prime_rl.utils.process import (
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
EVAL_SBATCH = "eval.sbatch"
|
||||
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
@@ -144,14 +139,20 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
assert config.slurm is not None
|
||||
assert config.slurm.template_path is not None
|
||||
|
||||
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
|
||||
template_dirs = [config.slurm.template_path.parent]
|
||||
bundled_templates = find_package_resource("templates")
|
||||
if bundled_templates is not None:
|
||||
template_dirs.append(bundled_templates)
|
||||
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
trainer_env_vars = {
|
||||
@@ -164,29 +165,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,
|
||||
"evals_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
config_dir=config_path.parent,
|
||||
log_dir=log_dir,
|
||||
output_dir=config.run_dir,
|
||||
launcher_dir=get_launcher_dir(config.run_dir),
|
||||
launcher_log_dir=get_launcher_log_dir(config.run_dir),
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
num_nodes=config.deployment.num_train_nodes,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
config.eval is not None
|
||||
and config.weight_broadcast is not None
|
||||
and config.weight_broadcast.type == "nccl"
|
||||
),
|
||||
**eval_vars,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -194,172 +228,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")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run", "clean"}
|
||||
if config.deployment.type == "multi_node"
|
||||
else {"slurm", "dry_run", "clean"}
|
||||
)
|
||||
if decoupled_eval:
|
||||
if online_eval:
|
||||
# The trainer job only needs [eval] for the weight-broadcast cadence; the
|
||||
# inference pool lives in the eval job.
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evals processes log to a single shared W&B run across both jobs,
|
||||
# keyed by the launcher's run id.
|
||||
# Trainer and evals processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if decoupled_eval and config.monitors.wandb is not None:
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
|
||||
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]
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
log_message = format_log_message(
|
||||
log_dir=latest_log_dir(config.run_dir),
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
evals=online_eval,
|
||||
inference=online_eval,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
if decoupled_eval:
|
||||
# The eval job logs at stable (non-attempt) paths under the run dir.
|
||||
log_message += "\n" + format_log_message(
|
||||
log_dir=get_log_dir(config.run_dir),
|
||||
evals=True,
|
||||
inference=True,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
).removeprefix("Logs:\n")
|
||||
|
||||
if config.dry_run:
|
||||
if decoupled_eval:
|
||||
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
|
||||
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
|
||||
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
eval_submit = (
|
||||
" sbatch --dependency=after:$TRAIN_JOB_ID "
|
||||
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
|
||||
)
|
||||
submit = "\n".join((trainer_submit, eval_submit))
|
||||
else:
|
||||
submit = f" sbatch {script_paths[0]}"
|
||||
note = (
|
||||
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
|
||||
if decoupled_eval
|
||||
else ""
|
||||
)
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
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,8 +297,8 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.run_dir)
|
||||
write_launch_toml(config.run_dir, "sft")
|
||||
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}")
|
||||
@@ -385,8 +313,6 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
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] = []
|
||||
@@ -484,6 +410,9 @@ def sft_local(config: SFTConfig):
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Checkpoint standalone eval progress cursor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import pickle
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
class CheckpointManager:
|
||||
def __init__(self, output_dir: Path) -> None:
|
||||
self.ckpt_dir = get_ckpt_dir(output_dir)
|
||||
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "evals"
|
||||
|
||||
def latest_step(self) -> int:
|
||||
steps = [
|
||||
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
|
||||
]
|
||||
if not steps:
|
||||
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
|
||||
return steps[-1]
|
||||
|
||||
def save(self, eval_source: EvalSource) -> None:
|
||||
cursor = eval_source.cursor
|
||||
ckpt_path = self.get_ckpt_path(cursor)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
# Replace atomically so resume never observes a partially written pickle.
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
pickle.dump(eval_source.state_dict(), f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
get_logger().debug(
|
||||
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
def load(
|
||||
self,
|
||||
step: int,
|
||||
eval_source: EvalSource,
|
||||
path: Path | None = None,
|
||||
) -> None:
|
||||
ckpt_path = path if path is not None else self.get_ckpt_path(step)
|
||||
state_file = ckpt_path / "progress.pt"
|
||||
if not state_file.is_file():
|
||||
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
|
||||
get_logger().info(f"Loading evals checkpoint from {state_file}")
|
||||
with open(state_file, "rb") as f:
|
||||
state = pickle.load(f)
|
||||
if state["cursor"] != step:
|
||||
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
|
||||
eval_source.load_state_dict(state)
|
||||
+146
-28
@@ -13,8 +13,9 @@ inside the handshake until the receiver acknowledges.
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
|
||||
are version-pinned measurements, so an overload cut only blocks admission and
|
||||
the in-flight pool drains through natural completions.
|
||||
are version-pinned measurements. By default, a newer online checkpoint cancels
|
||||
unfinished episodes from the prior version; callers can disable this when they need
|
||||
every epoch to drain.
|
||||
|
||||
Env servers: sources without an explicit ``serve.address`` get an env server
|
||||
spawned by the evals process at their derived address; sources with one are
|
||||
@@ -28,11 +29,13 @@ import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.evals.ckpt import CheckpointManager
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
@@ -47,11 +50,16 @@ from prime_rl.orchestrator.patches import (
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
eval_work,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -67,8 +75,13 @@ STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig) -> None:
|
||||
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
self.config = config
|
||||
self.log_dir = log_dir or (
|
||||
Path(os.environ["PRL_LOG_DIR"])
|
||||
if "PRL_LOG_DIR" in os.environ
|
||||
else create_attempt_log_dir(config.output_dir)
|
||||
)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
@@ -77,6 +90,8 @@ class Evals:
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.ckpt_manager = CheckpointManager(config.output_dir)
|
||||
self.last_saved_cursor = 0
|
||||
self.env_server_procs: list[Popen] = []
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
@@ -140,6 +155,20 @@ class Evals:
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
resume_step = config.resume.dir_step
|
||||
resume_path = config.resume.dir / "evals"
|
||||
else:
|
||||
resume_step = config.resume.step or self.ckpt_manager.latest_step()
|
||||
resume_path = None
|
||||
self.ckpt_manager.load(
|
||||
resume_step,
|
||||
self.eval_source,
|
||||
path=resume_path,
|
||||
)
|
||||
self.last_saved_cursor = self.eval_source.cursor
|
||||
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
|
||||
self.policy = Policy(version=0, model_name=config.model)
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
@@ -209,7 +238,7 @@ class Evals:
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = self.log_dir / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
@@ -246,6 +275,8 @@ class Evals:
|
||||
else:
|
||||
await self.watch()
|
||||
|
||||
self.maybe_save_checkpoint(force=True)
|
||||
|
||||
# The periodic logger and the collector log to the W&B run, so they
|
||||
# must stop before finalize marks the run finished.
|
||||
await self.periodic_logger.stop()
|
||||
@@ -316,6 +347,20 @@ class Evals:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def next_published_step(self, step: int) -> int | None:
|
||||
"""Return the first newer checkpoint offered by the trainer."""
|
||||
assert self.config.online is not None
|
||||
assert self.config.online.broadcasts_dir is not None
|
||||
assert self.receiver is not None
|
||||
return next(
|
||||
(
|
||||
candidate
|
||||
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
|
||||
if candidate > step and self.receiver.is_published(candidate)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest published broadcast that are missing from
|
||||
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
|
||||
@@ -350,49 +395,114 @@ class Evals:
|
||||
# Every offered version must be received: the trainer blocks inside
|
||||
# the handshake, so a failed receive fails the run loudly.
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
await self.dispatcher.on_version_pending(step)
|
||||
await self.receiver.receive(step)
|
||||
self.policy.version = step
|
||||
await self.dispatcher.on_new_version(step)
|
||||
|
||||
if not fired:
|
||||
return
|
||||
|
||||
for env_name in fired:
|
||||
task_count = self.eval_source.triggered_task_count(env_name, step)
|
||||
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
|
||||
|
||||
now = time.perf_counter()
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
total_rollouts = sum(
|
||||
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
|
||||
for env_name in fired
|
||||
self.eval_envs.get(request.env_name).config.group_size
|
||||
for request in self.eval_source.queue
|
||||
if request.step == step and request.env_name in fired
|
||||
)
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
self.policy.version = step
|
||||
if not reload_weights:
|
||||
self.policy.version = step
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
await self.consume_epoch(fired)
|
||||
await self.consume_epoch(fired, step)
|
||||
|
||||
async def consume_epoch(self, fired: list[str], step: int) -> None:
|
||||
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
superseding_step: int | None = None
|
||||
online = self.config.online
|
||||
|
||||
async def consume_epoch(self, fired: list[str]) -> None:
|
||||
"""Consume dispatcher episodes until every fired env's epoch finalizes,
|
||||
routing them through the sink and monitors."""
|
||||
# An env with no examples emits no episodes, so its epoch can never finalize.
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
while pending:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
if (
|
||||
cancellation_task is None
|
||||
and online is not None
|
||||
and self.config.eval.cancel_on_new_checkpoint
|
||||
and (superseding_step := self.next_published_step(step)) is not None
|
||||
):
|
||||
get_logger().warning(
|
||||
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
|
||||
)
|
||||
cancellation_task = asyncio.create_task(
|
||||
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
|
||||
)
|
||||
|
||||
try:
|
||||
if online is not None and self.config.eval.cancel_on_new_checkpoint:
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
|
||||
else:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
except asyncio.TimeoutError:
|
||||
if cancellation_task is not None and cancellation_task.done():
|
||||
cancellation_task.result()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
raise RuntimeError("Eval dispatcher emitted a group cancellation")
|
||||
if isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
group_completed = False
|
||||
group_id = item.group_id
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(item.group_id)
|
||||
group_id = item.group_id
|
||||
else:
|
||||
step = eval_work(item).step
|
||||
await monitors.log([item], step, "eval", "all")
|
||||
item_step = eval_work(item).step
|
||||
await monitors.log([item], item_step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
group_id = episode_group_id(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(group_id)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
if group_completed:
|
||||
source_index = self.dispatcher.pop_source_index(group_id)
|
||||
if self.config.online is not None:
|
||||
continue
|
||||
if source_index is None:
|
||||
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
|
||||
if self.eval_source.mark_completed(source_index):
|
||||
self.maybe_save_checkpoint()
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
|
||||
f"advancing to checkpoint {superseding_step}"
|
||||
)
|
||||
|
||||
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
|
||||
if self.config.ckpt is None:
|
||||
return
|
||||
cursor = self.eval_source.cursor
|
||||
if cursor <= 0 or cursor == self.last_saved_cursor:
|
||||
return
|
||||
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
|
||||
return
|
||||
self.ckpt_manager.save(self.eval_source)
|
||||
self.last_saved_cursor = cursor
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.episodes and not batch.failures:
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
@@ -404,12 +514,15 @@ class Evals:
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures)
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
@@ -417,6 +530,13 @@ class Evals:
|
||||
eff, full = effective.metrics, episodes.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
@@ -461,8 +581,8 @@ class Evals:
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig) -> None:
|
||||
evals = Evals(config)
|
||||
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
evals = Evals(config, log_dir)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
@@ -472,11 +592,9 @@ async def run_evals(config: EvalsConfig) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.entrypoints.evals import main as entrypoint_main
|
||||
|
||||
set_proc_title("Evals")
|
||||
asyncio.run(run_evals(cli(EvalsConfig)))
|
||||
entrypoint_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -207,7 +207,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -233,8 +232,10 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if envs.VLLM_USE_V2_MODEL_RUNNER:
|
||||
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
@@ -609,32 +610,6 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_harmony_stop_token_propagation():
|
||||
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
|
||||
|
||||
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
|
||||
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
|
||||
ignores them, using only self.stop_token_ids (which defaults to []).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/22519
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
|
||||
|
||||
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
|
||||
|
||||
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
|
||||
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
|
||||
# Merge harmony stop tokens from default_sampling_params
|
||||
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
|
||||
if default_stop_ids:
|
||||
existing = set(params.stop_token_ids or [])
|
||||
merged = list(existing | set(default_stop_ids))
|
||||
params.stop_token_ids = merged
|
||||
return params
|
||||
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
@@ -717,45 +692,6 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
|
||||
@@ -10,11 +10,15 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
|
||||
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
|
||||
# stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -20,17 +20,13 @@ from prime_rl.utils.logger import get_logger
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
|
||||
@@ -3,22 +3,20 @@
|
||||
vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
|
||||
defaulting. We subclass it for the bits still missing from the upstream handler:
|
||||
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
|
||||
defaulting and ``usage`` reporting. We subclass it for the bits still missing
|
||||
from the upstream handler:
|
||||
|
||||
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
|
||||
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
|
||||
now does this too; we keep the equivalent path for the DP-replicated
|
||||
inference servers prime-RL runs.
|
||||
1. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
|
||||
objects (the form the PD router can merge and the renderers parse) instead
|
||||
of upstream's single ``.npy`` base64 string.
|
||||
|
||||
2. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
|
||||
source fork.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
|
||||
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
|
||||
``get_max_tokens``); we keep an equivalent guard so callers that omit
|
||||
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
|
||||
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
|
||||
parses ``request.kv_transfer_params`` but never threads it into the engine,
|
||||
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
|
||||
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
|
||||
cut — drop the bridge once we pin a release that includes it.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
routed_experts: dict[str, Any] | None = None
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact
|
||||
# ``{data, shape, start, dtype}`` object the PD router merges and the
|
||||
# renderers parse.
|
||||
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=choices,
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
|
||||
instance, which means an unset ``max_tokens`` is indistinguishable from
|
||||
an explicit ``max_tokens=16`` once the request reaches the handler —
|
||||
both surface as ``sampling_params.max_tokens == 16``. We re-read the
|
||||
cached body to recover that distinction. When we can't (no raw_request,
|
||||
non-JSON body, or read error), pessimistically assume the client did
|
||||
set it so we never clobber an explicit value.
|
||||
"""
|
||||
if raw_request is None:
|
||||
return True
|
||||
try:
|
||||
body = await raw_request.json()
|
||||
except Exception:
|
||||
return True
|
||||
if not isinstance(body, dict):
|
||||
return True
|
||||
sp = body.get("sampling_params")
|
||||
return isinstance(sp, dict) and "max_tokens" in sp
|
||||
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
|
||||
|
||||
Computed lazily because ``custom_init_app_state`` swaps in this
|
||||
subclass via ``object.__new__`` + ``__dict__.update`` (so our
|
||||
``__init__`` never runs).
|
||||
"""
|
||||
diff = self.model_config.get_diff_sampling_param()
|
||||
mc = self.model_config
|
||||
override = (
|
||||
diff.get("max_tokens")
|
||||
if mc.generation_config not in ("auto", "vllm")
|
||||
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
|
||||
# in case a downstream caller ever sets the attribute to ``None``
|
||||
# (``getattr``'s default only fires when the attribute is missing,
|
||||
# not when it exists with a ``None`` value).
|
||||
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
|
||||
)
|
||||
return diff, override
|
||||
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
|
||||
|
||||
async def serve_tokens(
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
# (c) dispatch to our overridden response builder so ``routed_experts``
|
||||
# makes it into the JSON.
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
return error_check_ret
|
||||
|
||||
if self.engine_client.errored:
|
||||
raise self.engine_client.dead_error
|
||||
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
model_name = self.models.model_name(lora_request)
|
||||
|
||||
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
|
||||
request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = request_metadata
|
||||
|
||||
# Build the engine input — features-aware (MM) or text-only fallback.
|
||||
# Identical to upstream so we keep tracking it.
|
||||
if features := request.features:
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
PlaceholderRange,
|
||||
)
|
||||
|
||||
mm_placeholders = {
|
||||
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
|
||||
for modality, ranges in features.mm_placeholders.items()
|
||||
}
|
||||
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
|
||||
if features.kwargs_data is not None:
|
||||
for modality, items in features.kwargs_data.items():
|
||||
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
|
||||
else:
|
||||
for modality, hashes in features.mm_hashes.items():
|
||||
mm_kwargs[modality] = [None] * len(hashes)
|
||||
engine_input = mm_input(
|
||||
prompt_token_ids=request.token_ids,
|
||||
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
|
||||
mm_hashes=features.mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
cache_salt=request.cache_salt,
|
||||
)
|
||||
else:
|
||||
(engine_input,) = await self.online_renderer.preprocess_completion(
|
||||
request,
|
||||
prompt_input=request.token_ids,
|
||||
prompt_embeds=None,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
|
||||
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
|
||||
# engine's KV connector picks the params up.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Upstream parses ``request.kv_transfer_params`` but never threads it
|
||||
# into the engine, so decode receives an empty NIXL handshake and
|
||||
# re-prefills the prompt locally (~100x slower under concurrency).
|
||||
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
|
||||
# connector picks the params up. Fixed upstream by vllm#42644 (merged
|
||||
# after 0.28.0) — drop once we pin a release that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = sampling_params.extra_args or {}
|
||||
extra = request.sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
request.sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
|
||||
# ``ServingTokens`` now does this too; kept here so callers that omit
|
||||
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
|
||||
# default.
|
||||
if not await _client_set_max_tokens(raw_request):
|
||||
diff_sp, override = self._max_tokens_defaults
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
max_model_len=self.model_config.max_model_len,
|
||||
max_tokens=None,
|
||||
input_length=len(request.token_ids),
|
||||
default_sampling_params=diff_sp,
|
||||
override_max_tokens=override,
|
||||
)
|
||||
|
||||
if self.force_no_detokenize:
|
||||
sampling_params.detokenize = False
|
||||
if request.stream:
|
||||
sampling_params.output_kind = RequestOutputKind.DELTA
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
engine_input,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
result_generator = self.engine_client.generate(
|
||||
engine_input,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=self._get_data_parallel_rank(raw_request),
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
# Streaming path: defer to upstream — prime-RL's renderer client
|
||||
# only consumes the full response, so adding routed_experts to the
|
||||
# streaming choice schema is unnecessary churn.
|
||||
return self.serve_tokens_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
return await self.serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
return await super().serve_tokens(request, raw_request)
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
start = request.sampling_params.routed_experts_prompt_start
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=start,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -3,7 +3,6 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
@@ -21,6 +20,3 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
from prime_rl.transports.weights.nixl.agent import (
|
||||
MemDesc,
|
||||
NixlAgent,
|
||||
NixlPeer,
|
||||
PreparedRead,
|
||||
group_notification,
|
||||
make_agent_name,
|
||||
set_ucx_env_defaults,
|
||||
)
|
||||
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
|
||||
from prime_rl.transports.weights.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
@@ -44,7 +48,6 @@ else:
|
||||
Worker = object
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nixl")
|
||||
_BUFFER_POLL_INTERVAL = 0.01
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
|
||||
class WeightTransferGroup:
|
||||
name: str
|
||||
layers: list[LayerWeightTransferPlan]
|
||||
pulls: list[tuple[Any, Any, list[int]]]
|
||||
pulls: list[PreparedRead]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferPlan:
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor]
|
||||
receive_buffer_count: int
|
||||
trainer_peers: list[NixlPeer]
|
||||
groups: list[WeightTransferGroup]
|
||||
|
||||
|
||||
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults()
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=server_url),
|
||||
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
session_id=session_id,
|
||||
worker_id=f"inference-{global_rank}",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.weight_transfer_timeout = timeout
|
||||
self.weight_transfer_plan: WeightTransferPlan | None = None
|
||||
logger.info(
|
||||
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
trainer_ref = self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=None,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)[0]
|
||||
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
|
||||
copies = self.trace_weight_loads(table)
|
||||
plan = self.build_transfer_plan(table, copies)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(table.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=self.model_express.client,
|
||||
role="inference",
|
||||
rank=self.model_express.rank,
|
||||
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
# Join the current generation directly. Publishing a transient READY
|
||||
# before the first pull would let the trainer mistake initialization
|
||||
# for a completed acknowledgement.
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.weight_transfer_plan = plan
|
||||
self.group_generations = [0] * len(plan.groups)
|
||||
logger.info(
|
||||
"Initialized NIXL transfer plan on rank %d with %d groups",
|
||||
self.model_express.rank,
|
||||
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
copies,
|
||||
replay_plans,
|
||||
)
|
||||
receive_buffer_count = self.choose_receive_buffer_count(
|
||||
receive_buffer_elements,
|
||||
table.staging_buffer_count,
|
||||
)
|
||||
receive_buffer_count = table.staging_buffer_count
|
||||
receive_arenas = self.allocate_receive_arenas(
|
||||
receive_buffer_elements,
|
||||
receive_buffer_count,
|
||||
)
|
||||
peers: list[NixlPeer] = []
|
||||
for agent in table.agents:
|
||||
peer = self.nixl_agent.add_remote_agent(agent.metadata)
|
||||
self.nixl_agent.make_connection(peer)
|
||||
peers.append(peer)
|
||||
groups = self.build_transfer_groups(
|
||||
table,
|
||||
copies,
|
||||
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements,
|
||||
receive_arenas,
|
||||
receive_buffer_count,
|
||||
peers,
|
||||
)
|
||||
return WeightTransferPlan(
|
||||
receive_arenas=receive_arenas,
|
||||
receive_buffer_count=receive_buffer_count,
|
||||
trainer_peers=peers,
|
||||
groups=groups,
|
||||
)
|
||||
|
||||
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
|
||||
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
|
||||
def choose_receive_buffer_count(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
staging_buffer_count: int,
|
||||
) -> int:
|
||||
receive_buffer_bytes = max(
|
||||
1,
|
||||
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
|
||||
)
|
||||
allocated_bytes = torch.cuda.memory_allocated(self.device)
|
||||
peak_growth_bytes = max(
|
||||
0,
|
||||
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
|
||||
)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(self.device)
|
||||
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
return size_cuda_buffers(
|
||||
receive_buffer_bytes,
|
||||
max_receive_buffers,
|
||||
self.device,
|
||||
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
|
||||
)
|
||||
|
||||
def allocate_receive_arenas(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor],
|
||||
receive_buffer_count: int,
|
||||
peers: list[NixlPeer],
|
||||
) -> list[WeightTransferGroup]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
)
|
||||
|
||||
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
|
||||
peer_names: dict[int, str] = {}
|
||||
transfer_groups: list[WeightTransferGroup] = []
|
||||
|
||||
for group_index, group in enumerate(table.groups):
|
||||
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
persistent_plans_by_layer,
|
||||
),
|
||||
pulls=self.prepare_group_pulls(
|
||||
table,
|
||||
local_descs,
|
||||
remote_descs,
|
||||
peer_names,
|
||||
peers,
|
||||
),
|
||||
)
|
||||
)
|
||||
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def prepare_group_pulls(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
local_descs: dict[int, list[MemDesc]],
|
||||
remote_descs: dict[int, list[MemDesc]],
|
||||
peer_names: dict[int, str],
|
||||
) -> list[tuple[Any, Any, list[int]]]:
|
||||
pulls: list[tuple[Any, Any, list[int]]] = []
|
||||
for agent_index, remote in sorted(remote_descs.items()):
|
||||
peer_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
self.nixl_agent.make_connection(peer_name)
|
||||
peer_names[agent_index] = peer_name
|
||||
peers: list[NixlPeer],
|
||||
) -> list[PreparedRead]:
|
||||
pulls: list[PreparedRead] = []
|
||||
agent_indices = sorted(remote_descs)
|
||||
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
|
||||
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
|
||||
for agent_index in agent_indices:
|
||||
remote = remote_descs[agent_index]
|
||||
peer = peers[agent_index]
|
||||
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
|
||||
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
|
||||
pulls.append(
|
||||
self.nixl_agent.prepare_read(
|
||||
local_prepared,
|
||||
list(range(len(remote))),
|
||||
remote_prepared,
|
||||
)
|
||||
)
|
||||
return pulls
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
|
||||
del weight_dir
|
||||
plan = self.initialize_transfer()
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
self.apply_transfer_plan(plan)
|
||||
update_mla_absorbed_weights(self.raw_model)
|
||||
torch.cuda.synchronize(self.device)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
logger.info(
|
||||
"Applied NIXL policy update on rank %d in %.2fs",
|
||||
self.model_express.rank,
|
||||
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
def pull_group(group_index: int) -> WeightTransferGroup:
|
||||
transfer_group = plan.groups[group_index]
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
notification = group_notification(group_index, self.group_generations[group_index])
|
||||
self.nixl_agent.wait_for_notification(
|
||||
plan.trainer_peers,
|
||||
notification,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
|
||||
for local, remote, indices in transfer_group.pulls:
|
||||
handle = self.nixl_agent.post_read(local, indices, remote)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.post_read(read, notification)
|
||||
for read in transfer_group.pulls:
|
||||
self.nixl_agent.wait(
|
||||
handle,
|
||||
read,
|
||||
context=f"weight pull for {transfer_group.name}",
|
||||
timeout=self.weight_transfer_timeout,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
return transfer_group
|
||||
|
||||
def acknowledge_group(group_index: int) -> None:
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.group_generations[group_index] += 1
|
||||
return transfer_group
|
||||
|
||||
def prefetch_group(group_index: int) -> WeightTransferGroup:
|
||||
torch.cuda.set_device(self.device)
|
||||
transfer_group = pull_group(group_index)
|
||||
acknowledge_group(group_index)
|
||||
return transfer_group
|
||||
return pull_group(group_index)
|
||||
|
||||
def replay_group(transfer_group: WeightTransferGroup) -> None:
|
||||
for layer_plan in transfer_group.layers:
|
||||
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
|
||||
replay_group(transfer_group)
|
||||
torch.cuda.synchronize(self.device)
|
||||
|
||||
if not pipelined:
|
||||
acknowledge_group(group_index)
|
||||
finally:
|
||||
cancelled.set()
|
||||
if executor is not None:
|
||||
|
||||
@@ -33,7 +33,6 @@ OVERVIEW_NAME = "overview"
|
||||
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
|
||||
# dynamic, so also a regex) — and each section builder prepends its own.
|
||||
COMMON_METRICS = [
|
||||
"all/dispatch_failure/mean",
|
||||
"effective/num_total_tokens/mean",
|
||||
"effective/num_turns/mean",
|
||||
"effective/num_branches/mean",
|
||||
@@ -143,6 +142,7 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
|
||||
+ [f"eval/{env_pattern}/all/cancelled/mean"]
|
||||
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
|
||||
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
the weight update) drops train groups already past ``max_off_policy_steps`` — a
|
||||
compute-saving early cancel; the sink's queue sweep is what guarantees the
|
||||
bound. Eval episodes are measurements for the policy version they started
|
||||
with, so they are allowed to finish even if training advances. Train
|
||||
with. Online evals may explicitly cancel them when a newer checkpoint is ready. Train
|
||||
episodes sampled from a frozen model never go stale — their generation
|
||||
source doesn't change with policy updates.
|
||||
"""
|
||||
@@ -190,6 +190,7 @@ class Dispatcher:
|
||||
|
||||
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
|
||||
self.groups: dict[uuid.UUID, GroupState] = {}
|
||||
self.source_indices_by_group: dict[str, int] = {}
|
||||
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
@@ -466,6 +467,8 @@ class Dispatcher:
|
||||
return False
|
||||
gid = uuid.uuid4()
|
||||
self.groups[gid] = fresh
|
||||
if fresh.source_index is not None:
|
||||
self.source_indices_by_group[str(gid)] = fresh.source_index
|
||||
return await self.schedule_group_episode(gid, fresh)
|
||||
|
||||
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
|
||||
@@ -493,8 +496,12 @@ class Dispatcher:
|
||||
episodes_to_schedule=group_size,
|
||||
target_episodes=group_size,
|
||||
policy_version_at_start=self.policy.version,
|
||||
source_index=request.source_index,
|
||||
)
|
||||
|
||||
def pop_source_index(self, group_id: str) -> int | None:
|
||||
return self.source_indices_by_group.pop(group_id, None)
|
||||
|
||||
async def schedule_group_episode(self, group_id: uuid.UUID, group: GroupState) -> bool:
|
||||
"""Dispatch one ``run`` task for this group.
|
||||
|
||||
@@ -545,6 +552,7 @@ class Dispatcher:
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=group.step,
|
||||
source_index=group.source_index,
|
||||
client_config=client,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
@@ -702,6 +710,7 @@ class Dispatcher:
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
group_id=str(group_id),
|
||||
step=group.step if group is not None else claimed[-1][1].step,
|
||||
count=cancelled,
|
||||
reason=reason,
|
||||
)
|
||||
@@ -709,6 +718,7 @@ class Dispatcher:
|
||||
|
||||
if claimed:
|
||||
await safe_cancel_all([task for task, _ in claimed])
|
||||
self.source_indices_by_group.pop(str(group_id), None)
|
||||
return cancelled
|
||||
|
||||
async def cancel_inflight_episodes(self) -> None:
|
||||
@@ -720,6 +730,7 @@ class Dispatcher:
|
||||
tasks = list(self.inflight.keys())
|
||||
self.inflight.clear()
|
||||
self.groups.clear()
|
||||
self.source_indices_by_group.clear()
|
||||
if tasks:
|
||||
await safe_cancel_all(tasks)
|
||||
|
||||
@@ -745,6 +756,40 @@ class Dispatcher:
|
||||
await safe_cancel_all(train_tasks)
|
||||
return cancelled
|
||||
|
||||
async def cancel_eval_step(self, step: int) -> int:
|
||||
"""Cancel queued and active eval groups for a superseded checkpoint.
|
||||
|
||||
Scheduling remains paused until ``on_new_version`` runs after the
|
||||
replacement weights are live.
|
||||
"""
|
||||
if self.eval_source is None or self.eval_envs is None:
|
||||
return 0
|
||||
|
||||
self.policy_update_pending = True
|
||||
async with self.scheduling_lock:
|
||||
queued = self.eval_source.cancel_step(step)
|
||||
group_ids = [gid for gid, group in self.groups.items() if group.kind == "eval" and group.step == step]
|
||||
|
||||
cancelled = 0
|
||||
for group_id in group_ids:
|
||||
cancelled += await self.drop_group(group_id, reason="superseded")
|
||||
|
||||
for request in queued:
|
||||
count = self.eval_envs.get(request.env_name).config.group_size
|
||||
cancelled += count
|
||||
self.metrics.record_cancellation(kind="eval", env_name=request.env_name, n=count)
|
||||
await self.out_q.put(
|
||||
GroupCancellation(
|
||||
kind="eval",
|
||||
env_name=request.env_name,
|
||||
group_id=str(uuid.uuid4()),
|
||||
step=request.step,
|
||||
count=count,
|
||||
reason="superseded",
|
||||
)
|
||||
)
|
||||
return cancelled
|
||||
|
||||
# ── metrics ────────────────────────────────────────────────────────────
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
|
||||
@@ -131,6 +131,12 @@ class TrainEnv(Env):
|
||||
self.generation_source = generation_source
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = (
|
||||
config.sampling.truncates_distribution()
|
||||
and config.algo is not None
|
||||
and config.algo.sampling.source == "policy"
|
||||
)
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
|
||||
@@ -3,15 +3,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
|
||||
class EvalSink:
|
||||
"""Collect completed evaluation episodes into per-environment epochs."""
|
||||
@@ -20,8 +22,11 @@ class EvalSink:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
|
||||
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
|
||||
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
|
||||
self.expected_batch_sizes: dict[tuple[str, int], int] = {}
|
||||
|
||||
def add(self, episode: vf.Episode) -> EvalBatch | None:
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -32,7 +37,7 @@ class EvalSink:
|
||||
group.append(episode)
|
||||
if self._group_size(group_id) >= self.group_size_for(env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(env_name, eval_step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
@@ -46,66 +51,117 @@ class EvalSink:
|
||||
self.pending_group_failures[group_id].append(failure)
|
||||
if self._group_size(group_id) >= self.group_size_for(failure.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name):
|
||||
if self._batch_size(bkey) >= self.batch_size_for(failure.env_name, failure.step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def cancel(self, cancellation: GroupCancellation) -> EvalBatch | None:
|
||||
"""Count a dispatcher-cancelled group toward its superseded eval epoch."""
|
||||
if cancellation.kind != "eval":
|
||||
raise ValueError(f"EvalSink cannot process a {cancellation.kind} group cancellation")
|
||||
group_id = cancellation.group_id
|
||||
bkey = (cancellation.env_name, cancellation.step)
|
||||
self.pending_group_cancellations[group_id] = cancellation
|
||||
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
|
||||
self.process_group(group_id)
|
||||
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name, cancellation.step):
|
||||
return self.process_batch(bkey)
|
||||
return None
|
||||
|
||||
def _group_size(self, group_id: str) -> int:
|
||||
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
return (
|
||||
len(self.pending_groups[group_id])
|
||||
+ len(self.pending_group_failures[group_id])
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
|
||||
def _batch_size(self, key: tuple[str, int]) -> int:
|
||||
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
|
||||
return (
|
||||
len(self.pending_batches[key])
|
||||
+ len(self.pending_batch_failures[key])
|
||||
+ self.pending_batch_cancellations[key]
|
||||
)
|
||||
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.eval_envs.get(env_name).config.group_size
|
||||
|
||||
def batch_size_for(self, env_name: str) -> int:
|
||||
def set_batch_size(self, env_name: str, step: int, size: int) -> None:
|
||||
self.expected_batch_sizes[(env_name, step)] = size
|
||||
|
||||
def batch_size_for(self, env_name: str, step: int | None = None) -> int:
|
||||
if step is not None:
|
||||
key = (env_name, step)
|
||||
if key in self.expected_batch_sizes:
|
||||
return self.expected_batch_sizes[key]
|
||||
env = self.eval_envs.get(env_name)
|
||||
return len(env.examples) * env.config.group_size
|
||||
|
||||
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures)
|
||||
keys = set(self.pending_batches) | set(self.pending_batch_failures) | set(self.pending_batch_cancellations)
|
||||
batch_counts = {key: self._batch_size(key) for key in keys}
|
||||
buffered: dict[tuple[str, int], int] = {}
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
|
||||
group_ids = set(self.pending_groups) | set(self.pending_group_failures) | set(self.pending_group_cancellations)
|
||||
for group_id in group_ids:
|
||||
group = self.pending_groups[group_id]
|
||||
failures = self.pending_group_failures[group_id]
|
||||
if not group and not failures:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
if not group and not failures and cancellation is None:
|
||||
continue
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
|
||||
buffered[key] = (
|
||||
buffered.get(key, 0)
|
||||
+ len(group)
|
||||
+ len(failures)
|
||||
+ (cancellation.count if cancellation is not None else 0)
|
||||
)
|
||||
return [
|
||||
(
|
||||
env_name,
|
||||
eval_step,
|
||||
batch_counts.get((env_name, eval_step), 0),
|
||||
self.batch_size_for(env_name),
|
||||
self.batch_size_for(env_name, eval_step),
|
||||
buffered.get((env_name, eval_step), 0),
|
||||
)
|
||||
for env_name, eval_step in set(batch_counts) | set(buffered)
|
||||
]
|
||||
|
||||
def has_pending_group(self, group_id: str) -> bool:
|
||||
return bool(
|
||||
self.pending_groups.get(group_id)
|
||||
or self.pending_group_failures.get(group_id)
|
||||
or self.pending_group_cancellations.get(group_id)
|
||||
)
|
||||
|
||||
def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
failures = self.pending_group_failures.pop(group_id, [])
|
||||
if not group and not failures:
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and not failures and cancellation is None:
|
||||
return
|
||||
if group:
|
||||
env_name = episode_env_name(group[0])
|
||||
eval_step = eval_work(group[0]).step
|
||||
else:
|
||||
elif failures:
|
||||
env_name = failures[0].env_name
|
||||
eval_step = failures[0].step
|
||||
else:
|
||||
env_name = cancellation.env_name
|
||||
eval_step = cancellation.step
|
||||
key = (env_name, eval_step)
|
||||
self.pending_batches[key].extend(group)
|
||||
self.pending_batch_failures[key].extend(failures)
|
||||
if cancellation is not None:
|
||||
self.pending_batch_cancellations[key] += cancellation.count
|
||||
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for trace in traces if not trace.has_error]
|
||||
@@ -116,6 +172,7 @@ class EvalSink:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} "
|
||||
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
|
||||
f"cancelled={cancellation.count if cancellation is not None else 0} "
|
||||
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
@@ -123,9 +180,12 @@ class EvalSink:
|
||||
env_name, step = key
|
||||
episodes = self.pending_batches.pop(key, [])
|
||||
failures = self.pending_batch_failures.pop(key, [])
|
||||
cancelled = self.pending_batch_cancellations.pop(key, 0)
|
||||
self.expected_batch_sizes.pop(key, None)
|
||||
return EvalBatch(
|
||||
env_name=env_name,
|
||||
step=step,
|
||||
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
|
||||
failures=failures,
|
||||
cancelled=cancelled,
|
||||
)
|
||||
|
||||
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from collections import Counter, deque
|
||||
from itertools import zip_longest
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
|
||||
|
||||
class EvalSource:
|
||||
"""Finite-per-epoch source of eval examples."""
|
||||
@@ -36,6 +39,10 @@ class EvalSource:
|
||||
self.intervals[env.name] = env.config.interval
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
self.cursor = 0
|
||||
self._next_index = 0
|
||||
self._completed: set[int] = set()
|
||||
self._triggered_task_counts: dict[tuple[str, int], int] = {}
|
||||
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
@@ -51,8 +58,9 @@ class EvalSource:
|
||||
return []
|
||||
fired: list[str] = []
|
||||
for name, interval in self.intervals.items():
|
||||
if is_first or force or step % interval == 0:
|
||||
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]:
|
||||
fired.append(name)
|
||||
queued_counts: Counter[str] = Counter()
|
||||
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
@@ -62,8 +70,41 @@ class EvalSource:
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
continue
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step))
|
||||
return fired
|
||||
source_index = self._next_index
|
||||
self._next_index += 1
|
||||
if source_index < self.cursor:
|
||||
continue
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step, source_index=source_index))
|
||||
queued_counts[env_name] += 1
|
||||
for env_name, count in queued_counts.items():
|
||||
self._triggered_task_counts[(env_name, step)] = count
|
||||
return [name for name in fired if queued_counts[name]]
|
||||
|
||||
def triggered_task_count(self, env_name: str, step: int) -> int:
|
||||
return self._triggered_task_counts.get((env_name, step), 0)
|
||||
|
||||
def mark_completed(self, source_index: int) -> bool:
|
||||
"""Advance the durable cursor only across a fully completed prefix."""
|
||||
if source_index < self.cursor:
|
||||
return False
|
||||
self._completed.add(source_index)
|
||||
previous = self.cursor
|
||||
while self.cursor in self._completed:
|
||||
self._completed.remove(self.cursor)
|
||||
self.cursor += 1
|
||||
return self.cursor != previous
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
return {"cursor": self.cursor}
|
||||
|
||||
def load_state_dict(self, state_dict: dict) -> None:
|
||||
if set(state_dict) != {"cursor"}:
|
||||
raise ValueError("Eval source checkpoint must contain only a cursor")
|
||||
cursor = state_dict["cursor"]
|
||||
if type(cursor) is not int or cursor < 0:
|
||||
raise ValueError(f"Eval source checkpoint cursor must be a non-negative integer, got {cursor!r}")
|
||||
self.cursor = cursor
|
||||
self._completed.clear()
|
||||
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
@@ -71,6 +112,12 @@ class EvalSource:
|
||||
return None
|
||||
return self.queue.popleft()
|
||||
|
||||
def cancel_step(self, step: int) -> list[TaskRequest]:
|
||||
"""Remove and return queued examples for a superseded eval step."""
|
||||
cancelled = [request for request in self.queue if request.step == step]
|
||||
self.queue = deque(request for request in self.queue if request.step != step)
|
||||
return cancelled
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self.queue)
|
||||
|
||||
|
||||
@@ -854,10 +854,9 @@ class Orchestrator:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
|
||||
``Error``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window. Over the
|
||||
shipped set they are 0/0/share-of-shipped by construction, so the window is the only scope
|
||||
where they carry signal. A cancellation is a pipeline decision, not a rollout failure."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -866,16 +865,13 @@ class Orchestrator:
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
|
||||
num_attempts = len(episodes) + len(batch.failures)
|
||||
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
|
||||
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
@@ -884,10 +880,7 @@ class Orchestrator:
|
||||
|
||||
window_by_env = episodes.by_env()
|
||||
shipped_by_env = effective.by_env()
|
||||
failures_by_env: dict[str, list[DispatchFailure]] = {}
|
||||
for failure in batch.failures:
|
||||
failures_by_env.setdefault(failure.env_name, []).append(failure)
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env))
|
||||
name_width = max((len(name) for name in env_names), default=0)
|
||||
lines = [head]
|
||||
for env_name in env_names:
|
||||
@@ -895,15 +888,11 @@ class Orchestrator:
|
||||
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
|
||||
env_eff = env_eff_pool.metrics
|
||||
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
|
||||
env_failures = failures_by_env.get(env_name, [])
|
||||
env_attempts = len(pool) + len(env_failures)
|
||||
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
|
||||
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -277,6 +277,15 @@ class TrainSink:
|
||||
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
|
||||
for sample in samples:
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
if env.requires_sampling_masks and sample.sampling_mask is None:
|
||||
# Rollout logprobs are mask-renormalized; training without the masks
|
||||
# silently biases every importance ratio.
|
||||
raise RuntimeError(
|
||||
f"env '{env_name}' samples with truncation (top_p/top_k) but its rollouts "
|
||||
"carry no sampling masks. Set `enable_return_sampling_mask = true` on "
|
||||
"the inference server config (the rl entrypoint does this automatically) - "
|
||||
"it requires vLLM's native sampling-mask capture (>= 0.28)."
|
||||
)
|
||||
stamp_loss_routing(sample, env.algorithm.action_loss_type)
|
||||
if samples:
|
||||
samples_by_trace[trace.id] = samples
|
||||
|
||||
@@ -21,7 +21,7 @@ import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -66,6 +66,28 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> SamplingMask | None:
|
||||
"""Encode a branch sampling mask for a fixed token count.
|
||||
|
||||
The mask stores row sizes in `counts` and concatenates every row in `ids`.
|
||||
For example, `counts=[2, 1]` and `ids=[4, 7, 9]` become `counts=[2]` and
|
||||
`ids=[4, 7]` for one token. For three tokens, they become
|
||||
`counts=[2, 1, 0]` with unchanged ids. Zero-count rows disable replay.
|
||||
"""
|
||||
if mask is None:
|
||||
return None
|
||||
ids, counts = mask.ids, mask.counts
|
||||
if len(counts) > num_tokens:
|
||||
counts = counts[:num_tokens]
|
||||
ids = ids[: int(counts.sum())]
|
||||
elif len(counts) < num_tokens:
|
||||
counts = np.concatenate([counts, np.zeros(num_tokens - len(counts), dtype=np.int32)])
|
||||
return SamplingMask(
|
||||
ids=np.ascontiguousarray(ids, dtype=np.int32).tobytes(),
|
||||
counts=np.ascontiguousarray(counts, dtype=np.int32).tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
@@ -143,6 +165,7 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam
|
||||
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
|
||||
ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]),
|
||||
advantages=branch.advantages,
|
||||
sampling_mask=_encode_sampling_mask(branch.sampling_mask, len(token_ids)),
|
||||
)
|
||||
)
|
||||
if not samples:
|
||||
|
||||
@@ -4,13 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
|
||||
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ class Progress:
|
||||
|
||||
WorkKind = Literal["train", "eval"]
|
||||
|
||||
CancelReason = Literal["stale", "overload"]
|
||||
CancelReason = Literal["stale", "overload", "superseded"]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -43,11 +43,12 @@ class GroupCancellation:
|
||||
"""Terminal marker for a dropped group: one message covering every episode
|
||||
the group still owed the sink (in-flight and never-dispatched), so
|
||||
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
|
||||
pipeline decisions (staleness, overload cut) from episode errors."""
|
||||
pipeline decisions (staleness, overload cut, superseded eval) from episode errors."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
group_id: str
|
||||
step: int
|
||||
count: int
|
||||
reason: CancelReason
|
||||
|
||||
@@ -67,7 +68,10 @@ class DispatchFailure:
|
||||
error: vf.Error
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
|
||||
if TYPE_CHECKING:
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | DispatchFailure | GroupCancellation
|
||||
else:
|
||||
DispatchResult: TypeAlias = Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -77,6 +81,7 @@ class TaskRequest:
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
step: int
|
||||
source_index: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -89,6 +94,7 @@ class InflightEpisode:
|
||||
task: vf.Task
|
||||
policy_version: int
|
||||
step: int
|
||||
source_index: int | None = None
|
||||
client_config: vf.ClientConfig | None = None
|
||||
started_at: float = 0.0
|
||||
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
|
||||
@@ -107,6 +113,7 @@ class GroupState:
|
||||
target_episodes: int
|
||||
emitted: int = 0
|
||||
policy_version_at_start: int = 0
|
||||
source_index: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -131,6 +138,7 @@ class EvalBatch:
|
||||
step: int
|
||||
episodes: EvalEpisodes
|
||||
failures: list[DispatchFailure]
|
||||
cancelled: int = 0
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
|
||||
@@ -52,13 +52,12 @@ export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
# Per-attempt log dir: a relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
# Setup environment
|
||||
|
||||
@@ -59,12 +59,10 @@ export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/trainer $LOG_DIR/inference
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
|
||||
@@ -140,6 +138,17 @@ export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nixl_broadcast -%}
|
||||
{% if launch_modelexpress -%}
|
||||
export WEIGHT_BROADCAST_HOST="$MASTER_ADDR"
|
||||
{% else -%}
|
||||
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
|
||||
{% endif -%}
|
||||
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
|
||||
export MODEL_EXPRESS_REDIS_PORT={{ modelexpress_redis_port }}
|
||||
echo "WEIGHT_BROADCAST_HOST=${WEIGHT_BROADCAST_HOST}"
|
||||
echo "MODEL_EXPRESS_PORT=${MODEL_EXPRESS_PORT}"
|
||||
{% endif %}
|
||||
|
||||
# The orchestrator runs on trainer rank 0's node (SLURM_PROCID == NUM_INFER_NODES) by
|
||||
# default; with orchestrator_on_inference it moves to the last inference node (a decode
|
||||
@@ -200,6 +209,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
# the exact process name, so it never hits the worktree path (e.g. mooncake-baby).
|
||||
pkill -9 -x mooncake_master 2>/dev/null
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
{% if use_nixl_broadcast and launch_modelexpress %}
|
||||
pkill -9 -f "[m]odelexpress-server" 2>/dev/null
|
||||
pkill -9 -x redis-server 2>/dev/null
|
||||
{% endif %}
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
@@ -236,6 +249,83 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if use_nixl_broadcast -%}
|
||||
UCX_DIR="$PROJECT_DIR/third_party/ucx"
|
||||
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
|
||||
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
|
||||
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX cuda_copy support" >&2
|
||||
exit 1
|
||||
}
|
||||
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX rc_verbs support" >&2
|
||||
exit 1
|
||||
}
|
||||
{% if launch_modelexpress %}
|
||||
|
||||
if [ "$SLURM_PROCID" -eq "$NUM_INFER_NODES" ]; then
|
||||
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
|
||||
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
MX_STATE_DIR="$LOG_DIR/modelexpress"
|
||||
mkdir -p "$MX_STATE_DIR/cache"
|
||||
"$MX_BIN/redis-server" \
|
||||
--port "$MODEL_EXPRESS_REDIS_PORT" \
|
||||
--bind 127.0.0.1 \
|
||||
--protected-mode no \
|
||||
--save "" \
|
||||
--appendonly no \
|
||||
--dir "$MX_STATE_DIR" \
|
||||
> "$MX_STATE_DIR/redis.log" 2>&1 &
|
||||
REDIS_PID=$!
|
||||
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null && break
|
||||
kill -0 "$REDIS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/redis.log" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/$MODEL_EXPRESS_REDIS_PORT" 2>/dev/null || {
|
||||
echo "Redis did not become ready on port $MODEL_EXPRESS_REDIS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
MX_METADATA_BACKEND=redis \
|
||||
REDIS_URL="redis://127.0.0.1:$MODEL_EXPRESS_REDIS_PORT" \
|
||||
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
|
||||
"$MX_BIN/modelexpress-server" \
|
||||
--port "$MODEL_EXPRESS_PORT" \
|
||||
--database-path "$MX_STATE_DIR/models.db" \
|
||||
--cache-directory "$MX_STATE_DIR/cache" \
|
||||
> "$MX_STATE_DIR/server.log" 2>&1 &
|
||||
MODEL_EXPRESS_PID=$!
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
|
||||
if [ -n "${MODEL_EXPRESS_PID:-}" ] && ! kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null; then
|
||||
tail -50 "$MX_STATE_DIR/server.log" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
|
||||
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
@@ -425,7 +515,8 @@ else
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.json \
|
||||
{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% if use_nixl_broadcast %}--weight-broadcast.host $WEIGHT_BROADCAST_HOST \
|
||||
{% endif %}{% if use_zmq_transport %}--rollout_transport.host $ORCH_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
@@ -470,6 +561,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
|
||||
(
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% elif use_nixl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $WEIGHT_BROADCAST_HOST"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $ORCH_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $LOG_DIR/orchestrator.log
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
@@ -26,87 +26,111 @@
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
export NUM_INFER_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if online_eval -%}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
export DP_PER_NODE={{ dp_per_node }}
|
||||
{%- endif %}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_PATH={{ config_path }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export TRAIN_CONFIG_PATH={{ config_path }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Per-attempt log dir: a resume or relaunch never overwrites an earlier attempt's logs.
|
||||
ATTEMPT=1
|
||||
while [ -e $OUTPUT_DIR/logs/attempt_$ATTEMPT ]; do ATTEMPT=$((ATTEMPT+1)); done
|
||||
export LOG_DIR=$OUTPUT_DIR/logs/attempt_$ATTEMPT
|
||||
export LOG_DIR={{ log_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR=$CONFIG_DIR
|
||||
export PRL_ATTEMPT_LOG_DIR=$LOG_DIR
|
||||
mkdir -p $LOG_DIR/trainer
|
||||
ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
|
||||
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
|
||||
{% if online_eval -%}
|
||||
mkdir -p $LOG_DIR/inference
|
||||
ln -sfn inference/node_0.log $LOG_DIR/inference.log
|
||||
{% endif %}
|
||||
# Clean exits do not trigger srun --kill-on-bad-exit. Each terminal role
|
||||
# publishes its successful exit so every node uses the same completion condition.
|
||||
export TRAINER_DONE=$LAUNCHER_DIR/.sft_trainer_done_$SLURM_JOB_ID
|
||||
{% if online_eval -%}
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
|
||||
{%- endif %}
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
|
||||
|
||||
{% if prl_run_id %}
|
||||
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
# Trainer and evals log to one shared W&B run. The trainer creates the run,
|
||||
# and the evals process finalizes it after the final epoch.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_SHARED_LABEL=trainer
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
# Networking. Inference nodes occupy the first ranks, followed by trainer nodes.
|
||||
HOSTNAMES=( $(scontrol show hostnames $SLURM_JOB_NODELIST) )
|
||||
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$NUM_TRAIN_NODES} )
|
||||
export ALL_HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
export MASTER_ADDR="${TRAIN_HOSTS[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
{% if use_nccl_broadcast %}
|
||||
# The eval job has a separate allocation. Publish the trainer's NCCL host through
|
||||
# the shared run directory under this job ID.
|
||||
printf '%s\n' "$MASTER_ADDR" > "$LAUNCHER_DIR/.sft_nccl_host_$SLURM_JOB_ID"
|
||||
{% endif %}
|
||||
|
||||
{% if online_eval -%}
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
export HOSTNAMES_STR="${INFER_HOSTS[*]}"
|
||||
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${INFER_HOSTS[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
{%- endif %}
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): run the sync once on
|
||||
# every node. Re-source .env because unexported vars do not cross srun.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
# Shared venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python, torchrun, and
|
||||
# vLLM processes can otherwise retain GPUs or IPC files after SLURM termination.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
@@ -116,53 +140,141 @@ srun bash -s <<'CLEANUP_SH'
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run SFT
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a single trainer crash terminates the entire SLURM job instead of
|
||||
# leaving the surviving ranks (and their nodes) idle.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# need no escaping. Nothing in the body reads stdin, which would otherwise eat
|
||||
# the rest of the script.
|
||||
# Run trainer and online-eval roles in one SLURM step. A non-zero exit on any
|
||||
# node terminates the other roles. Clean trainer exits let the final eval drain.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
set -o pipefail
|
||||
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if online_eval -%}
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $LOG_DIR/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$LOG_DIR/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
mkdir -p $LOG_DIR/envs/eval
|
||||
{%- for name in eval_env_names %}
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $LOG_DIR/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# Evals drives inference through the router and sends admin operations
|
||||
# directly to each engine.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
(
|
||||
PRL_LOG_DIR=$LOG_DIR WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $MASTER_ADDR \
|
||||
{%- endif %}
|
||||
2>&1 | tee $LOG_DIR/evals.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ]; then
|
||||
touch "$EVAL_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
fi
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
|
||||
# Trainer env vars: launcher defaults + [env_vars]
|
||||
{%- for key, value in trainer_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
echo $HOSTNAMES | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_PATH \
|
||||
echo $ALL_HOSTNAMES_STR | tee $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
(
|
||||
WANDB_SHARED_LABEL=trainer uv run torchrun \
|
||||
--role=trainer \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$LOG_DIR/trainer/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $TRAIN_CONFIG_PATH \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
--weight-broadcast.host 0.0.0.0 \
|
||||
{%- endif %}
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $LOG_DIR/trainer/node_${TRAIN_NODE_RANK}.log
|
||||
COMPONENT_CODE=$?
|
||||
if [ "$COMPONENT_CODE" -eq 0 ] && [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
touch "$TRAINER_DONE" || exit $?
|
||||
fi
|
||||
exit "$COMPONENT_CODE"
|
||||
) &
|
||||
{% if online_eval %}fi{% endif %}
|
||||
|
||||
# Every node stays in the shared srun step until all terminal roles finish.
|
||||
{% if online_eval -%}
|
||||
( until [ -f "$TRAINER_DONE" ] && [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
{% else -%}
|
||||
( until [ -f "$TRAINER_DONE" ]; do sleep 10; done ) &
|
||||
{% endif -%}
|
||||
COMPLETION_PID=$!
|
||||
|
||||
# Ignore clean component exits until the shared completion condition is met.
|
||||
# Propagate failures through --kill-on-bad-exit=1.
|
||||
while true; do
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "$EXIT_CODE" -ne 0 ] || [ "${FINISHED_PID:-}" = "$COMPLETION_PID" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
REMAINING_PIDS=$(jobs -p)
|
||||
echo "[$(hostname)] completion condition met with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $REMAINING_PIDS; do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
|
||||
@@ -1,260 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}-eval
|
||||
#SBATCH --nodes={{ num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition={{ partition }}
|
||||
{%- if account %}
|
||||
#SBATCH --account={{ account }}
|
||||
{%- endif %}
|
||||
{%- if time %}
|
||||
#SBATCH --time={{ time }}
|
||||
{%- endif %}
|
||||
{%- if nodelist %}
|
||||
#SBATCH --nodelist={{ nodelist }}
|
||||
{%- endif %}
|
||||
{%- if exclude %}
|
||||
#SBATCH --exclude={{ exclude }}
|
||||
{%- endif %}
|
||||
#SBATCH --exclusive
|
||||
#SBATCH --output={{ launcher_log_dir }}/eval_job_%j.log
|
||||
#SBATCH --error={{ launcher_log_dir }}/eval_job_%j.log
|
||||
|
||||
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
|
||||
# DP rank behind a single router) plus the evals process and its env servers. The trainer
|
||||
# runs in a separate SLURM job. This job exits after evaluating the final weight
|
||||
# broadcast (max_steps).
|
||||
|
||||
# Exit immediately on any failed command so a crash anywhere releases the
|
||||
# allocation instead of leaving zombie processes holding nodes.
|
||||
set -e
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export CONFIG_PATH=$CONFIG_DIR/inference.json
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export LAUNCHER_DIR={{ launcher_dir }}
|
||||
# Move a previous job's inference logs aside instead of deleting them: rm of log
|
||||
# files another job's processes still hold open can wedge in the NFS client and
|
||||
# hang the whole job before srun even runs.
|
||||
[ -d $OUTPUT_DIR/logs/inference ] && mv $OUTPUT_DIR/logs/inference $OUTPUT_DIR/logs/inference_prev_$(date +%s)
|
||||
mkdir -p $OUTPUT_DIR/logs/inference
|
||||
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
|
||||
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
|
||||
# failures), so node 0 publishes completion through this sentinel and the other nodes
|
||||
# watch for it to release their engines.
|
||||
export EVAL_DONE=$LAUNCHER_DIR/.eval.done
|
||||
rm -f "$EVAL_DONE"
|
||||
{% if prl_run_id %}
|
||||
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
|
||||
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
|
||||
# outlives the trainer) finalizes it.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
export WANDB_SHARED_FINISHER=evals
|
||||
export WANDB_PROGRAM="uv run sft"
|
||||
{% endif %}
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if use_nccl_broadcast %}
|
||||
: "${TRAIN_JOB_ID:?TRAIN_JOB_ID is required for NCCL weight broadcast}"
|
||||
TRAIN_HOST_FILE="$LAUNCHER_DIR/.sft_nccl_host_$TRAIN_JOB_ID"
|
||||
until [ -s "$TRAIN_HOST_FILE" ]; do sleep 1; done
|
||||
export TRAIN_HOST=$(<"$TRAIN_HOST_FILE")
|
||||
rm -f "$TRAIN_HOST_FILE"
|
||||
echo "TRAIN_HOST=${TRAIN_HOST}"
|
||||
{% endif %}
|
||||
|
||||
# Single global router on node 0 fronts every per-rank endpoint; admin ops
|
||||
# (pause/update_weights/resume) bypass it and hit each rank directly.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
ADMIN_URLS=""
|
||||
ROUTER_ARGS=""
|
||||
for host in ${HOSTNAMES[@]}; do
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
|
||||
done
|
||||
done
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ROUTER_ARGS
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
|
||||
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
|
||||
SYNC_SH
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/vllm processes and
|
||||
# vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM termination and
|
||||
# cause the next launch to hang. Harmless on clean nodes.
|
||||
#
|
||||
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
|
||||
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
|
||||
# because the surviving literal `vllm` strings below appear in the cmdline.
|
||||
srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
|
||||
# Run the eval deployment
|
||||
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
|
||||
# tasks so a crashed engine/router/evals terminates the SLURM job instead
|
||||
# of leaving the surviving ranks holding nodes.
|
||||
#
|
||||
# The body goes to bash on stdin through a quoted heredoc instead of a
|
||||
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
|
||||
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
|
||||
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
|
||||
# the body reads stdin, which would otherwise eat the rest of the script.
|
||||
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
|
||||
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
|
||||
# wait/cleanup block at the end of this script surfaces background
|
||||
# process crashes (router, engines) as task failures.
|
||||
set -o pipefail
|
||||
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
|
||||
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
|
||||
{%- for key, value in inference_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
|
||||
{% include '_launch_rank.sh.j2' %}
|
||||
{% include '_launch_router.sh.j2' %}
|
||||
|
||||
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
DP_PER_NODE={{ dp_per_node }}
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
|
||||
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
|
||||
# independent single-engine servers. vLLM rejects the external-LB DP
|
||||
# args when data_parallel_size == 1; enable_expert_parallel in the
|
||||
# inference config alone shards experts across the TP group.
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
# Single global router on node 0 (external LB across all per-rank endpoints)
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
{%- if eval_env_names %}
|
||||
|
||||
# One env server per eval source next to the evals process, which connects to each
|
||||
# source at its deterministic loopback address (so this node), polling until
|
||||
# they are up - the servers and the evals process start in parallel.
|
||||
{%- for name in eval_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
|
||||
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
# The evals process watches trainer broadcast markers and drives the pool:
|
||||
# data plane through the router, admin ops per rank.
|
||||
{%- for key, value in evals_env_vars.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
WANDB_SHARED_LABEL=evals uv run evals \
|
||||
@ $CONFIG_DIR/evals.json \
|
||||
--eval.client.base-url $INFER_URLS \
|
||||
--eval.client.admin-base-url $ADMIN_URLS \
|
||||
{%- if use_nccl_broadcast %}
|
||||
--weight-broadcast.host $TRAIN_HOST \
|
||||
{%- endif %}
|
||||
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
|
||||
EVALS_PID=$!
|
||||
else
|
||||
# Watch for the completion sentinel so this node's wait below returns when
|
||||
# the evals process (on node 0) finishes cleanly.
|
||||
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
|
||||
fi
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (engines, router, env servers, evals)
|
||||
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
|
||||
# so the whole job tears down instead of leaving zombies holding the allocation.
|
||||
wait -n -p FINISHED_PID
|
||||
EXIT_CODE=$?
|
||||
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
|
||||
# Publish completion so the sentinel watchers on the other nodes release too
|
||||
# (a zero exit here never trips --kill-on-bad-exit).
|
||||
touch "$EVAL_DONE"
|
||||
fi
|
||||
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
|
||||
for pid in $(jobs -p); do
|
||||
kill -TERM $pid 2>/dev/null || true
|
||||
done
|
||||
exit $EXIT_CODE
|
||||
LAUNCH_SH
|
||||
@@ -26,6 +26,8 @@
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
@@ -38,4 +40,87 @@ uv sync --all-extras --all-packages
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
export PRL_RUN_ID=${PRL_RUN_ID:-$(python3 -c "import uuid; print(uuid.uuid4().hex)")}
|
||||
uv run rl @ {{ config_path }}
|
||||
{% if use_nixl_broadcast %}
|
||||
{% if launch_modelexpress -%}
|
||||
export WEIGHT_BROADCAST_HOST="127.0.0.1"
|
||||
{% else -%}
|
||||
export WEIGHT_BROADCAST_HOST="{{ modelexpress_host }}"
|
||||
{% endif -%}
|
||||
export MODEL_EXPRESS_PORT={{ modelexpress_port }}
|
||||
UCX_DIR="$PROJECT_DIR/third_party/ucx"
|
||||
if [ ! -x "$UCX_DIR/bin/ucx_info" ]; then
|
||||
echo "NIXL requires the UCX build installed by scripts/install_nixl_from_source.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
export LD_LIBRARY_PATH="$UCX_DIR/lib:$UCX_DIR/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
UCX_TRANSPORTS=$("$UCX_DIR/bin/ucx_info" -d)
|
||||
grep -q "Transport: cuda_copy" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX cuda_copy support" >&2
|
||||
exit 1
|
||||
}
|
||||
grep -q "Transport: rc_verbs" <<< "$UCX_TRANSPORTS" || {
|
||||
echo "NIXL requires UCX rc_verbs support" >&2
|
||||
exit 1
|
||||
}
|
||||
{% if launch_modelexpress %}
|
||||
MX_BIN="$PROJECT_DIR/third_party/modelexpress/bin"
|
||||
if [ ! -x "$MX_BIN/modelexpress-server" ] || [ ! -x "$MX_BIN/redis-server" ]; then
|
||||
echo "ModelExpress server dependencies are missing; run scripts/install_modelexpress.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
pkill -9 -f "[m]odelexpress-server" 2>/dev/null || true
|
||||
pkill -9 -x redis-server 2>/dev/null || true
|
||||
|
||||
MX_STATE_DIR="{{ output_dir }}/modelexpress"
|
||||
mkdir -p "$MX_STATE_DIR/cache"
|
||||
"$MX_BIN/redis-server" \
|
||||
--port {{ modelexpress_redis_port }} \
|
||||
--bind 127.0.0.1 \
|
||||
--protected-mode no \
|
||||
--save "" \
|
||||
--appendonly no \
|
||||
--dir "$MX_STATE_DIR" \
|
||||
> "$MX_STATE_DIR/redis.log" 2>&1 &
|
||||
REDIS_PID=$!
|
||||
trap '[ -z "${MODEL_EXPRESS_PID:-}" ] || kill -TERM "$MODEL_EXPRESS_PID" 2>/dev/null; kill -TERM "$REDIS_PID" 2>/dev/null || true' EXIT
|
||||
|
||||
for _ in $(seq 1 60); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null && break
|
||||
kill -0 "$REDIS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/redis.log" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/127.0.0.1/{{ modelexpress_redis_port }}" 2>/dev/null || {
|
||||
echo "Redis did not become ready on port {{ modelexpress_redis_port }}" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
MX_METADATA_BACKEND=redis \
|
||||
REDIS_URL="redis://127.0.0.1:{{ modelexpress_redis_port }}" \
|
||||
MX_HEARTBEAT_TIMEOUT_SECS=31536000 \
|
||||
"$MX_BIN/modelexpress-server" \
|
||||
--port {{ modelexpress_port }} \
|
||||
--database-path "$MX_STATE_DIR/models.db" \
|
||||
--cache-directory "$MX_STATE_DIR/cache" \
|
||||
> "$MX_STATE_DIR/server.log" 2>&1 &
|
||||
MODEL_EXPRESS_PID=$!
|
||||
{% endif %}
|
||||
|
||||
for _ in $(seq 1 120); do
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null && break
|
||||
{% if launch_modelexpress %}
|
||||
kill -0 "$MODEL_EXPRESS_PID" 2>/dev/null || {
|
||||
tail -50 "$MX_STATE_DIR/server.log" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
sleep 1
|
||||
done
|
||||
timeout 1 bash -c "echo > /dev/tcp/$WEIGHT_BROADCAST_HOST/$MODEL_EXPRESS_PORT" 2>/dev/null || {
|
||||
echo "ModelExpress is not reachable at $WEIGHT_BROADCAST_HOST:$MODEL_EXPRESS_PORT" >&2
|
||||
exit 1
|
||||
}
|
||||
{% endif %}
|
||||
uv run rl @ {{ config_path }}{% if use_nixl_broadcast %} --weight-broadcast.host "$WEIGHT_BROADCAST_HOST"{% endif %}
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
set -e
|
||||
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export PRL_ATTEMPT_CONFIG_DIR={{ config_dir }}
|
||||
export PRL_ATTEMPT_LOG_DIR={{ log_dir }}
|
||||
|
||||
# Setup environment
|
||||
cd $PROJECT_DIR
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Whole-block activation checkpointing with an operator-based policy."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from functools import partial
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
|
||||
from torch.utils.checkpoint import (
|
||||
SAC_IGNORED_OPS,
|
||||
CheckpointPolicy,
|
||||
SelectiveCheckpointContext,
|
||||
create_selective_checkpoint_contexts,
|
||||
)
|
||||
|
||||
from prime_rl.configs.trainer import ActivationCheckpointConfig
|
||||
|
||||
# FSDP's replay-specific hooks emit a different number of profiler markers.
|
||||
SAC_IGNORED_OPS.update(
|
||||
{
|
||||
torch.ops.profiler._record_function_enter.default,
|
||||
torch.ops.profiler._record_function_enter_new.default,
|
||||
torch.ops.profiler._record_function_exit.default,
|
||||
torch.ops.profiler._record_function_exit._RecordFunction,
|
||||
}
|
||||
)
|
||||
|
||||
# Adapted from TorchTitan's whole-block selective activation checkpointing policy.
|
||||
# These targets and the CUDA-to-CPU copy rule are correctness requirements. They
|
||||
# must remain active when custom targets replace the default selective targets.
|
||||
MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
|
||||
MANDATORY_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::topk",
|
||||
"prime_rl::record_moe_routing_statistics",
|
||||
}
|
||||
)
|
||||
|
||||
DEFAULT_SELECTIVE_SAVE_NAMESPACES = frozenset(
|
||||
{
|
||||
"_c10d_functional",
|
||||
"flash_attn",
|
||||
"flash_attn_3",
|
||||
"prime_rl_collectives",
|
||||
"prime_rl_ring",
|
||||
}
|
||||
)
|
||||
DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::_efficient_attention_forward",
|
||||
"aten::_flash_attention_forward",
|
||||
"aten::_scaled_dot_product_attention_math",
|
||||
"aten::_scaled_dot_product_cudnn_attention",
|
||||
"aten::_scaled_dot_product_efficient_attention",
|
||||
"aten::_scaled_dot_product_flash_attention",
|
||||
"aten::_scaled_dot_product_flash_attention_for_cpu",
|
||||
"aten::_scaled_dot_product_fused_attention_overrideable",
|
||||
"aten::_scaled_grouped_mm",
|
||||
"aten::_scaled_mm",
|
||||
"aten::_scaled_mm_v2",
|
||||
"aten::_grouped_mm",
|
||||
"aten::addmm",
|
||||
"aten::bmm",
|
||||
"aten::convolution",
|
||||
"aten::linear",
|
||||
"aten::mm",
|
||||
"prime_rl::fp8_blockwise_mm",
|
||||
"prime_rl::grouped_fp8_gemm",
|
||||
"prime_rl::sparse_mla",
|
||||
}
|
||||
)
|
||||
# An operation target matches one qualified operator name, while a namespace
|
||||
# target matches every operation registered in that namespace.
|
||||
DEFAULT_SELECTIVE_TARGETS = DEFAULT_SELECTIVE_SAVE_NAMESPACES | DEFAULT_SELECTIVE_SAVE_OPERATIONS
|
||||
|
||||
|
||||
# PyTorch calls checkpoint policies with the dispatched operation's operands.
|
||||
# Keyword operands let us distinguish CUDA-to-CPU copies from other _to_copy calls.
|
||||
def _mandatory_checkpoint_policy(
|
||||
_context: SelectiveCheckpointContext,
|
||||
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> CheckpointPolicy:
|
||||
if operation.namespace in MANDATORY_SAVE_NAMESPACES or operation.name() in MANDATORY_SAVE_OPERATIONS:
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
|
||||
if operation.name() == "aten::_to_copy":
|
||||
device = kwargs.get("device")
|
||||
if isinstance(device, torch.device) and device.type == "cpu":
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
|
||||
return CheckpointPolicy.PREFER_RECOMPUTE
|
||||
|
||||
|
||||
def _selective_checkpoint_policy(
|
||||
context: SelectiveCheckpointContext,
|
||||
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
|
||||
*args,
|
||||
targets: frozenset[str] = DEFAULT_SELECTIVE_TARGETS,
|
||||
**kwargs,
|
||||
) -> CheckpointPolicy:
|
||||
runtime_policy = _mandatory_checkpoint_policy(context, operation, *args, **kwargs)
|
||||
if runtime_policy is CheckpointPolicy.MUST_SAVE:
|
||||
return runtime_policy
|
||||
if operation.namespace in targets or operation.name() in targets:
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
return CheckpointPolicy.PREFER_RECOMPUTE
|
||||
|
||||
|
||||
def get_activation_checkpoint_wrapper(config: ActivationCheckpointConfig) -> Callable[[nn.Module], nn.Module]:
|
||||
if config.mode == "full":
|
||||
policy = _mandatory_checkpoint_policy
|
||||
else:
|
||||
targets = DEFAULT_SELECTIVE_TARGETS if config.targets is None else frozenset(config.targets)
|
||||
policy = partial(_selective_checkpoint_policy, targets=targets)
|
||||
|
||||
return partial(
|
||||
checkpoint_wrapper,
|
||||
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
|
||||
context_fn=partial(create_selective_checkpoint_contexts, policy),
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_SELECTIVE_SAVE_NAMESPACES",
|
||||
"DEFAULT_SELECTIVE_SAVE_OPERATIONS",
|
||||
"DEFAULT_SELECTIVE_TARGETS",
|
||||
"MANDATORY_SAVE_NAMESPACES",
|
||||
"MANDATORY_SAVE_OPERATIONS",
|
||||
"get_activation_checkpoint_wrapper",
|
||||
]
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
@@ -278,6 +278,31 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts.shape[0] += padding_size
|
||||
|
||||
|
||||
_SAMPLING_MASK_ITEMSIZE = np.dtype(np.int32).itemsize
|
||||
|
||||
|
||||
def _empty_sampling_mask(num_tokens: int) -> SamplingMask:
|
||||
return SamplingMask(ids=b"", counts=b"\0" * (num_tokens * _SAMPLING_MASK_ITEMSIZE))
|
||||
|
||||
|
||||
def _slice_sampling_mask(sampling_mask: SamplingMask, seq_len: int) -> SamplingMask:
|
||||
counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)[:seq_len]
|
||||
return SamplingMask(
|
||||
ids=sampling_mask.ids[: int(counts.sum()) * _SAMPLING_MASK_ITEMSIZE],
|
||||
counts=counts.tobytes(),
|
||||
)
|
||||
|
||||
|
||||
def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
"""Add zero-count mask rows for sequence-padding tokens.
|
||||
|
||||
Padding adds token positions but no eligible token ids, so only `counts` grows.
|
||||
"""
|
||||
sampling_mask = micro_batch.sampling_mask
|
||||
assert sampling_mask is not None
|
||||
sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE)
|
||||
|
||||
|
||||
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
|
||||
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
|
||||
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
|
||||
@@ -383,6 +408,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
routed_experts = (
|
||||
_copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None
|
||||
)
|
||||
# No copy needed: SamplingMask holds immutable bytes, and _pad_sampling_mask only
|
||||
# ever mutates _materialize_bin's own accumulator.
|
||||
sampling_mask = training_example.sampling_mask
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
|
||||
@@ -406,6 +434,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ref_kl_weights = ref_kl_weights[:cut]
|
||||
if routed_experts is not None:
|
||||
routed_experts = _slice_routed_experts(routed_experts, cut)
|
||||
if sampling_mask is not None:
|
||||
sampling_mask = _slice_sampling_mask(sampling_mask, cut)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:cut]
|
||||
env_names = env_names[:cut]
|
||||
@@ -436,6 +466,13 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
)
|
||||
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
||||
|
||||
if sampling_mask is not None:
|
||||
mask_counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)
|
||||
assert len(mask_counts) == len(input_ids), (
|
||||
f"sampling_mask counts: {len(mask_counts)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
assert len(sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE
|
||||
|
||||
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
||||
|
||||
return MicroBatch(
|
||||
@@ -448,6 +485,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
ref_logprobs=ref_logprobs,
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
@@ -541,6 +579,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
# A weight stream materializes as soon as one packed sample carries it; the
|
||||
# samples that lack it get the stream's identity fill (STREAM_FILL).
|
||||
has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL}
|
||||
# Sampling masks are per-token optional (unlike routed_experts): samples
|
||||
# without them get zero-count backfill instead of constraining packing.
|
||||
has_sampling_mask = any(sample.sampling_mask is not None for sample in bin_content.samples)
|
||||
|
||||
input_ids: list[int] = []
|
||||
loss_mask: list[bool] = []
|
||||
@@ -555,6 +596,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||
seq_lens: list[int] = []
|
||||
routed_experts: RoutedExperts | None = None
|
||||
sampling_mask: SamplingMask | None = SamplingMask(ids=b"", counts=b"") if has_sampling_mask else None
|
||||
|
||||
for sample in bin_content.samples:
|
||||
sample_len = len(sample.input_ids)
|
||||
@@ -592,6 +634,10 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||
seq_lens.extend(sample.seq_lens)
|
||||
if sampling_mask is not None:
|
||||
sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len)
|
||||
sampling_mask.ids += sample_mask.ids
|
||||
sampling_mask.counts += sample_mask.counts
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
@@ -607,6 +653,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch:
|
||||
ref_logprobs=ref_logprobs,
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
sampling_mask=sampling_mask,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=mm_kwargs,
|
||||
@@ -733,6 +780,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
if micro_batch.routed_experts is not None:
|
||||
_pad_routed_experts(micro_batch, padding_size)
|
||||
if micro_batch.sampling_mask is not None:
|
||||
_pad_sampling_mask(micro_batch, padding_size)
|
||||
micro_batch.env_names.extend([""] * padding_size)
|
||||
|
||||
return micro_batch
|
||||
@@ -769,6 +818,15 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None:
|
||||
assert micro_batch.routed_experts.shape[0] == num_tokens, (
|
||||
f"routed_experts misaligned after packing: {micro_batch.routed_experts.shape[0]} != {num_tokens} tokens"
|
||||
)
|
||||
if micro_batch.sampling_mask is not None:
|
||||
mask_counts = np.frombuffer(micro_batch.sampling_mask.counts, dtype=np.int32)
|
||||
assert len(mask_counts) == num_tokens, (
|
||||
f"sampling_mask misaligned after packing: {len(mask_counts)} != {num_tokens} tokens"
|
||||
)
|
||||
assert len(micro_batch.sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE, (
|
||||
f"sampling_mask ids/counts inconsistent after packing: "
|
||||
f"{len(micro_batch.sampling_mask.ids)} bytes != {int(mask_counts.sum())} ids"
|
||||
)
|
||||
|
||||
|
||||
def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
|
||||
@@ -781,6 +839,8 @@ def _make_dummy_batch(source: MicroBatch) -> MicroBatch:
|
||||
dummy.rl_weights = None
|
||||
dummy.ce_weights = None
|
||||
dummy.ref_kl_weights = None
|
||||
# Fully loss-masked, so replaying sampling masks would be pure wasted work.
|
||||
dummy.sampling_mask = None
|
||||
return dummy
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
|
||||
from prime_rl.trainer.distributed.expert_parallel import ExpertWeightParallel
|
||||
|
||||
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
|
||||
__all__ = ["ExpertWeightParallel"]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Autograd and compile-friendly distributed collectives."""
|
||||
|
||||
import prime_kernels
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_to_all_single", mutates_args=())
|
||||
def _all_to_all_single(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
) -> torch.Tensor:
|
||||
output_split_list = output_splits.tolist()
|
||||
input_split_list = input_splits.tolist()
|
||||
output = x.new_empty((sum(output_split_list), *x.shape[1:]))
|
||||
dist.all_to_all_single(
|
||||
output,
|
||||
x.contiguous(),
|
||||
output_split_list,
|
||||
input_split_list,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@_all_to_all_single.register_fake
|
||||
def _all_to_all_single_fake(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
) -> torch.Tensor:
|
||||
output_size = torch.library.get_ctx().new_dynamic_size()
|
||||
return x.new_empty((output_size, *x.shape[1:]))
|
||||
|
||||
|
||||
def _all_to_all_setup_context(ctx, inputs, output) -> None:
|
||||
_, output_splits, input_splits, group_name = inputs
|
||||
ctx.save_for_backward(output_splits, input_splits)
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
def _all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
output_splits, input_splits = ctx.saved_tensors
|
||||
return (
|
||||
_all_to_all_single(
|
||||
grad_output,
|
||||
input_splits,
|
||||
output_splits,
|
||||
ctx.group_name,
|
||||
),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_all_to_all_single.register_autograd(_all_to_all_backward, setup_context=_all_to_all_setup_context)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_to_all_single_equal", mutates_args=())
|
||||
def _all_to_all_single_equal(x: torch.Tensor, group_name: str) -> torch.Tensor:
|
||||
output = x.new_empty(x.shape)
|
||||
dist.all_to_all_single(
|
||||
output,
|
||||
x.contiguous(),
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@_all_to_all_single_equal.register_fake
|
||||
def _all_to_all_single_equal_fake(x: torch.Tensor, group_name: str) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _all_to_all_equal_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
return _all_to_all_single_equal(grad_output, ctx.group_name), None
|
||||
|
||||
|
||||
def _all_to_all_equal_setup_context(ctx, inputs, output) -> None:
|
||||
_, group_name = inputs
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
_all_to_all_single_equal.register_autograd(
|
||||
_all_to_all_equal_backward,
|
||||
setup_context=_all_to_all_equal_setup_context,
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::mxfp8_all_to_all", mutates_args=())
|
||||
def _mxfp8_all_to_all(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
quantized: bool,
|
||||
) -> torch.Tensor:
|
||||
kernel = prime_kernels.load("mxfp8_moe")
|
||||
operation = kernel.all_to_all_dispatch if quantized else kernel.all_to_all_combine
|
||||
return operation(
|
||||
x,
|
||||
output_splits.tolist(),
|
||||
input_splits.tolist(),
|
||||
dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
|
||||
|
||||
@_mxfp8_all_to_all.register_fake
|
||||
def _mxfp8_all_to_all_fake(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
quantized: bool,
|
||||
) -> torch.Tensor:
|
||||
output_size = torch.library.get_ctx().new_dynamic_size()
|
||||
return x.new_empty((output_size, *x.shape[1:]))
|
||||
|
||||
|
||||
def _mxfp8_all_to_all_setup_context(ctx, inputs, output) -> None:
|
||||
_, output_splits, input_splits, group_name, quantized = inputs
|
||||
ctx.save_for_backward(output_splits, input_splits)
|
||||
ctx.group_name = group_name
|
||||
ctx.quantized = quantized
|
||||
|
||||
|
||||
def _mxfp8_all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None, None]:
|
||||
output_splits, input_splits = ctx.saved_tensors
|
||||
return (
|
||||
_mxfp8_all_to_all(
|
||||
grad_output,
|
||||
input_splits,
|
||||
output_splits,
|
||||
ctx.group_name,
|
||||
not ctx.quantized,
|
||||
),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_mxfp8_all_to_all.register_autograd(
|
||||
_mxfp8_all_to_all_backward,
|
||||
setup_context=_mxfp8_all_to_all_setup_context,
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_gather", mutates_args=())
|
||||
def _all_gather(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
gathered = x.movedim(dim, 0).contiguous()
|
||||
output = gathered.new_empty((gathered.shape[0] * group_size, *gathered.shape[1:]))
|
||||
dist.all_gather_into_tensor(
|
||||
output,
|
||||
gathered,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
|
||||
@_all_gather.register_fake
|
||||
def _all_gather_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
shape = list(x.shape)
|
||||
shape[dim] *= group_size
|
||||
return x.new_empty(shape)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::reduce_scatter_sum", mutates_args=())
|
||||
def _reduce_scatter_sum(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
scattered = x.movedim(dim, 0).contiguous()
|
||||
output = scattered.new_empty((scattered.shape[0] // group_size, *scattered.shape[1:]))
|
||||
dist.reduce_scatter_tensor(
|
||||
output,
|
||||
scattered,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
|
||||
@_reduce_scatter_sum.register_fake
|
||||
def _reduce_scatter_sum_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
shape = list(x.shape)
|
||||
shape[dim] //= group_size
|
||||
return x.new_empty(shape)
|
||||
|
||||
|
||||
def _collective_setup_context(ctx, inputs, output) -> None:
|
||||
_, dim, group_size, group_name = inputs
|
||||
ctx.dim = dim
|
||||
ctx.group_size = group_size
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
def _all_gather_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
return (
|
||||
_reduce_scatter_sum(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _reduce_scatter_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
return (
|
||||
_all_gather(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_all_gather.register_autograd(_all_gather_backward, setup_context=_collective_setup_context)
|
||||
_reduce_scatter_sum.register_autograd(_reduce_scatter_backward, setup_context=_collective_setup_context)
|
||||
|
||||
|
||||
def all_to_all_single(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _all_to_all_single(x, output_splits, input_splits, group.group_name)
|
||||
|
||||
|
||||
def all_to_all_single_equal(x: torch.Tensor, group: ProcessGroup) -> torch.Tensor:
|
||||
return _all_to_all_single_equal(x, group.group_name)
|
||||
|
||||
|
||||
def mxfp8_all_to_all_dispatch(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, True)
|
||||
|
||||
|
||||
def mxfp8_all_to_all_combine(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, False)
|
||||
|
||||
|
||||
def all_gather(x: torch.Tensor, dim: int, group: ProcessGroup) -> torch.Tensor:
|
||||
return _all_gather(x, dim, group.size(), group.group_name)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"all_gather",
|
||||
"all_to_all_single",
|
||||
"all_to_all_single_equal",
|
||||
"mxfp8_all_to_all_combine",
|
||||
"mxfp8_all_to_all_dispatch",
|
||||
]
|
||||
@@ -1,15 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
import torch
|
||||
from deep_ep import Buffer
|
||||
from deep_ep.utils import EventHandle, EventOverlap
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import (
|
||||
ExpertFunction,
|
||||
PermutationState,
|
||||
TokenDispatcherBase,
|
||||
permute_for_grouped_gemm,
|
||||
unpermute_from_grouped_gemm,
|
||||
)
|
||||
|
||||
_buffer: Buffer | None = None
|
||||
_handle_cache: dict[int, object] = {}
|
||||
_combine_backward_handles: dict[int, object] = {}
|
||||
# The custom-op schema can carry only the dispatcher ID; weak values avoid extending dispatcher lifetimes.
|
||||
_combine_dispatchers: WeakValueDictionary[int, DeepEPTokenDispatcher] = WeakValueDictionary()
|
||||
_pending_dispatch_events: dict[int, EventOverlap] = {}
|
||||
_handle_counter = 0
|
||||
_pending_combine_event: EventOverlap | None = None
|
||||
_deepep_cuda_ops_registered = False
|
||||
_deepep_cuda_lib: torch.library.Library | None = None
|
||||
|
||||
@@ -37,10 +50,13 @@ def register_deepep_cuda_ops() -> None:
|
||||
"Tensor is_token_in_rank, Tensor num_tokens_per_expert) "
|
||||
"-> (Tensor, Tensor, Tensor, Tensor, Tensor)"
|
||||
)
|
||||
_deepep_cuda_lib.define("combine(Tensor x, Tensor handle_id, int dispatcher_id) -> Tensor")
|
||||
|
||||
torch.library.impl(_deepep_cuda_lib, "dispatch", "CUDA")(_dispatch_op_impl)
|
||||
torch.library.impl(_deepep_cuda_lib, "combine", "CUDA")(_combine_op_impl)
|
||||
|
||||
torch.library.register_autograd("deepep::dispatch", _dispatch_backward, setup_context=_dispatch_setup_context)
|
||||
torch.library.register_autograd("deepep::combine", _combine_backward, setup_context=_combine_setup_context)
|
||||
|
||||
_deepep_cuda_ops_registered = True
|
||||
|
||||
@@ -113,57 +129,53 @@ def _dispatch_backward(
|
||||
return grad_x, None, grad_topk_weights, None, None, None, None
|
||||
|
||||
|
||||
class _DeepEPCombine(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, handle_id: torch.Tensor) -> torch.Tensor:
|
||||
global _pending_combine_event
|
||||
def _combine_op_impl(x: torch.Tensor, handle_id: torch.Tensor, dispatcher_id: int) -> torch.Tensor:
|
||||
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
|
||||
handle_key = handle_id.item()
|
||||
handle = _handle_cache.pop(handle_key, None)
|
||||
assert handle is not None, f"Handle not found for handle_id={handle_key}"
|
||||
|
||||
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
|
||||
handle = _handle_cache.pop(handle_id.item(), None)
|
||||
assert handle is not None, f"Handle not found for handle_id={handle_id.item()}"
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
combined, _, after_event = _buffer.combine(
|
||||
x=x,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
_pending_combine_event = after_event
|
||||
ctx.handle = handle
|
||||
return combined
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
handle = ctx.handle
|
||||
assert handle is not None, "Handle not found in DeepEP combine backward."
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
grad_x, _, _, _, _, after_event = _buffer.dispatch(
|
||||
x=grad_combined,
|
||||
topk_idx=None,
|
||||
topk_weights=None,
|
||||
num_tokens_per_rank=None,
|
||||
num_tokens_per_rdma_rank=None,
|
||||
is_token_in_rank=None,
|
||||
num_tokens_per_expert=None,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
after_event.current_stream_wait()
|
||||
return grad_x, None
|
||||
previous_event = _new_event_overlap()
|
||||
combined, _, after_event = _buffer.combine(
|
||||
x=x,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
dispatcher = _combine_dispatchers.get(dispatcher_id)
|
||||
assert dispatcher is not None, "DeepEP dispatcher was released before combine completed."
|
||||
dispatcher._pending_combine_events.append(after_event)
|
||||
if x.requires_grad:
|
||||
_combine_backward_handles[handle_key] = handle
|
||||
return combined
|
||||
|
||||
|
||||
@torch.compiler.disable()
|
||||
def sync_combine() -> None:
|
||||
global _pending_combine_event
|
||||
def _combine_setup_context(ctx, inputs, output) -> None:
|
||||
_, handle_id, _ = inputs
|
||||
ctx.handle = _combine_backward_handles.pop(handle_id.item(), None)
|
||||
|
||||
if _pending_combine_event is not None:
|
||||
_pending_combine_event.current_stream_wait()
|
||||
_pending_combine_event = None
|
||||
|
||||
def _combine_backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
handle = ctx.handle
|
||||
assert handle is not None, "Handle not found in DeepEP combine backward."
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
grad_x, _, _, _, _, after_event = _buffer.dispatch(
|
||||
x=grad_combined,
|
||||
topk_idx=None,
|
||||
topk_weights=None,
|
||||
num_tokens_per_rank=None,
|
||||
num_tokens_per_rdma_rank=None,
|
||||
is_token_in_rank=None,
|
||||
num_tokens_per_expert=None,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
after_event.current_stream_wait()
|
||||
return grad_x, None, None
|
||||
|
||||
|
||||
@torch.compiler.disable()
|
||||
@@ -235,14 +247,6 @@ def _unpermute_tokens(
|
||||
return output_hidden_states
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DispatchState:
|
||||
handle_id: torch.Tensor
|
||||
permuted_indices: torch.Tensor
|
||||
num_recv_tokens: int
|
||||
permuted_scores: torch.Tensor | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingDispatchState:
|
||||
hidden_states: torch.Tensor
|
||||
@@ -295,50 +299,177 @@ def dispatch_tokens_async(
|
||||
)
|
||||
|
||||
|
||||
def finalize_dispatch_tokens(pending_state: _PendingDispatchState) -> tuple[torch.Tensor, torch.Tensor, _DispatchState]:
|
||||
_sync_dispatch(pending_state.handle_id)
|
||||
@dataclass(frozen=True)
|
||||
class DeepEPDispatchState:
|
||||
handle_id: torch.Tensor
|
||||
deep_ep_permuted_indices: torch.Tensor
|
||||
num_received_tokens: int
|
||||
scores_after_experts: torch.Tensor | None
|
||||
grouped_gemm_permutation: PermutationState
|
||||
|
||||
hidden_states = pending_state.hidden_states
|
||||
num_recv_tokens = hidden_states.shape[0]
|
||||
hidden_states, permuted_scores, permuted_indices = _permute_tokens(
|
||||
hidden_states,
|
||||
pending_state.dispatched_indices,
|
||||
pending_state.dispatched_scores,
|
||||
)
|
||||
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
|
||||
|
||||
if pending_state.score_before_experts and permuted_scores is not None:
|
||||
hidden_states = (hidden_states.to(torch.float32) * permuted_scores.to(torch.float32).reshape(-1, 1)).to(
|
||||
hidden_states.dtype
|
||||
class DeepEPTokenDispatcher(TokenDispatcherBase[DeepEPDispatchState]):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
num_experts: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
num_sms: int,
|
||||
token_chunk_size: int | None,
|
||||
) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.num_local_experts = num_experts // group.size()
|
||||
self.group = group
|
||||
self.token_chunk_size = token_chunk_size
|
||||
self._pending_combine_events: list[EventOverlap] = []
|
||||
self._dispatcher_id = id(self)
|
||||
_combine_dispatchers[self._dispatcher_id] = self
|
||||
self._concatenate_stream: torch.cuda.Stream | None = None
|
||||
self._output_event: torch.cuda.Event | None = None
|
||||
configure_num_sms(num_sms)
|
||||
|
||||
def _finalize_dispatch(
|
||||
self, pending_state: _PendingDispatchState
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
|
||||
_sync_dispatch(pending_state.handle_id)
|
||||
|
||||
hidden_states = pending_state.hidden_states
|
||||
num_received_tokens = hidden_states.shape[0]
|
||||
hidden_states, permuted_scores, deep_ep_permuted_indices = _permute_tokens(
|
||||
hidden_states,
|
||||
pending_state.dispatched_indices,
|
||||
pending_state.dispatched_scores,
|
||||
)
|
||||
permuted_scores_for_state = None
|
||||
else:
|
||||
permuted_scores_for_state = permuted_scores
|
||||
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
|
||||
|
||||
state = _DispatchState(
|
||||
handle_id=pending_state.handle_id,
|
||||
permuted_indices=permuted_indices,
|
||||
num_recv_tokens=num_recv_tokens,
|
||||
permuted_scores=permuted_scores_for_state,
|
||||
)
|
||||
return hidden_states, num_tokens_per_expert, state
|
||||
if pending_state.score_before_experts:
|
||||
hidden_states = (hidden_states.float() * permuted_scores.float().reshape(-1, 1)).to(hidden_states.dtype)
|
||||
scores_after_experts = None
|
||||
else:
|
||||
scores_after_experts = permuted_scores
|
||||
|
||||
|
||||
def combine_tokens(hidden_states: torch.Tensor, state: _DispatchState) -> torch.Tensor:
|
||||
if state.permuted_scores is not None:
|
||||
hidden_states = (hidden_states.to(torch.float32) * state.permuted_scores.to(torch.float32).reshape(-1, 1)).to(
|
||||
hidden_states.dtype
|
||||
hidden_states, num_tokens_per_expert, grouped_gemm_permutation = permute_for_grouped_gemm(
|
||||
hidden_states,
|
||||
num_tokens_per_expert,
|
||||
experts_per_rank=self.num_local_experts,
|
||||
num_ranks=1,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
hidden_states = _unpermute_tokens(hidden_states, state.permuted_indices, state.num_recv_tokens)
|
||||
return _DeepEPCombine.apply(hidden_states, state.handle_id)
|
||||
state = DeepEPDispatchState(
|
||||
handle_id=pending_state.handle_id,
|
||||
deep_ep_permuted_indices=deep_ep_permuted_indices,
|
||||
num_received_tokens=num_received_tokens,
|
||||
scores_after_experts=scores_after_experts,
|
||||
grouped_gemm_permutation=grouped_gemm_permutation,
|
||||
)
|
||||
return hidden_states, num_tokens_per_expert, state
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
|
||||
pending_state = dispatch_tokens_async(
|
||||
x,
|
||||
selected_experts_indices,
|
||||
top_scores,
|
||||
num_experts=self.num_experts,
|
||||
group=self.group,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
return self._finalize_dispatch(pending_state)
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: DeepEPDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.grouped_gemm_permutation)
|
||||
if state.scores_after_experts is not None:
|
||||
routed_output = (routed_output.float() * state.scores_after_experts.float().reshape(-1, 1)).to(
|
||||
routed_output.dtype
|
||||
)
|
||||
routed_output = _unpermute_tokens(
|
||||
routed_output,
|
||||
state.deep_ep_permuted_indices,
|
||||
state.num_received_tokens,
|
||||
)
|
||||
combined = torch.ops.deepep.combine(routed_output, state.handle_id, self._dispatcher_id)
|
||||
return combined
|
||||
|
||||
def _run_dispatched_chunk(
|
||||
self,
|
||||
pending_state: _PendingDispatchState,
|
||||
experts: ExpertFunction,
|
||||
) -> torch.Tensor:
|
||||
hidden_states, num_tokens_per_expert, dispatch_state = self._finalize_dispatch(pending_state)
|
||||
routed_output = experts(hidden_states, num_tokens_per_expert)
|
||||
return self.combine(routed_output, dispatch_state)
|
||||
|
||||
@torch.compiler.disable()
|
||||
def _synchronize_combines(self) -> None:
|
||||
for event in self._pending_combine_events:
|
||||
event.current_stream_wait()
|
||||
self._pending_combine_events.clear()
|
||||
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor:
|
||||
if self.token_chunk_size is None:
|
||||
chunk_ranges = [(0, x.shape[0])]
|
||||
else:
|
||||
chunk_ranges = [
|
||||
(start, min(start + self.token_chunk_size, x.shape[0]))
|
||||
for start in range(0, x.shape[0], self.token_chunk_size)
|
||||
]
|
||||
|
||||
pending_states = (
|
||||
dispatch_tokens_async(
|
||||
x[start:end],
|
||||
selected_experts_indices[start:end],
|
||||
top_scores[start:end],
|
||||
num_experts=self.num_experts,
|
||||
group=self.group,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
for start, end in chunk_ranges
|
||||
)
|
||||
|
||||
pending_state = next(pending_states)
|
||||
routed_outputs: list[torch.Tensor] = []
|
||||
for next_pending_state in pending_states:
|
||||
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
|
||||
pending_state = next_pending_state
|
||||
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
|
||||
if len(routed_outputs) == 1:
|
||||
return routed_outputs[0]
|
||||
|
||||
if self._concatenate_stream is None:
|
||||
self._concatenate_stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(self._concatenate_stream):
|
||||
self._synchronize_combines()
|
||||
output = torch.cat(routed_outputs, dim=0)
|
||||
self._output_event = self._concatenate_stream.record_event()
|
||||
return output
|
||||
|
||||
def synchronize(self) -> None:
|
||||
if self._output_event is not None:
|
||||
torch.cuda.current_stream().wait_event(self._output_event)
|
||||
self._output_event = None
|
||||
return
|
||||
self._synchronize_combines()
|
||||
|
||||
|
||||
register_deepep_cuda_ops()
|
||||
|
||||
__all__ = [
|
||||
"combine_tokens",
|
||||
"configure_num_sms",
|
||||
"DeepEPTokenDispatcher",
|
||||
"dispatch_tokens_async",
|
||||
"finalize_dispatch_tokens",
|
||||
"sync_combine",
|
||||
]
|
||||
|
||||
@@ -1,87 +1,14 @@
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed import ProcessGroup
|
||||
from torch.distributed.distributed_c10d import _resolve_process_group
|
||||
from torch.distributed.tensor import DeviceMesh, Shard, distribute_module, distribute_tensor
|
||||
from torch.distributed.tensor.parallel import ParallelStyle
|
||||
from torchao.prototype.moe_training.ep import a2a_combine_hp_fwd_mxfp8_bwd, a2a_dispatch_mxfp8_fwd_hp_bwd
|
||||
from torchao.prototype.mx_formats.mx_tensor import MXTensor
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
|
||||
|
||||
class _MXFP8Dispatch(torch.autograd.Function):
|
||||
class ExpertWeightParallel(ParallelStyle):
|
||||
@staticmethod
|
||||
def forward(ctx, routed_input, output_splits, input_splits, group_name):
|
||||
mx_routed_input = a2a_dispatch_mxfp8_fwd_hp_bwd(routed_input, output_splits, input_splits, group_name)
|
||||
ctx.input_splits = input_splits
|
||||
ctx.output_splits = output_splits
|
||||
ctx.group = _resolve_process_group(group_name)
|
||||
return mx_routed_input.dequantize(routed_input.dtype)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
grad_input = grad_output.new_empty((sum(ctx.input_splits),) + tuple(grad_output.shape[1:]))
|
||||
dist.all_to_all_single(
|
||||
grad_input, grad_output.contiguous(), ctx.input_splits, ctx.output_splits, group=ctx.group
|
||||
)
|
||||
return grad_input, None, None, None
|
||||
|
||||
|
||||
class _DequantMXGradInBwd(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x, hp_dtype):
|
||||
ctx.hp_dtype = hp_dtype
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
if isinstance(grad_output, MXTensor):
|
||||
grad_output = grad_output.dequantize(ctx.hp_dtype)
|
||||
return grad_output, None
|
||||
|
||||
|
||||
class MXFP8AllToAllExpertParallel(ExpertParallel):
|
||||
def _token_dispatch(self, mod, inputs, device_mesh):
|
||||
routed_input, num_tokens_per_expert = inputs
|
||||
with torch.no_grad():
|
||||
num_tokens_per_expert_group = num_tokens_per_expert.new_empty(num_tokens_per_expert.shape[0])
|
||||
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=device_mesh.get_group())
|
||||
self.input_splits = num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
|
||||
self.output_splits = num_tokens_per_expert_group.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
|
||||
routed_input = _MXFP8Dispatch.apply(
|
||||
routed_input, self.output_splits, self.input_splits, device_mesh.get_group().group_name
|
||||
)
|
||||
return routed_input, num_tokens_per_expert_group
|
||||
|
||||
def _token_combine(self, mod, routed_output, device_mesh):
|
||||
routed_output = _DequantMXGradInBwd.apply(routed_output, routed_output.dtype)
|
||||
return a2a_combine_hp_fwd_mxfp8_bwd(
|
||||
routed_output,
|
||||
self.input_splits,
|
||||
self.output_splits,
|
||||
device_mesh.get_group().group_name,
|
||||
)
|
||||
|
||||
|
||||
class DeepEPExpertParallel(ParallelStyle):
|
||||
"""Expert-parallel style backed by DeepEP dispatch/combine.
|
||||
|
||||
Only handles weight sharding (Shard(0) on expert dim) and stores the EP
|
||||
process group on the module. PrimeRL drives DeepEP dispatch/combine from
|
||||
`MoE.forward()` so communication stays outside the selective-AC checkpoint
|
||||
boundary while local expert matmuls remain checkpointable.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _partition_fn(name: str, mod: nn.Module, device_mesh: DeviceMesh) -> None:
|
||||
for param_name, param in mod.named_parameters(recurse=False):
|
||||
mod.register_parameter(param_name, nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)])))
|
||||
mod._ep_group = device_mesh.get_group()
|
||||
def _partition_fn(_name: str, module: nn.Module, device_mesh: DeviceMesh) -> None:
|
||||
for parameter_name, parameter in module.named_parameters(recurse=False):
|
||||
sharded = distribute_tensor(parameter, device_mesh, [Shard(0)])
|
||||
module.register_parameter(parameter_name, nn.Parameter(sharded))
|
||||
|
||||
def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
|
||||
return distribute_module(module, device_mesh, partition_fn=self._partition_fn)
|
||||
|
||||
|
||||
def get_ep_group(experts: nn.Module) -> ProcessGroup:
|
||||
return experts._ep_group
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Generic, Protocol, TypeVar
|
||||
|
||||
import torch
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import (
|
||||
all_to_all_single,
|
||||
all_to_all_single_equal,
|
||||
mxfp8_all_to_all_combine,
|
||||
mxfp8_all_to_all_dispatch,
|
||||
)
|
||||
|
||||
|
||||
class ExpertFunction(Protocol):
|
||||
def __call__(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor: ...
|
||||
|
||||
|
||||
class TokenDispatcher(Protocol):
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor: ...
|
||||
|
||||
def synchronize(self) -> None: ...
|
||||
|
||||
|
||||
DispatchState = TypeVar("DispatchState")
|
||||
|
||||
|
||||
class TokenDispatcherBase(ABC, Generic[DispatchState]):
|
||||
def __init__(self, num_experts: int, token_group_alignment: int) -> None:
|
||||
self.num_experts = num_experts
|
||||
self.token_group_alignment = token_group_alignment
|
||||
|
||||
@abstractmethod
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DispatchState]: ...
|
||||
|
||||
@abstractmethod
|
||||
def combine(self, routed_output: torch.Tensor, state: DispatchState) -> torch.Tensor: ...
|
||||
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor:
|
||||
routed_input, num_tokens_per_expert, state = self.dispatch(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
routed_output = experts(routed_input, num_tokens_per_expert)
|
||||
return self.combine(routed_output, state)
|
||||
|
||||
def synchronize(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PermutationState:
|
||||
input_shape: torch.Size
|
||||
permuted_indices: torch.Tensor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LocalDispatchState:
|
||||
num_tokens: int
|
||||
token_indices_experts_sorted: torch.Tensor
|
||||
scores_after_experts: torch.Tensor | None
|
||||
permutation: PermutationState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TorchDispatchState(LocalDispatchState):
|
||||
input_splits: torch.Tensor
|
||||
output_splits: torch.Tensor
|
||||
|
||||
|
||||
def permute_for_grouped_gemm(
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert_group: torch.Tensor,
|
||||
*,
|
||||
experts_per_rank: int,
|
||||
num_ranks: int,
|
||||
alignment: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, PermutationState]:
|
||||
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
|
||||
|
||||
max_len = x.shape[0] + experts_per_rank * alignment
|
||||
max_len = (max_len + alignment - 1) // alignment * alignment
|
||||
with torch.no_grad():
|
||||
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
|
||||
num_tokens_per_expert_group,
|
||||
experts_per_rank,
|
||||
num_ranks,
|
||||
max_len,
|
||||
alignment,
|
||||
use_cpu=x.device.type == "cpu",
|
||||
)
|
||||
|
||||
x = torch.vstack((x, x.new_zeros((1, x.shape[-1]))))
|
||||
state = PermutationState(input_shape=x.shape, permuted_indices=permuted_indices)
|
||||
return x[permuted_indices], num_tokens_per_expert, state
|
||||
|
||||
|
||||
def unpermute_from_grouped_gemm(x: torch.Tensor, state: PermutationState) -> torch.Tensor:
|
||||
output = x.new_empty(state.input_shape)
|
||||
output[state.permuted_indices] = x
|
||||
return output[:-1]
|
||||
|
||||
|
||||
def _local_reorder(
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
flattened_experts = selected_experts_indices.reshape(-1)
|
||||
num_tokens_per_expert = torch.histc(
|
||||
flattened_experts.float(),
|
||||
bins=num_experts,
|
||||
min=0,
|
||||
max=num_experts,
|
||||
).to(torch.int64)
|
||||
token_indices_experts_sorted = torch.argsort(flattened_experts, stable=True)
|
||||
top_scores_experts_sorted = top_scores.reshape(-1)[token_indices_experts_sorted]
|
||||
token_indices_experts_sorted = token_indices_experts_sorted // top_k
|
||||
routed_input = x[token_indices_experts_sorted]
|
||||
return routed_input, token_indices_experts_sorted, top_scores_experts_sorted, num_tokens_per_expert
|
||||
|
||||
|
||||
def _scatter_routed_output(
|
||||
routed_output: torch.Tensor,
|
||||
*,
|
||||
num_tokens: int,
|
||||
token_indices_experts_sorted: torch.Tensor,
|
||||
scores_after_experts: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
if scores_after_experts is not None:
|
||||
routed_output = (routed_output.float() * scores_after_experts.reshape(-1, 1)).to(routed_output.dtype)
|
||||
|
||||
dim = routed_output.shape[-1]
|
||||
output = routed_output.new_zeros((num_tokens, dim))
|
||||
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
return output.scatter_add(0, routed_indices, routed_output)
|
||||
|
||||
|
||||
class LocalTokenDispatcher(TokenDispatcherBase[LocalDispatchState]):
|
||||
def __init__(self, num_experts: int, top_k: int, token_group_alignment: int) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.top_k = top_k
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, LocalDispatchState]:
|
||||
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
num_experts=self.num_experts,
|
||||
top_k=self.top_k,
|
||||
)
|
||||
scores_after_experts = None
|
||||
if score_before_experts:
|
||||
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
|
||||
else:
|
||||
scores_after_experts = sorted_scores
|
||||
|
||||
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
|
||||
routed_input,
|
||||
num_tokens_per_expert,
|
||||
experts_per_rank=self.num_experts,
|
||||
num_ranks=1,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
state = LocalDispatchState(
|
||||
num_tokens=x.shape[0],
|
||||
token_indices_experts_sorted=token_indices,
|
||||
scores_after_experts=scores_after_experts,
|
||||
permutation=permutation,
|
||||
)
|
||||
return routed_input, num_tokens_per_expert, state
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: LocalDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
|
||||
return _scatter_routed_output(
|
||||
routed_output,
|
||||
num_tokens=state.num_tokens,
|
||||
token_indices_experts_sorted=state.token_indices_experts_sorted,
|
||||
scores_after_experts=state.scores_after_experts,
|
||||
)
|
||||
|
||||
|
||||
class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
|
||||
def __init__(
|
||||
self,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.top_k = top_k
|
||||
self.group = group
|
||||
|
||||
def _dispatch_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return all_to_all_single(x, output_splits, input_splits, self.group)
|
||||
|
||||
def _combine_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return all_to_all_single(x, output_splits, input_splits, self.group)
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, TorchDispatchState]:
|
||||
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
num_experts=self.num_experts,
|
||||
top_k=self.top_k,
|
||||
)
|
||||
scores_after_experts = None
|
||||
if score_before_experts:
|
||||
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
|
||||
else:
|
||||
scores_after_experts = sorted_scores
|
||||
|
||||
ep_degree = self.group.size()
|
||||
with torch.no_grad():
|
||||
num_tokens_per_expert_group = all_to_all_single_equal(num_tokens_per_expert, self.group)
|
||||
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1)
|
||||
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1)
|
||||
|
||||
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
|
||||
experts_per_rank = self.num_experts // ep_degree
|
||||
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
|
||||
routed_input,
|
||||
num_tokens_per_expert_group,
|
||||
experts_per_rank=experts_per_rank,
|
||||
num_ranks=ep_degree,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
state = TorchDispatchState(
|
||||
num_tokens=x.shape[0],
|
||||
token_indices_experts_sorted=token_indices,
|
||||
scores_after_experts=scores_after_experts,
|
||||
permutation=permutation,
|
||||
input_splits=input_splits,
|
||||
output_splits=output_splits,
|
||||
)
|
||||
return routed_input, num_tokens_per_expert, state
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: TorchDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
|
||||
routed_output = self._combine_tokens(routed_output, state.input_splits, state.output_splits)
|
||||
return _scatter_routed_output(
|
||||
routed_output,
|
||||
num_tokens=state.num_tokens,
|
||||
token_indices_experts_sorted=state.token_indices_experts_sorted,
|
||||
scores_after_experts=state.scores_after_experts,
|
||||
)
|
||||
|
||||
|
||||
class MXFP8TorchTokenDispatcher(TorchTokenDispatcher):
|
||||
def __init__(
|
||||
self,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
) -> None:
|
||||
super().__init__(num_experts, top_k, token_group_alignment, group)
|
||||
|
||||
def _dispatch_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return mxfp8_all_to_all_dispatch(x, output_splits, input_splits, self.group)
|
||||
|
||||
def _combine_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return mxfp8_all_to_all_combine(x, output_splits, input_splits, self.group)
|
||||
@@ -18,7 +18,7 @@ from prime_rl.trainer.models.layers.lora.multi_moe import (
|
||||
MultiLoRAGroupedExperts,
|
||||
MultiLoRANonGatedGroupedExperts,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -156,8 +156,8 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
|
||||
target_modules = []
|
||||
|
||||
for name, module in model.named_modules():
|
||||
# Check if module is Linear or one of the supported expert classes
|
||||
if not isinstance(module, (nn.Linear, GroupedExperts, NonGatedGroupedExperts, GptOssGroupedExperts)):
|
||||
# Check if module is Linear or a supported expert class
|
||||
if not isinstance(module, (nn.Linear, GroupedExperts)):
|
||||
continue
|
||||
|
||||
for pattern in target_patterns:
|
||||
@@ -224,6 +224,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_state = setup_lora_state(config, torch.device("cuda", get_world().local_rank))
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
lora_state.register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
|
||||
uses_gpt_oss_moe_adapter = (
|
||||
isinstance(model, PreTrainedModelPrimeRL) and getattr(model.config, "model_type", None) == "gpt_oss"
|
||||
)
|
||||
|
||||
from torch.distributed.fsdp import FSDPModule
|
||||
|
||||
@@ -256,25 +259,13 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
)
|
||||
# Handle GroupedExperts (MoE)
|
||||
elif isinstance(base_module, GroupedExperts):
|
||||
lora_module = MultiLoRAGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle NonGatedGroupedExperts (relu2 experts used by NemotronH's LatentMoE)
|
||||
elif isinstance(base_module, NonGatedGroupedExperts):
|
||||
lora_module = MultiLoRANonGatedGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle GptOssGroupedExperts (gpt-oss fused gate_up + biases)
|
||||
elif isinstance(base_module, GptOssGroupedExperts):
|
||||
lora_module = MultiLoRAGptOssGroupedExperts(
|
||||
if uses_gpt_oss_moe_adapter:
|
||||
wrapper = MultiLoRAGptOssGroupedExperts
|
||||
elif base_module.gate_proj is not None:
|
||||
wrapper = MultiLoRAGroupedExperts
|
||||
else:
|
||||
wrapper = MultiLoRANonGatedGroupedExperts
|
||||
lora_module = wrapper(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
@@ -284,7 +275,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
else:
|
||||
logger.warning(
|
||||
f"Module {module_name} is type {type(base_module).__name__}, "
|
||||
f"expected nn.Linear, GroupedExperts, NonGatedGroupedExperts, or GptOssGroupedExperts. Skipping."
|
||||
"expected nn.Linear or GroupedExperts. Skipping."
|
||||
)
|
||||
continue
|
||||
|
||||
|
||||
+54
-157
@@ -15,13 +15,10 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
@@ -32,10 +29,9 @@ from prime_rl.configs.trainer import (
|
||||
FP8Config,
|
||||
ModelConfig,
|
||||
MXFP8Config,
|
||||
QuantizationConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.trainer.distributed import DeepEPExpertParallel, MXFP8AllToAllExpertParallel
|
||||
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
AutoModelForCausalLMPrimeRL,
|
||||
@@ -46,16 +42,11 @@ from prime_rl.trainer.models import (
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRouter, _load_fused_moe_kernel
|
||||
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
|
||||
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -403,8 +394,8 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
if mlp is None:
|
||||
continue
|
||||
|
||||
# Custom implementation: MoE/LatentMoE class with router attribute
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
# Custom implementation
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
@@ -431,7 +422,7 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
@@ -443,39 +434,6 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Running {num_routers} MoE router gates in fp32")
|
||||
|
||||
|
||||
def apply_fused_moe_kernel(model: nn.Module, quantization: QuantizationConfig | None) -> None:
|
||||
"""
|
||||
Route MoE routed-expert compute through the our fused bf16/mxfp8 MoE CUDA kernel.
|
||||
Forward runs the kernel, backward recomputes the reference grouped-mm path.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_moe_layers = 0
|
||||
|
||||
# MXFP8 with grouped GEMM is the one setting that quantizes the experts themselves, so this also picks the MXFP8 kernel."""
|
||||
dtype = "mxfp8" if isinstance(quantization, MXFP8Config) and quantization.enable_grouped_gemm else "bf16"
|
||||
kernel = _load_fused_moe_kernel()
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
if mlp.score_before_experts:
|
||||
raise ValueError(
|
||||
"model.moe_fused_kernel=true requires MoE layers with score_before_experts=false, because the fused kernel applies the routing scores to the expert outputs."
|
||||
)
|
||||
_, hidden_dim, dim = mlp.experts.w1.shape
|
||||
reason = kernel.unsupported_shape_reason(dim, hidden_dim, mxfp8=dtype == "mxfp8")
|
||||
if reason is not None:
|
||||
raise ValueError(f"model.moe_fused_kernel=true does not support this model: {reason}")
|
||||
mlp.fused_kernel = dtype
|
||||
num_moe_layers += 1
|
||||
|
||||
if num_moe_layers == 0:
|
||||
raise ValueError("model.moe_fused_kernel=true but no MoE layers found. Is this a custom-impl MoE model?")
|
||||
|
||||
logger.info(f"Using the fused {dtype} MoE kernel for {num_moe_layers} MoE layers")
|
||||
|
||||
|
||||
def get_full_offload_dtype_policy(
|
||||
model: nn.Module,
|
||||
config: ModelConfig,
|
||||
@@ -489,7 +447,7 @@ def get_full_offload_dtype_policy(
|
||||
language_model = get_language_model(model)
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
@@ -527,7 +485,7 @@ def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
@@ -544,20 +502,6 @@ def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
|
||||
|
||||
def configure_moe_ep_backend(model: nn.Module, config: ModelConfig) -> None:
|
||||
backend = config.ep_comm_backend
|
||||
if backend == "deepep":
|
||||
from prime_rl.trainer.distributed.deepep import configure_num_sms
|
||||
|
||||
configure_num_sms(config.deepep_num_sms)
|
||||
language_model = get_language_model(model)
|
||||
for transformer_block in language_model.layers:
|
||||
if not isinstance(transformer_block.mlp, (MoE, LatentMoE)):
|
||||
continue
|
||||
transformer_block.mlp.set_ep_comm_backend(backend)
|
||||
transformer_block.mlp.set_deepep_token_chunk_size(config.deepep_token_chunk_size)
|
||||
|
||||
|
||||
def get_load_balance_stats(
|
||||
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
|
||||
) -> dict[str, Tensor | None]:
|
||||
@@ -647,13 +591,6 @@ def get_model(
|
||||
subconfig = getattr(model_config, subconfig_key, None)
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
# MoEArgs.fp8 (read via getattr(config, "fp8") in the modeling files) gates the
|
||||
# DeepGEMM FP8 grouped GEMM. MXFP8 grouped GEMM is applied by wrapping the expert
|
||||
# weights with torchao (see apply_quantization), so it leaves this flag False and
|
||||
# the experts keep calling torch._grouped_mm — which the wrapper tensor intercepts.
|
||||
model_config.fp8 = isinstance(config.quantization, FP8Config) and config.quantization.enable_grouped_gemm
|
||||
|
||||
if config.index_cache is not None:
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
@@ -855,12 +792,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
for transformer_block in transformer_layers:
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, MoE):
|
||||
fully_shard(block_mlp.experts, mesh=dp_mod_ep_mesh, **fsdp_config)
|
||||
|
||||
block_mlp.experts.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, MoE):
|
||||
# Own FSDP unit with an fp32 policy so the gate weight is not cast to
|
||||
# bf16 for forward and its gradients reduce in fp32.
|
||||
fully_shard(
|
||||
@@ -923,7 +860,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
for transformer_block, next_transformer_block in zip(transformer_blocks, next_transformer_blocks):
|
||||
if next_transformer_block is not None:
|
||||
next_mlp = getattr(next_transformer_block, "mlp", None)
|
||||
if next_mlp is not None and isinstance(next_mlp, (MoE, LatentMoE)):
|
||||
if next_mlp is not None and isinstance(next_mlp, MoE):
|
||||
prefetch_modules = [next_transformer_block]
|
||||
if isinstance(next_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(next_mlp.router)
|
||||
@@ -940,15 +877,23 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
prev_transformer_blocks = reversed_transformer_blocks[1:] + [None]
|
||||
|
||||
if language_model.norm is not None and model.lm_head is not None and len(language_model.layers) > 0:
|
||||
last_transformer_block = reversed_transformer_blocks[0]
|
||||
prefetch_modules = [last_transformer_block]
|
||||
last_mlp = getattr(last_transformer_block, "mlp", None)
|
||||
if last_mlp is not None and isinstance(last_mlp, MoE):
|
||||
prefetch_modules.append(last_mlp.experts)
|
||||
if isinstance(last_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(last_mlp.router)
|
||||
|
||||
if shard_norm_and_lm_head:
|
||||
model.lm_head.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
|
||||
model.lm_head.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
else:
|
||||
model.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
|
||||
model.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
|
||||
for transformer_block, prev_transformer_block in zip(reversed_transformer_blocks, prev_transformer_blocks):
|
||||
if prev_transformer_block is not None:
|
||||
prev_mlp = getattr(prev_transformer_block, "mlp", None)
|
||||
if prev_mlp is not None and isinstance(prev_mlp, (MoE, LatentMoE)):
|
||||
if prev_mlp is not None and isinstance(prev_mlp, MoE):
|
||||
prefetch_modules = [prev_transformer_block, prev_mlp.experts]
|
||||
if isinstance(prev_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(prev_mlp.router)
|
||||
@@ -994,6 +939,9 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
|
||||
model_keys = dict.fromkeys(model.state_dict().keys())
|
||||
|
||||
if source_path.name == "prime" and not (source_path / ".prime-v1").is_file():
|
||||
raise RuntimeError(f"PrimeRL conversion cache {source_path} is missing the required .prime-v1 marker")
|
||||
|
||||
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
|
||||
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
|
||||
|
||||
@@ -1009,6 +957,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
snapshot_state_dict = load_state_dict(source_path)
|
||||
model.convert_to_prime(snapshot_state_dict)
|
||||
save_state_dict(snapshot_state_dict, snapshot_path)
|
||||
(snapshot_path / ".prime-v1").touch()
|
||||
del snapshot_state_dict
|
||||
|
||||
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
|
||||
@@ -1027,6 +976,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
|
||||
# All ranks wait for master rank to finish conversion
|
||||
torch.distributed.barrier()
|
||||
if (
|
||||
isinstance(model, PreTrainedModelPrimeRL)
|
||||
and snapshot_path.name == "prime"
|
||||
and not (snapshot_path / ".prime-v1").is_file()
|
||||
):
|
||||
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
|
||||
|
||||
logger.info(f"Loading weights using HF DCP from {snapshot_path}")
|
||||
load_dcp_start_time = time.perf_counter()
|
||||
@@ -1079,7 +1034,9 @@ def can_reinit_empty_buffers(model: nn.Module):
|
||||
if not (name.startswith("model.layers.") and name.endswith("mlp.tokens_per_expert"))
|
||||
]
|
||||
buffer_names = [
|
||||
name for name in buffer_names if not (name.startswith("model.layers.") and name.endswith("mlp.expert_bias"))
|
||||
name
|
||||
for name in buffer_names
|
||||
if not (name.startswith("model.layers.") and name.endswith("mlp.router.selection_bias"))
|
||||
]
|
||||
# HF standard transformer model
|
||||
if len(buffer_names) == 1 and buffer_names[0] == "model.rotary_emb.inv_freq":
|
||||
@@ -1139,50 +1096,20 @@ def reshard_module(model: nn.Module):
|
||||
|
||||
|
||||
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
target_list = sorted(frozenset(ac_config.targets))
|
||||
selective_layers = 0
|
||||
full_layers = 0
|
||||
fallback_layer_types: set[str] = set()
|
||||
model_supported_targets: set[str] = set()
|
||||
wrap_block = get_activation_checkpoint_wrapper(ac_config)
|
||||
checkpointed_layers = 0
|
||||
|
||||
for layer_id, (layer_name, transformer_block) in enumerate(language_model.layers.named_children()):
|
||||
if layer_id % ac_config.freq != 0:
|
||||
continue
|
||||
|
||||
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
|
||||
model_supported_targets.update(get_supported_targets(transformer_block))
|
||||
set_selective_activation_checkpointing(transformer_block, target_list)
|
||||
selective_layers += 1
|
||||
else:
|
||||
if ac_config.mode == "selective":
|
||||
fallback_layer_types.add(type(transformer_block).__name__)
|
||||
transformer_block = checkpoint_wrapper(transformer_block, preserve_rng_state=False)
|
||||
full_layers += 1
|
||||
language_model.layers.register_module(layer_name, wrap_block(transformer_block))
|
||||
checkpointed_layers += 1
|
||||
|
||||
language_model.layers.register_module(layer_name, transformer_block)
|
||||
|
||||
if ac_config.mode == "selective":
|
||||
unsupported_targets = frozenset(target_list) - model_supported_targets
|
||||
if unsupported_targets:
|
||||
raise ValueError(
|
||||
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
|
||||
f"by the selected model layers. Supported targets across the model: {sorted(model_supported_targets)}"
|
||||
)
|
||||
if fallback_layer_types:
|
||||
logger.warning(
|
||||
"Selective activation checkpointing is not supported for layer types "
|
||||
f"{sorted(fallback_layer_types)}; falling back to full checkpointing for those layers."
|
||||
)
|
||||
logger.info(
|
||||
"Applied selective activation checkpointing "
|
||||
f"(freq={ac_config.freq}, targets={target_list}, selective_layers={selective_layers}, "
|
||||
f"full_fallback_layers={full_layers})"
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(f"Applied activation checkpointing (freq={ac_config.freq})")
|
||||
get_logger().info(
|
||||
f"Applied {ac_config.mode} activation checkpointing to {checkpointed_layers} layers (freq={ac_config.freq})"
|
||||
)
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
@@ -1195,13 +1122,9 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
|
||||
|
||||
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
"""Swap dense linears and MoE expert GEMMs to the configured low-precision path.
|
||||
"""Swap dense linear modules to the configured low-precision path.
|
||||
|
||||
Runs after the LM head is injected but before LoRA / EP / FSDP so the swapped
|
||||
modules and wrapped parameters are picked up by the later parallelisms. The
|
||||
FP8 grouped GEMM (DeepGEMM) is gated separately via ``model_config.fp8`` since
|
||||
it lives inside the modeling code; here we only handle the dense-linear swap
|
||||
and the torchao MXFP8 expert-weight wrapping.
|
||||
Routed-expert compute is configured independently by ``model.moe.compute``.
|
||||
"""
|
||||
quant = config.quantization
|
||||
if quant is None:
|
||||
@@ -1211,33 +1134,11 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
|
||||
elif isinstance(quant, MXFP8Config):
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability < (10, 0):
|
||||
if capability != (10, 0):
|
||||
raise ValueError(
|
||||
f"MXFP8 quantization requires SM100 (Blackwell) or newer, but device is SM{capability[0]}{capability[1]}."
|
||||
f"MXFP8 quantization requires SM100 (Blackwell), but device is SM{capability[0]}{capability[1]}."
|
||||
)
|
||||
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
|
||||
if quant.enable_grouped_gemm:
|
||||
apply_mxfp8_moe_grouped_gemm(model, recipe=quant.recipe)
|
||||
|
||||
|
||||
def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
language_model = get_language_model(model)
|
||||
for transformer_block in language_model.layers:
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if config.ep_comm_backend == "torch":
|
||||
quant = config.quantization
|
||||
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
|
||||
parallelize_plan = MXFP8AllToAllExpertParallel()
|
||||
else:
|
||||
parallelize_plan = ExpertParallel()
|
||||
else:
|
||||
parallelize_plan = DeepEPExpertParallel()
|
||||
parallelize_module(
|
||||
block_mlp.experts,
|
||||
device_mesh=parallel_dims.get_mesh("ep"),
|
||||
parallelize_plan=parallelize_plan,
|
||||
)
|
||||
|
||||
|
||||
def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None:
|
||||
@@ -1266,7 +1167,7 @@ def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
|
||||
|
||||
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, (MoE, LatentMoE)) and module.tokens_per_expert.device.type != "meta":
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
|
||||
|
||||
@@ -1330,7 +1231,6 @@ def setup_model(
|
||||
|
||||
# 1. We load to meta device by default
|
||||
model = get_model(config, device=torch.device("meta"), dtype=DTYPE_MAP[config.optimization_dtype])
|
||||
configure_moe_ep_backend(model, config)
|
||||
|
||||
possible_to_load_to_meta = can_reinit_empty_buffers(model)
|
||||
|
||||
@@ -1343,7 +1243,6 @@ def setup_model(
|
||||
if not possible_to_load_to_meta:
|
||||
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
|
||||
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
|
||||
configure_moe_ep_backend(model, config)
|
||||
|
||||
lm_head_chunk_size: int | None = None
|
||||
if isinstance(config.fused_lm_head_token_chunk_size, int):
|
||||
@@ -1361,14 +1260,6 @@ def setup_model(
|
||||
if config.moe_router_dtype == "float32":
|
||||
apply_fp32_moe_router(model)
|
||||
|
||||
if config.moe_fused_kernel:
|
||||
if parallel_dims.ep_enabled:
|
||||
raise ValueError(
|
||||
"model.moe_fused_kernel=true requires ep=1: the fused kernel bypasses the EP "
|
||||
"all-to-all and indexes experts with global ids."
|
||||
)
|
||||
apply_fused_moe_kernel(model, config.quantization)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
@@ -1377,8 +1268,8 @@ def setup_model(
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
configure_moe_runtime(model, config, parallel_dims)
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, config, parallel_dims)
|
||||
# EP replaces params with DTensors that default to requires_grad=True,
|
||||
# re-freeze base params that LoRA froze earlier.
|
||||
if config.lora is not None:
|
||||
@@ -1437,6 +1328,7 @@ def forward(
|
||||
labels: Int[Tensor, "batch seq"] | None = None,
|
||||
temperature: Tensor | None = None,
|
||||
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None = None,
|
||||
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
|
||||
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
|
||||
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
|
||||
@@ -1454,6 +1346,11 @@ def forward(
|
||||
"temperature": temperature,
|
||||
}
|
||||
|
||||
# Sampling masks are consumed by the injected prime lm_head; HF
|
||||
# forwards don't know the kwarg, so only pass it when present.
|
||||
if sampling_mask is not None:
|
||||
kwargs["sampling_mask"] = sampling_mask
|
||||
|
||||
if mm_kwargs:
|
||||
# Forward the per-model multimodal tensors verbatim, plus the
|
||||
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
|
||||
|
||||
@@ -37,21 +37,16 @@ class AfmoeConfig(PretrainedConfig):
|
||||
num_experts=64,
|
||||
num_experts_per_tok=6,
|
||||
num_shared_experts=2,
|
||||
num_expert_groups=1,
|
||||
num_limited_groups=1,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts: bool = False,
|
||||
load_balance_coeff: float = 5e-4,
|
||||
use_grouped_mm: bool = True,
|
||||
global_attn_every_n_layers=4,
|
||||
sliding_window=1024,
|
||||
mup_enabled=False,
|
||||
layer_types=None,
|
||||
attention_dropout: float = 0.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
@@ -71,18 +66,13 @@ class AfmoeConfig(PretrainedConfig):
|
||||
# MoE specific
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts = num_experts
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.num_expert_groups = num_expert_groups
|
||||
self.num_limited_groups = num_limited_groups
|
||||
self.score_func = score_func
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.score_before_experts = score_before_experts
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
# Attention specific
|
||||
self.attention_dropout = attention_dropout
|
||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
AFMoE specifics:
|
||||
|
||||
* Per-layer MLP prefix is ``model.layers.{i}.mlp``.
|
||||
* The router shares its name between HF and prime, so it is *not* renamed.
|
||||
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to prime
|
||||
``shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on the prime side).
|
||||
* The router gate shares its name between HF and prime, while HF
|
||||
``mlp.expert_bias`` maps to PrimeRL ``mlp.router.selection_bias``.
|
||||
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to PrimeRL
|
||||
``shared_expert.{gate,down,up}_proj.weight``.
|
||||
* Routed experts: HF per-expert ``experts.{e}.{gate,down,up}_proj.weight`` stack
|
||||
into prime ``experts.{w1,w2,w3}`` along dim 0 (no fused gate_up layout).
|
||||
into PrimeRL ``experts.{gate,down,up}_proj`` along dim 0.
|
||||
* Prime-only runtime buffers ``mlp.tokens_per_expert`` and ``mlp.reorderer.*``
|
||||
are dropped on the way back to HF.
|
||||
"""
|
||||
@@ -21,8 +22,9 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}.mlp"
|
||||
ops.append(Rename(f"{p}.expert_bias", f"{p}.router.selection_bias"))
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Stack(stacked=f"{p}.experts.{wn}", item=f"{p}.experts.{{e}}.{hf_proj}.weight"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
|
||||
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
@@ -82,18 +82,6 @@ class AfmoeAttentionBase(nn.Module):
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def output_proj(
|
||||
self,
|
||||
attn_output: torch.Tensor,
|
||||
gate_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
input_shape = gate_states.shape[:-1]
|
||||
if attn_output.dim() == 4:
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
|
||||
class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
@@ -125,21 +113,14 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
def attn_projections(
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -159,25 +140,10 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
return query_states, key_states, value_states, gate_states
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
return self.output_proj(attn_output, gate_states), None
|
||||
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
AFMOE_ATTN_IMPL2CLASS = {
|
||||
@@ -242,28 +208,38 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
self.post_mlp_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
self.moe_enabled = layer_idx >= config.num_dense_layers
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=config.num_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func=config.score_func,
|
||||
route_norm=config.route_norm,
|
||||
route_scale=config.route_scale,
|
||||
score_before_experts=getattr(config, "score_before_experts", False),
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.num_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.num_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -325,7 +301,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -213,24 +213,6 @@ class SplitConcat(ConvOp):
|
||||
sd[self.combined] = torch.cat(tensors, dim=self.dim)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Synthetic(ConvOp):
|
||||
"""A prime-only tensor with no HF counterpart, created on forward and
|
||||
dropped on backward (e.g. NemotronH's dummy ``experts.w3`` of shape (0,)).
|
||||
|
||||
``factory`` builds the tensor from the current state dict (so it can match
|
||||
device/dtype of a sibling)."""
|
||||
|
||||
prime: str
|
||||
factory: Callable[[StateDict], Tensor]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
sd[self.prime] = self.factory(sd)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
sd.pop(self.prime, None)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MapValue(ConvOp):
|
||||
"""Apply a value transform to one key. ``forward`` runs HF->prime,
|
||||
@@ -314,11 +296,11 @@ def key_present(name: str) -> Callable[[StateDict], bool]:
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Shared composition helper for Llama-style routed experts (prime w1=gate,
|
||||
# w2=down, w3=up). Used by several models' converting_<model>.py.
|
||||
# Shared composition helper for Llama-style routed experts (prime gate_proj=gate,
|
||||
# down_proj=down, up_proj=up). Used by several models' converting_<model>.py.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GATE_DOWN_UP = (("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj"))
|
||||
GATE_DOWN_UP = (("gate_proj", "gate_proj"), ("down_proj", "down_proj"), ("up_proj", "up_proj"))
|
||||
|
||||
|
||||
def routed_experts_op(
|
||||
@@ -335,14 +317,14 @@ def routed_experts_op(
|
||||
Per-expert HF weights <-> stacked prime tensors is a :class:`Stack` per
|
||||
proj. ``hf_experts``/``prime_experts`` are the (relative) expert container
|
||||
names (e.g. ``mlp.experts`` / ``block_sparse_moe.experts``); ``proj_order``
|
||||
maps prime ``wN`` to the HF per-expert proj name.
|
||||
maps prime projection names to the HF per-expert proj name.
|
||||
|
||||
With ``fused`` set, the transformers-v5 fused ``gate_up_proj`` input is also
|
||||
accepted: a :class:`Conditional` on its presence splits it (dim 1) into
|
||||
w1/w3 and renames ``down_proj`` -> w2; otherwise the per-expert ``Stack``s
|
||||
run. Prime always stores split w1/w2/w3, so the backward path always goes
|
||||
through the per-expert ``Stack`` unstack (the fused key is absent in prime,
|
||||
so the conditional takes the else branch)."""
|
||||
gate_proj/up_proj and renames ``down_proj``; otherwise the per-expert
|
||||
``Stack``s run. Prime always stores split gate/down/up projections, so the
|
||||
backward path always goes through the per-expert ``Stack`` unstack (the
|
||||
fused key is absent in prime, so the conditional takes the else branch)."""
|
||||
stacks = [
|
||||
Stack(
|
||||
stacked=f"{prefix}.{prime_experts}.{wn}",
|
||||
@@ -356,9 +338,12 @@ def routed_experts_op(
|
||||
fused_then = [
|
||||
SplitConcat(
|
||||
combined=gate_up,
|
||||
parts=[(f"{prefix}.{prime_experts}.w1", None), (f"{prefix}.{prime_experts}.w3", None)],
|
||||
parts=[
|
||||
(f"{prefix}.{prime_experts}.gate_proj", None),
|
||||
(f"{prefix}.{prime_experts}.up_proj", None),
|
||||
],
|
||||
dim=1,
|
||||
),
|
||||
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.w2"),
|
||||
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.down_proj"),
|
||||
]
|
||||
return Conditional(key_present(gate_up), then=fused_then, else_=stacks)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import warnings
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
@@ -97,10 +95,6 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
Number of routed experts.
|
||||
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
||||
Scaling factor or routed experts.
|
||||
n_group (`int`, *optional*, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, *optional*, defaults to 1):
|
||||
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
||||
first_k_dense_replace (`int`, *optional*, defaults to 1):
|
||||
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
||||
\--k dense layers--/
|
||||
@@ -128,9 +122,9 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
@@ -165,12 +159,9 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
n_shared_experts=1,
|
||||
n_routed_experts=128,
|
||||
routed_scaling_factor=1.0,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
first_k_dense_replace=1,
|
||||
norm_topk_prob=True,
|
||||
use_qk_norm=False,
|
||||
use_grouped_mm=True,
|
||||
pad_token_id=None,
|
||||
**kwargs,
|
||||
):
|
||||
@@ -196,18 +187,12 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
# MoE arguments
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
|
||||
@@ -4,15 +4,14 @@ GLM-4 MoE specifics:
|
||||
|
||||
* Router: HF ``mlp.gate.weight`` -> prime ``mlp.router.gate.weight``.
|
||||
* Expert bias: HF ``mlp.gate.e_score_correction_bias`` -> prime
|
||||
``mlp.expert_bias``.
|
||||
``mlp.router.selection_bias``.
|
||||
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
|
||||
stack into prime ``mlp.experts.{w1,w2,w3}`` along dim 0; the fused
|
||||
stack into prime ``mlp.experts.{gate,down,up}_proj`` along dim 0; the fused
|
||||
transformers-v5 ``mlp.experts.gate_up_proj`` / ``down_proj`` layout is also
|
||||
accepted on the way in (split along dim 1).
|
||||
* Shared experts: HF ``mlp.shared_experts.{gate,down,up}_proj.weight`` map to
|
||||
prime ``mlp.shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on prime; this
|
||||
is a plain rename forward). On the way back to HF, GLM strips a leading
|
||||
singleton dim from each shared-expert tensor when present
|
||||
prime ``mlp.shared_expert.{gate,down,up}_proj.weight``. On the way back to HF,
|
||||
GLM strips a leading singleton dim from each shared-expert tensor when present
|
||||
(:class:`~prime_rl.trainer.models.conversion_ops.SqueezeLeading`,
|
||||
backward-only).
|
||||
* Prime-only runtime buffer ``mlp.tokens_per_expert`` is dropped on the way
|
||||
@@ -42,7 +41,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
|
||||
p = f"model.layers.{layer_idx}.mlp"
|
||||
ops: list[ConvOp] = [
|
||||
Rename(f"{p}.gate.weight", f"{p}.router.gate.weight"),
|
||||
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.expert_bias"),
|
||||
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.router.selection_bias"),
|
||||
routed_experts_op(
|
||||
f"model.layers.{layer_idx}",
|
||||
hf_experts="mlp.experts",
|
||||
@@ -55,7 +54,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
|
||||
# restored the HF key, so it precedes the Rename in the forward list
|
||||
# (apply_prime_to_hf plays the chain in reverse).
|
||||
ops.append(SqueezeLeading(f"{p}.shared_experts.{hf_proj}.weight"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
return ops
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfi
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import conversion_chain
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
@@ -55,27 +55,36 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
num_shared_experts=config.n_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if layer_idx >= config.first_k_dense_replace:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.n_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -126,7 +135,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
return name.endswith("mlp.router.selection_bias")
|
||||
|
||||
def _init_weights(self, module):
|
||||
super()._init_weights(module)
|
||||
@@ -140,7 +149,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
"""Check if the state dict contains MoE layers in PrimeRL training format."""
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import warnings
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
@@ -56,10 +54,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
Dimension of value heads.
|
||||
qk_nope_head_dim (`int`, defaults to 192):
|
||||
Dimension of query/key heads that don't use rotary position embeddings.
|
||||
n_group (`int`, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, defaults to 1):
|
||||
Number of selected groups per token.
|
||||
num_experts_per_tok (`int`, defaults to 8):
|
||||
Number of active experts per token.
|
||||
first_k_dense_replace (`int`, defaults to 3):
|
||||
@@ -101,8 +95,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
field is absent from the config).
|
||||
topk_method (`str`, defaults to `"noaux_tc"`):
|
||||
MoE routing top-k method used by GLM-5 checkpoints.
|
||||
use_grouped_mm (`bool`, defaults to `True`):
|
||||
Whether to use grouped matrix multiplication for MoE.
|
||||
"""
|
||||
|
||||
model_type = "glm_moe_dsa"
|
||||
@@ -111,9 +103,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
@@ -141,8 +133,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
qk_nope_head_dim=192,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
num_experts_per_tok=8,
|
||||
first_k_dense_replace=3,
|
||||
norm_topk_prob=True,
|
||||
@@ -169,7 +159,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
indexer_types=None,
|
||||
scoring_func="sigmoid",
|
||||
topk_method="noaux_tc",
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
@@ -194,8 +183,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
@@ -226,12 +213,8 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.indexer_types = indexer_types
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
|
||||
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
|
||||
# overwrite self.head_dim and break the rotary embedding dimension.
|
||||
|
||||
@@ -90,13 +90,13 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
|
||||
expert_bias_key = f"{prefix}.mlp.expert_bias"
|
||||
if expert_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[expert_bias_key])
|
||||
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
|
||||
if selection_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
|
||||
|
||||
w1_key = f"{prefix}.mlp.experts.w1"
|
||||
w2_key = f"{prefix}.mlp.experts.w2"
|
||||
w3_key = f"{prefix}.mlp.experts.w3"
|
||||
w1_key = f"{prefix}.mlp.experts.gate_proj"
|
||||
w2_key = f"{prefix}.mlp.experts.down_proj"
|
||||
w3_key = f"{prefix}.mlp.experts.up_proj"
|
||||
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
|
||||
w1 = state_dict[w1_key]
|
||||
w2 = state_dict[w2_key]
|
||||
@@ -124,9 +124,9 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = w13
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = w2
|
||||
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.w1"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.w2"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.w3"
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
|
||||
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
|
||||
sw1 = state_dict[sw1_key]
|
||||
sw2 = state_dict[sw2_key]
|
||||
|
||||
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
@@ -56,27 +56,36 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
num_shared_experts=config.n_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if layer_idx >= config.first_k_dense_replace:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.n_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -136,7 +145,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
return name.endswith("mlp.router.selection_bias")
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
@@ -144,7 +153,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -10,11 +10,9 @@ from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
|
||||
except ImportError:
|
||||
sparse_mla_fwd_interface = None # type: ignore
|
||||
sparse_mla_bwd = None # type: ignore
|
||||
sparse_mla = None # type: ignore
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -36,23 +34,6 @@ class SparseMlaAttentionArgs:
|
||||
skip_topk: bool = False
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, q, kv, indices, sm_scale):
|
||||
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, do):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
def apply_rope_interleave_single(
|
||||
t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
@@ -177,7 +158,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
|
||||
def attn_projections(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
||||
@@ -224,15 +205,6 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
assert sparse_kv.shape[1] == s_full + 1
|
||||
return sparse_q, sparse_kv, w_v
|
||||
|
||||
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
return torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
|
||||
def output_proj(self, attn_output: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
attn_output = self._mla_unabsorb(attn_output, w_v)
|
||||
batch_size, total_tokens = attn_output.shape[:2]
|
||||
attn_output = attn_output.reshape(batch_size, total_tokens, -1)
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -241,7 +213,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
ke: torch.Tensor | None = None,
|
||||
cached_indices: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
|
||||
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
@@ -268,6 +240,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
position_embeddings_full=position_embeddings,
|
||||
)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out = torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
batch_size, total_tokens = out.shape[:2]
|
||||
out = out.reshape(batch_size, total_tokens, -1)
|
||||
cached_indices = indices if self.use_index_cache else None
|
||||
return self.output_proj(out, w_v), cached_indices
|
||||
return self.o_proj(out), cached_indices
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Re-export HF's GptOssConfig so the parameter naming and rope/sliding-window defaults
|
||||
# stay in sync with upstream. We don't need to subclass it: the only PrimeRL-specific
|
||||
# behavior lives in modeling_gpt_oss.py (custom MoE for LoRA detection).
|
||||
# behavior lives in the model and checkpoint conversion modules.
|
||||
from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
|
||||
__all__ = ["GptOssConfig"]
|
||||
|
||||
@@ -1,27 +1,58 @@
|
||||
"""State-dict conversion for GPT-OSS.
|
||||
|
||||
The custom prime-rl GPT-OSS implementation mirrors HuggingFace's parameter naming
|
||||
exactly (gate_up_proj/gate_up_proj_bias/down_proj/down_proj_bias plus router.weight
|
||||
and router.bias as nn.Parameters). So loading the unsloth BF16 checkpoint requires
|
||||
no key conversion - HF and prime formats are identical for this model.
|
||||
"""
|
||||
"""HF <-> PrimeRL weight conversion for GPT-OSS."""
|
||||
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename
|
||||
|
||||
|
||||
class GptOssExperts(ConvOp):
|
||||
def __init__(self, prefix: str) -> None:
|
||||
self.prefix = prefix
|
||||
|
||||
def hf_to_prime(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_up_name = f"{self.prefix}.gate_up_proj"
|
||||
gate_up = state_dict.pop(gate_up_name)
|
||||
gate_up_bias = state_dict.pop(f"{self.prefix}.gate_up_proj_bias")
|
||||
state_dict[f"{self.prefix}.gate_proj"] = gate_up[..., ::2].transpose(-2, -1)
|
||||
state_dict[f"{self.prefix}.up_proj"] = gate_up[..., 1::2].transpose(-2, -1)
|
||||
state_dict[f"{self.prefix}.gate_proj_bias"] = gate_up_bias[..., ::2]
|
||||
state_dict[f"{self.prefix}.up_proj_bias"] = gate_up_bias[..., 1::2]
|
||||
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
|
||||
|
||||
def prime_to_hf(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_name = f"{self.prefix}.gate_proj"
|
||||
gate = state_dict.pop(gate_name).transpose(-2, -1)
|
||||
up = state_dict.pop(f"{self.prefix}.up_proj").transpose(-2, -1)
|
||||
gate_bias = state_dict.pop(f"{self.prefix}.gate_proj_bias")
|
||||
up_bias = state_dict.pop(f"{self.prefix}.up_proj_bias")
|
||||
state_dict[f"{self.prefix}.gate_up_proj"] = gate.new_empty((*gate.shape[:-1], 2 * gate.shape[-1]))
|
||||
state_dict[f"{self.prefix}.gate_up_proj"][..., ::2] = gate
|
||||
state_dict[f"{self.prefix}.gate_up_proj"][..., 1::2] = up
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"] = gate_bias.new_empty(
|
||||
(*gate_bias.shape[:-1], 2 * gate_bias.shape[-1])
|
||||
)
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., ::2] = gate_bias
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., 1::2] = up_bias
|
||||
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict)
|
||||
|
||||
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
# Prime format equals HF format for GPT-OSS, so we never claim to be a separate
|
||||
# prime format - this disables the auto-conversion path in load_dcp_from_hf and
|
||||
# lets DCP load HF safetensors directly.
|
||||
return False
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
# HF and prime layouts coincide for GPT-OSS, so the conversion is the identity.
|
||||
return []
|
||||
operations: list[ConvOp] = []
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
prefix = f"model.layers.{layer_idx}.mlp"
|
||||
operations.extend(
|
||||
[
|
||||
Rename(f"{prefix}.router.weight", f"{prefix}.router.gate.weight"),
|
||||
Rename(f"{prefix}.router.bias", f"{prefix}.router.gate.bias"),
|
||||
GptOssExperts(f"{prefix}.experts"),
|
||||
]
|
||||
)
|
||||
return operations
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
# GPT-OSS model with PrimeRL custom MoE.
|
||||
#
|
||||
# This file mirrors HuggingFace's modeling_gpt_oss.py but swaps the experts module for
|
||||
# `GptOssGroupedExperts` so the LoRA detection logic in `prime_rl/trainer/lora.py` can
|
||||
# find and adapt the expert weights. Attention, rotary embedding, and RMSNorm are reused
|
||||
# from HF as-is - they correctly handle attention sinks and gpt-oss's split-rotate RoPE.
|
||||
# GPT-OSS model with PrimeRL grouped experts. Attention, rotary embedding, and
|
||||
# RMSNorm are reused from HuggingFace.
|
||||
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
@@ -31,101 +26,11 @@ from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts
|
||||
|
||||
|
||||
class GptOssTopKRouter(nn.Module):
|
||||
"""Token-choice top-k router matching HF's GptOssTopKRouter parameter naming.
|
||||
|
||||
Stores `weight` (num_experts, hidden_size) and `bias` (num_experts) as raw nn.Parameters
|
||||
so the unsloth BF16 checkpoint loads with no key conversion. Returns the same outputs as
|
||||
`TokenChoiceTopKRouter` so the surrounding MoE plumbing matches the rest of the repo.
|
||||
"""
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.hidden_size = config.hidden_size
|
||||
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
|
||||
self.bias = nn.Parameter(torch.empty(self.num_experts))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""x: (T, hidden). Returns (top_scores, top_indices, num_tokens_per_expert).
|
||||
|
||||
Matches HF's softmax-after-topk semantics: we softmax the top-k logits only,
|
||||
not the full distribution.
|
||||
"""
|
||||
logits = F.linear(x, self.weight, self.bias) # (T, num_experts)
|
||||
top_logits, top_indices = torch.topk(logits, self.top_k, dim=-1)
|
||||
top_scores = F.softmax(top_logits, dim=-1, dtype=top_logits.dtype)
|
||||
num_tokens_per_expert = torch.histc(
|
||||
top_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
)
|
||||
return top_scores, top_indices, num_tokens_per_expert
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
nn.init.trunc_normal_(self.weight, mean=0.0, std=init_std)
|
||||
nn.init.zeros_(self.bias)
|
||||
|
||||
|
||||
class GptOssMoE(nn.Module):
|
||||
"""GPT-OSS sparse MLP: top-k router + grouped experts with biases.
|
||||
|
||||
Wraps `GptOssGroupedExperts` (which expects pre-permuted tokens + num_tokens_per_expert)
|
||||
with the standard MoE permute/unpermute pipeline. Routing weights are applied AFTER
|
||||
the expert computation, matching HF's `routing_weights[token_idx, top_k_pos]` index_add.
|
||||
"""
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
|
||||
# current FP8 grouped-GEMM path doesn't model that yet.
|
||||
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.router = GptOssTopKRouter(config)
|
||||
self.experts = GptOssGroupedExperts(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
num_experts=self.num_experts,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
bs, slen, dim = hidden_states.shape
|
||||
x = hidden_states.reshape(-1, dim) # (T, dim)
|
||||
|
||||
top_scores, top_indices, num_tokens_per_expert = self.router(x)
|
||||
# top_scores, top_indices: (T, top_k)
|
||||
|
||||
# Sort tokens by expert. Each token contributes top_k entries (one per chosen expert).
|
||||
flat_expert_indices = top_indices.reshape(-1) # (T*top_k,)
|
||||
sorted_perm = torch.argsort(flat_expert_indices, stable=True) # (T*top_k,)
|
||||
# token id of each (token, k) entry, in expert-sorted order
|
||||
token_indices_experts_sorted = sorted_perm // self.top_k
|
||||
# routing weight for each (token, k) entry, in expert-sorted order
|
||||
top_scores_experts_sorted = top_scores.reshape(-1)[sorted_perm]
|
||||
|
||||
# Gather inputs for each expert in expert-sorted order
|
||||
gather_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
routed_input = torch.gather(x, dim=0, index=gather_indices) # (T*top_k, dim)
|
||||
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert) # (T*top_k, dim)
|
||||
|
||||
# Apply routing weights post-experts (HF: weighted_output = out * routing_weights)
|
||||
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
|
||||
|
||||
# Scatter-add back to original token positions
|
||||
out = torch.zeros_like(x)
|
||||
scatter_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
out = out.scatter_add(dim=0, index=scatter_indices, src=routed_output)
|
||||
|
||||
out = out.reshape(bs, slen, dim)
|
||||
return out, top_scores # router_scores returned only for compatibility; trainer ignores
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
|
||||
|
||||
class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
@@ -133,7 +38,30 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
|
||||
self.mlp = GptOssMoE(config)
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.num_local_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="topk_softmax",
|
||||
route_norm=False,
|
||||
route_scale=1.0,
|
||||
gate_bias=True,
|
||||
)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
num_experts=config.num_local_experts,
|
||||
expert_type="gated",
|
||||
activation="clamped_swiglu",
|
||||
bias=True,
|
||||
)
|
||||
self.mlp = MoE(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=None,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=None,
|
||||
)
|
||||
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
@@ -162,7 +90,7 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states, _ = self.mlp(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
@@ -276,11 +276,21 @@ def bwd(
|
||||
return sparse_mla_bwd_kernel
|
||||
|
||||
|
||||
def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
|
||||
@torch.library.custom_op("prime_rl::sparse_mla_backward", mutates_args=())
|
||||
def sparse_mla_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous()
|
||||
assert kv.is_contiguous()
|
||||
assert indices.is_contiguous()
|
||||
assert lse.is_contiguous()
|
||||
grad_out = grad_out.contiguous()
|
||||
B, S, H, dim_plus_tail_dim = q.shape
|
||||
_, S_kv, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim_plus_tail_dim
|
||||
@@ -295,9 +305,22 @@ def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
|
||||
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
|
||||
postprocess_kernel = postprocess(D, D_tail, kv_group)
|
||||
|
||||
delta = preprocess_kernel(o, do)
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, do, indices, lse, delta, dkv)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv
|
||||
|
||||
|
||||
@sparse_mla_backward.register_fake
|
||||
def _sparse_mla_backward_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(kv)
|
||||
|
||||
@@ -14,8 +14,11 @@ except Exception:
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_backward
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2, -1],
|
||||
@@ -183,7 +186,17 @@ def sparse_mla_fwd(
|
||||
return main
|
||||
|
||||
|
||||
def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64, num_stages=2, threads=256):
|
||||
@torch.library.custom_op("prime_rl::sparse_mla", mutates_args=())
|
||||
def sparse_mla(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
d_v: int = 512,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
|
||||
batch, seq_len, heads, dim_plus_tail_dim = q.shape
|
||||
_, seq_len_kv, kv_group, _ = kv.shape
|
||||
@@ -210,3 +223,42 @@ def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices)
|
||||
return out, lse
|
||||
|
||||
|
||||
@sparse_mla.register_fake
|
||||
def _sparse_mla_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
d_v: int = 512,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return q.new_empty((*q.shape[:-1], d_v)), q.new_empty(q.shape[:-1], dtype=torch.float32)
|
||||
|
||||
|
||||
def _sparse_mla_setup_context(ctx, inputs, output) -> None:
|
||||
q, kv, indices, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
ctx.mark_non_differentiable(lse)
|
||||
|
||||
|
||||
def _sparse_mla_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_backward(
|
||||
q.detach(),
|
||||
kv.detach(),
|
||||
out.detach(),
|
||||
grad_out,
|
||||
indices,
|
||||
lse.detach(),
|
||||
ctx.sm_scale,
|
||||
)
|
||||
return dq, dkv, None, None, None, None, None, None
|
||||
|
||||
|
||||
sparse_mla.register_autograd(_sparse_mla_autograd_backward, setup_context=_sparse_mla_setup_context)
|
||||
|
||||
@@ -21,12 +21,13 @@ class LagunaConfig(PretrainedConfig):
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
"layers.*.shared_expert.w1": "colwise",
|
||||
"layers.*.shared_expert.w2": "rowwise",
|
||||
"layers.*.shared_expert.w3": "colwise",
|
||||
"layers.*.mlp.shared_expert.gate_proj": "colwise",
|
||||
"layers.*.mlp.shared_expert.up_proj": "colwise",
|
||||
"layers.*.mlp.shared_expert.down_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
@@ -72,7 +73,6 @@ class LagunaConfig(PretrainedConfig):
|
||||
moe_apply_router_weight_on_input: bool = False,
|
||||
moe_router_logit_softcapping: float = 0.0,
|
||||
load_balance_coeff: float | None = 1e-3,
|
||||
use_grouped_mm: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
|
||||
@@ -107,7 +107,6 @@ class LagunaConfig(PretrainedConfig):
|
||||
self.moe_apply_router_weight_on_input = moe_apply_router_weight_on_input
|
||||
self.moe_router_logit_softcapping = moe_router_logit_softcapping
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user