Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3587b285f5 | ||
|
|
f3827c4ed2 | ||
|
|
93a0fe0d6b | ||
|
|
db2c00e9ed | ||
|
|
4250d895bc | ||
|
|
78bc69ccc4 | ||
|
|
81052082a9 | ||
|
|
b9c0bfe87b | ||
|
|
51879014fc | ||
|
|
52e985ae9d | ||
|
|
63b3e85864 | ||
|
|
7133f8f8f2 | ||
|
|
b029ef253e | ||
|
|
eae8bd9462 | ||
|
|
c8af127357 | ||
|
|
2b688edcf6 | ||
|
|
883b8f32c5 | ||
|
|
407e8ba223 | ||
|
|
cf9962c13b | ||
|
|
34e26e39a5 | ||
|
|
8acaaf2baa | ||
|
|
f42630873d | ||
|
|
1eeea3a047 |
+2
-1
@@ -1,4 +1,5 @@
|
||||
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
|
||||
.git
|
||||
**/.git
|
||||
outputs
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
@@ -172,7 +172,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
ref: ${{ needs.prepare.outputs.full_sha }}
|
||||
fetch-depth: 0
|
||||
submodules: false
|
||||
|
||||
@@ -193,21 +193,55 @@ jobs:
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "0.11.9"
|
||||
enable-cache: false
|
||||
|
||||
- name: Resolve dependency image and package versions
|
||||
id: dependency
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
|
||||
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
|
||||
echo "image=${image}" >> "$GITHUB_OUTPUT"
|
||||
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
|
||||
bash scripts/docker-editable-pretend-versions.sh --github-output . >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build and push dependencies
|
||||
id: dependencies
|
||||
if: steps.dependency.outputs.digest == ''
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
target: dependencies
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: ${{ steps.dependency.outputs.image }}
|
||||
|
||||
- name: Build and push
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.cuda
|
||||
# zstd compresses the multi-GB venv layers several times faster than gzip at a
|
||||
# comparable ratio. No `force-compression`, so base-image layers are reused as-is
|
||||
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
|
||||
# or Docker >= 23.
|
||||
target: runtime
|
||||
build-args: |
|
||||
DEPENDENCY_IMAGE=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
VERIFIERS_PRETEND_VERSION=${{ steps.dependency.outputs.verifiers }}
|
||||
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
|
||||
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
# The per-job builder is ephemeral; mode=max caches builder-stage
|
||||
# layers so warm builds skip the dependency sync.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
@@ -223,6 +257,8 @@ jobs:
|
||||
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
|
||||
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
|
||||
DEPENDENCY_IMAGE: ${{ steps.dependency.outputs.image }}
|
||||
DEPENDENCY_DIGEST: ${{ steps.dependencies.outputs.digest || steps.dependency.outputs.digest }}
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
SUFFIX: ${{ matrix.suffix }}
|
||||
run: |
|
||||
@@ -236,6 +272,7 @@ jobs:
|
||||
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
|
||||
echo "| **Commit** | \`${IMAGE_SHA}\` |"
|
||||
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
|
||||
echo "| **Dependencies** | \`${DEPENDENCY_IMAGE}@${DEPENDENCY_DIGEST}\` |"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
manifest:
|
||||
|
||||
@@ -75,7 +75,7 @@ jobs:
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import validate_shared_ckpt_config
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
|
||||
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
|
||||
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
|
||||
|
||||
@@ -13,7 +13,7 @@ concurrency:
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
runs-on: vm
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
@@ -61,34 +61,34 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
runner: prime-rl-2xh200
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
|
||||
+55
-78
@@ -1,21 +1,27 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# ^ `COPY --exclude` (used to split the venv into parallel-compressible layers) needs
|
||||
# Dockerfile syntax >= 1.19; `docker/dockerfile:1` resolves to the latest stable 1.x.
|
||||
|
||||
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
|
||||
ARG DEPENDENCY_IMAGE=dependencies
|
||||
|
||||
FROM ghcr.io/astral-sh/uv:0.11.9@sha256:6b6fa841d71a48fbc9e2c55651c5ad570e01104d7a7d701f57b2b22c0f58e9b1 AS uv
|
||||
|
||||
FROM ubuntu:24.04@sha256:a853f94d226358a79c740cfc7bce0c289748f3fe3488d921d038ccd752c61b60 AS python-builder
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates python3.12 python3.12-venv \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV UV_PYTHON_PREFERENCE=only-system UV_LINK_MODE=copy
|
||||
|
||||
# Every pyproject.toml + uv.lock, so the dependency sync below caches
|
||||
# independently of source edits.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
|
||||
# .git is ~735 MB, changes every commit, and would land in the registry cache.
|
||||
COPY --exclude=.git . /ctx
|
||||
FROM python-builder AS manifests
|
||||
COPY . /ctx
|
||||
RUN mkdir -p /manifests \
|
||||
&& cd /ctx \
|
||||
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
|
||||
&& cp uv.lock /manifests/
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04@sha256:8b2705ea7a8653ad3451b46ab835eced92d77b44e671b9cf3ad4f95fbb2efe5e AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -72,18 +78,12 @@ RUN git clone --depth 1 --branch v${UCX_VERSION} https://github.com/openucx/ucx.
|
||||
&& make install \
|
||||
&& rm -rf /tmp/ucx
|
||||
|
||||
# Download the latest installer
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies
|
||||
@@ -91,51 +91,11 @@ WORKDIR /app
|
||||
|
||||
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
|
||||
# Third-party deps only — source edits don't bust this layer. First-party
|
||||
# editables install in the source-layer sync below. No build-context bind
|
||||
# mount here: .git would bust the cache every commit.
|
||||
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
|
||||
# The runtime dependency image contains no first-party source or editable installs.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
--no-install-package renderers \
|
||||
--no-install-package prime-pydantic-config
|
||||
|
||||
COPY pyproject.toml /app/pyproject.toml
|
||||
COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY k8s /app/k8s
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
|
||||
# Use submodule git metadata from the build context when present. Docker copies
|
||||
# only the submodule .git pointer files into /app/deps, so we temporarily link
|
||||
# /app/.git/modules to the read-only context before resolving versions.
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
--mount=type=bind,source=.,target=/build-context,readonly \
|
||||
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
|
||||
&& \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& \
|
||||
if [ -L /app/.git/modules ]; then rm /app/.git/modules && rmdir /app/.git 2>/dev/null || true; fi \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" /app/deps/verifiers/pyproject.toml \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
--no-install-local
|
||||
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
@@ -185,7 +145,7 @@ RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04@sha256:f8ef28f579ea42a44b415d2c5d46f788e6a9b395c6c83f2929416e1fc192c143 AS dependencies
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -263,19 +223,12 @@ RUN userdel -r ubuntu 2>/dev/null || true; \
|
||||
echo "appuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
|
||||
|
||||
# Install uv for development use
|
||||
ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
COPY --from=uv /uv /uvx /usr/local/bin/
|
||||
|
||||
USER appuser
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
WORKDIR /app
|
||||
# Copy the application from the builder, splitting the venv's largest trees into their
|
||||
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
|
||||
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
|
||||
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
|
||||
# per-tree copies above, or the data lands in the image twice.
|
||||
# The volatile /app remainder goes last so a source edit re-pushes one layer,
|
||||
# not all of them.
|
||||
# Split the largest dependency trees so compression and pulls can run in parallel.
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
|
||||
@@ -283,17 +236,17 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=.venv/lib/python3.12/site-packages/nvidia \
|
||||
--exclude=.venv/lib/python3.12/site-packages/torch \
|
||||
--exclude=.venv/lib/python3.12/site-packages/vllm \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app /app
|
||||
--exclude=lib/python3.12/site-packages/nvidia \
|
||||
--exclude=lib/python3.12/site-packages/torch \
|
||||
--exclude=lib/python3.12/site-packages/vllm \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app/.venv /app/.venv
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
|
||||
&& if [ "$(uname -m)" = "x86_64" ]; then \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
|
||||
fi
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
@@ -304,6 +257,30 @@ ENV LD_LIBRARY_PATH="/opt/ucx/lib:/opt/ucx/lib/ucx${LD_LIBRARY_PATH:+:${LD_LIBRA
|
||||
ENV HF_HUB_ETAG_TIMEOUT=500
|
||||
ENV HF_HUB_DOWNLOAD_TIMEOUT=300
|
||||
|
||||
# Use entrypoint for setup (ulimit, etc) but default to sleep infinity for K8s
|
||||
FROM python-builder AS application-builder
|
||||
WORKDIR /app
|
||||
COPY pyproject.toml uv.lock README.md /app/
|
||||
COPY src /app/src
|
||||
COPY packages /app/packages
|
||||
COPY deps /app/deps
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
|
||||
COPY scripts/docker_application.py /build/docker_application.py
|
||||
ARG VERIFIERS_PRETEND_VERSION
|
||||
ARG RENDERERS_PRETEND_VERSION
|
||||
ARG PYDANTIC_CONFIG_PRETEND_VERSION
|
||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
eval "$(bash /app/scripts/docker-editable-pretend-versions.sh --shell /app)" \
|
||||
&& uv run --no-project --python /usr/bin/python3.12 /build/docker_application.py /app /out/app
|
||||
|
||||
# COPY --link and numeric ownership let source builds reuse dependency blobs without unpacking them.
|
||||
FROM ${DEPENDENCY_IMAGE} AS runtime
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
COPY --link --from=application-builder --chown=${USER_ID}:${GROUP_ID} /out/app /app
|
||||
# Preserve the executable Git mode; --chmod disables BuildKit's linked-copy optimization.
|
||||
COPY --link --chown=${USER_ID}:${GROUP_ID} scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
@@ -35,7 +35,7 @@ prime-rl is a framework for large-scale reinforcement learning. It is designed t
|
||||
2. Performant: built to train 1T+ MoE models on 1000+ GPUs with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) for training and [vLLM](https://github.com/vllm-project/vllm) for inference, with FP8 inference, PD disaggregation, EP and CP parallelism, and more.
|
||||
3. Native integration with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments through the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars), including built-in support for SWE and agentic environments.
|
||||
4. End-to-end post-training: SFT, RL training, and evals.
|
||||
5. Multi-node deployment with Slurm and Kubernetes support.
|
||||
5. Multi-node deployment with Slurm support.
|
||||
6. Multimodal support for VLMs such as Qwen3.5.
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/advanced/glm-5.3/).
|
||||
@@ -181,7 +181,7 @@ Follow this guide to learn the basics of prime-rl. You can train your own models
|
||||
### Advanced Training: 32 - 2048 GPUs:
|
||||
|
||||
Follow this guide to train large models on hard reasoning and agentic tasks.
|
||||
These guides are designed to be run from a Slurm cluster but can also be adapted to k8s deployments.
|
||||
These guides are designed to be run from a Slurm cluster.
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
|
||||
@@ -9,8 +9,8 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:True"
|
||||
[slurm]
|
||||
job_name = "nemotron-3-super-swe"
|
||||
partition = "prod"
|
||||
# Nemotron-H needs the mamba-ssm kernels; sync that group, then clear this run's orphaned sandboxes.
|
||||
pre_run_command = 'uv sync --all-extras --all-packages --group mamba-ssm ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
|
||||
# Sync the env (the gpu extra brings Nemotron-H's mamba-ssm kernels), then clear this run's orphaned sandboxes.
|
||||
pre_run_command = 'uv sync --all-extras --all-packages ; timeout 120 prime sandbox delete --label "nemotron-3-super-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 4fd5921071...7ba657f2a4
+1
-1
@@ -187,7 +187,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
+2
-2
@@ -157,9 +157,9 @@ Algorithms operate on native verifier artifacts and annotate their message graph
|
||||
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
|
||||
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
|
||||
|
||||
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
The pipeline calls `score_group` directly and `score_episode` through `finalize_episode`, which skips episodes with no trainable sampled tokens. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
|
||||
|
||||
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
|
||||
The algorithm config states which loss component its action tokens feed (`action_loss_type`, a class variable on each config class). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy clients (`self.clients`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). Writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.train.algo.advantage`.
|
||||
|
||||
## Async / Off-Policy Training
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
|
||||
+2
-2
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -313,6 +313,6 @@ top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
+2
-2
@@ -94,7 +94,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput.
|
||||
|
||||
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
|
||||
`ep` defaults to `"auto"`. At startup it loads the model config to check whether the model is MoE. For MoE models it resolves to `min(world_size // dp_replicate, 8)`: the FSDP island size, capped at 8. For non-MoE models it resolves to 1 (no-op). `"auto"` does not look at `num_experts` or `cp`; the resolved degree must still be a multiple of `cp` and divide `num_experts`, so set it explicitly when it does not. Set `ep` to an explicit integer to override:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
@@ -241,7 +241,7 @@ Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transf
|
||||
|
||||
```bash
|
||||
bash scripts/install_nixl_from_source.sh
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
|
||||
bash scripts/install_modelexpress.sh
|
||||
```
|
||||
|
||||
|
||||
+2
-1
@@ -37,7 +37,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. on their own host) and the launcher expects the server to already run there. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `orchestrator.train.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
|
||||
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
|
||||
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
|
||||
|
||||
@@ -113,5 +113,17 @@ This will start a SFT run with the following configuration:
|
||||
|
||||
- The model is `zai-org/GLM-5.3-BF16`
|
||||
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
|
||||
- 8 nodes at 131k context: CP 8, EP 8, full activation checkpointing with activation offloading, optimizer state offloaded to CPU
|
||||
- DSA attention runs on the FlashMLA sparse forward and the cuDNN sparse backward (`model.dsa_backend = "cudnn_flashmla"`)
|
||||
|
||||
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
|
||||
|
||||
### 12 nodes at 16k
|
||||
|
||||
For 16k-token samples, append [`16k-12-node.toml`](sft/h200/16k-12-node.toml) after the data overlay:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml @ examples/advanced/glm-5.3/sft/h200/16k-12-node.toml
|
||||
```
|
||||
|
||||
On 12 nodes the sharded model state fits in GPU memory without CP or any offloading. Each GPU runs one 16k sequence per step (batch 96), and transformer blocks compile with `fullgraph = true`. Full activation checkpointing stays on; peak memory is about 115 GiB per GPU.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# 12-node, 16k-token overlay: enough GPUs that the model state fits without CP or offloading,
|
||||
# so each GPU runs one 16k sequence per micro-batch and blocks compile with fullgraph.
|
||||
# Compose after the data overlay, e.g. base.toml @ math-10k.toml @ 16k-12-node.toml.
|
||||
|
||||
[model]
|
||||
cp = 1
|
||||
optim_cpu_offload = false
|
||||
ac_offloading = "None"
|
||||
|
||||
[model.compile]
|
||||
fullgraph = true
|
||||
|
||||
[data]
|
||||
seq_len = 16384
|
||||
batch_size = 96
|
||||
micro_batch_size = 1
|
||||
|
||||
[deployment]
|
||||
num_train_nodes = 12
|
||||
@@ -10,6 +10,7 @@ attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
@@ -98,123 +98,3 @@ uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B
|
||||
```
|
||||
|
||||
Way better! Now we get an **average reward of ~0.8**.
|
||||
|
||||
## Kubernetes Deployment
|
||||
|
||||
If you're running on Kubernetes, you can deploy this example using the provided Helm chart. The Helm chart automatically configures all components with proper networking and shared storage.
|
||||
|
||||
### Step 1: Deploy for SFT Training
|
||||
|
||||
The reverse-text example is configured with `autoStart: true` for RL training, but we need to run SFT first. Deploy with autoStart disabled:
|
||||
|
||||
```bash
|
||||
cd k8s
|
||||
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml \
|
||||
--set orchestrator.autoStart=false \
|
||||
--set inference.autoStart=false \
|
||||
--set trainer.autoStart=false
|
||||
|
||||
# Check pods are ready
|
||||
kubectl get pods -l app=prime-rl,example=reverse-text
|
||||
# All pods should show 1/1 Running
|
||||
```
|
||||
|
||||
### Step 2: Run SFT Training
|
||||
|
||||
Exec into the trainer pod and run SFT:
|
||||
|
||||
```bash
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
|
||||
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
|
||||
```
|
||||
|
||||
### Step 3: Deploy RL Training
|
||||
|
||||
Now upgrade the deployment to enable autoStart (uses the default `autoStart: true` from reverse-text.yaml):
|
||||
|
||||
```bash
|
||||
# Exit the pod first (Ctrl+D)
|
||||
cd k8s
|
||||
helm upgrade my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# Check pods have restarted
|
||||
kubectl get pods -l app=prime-rl,example=reverse-text
|
||||
```
|
||||
|
||||
The RL components will automatically start. Monitor the logs:
|
||||
|
||||
```bash
|
||||
# View inference server logs
|
||||
kubectl logs -f my-exp-inference-0
|
||||
|
||||
# View orchestrator logs
|
||||
kubectl logs -f my-exp-orchestrator-0
|
||||
|
||||
# View trainer logs
|
||||
kubectl logs -f my-exp-trainer-0
|
||||
```
|
||||
|
||||
### Alternative: Manual RL Training
|
||||
|
||||
If you prefer to run RL components manually, keep `autoStart: false` and exec into each pod:
|
||||
|
||||
```bash
|
||||
# Terminal 1 - Inference
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml
|
||||
|
||||
# Terminal 2 - Orchestrator
|
||||
kubectl exec -it my-exp-orchestrator-0 -- bash
|
||||
uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url '["'$INFERENCE_URL'"]'
|
||||
|
||||
# Terminal 3 - Trainer
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs
|
||||
```
|
||||
|
||||
### Access Outputs and Checkpoints
|
||||
|
||||
All outputs are written to `/data/outputs` on the shared NFS storage:
|
||||
|
||||
```bash
|
||||
# Exec into any pod to access outputs
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
ls -lh /data/outputs/weights/
|
||||
ls -lh /data/outputs/rollouts/
|
||||
```
|
||||
|
||||
### Step 4: Run Evaluation
|
||||
|
||||
To evaluate the trained RL model:
|
||||
|
||||
```bash
|
||||
# Exec into trainer pod
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
|
||||
# If inference server isn't running with the RL model, start it in another terminal:
|
||||
kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL
|
||||
```
|
||||
|
||||
### Clean Up
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
|
||||
kubectl delete pvc my-exp-shared-data
|
||||
```
|
||||
|
||||
**What the Helm chart provides:**
|
||||
- Predictably named pods: `<release-name>-trainer-0`, `<release-name>-inference-0`, `<release-name>-orchestrator-0`
|
||||
- Shared NFS storage at `/data` for model checkpoints and outputs
|
||||
- GPU resources (1 GPU per inference/trainer pod)
|
||||
- Kubernetes services for component communication
|
||||
- Auto-start capability with proper networking configured
|
||||
|
||||
See the [K8s deployment guide](../../../k8s/README.md) for more details on scaling, distributed training, and advanced configurations.
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
# Kubernetes Deployment with Helm
|
||||
|
||||
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Deploy with the reverse-text example
|
||||
helm install my-exp ./prime-rl -f ./prime-rl/examples/reverse-text.yaml
|
||||
|
||||
# Verify deployment
|
||||
kubectl get pods -l app.kubernetes.io/instance=my-exp
|
||||
|
||||
# Exec into trainer and run training
|
||||
kubectl exec -it my-exp-trainer-0 -- bash
|
||||
cd /data && uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Kubernetes cluster with GPU nodes
|
||||
- [NVIDIA GPU Operator](https://docs.nvidia.com/datacenter/cloud-native/gpu-operator/getting-started.html) installed
|
||||
- [Helm 3.x](https://helm.sh/docs/intro/install/) installed
|
||||
- Storage class that supports `ReadWriteMany` (e.g., NFS, CephFS)
|
||||
|
||||
## Chart Structure
|
||||
|
||||
```
|
||||
prime-rl/
|
||||
├── Chart.yaml
|
||||
├── values.yaml # Default configuration
|
||||
├── examples/
|
||||
│ ├── reverse-text.yaml # Example values for reverse-text
|
||||
│ └── reverse-text/ # Split orchestrator/inference/trainer configs the example runs
|
||||
└── templates/
|
||||
├── deployment.yaml # StatefulSets for orchestrator, inference, trainer
|
||||
├── service.yaml # Headless services for pod discovery
|
||||
└── pvc.yaml # Shared storage
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
See [values.yaml](./prime-rl/values.yaml) for all available options. Common overrides:
|
||||
|
||||
```bash
|
||||
# Custom GPU allocation
|
||||
helm install my-exp ./prime-rl \
|
||||
--set inference.gpu.count=4 \
|
||||
--set trainer.gpu.count=2
|
||||
|
||||
# With secrets for W&B/HF
|
||||
kubectl create secret generic prime-rl-secrets \
|
||||
--from-literal=wandb-api-key=YOUR_KEY \
|
||||
--from-literal=hf-token=YOUR_TOKEN
|
||||
|
||||
helm install my-exp ./prime-rl \
|
||||
--set config.secrets.enabled=true \
|
||||
--set config.secrets.name=prime-rl-secrets
|
||||
```
|
||||
|
||||
## Uninstalling
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
|
||||
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
|
||||
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
|
||||
```
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
|
||||
@@ -1,16 +0,0 @@
|
||||
apiVersion: v2
|
||||
name: prime-rl
|
||||
description: A Helm chart for deploying PRIME-RL training infrastructure on Kubernetes
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "main"
|
||||
keywords:
|
||||
- machine-learning
|
||||
- reinforcement-learning
|
||||
- training
|
||||
- gpu
|
||||
maintainers:
|
||||
- name: Prime Intellect
|
||||
url: https://github.com/PrimeIntellect-ai/prime-rl
|
||||
sources:
|
||||
- https://github.com/PrimeIntellect-ai/prime-rl
|
||||
@@ -1,44 +0,0 @@
|
||||
# Values for reverse_text example
|
||||
# Small model (Qwen3-0.6B) - runs on single consumer GPU
|
||||
|
||||
config:
|
||||
example: "reverse-text"
|
||||
|
||||
image:
|
||||
tag: "main"
|
||||
|
||||
# Orchestrator - no GPU needed
|
||||
orchestrator:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL ; sleep infinity"
|
||||
resources:
|
||||
requests:
|
||||
memory: "1Gi"
|
||||
cpu: "500m"
|
||||
|
||||
# Inference - 1 GPU
|
||||
inference:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml ; sleep infinity"
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
# Trainer - 1 GPU
|
||||
trainer:
|
||||
enabled: true
|
||||
autoStart: true
|
||||
command: "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs ; sleep infinity"
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
@@ -1,2 +0,0 @@
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -1,27 +0,0 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
batch_size = 128
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[train]
|
||||
group_size = 16
|
||||
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
@@ -1,14 +0,0 @@
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
seq_len = 2048
|
||||
|
||||
[monitors.wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
@@ -1,59 +0,0 @@
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "prime-rl.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
*/}}
|
||||
{{- define "prime-rl.fullname" -}}
|
||||
{{- if .Values.fullnameOverride }}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- $name := default .Chart.Name .Values.nameOverride }}
|
||||
{{- if contains $name .Release.Name }}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
|
||||
{{- else }}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create chart name and version as used by the chart label.
|
||||
*/}}
|
||||
{{- define "prime-rl.chart" -}}
|
||||
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Common labels
|
||||
*/}}
|
||||
{{- define "prime-rl.labels" -}}
|
||||
helm.sh/chart: {{ include "prime-rl.chart" . }}
|
||||
{{ include "prime-rl.selectorLabels" . }}
|
||||
{{- if .Chart.AppVersion }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
{{- end }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Selector labels
|
||||
*/}}
|
||||
{{- define "prime-rl.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ include "prime-rl.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Component labels
|
||||
*/}}
|
||||
{{- define "prime-rl.componentLabels" -}}
|
||||
app: prime-rl
|
||||
{{- if .Values.config.example }}
|
||||
example: {{ .Values.config.example }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -1,378 +0,0 @@
|
||||
{{- if .Values.orchestrator.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-orchestrator-headless
|
||||
replicas: {{ .Values.orchestrator.replicas }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: orchestrator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
{{- with .Values.orchestrator.nodeSelector }}
|
||||
nodeSelector:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-orchestrator
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.orchestrator.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.orchestrator.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.orchestrator.service.port }}
|
||||
name: api
|
||||
- containerPort: {{ .Values.orchestrator.service.ncclPort }}
|
||||
name: nccl
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "orchestrator"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.orchestrator.replicas }}"
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
{{- $replicas := int .Values.inference.replicas }}
|
||||
{{- $urls := list }}
|
||||
{{- range $i := until $replicas }}
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.orchestrator.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.orchestrator.resources | nindent 10 }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-inference-headless
|
||||
replicas: {{ .Values.inference.replicas }}
|
||||
podManagementPolicy: Parallel
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: inference
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: inference
|
||||
spec:
|
||||
{{- if .Values.inference.runtimeClassName }}
|
||||
runtimeClassName: {{ .Values.inference.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-inference
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.inference.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.inference.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.inference.service.port }}
|
||||
name: api
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "inference"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.inference.replicas }}"
|
||||
{{- with .Values.inference.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
{{- if .Values.inference.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
|
||||
{{- end }}
|
||||
memory: {{ .Values.inference.resources.requests.memory }}
|
||||
cpu: {{ .Values.inference.resources.requests.cpu }}
|
||||
limits:
|
||||
{{- if .Values.inference.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.inference.gpu.count }}
|
||||
{{- end }}
|
||||
{{- if .Values.inference.resources.limits }}
|
||||
memory: {{ .Values.inference.resources.limits.memory }}
|
||||
cpu: {{ .Values.inference.resources.limits.cpu }}
|
||||
{{- end }}
|
||||
{{- if and .Values.inference.probes .Values.inference.probes.enabled }}
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.startup.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.startup.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /liveness
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.liveness.timeoutSeconds }}
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.readiness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.readiness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.inference.probes.readiness.timeoutSeconds }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
serviceName: {{ .Release.Name }}-trainer-headless
|
||||
replicas: {{ .Values.trainer.replicas }}
|
||||
podManagementPolicy: Parallel
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 6 }}
|
||||
role: trainer
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "prime-rl.selectorLabels" . | nindent 8 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 8 }}
|
||||
role: trainer
|
||||
spec:
|
||||
{{- if .Values.trainer.runtimeClassName }}
|
||||
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl-trainer
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.trainer.autoStart }}
|
||||
command: ["/bin/bash", "-c"]
|
||||
args:
|
||||
- {{ .Values.trainer.command }}
|
||||
{{- else }}
|
||||
command: ["sleep", "infinity"]
|
||||
{{- end }}
|
||||
ports:
|
||||
- containerPort: {{ .Values.trainer.service.port }}
|
||||
name: api
|
||||
- containerPort: {{ .Values.trainer.service.ncclPort }}
|
||||
name: nccl
|
||||
env:
|
||||
- name: POD_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: ROLE
|
||||
value: "trainer"
|
||||
- name: POD_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: STATEFUL_REPLICAS
|
||||
value: "{{ .Values.trainer.replicas }}"
|
||||
{{- if .Values.trainer.pytorchCudaAllocConf }}
|
||||
- name: PYTORCH_CUDA_ALLOC_CONF
|
||||
value: {{ .Values.trainer.pytorchCudaAllocConf | quote }}
|
||||
{{- end }}
|
||||
{{- $releaseName := .Release.Name }}
|
||||
{{- $namespace := .Values.namespace }}
|
||||
{{- $port := int .Values.inference.service.port }}
|
||||
{{- $replicas := int .Values.inference.replicas }}
|
||||
{{- $urls := list }}
|
||||
{{- range $i := until $replicas }}
|
||||
{{- $url := printf "http://%s-inference-%d.%s-inference-headless.%s.svc.cluster.local:%d/v1" $releaseName $i $releaseName $namespace $port }}
|
||||
{{- $urls = append $urls $url }}
|
||||
{{- end }}
|
||||
- name: INFERENCE_URL
|
||||
value: {{ first $urls | quote }}
|
||||
- name: ADMIN_INFERENCE_URLS
|
||||
value: {{ $urls | join "," | quote }}
|
||||
{{- with .Values.trainer.env }}
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
{{- if .Values.config.secrets.enabled }}
|
||||
- name: WANDB_API_KEY
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: wandb-api-key
|
||||
optional: true
|
||||
- name: HF_TOKEN
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.config.secrets.name }}
|
||||
key: hf-token
|
||||
optional: true
|
||||
{{- end }}
|
||||
resources:
|
||||
requests:
|
||||
{{- if .Values.trainer.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
|
||||
{{- end }}
|
||||
memory: {{ .Values.trainer.resources.requests.memory }}
|
||||
cpu: {{ .Values.trainer.resources.requests.cpu }}
|
||||
limits:
|
||||
{{- if .Values.trainer.gpu.enabled }}
|
||||
nvidia.com/gpu: {{ .Values.trainer.gpu.count }}
|
||||
{{- end }}
|
||||
{{- if .Values.trainer.resources.limits }}
|
||||
memory: {{ .Values.trainer.resources.limits.memory }}
|
||||
cpu: {{ .Values.trainer.resources.limits.cpu }}
|
||||
{{- end }}
|
||||
{{- if and .Values.trainer.probes .Values.trainer.probes.enabled }}
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.startup.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.startup.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.liveness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.liveness.timeoutSeconds }}
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: {{ .Values.trainer.service.port }}
|
||||
periodSeconds: {{ .Values.trainer.probes.readiness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.trainer.probes.readiness.failureThreshold }}
|
||||
timeoutSeconds: {{ .Values.trainer.probes.readiness.timeoutSeconds }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumeMounts:
|
||||
- name: shared-data
|
||||
mountPath: {{ .Values.storage.mountPath }}
|
||||
{{- end }}
|
||||
{{- if .Values.storage.enabled }}
|
||||
volumes:
|
||||
- name: shared-data
|
||||
persistentVolumeClaim:
|
||||
claimName: {{ .Release.Name }}-shared-data
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -1,16 +0,0 @@
|
||||
{{- if .Values.storage.enabled }}
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-shared-data
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
spec:
|
||||
accessModes:
|
||||
{{- toYaml .Values.storage.accessModes | nindent 4 }}
|
||||
storageClassName: {{ .Values.storage.storageClassName }}
|
||||
resources:
|
||||
requests:
|
||||
storage: {{ .Values.storage.size }}
|
||||
{{- end }}
|
||||
@@ -1,141 +0,0 @@
|
||||
{{- if .Values.orchestrator.enabled }}
|
||||
{{- if .Values.orchestrator.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
type: {{ .Values.orchestrator.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
ports:
|
||||
- port: {{ .Values.orchestrator.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
- port: {{ .Values.orchestrator.service.ncclPort }}
|
||||
targetPort: nccl
|
||||
protocol: TCP
|
||||
name: nccl
|
||||
{{- end }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-orchestrator-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: orchestrator
|
||||
ports:
|
||||
- port: {{ .Values.orchestrator.service.port }}
|
||||
name: api
|
||||
- port: {{ .Values.orchestrator.service.ncclPort }}
|
||||
name: nccl
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
{{- if .Values.inference.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
type: {{ .Values.inference.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
ports:
|
||||
- port: {{ .Values.inference.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
{{- if .Values.trainer.service.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
type: {{ .Values.trainer.service.type }}
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
ports:
|
||||
- port: {{ .Values.trainer.service.port }}
|
||||
targetPort: api
|
||||
protocol: TCP
|
||||
name: api
|
||||
- port: {{ .Values.trainer.service.ncclPort }}
|
||||
targetPort: nccl
|
||||
protocol: TCP
|
||||
name: nccl
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.inference.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-inference-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: inference
|
||||
ports:
|
||||
- port: {{ .Values.inference.service.port }}
|
||||
name: api
|
||||
{{- end }}
|
||||
---
|
||||
{{- if .Values.trainer.enabled }}
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ .Release.Name }}-trainer-headless
|
||||
namespace: {{ .Values.namespace }}
|
||||
labels:
|
||||
{{- include "prime-rl.labels" . | nindent 4 }}
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
spec:
|
||||
clusterIP: None # Headless service for StatefulSet
|
||||
selector:
|
||||
{{- include "prime-rl.componentLabels" . | nindent 4 }}
|
||||
role: trainer
|
||||
ports:
|
||||
- port: {{ .Values.trainer.service.port }}
|
||||
name: api
|
||||
- port: {{ .Values.trainer.service.ncclPort }}
|
||||
name: nccl
|
||||
{{- end }}
|
||||
@@ -1,156 +0,0 @@
|
||||
# Default values for prime-rl
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
# Global settings
|
||||
namespace: default
|
||||
|
||||
# Docker image configuration
|
||||
image:
|
||||
repository: primeintellect/prime-rl
|
||||
pullPolicy: IfNotPresent
|
||||
tag: "main"
|
||||
|
||||
# Shared storage configuration
|
||||
storage:
|
||||
enabled: true
|
||||
# PVC name will be automatically set to {{ .Release.Name }}-shared-data
|
||||
storageClassName: nfs
|
||||
accessModes:
|
||||
- ReadWriteMany
|
||||
size: 1Ti
|
||||
mountPath: /data
|
||||
|
||||
# Orchestrator component
|
||||
orchestrator:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
# Example command - use $INFERENCE_URL directly (the first inference server URL)
|
||||
command: "" # e.g., 'uv run orchestrator @ /app/k8s/prime-rl/examples/reverse-text/orch.toml --output-dir /data/outputs --client.base-url $INFERENCE_URL'
|
||||
# $INFERENCE_URL is auto-set to 'http://<release>-inference-0...:8000/v1'. With more than one
|
||||
# inference replica, put a router in front and point --client.base-url at it; admin operations
|
||||
# (weight updates, health checks) fan out to every replica via
|
||||
# --client.admin-base-url $ADMIN_INFERENCE_URLS (comma-separated list of all replica URLs).
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "2Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
ncclPort: 29501
|
||||
|
||||
env: []
|
||||
# - name: CUSTOM_ENV
|
||||
# value: "value"
|
||||
|
||||
nodeSelector: {}
|
||||
# nvidia.com/gpu.present: "true" # Orchestrator doesn't need GPUs
|
||||
|
||||
# Inference component
|
||||
inference:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
command: "" # e.g., "uv run inference @ /app/k8s/prime-rl/examples/reverse-text/infer.toml"
|
||||
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows long model loading time (up to 45 min by default)
|
||||
startup:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 270 # 270 * 10s = 45 min max startup time
|
||||
timeoutSeconds: 5
|
||||
liveness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 10
|
||||
readiness:
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
timeoutSeconds: 5
|
||||
|
||||
# Trainer component
|
||||
trainer:
|
||||
enabled: true
|
||||
replicas: 1
|
||||
|
||||
# Auto-start configuration (set to false to use sleep infinity for debugging)
|
||||
autoStart: false
|
||||
command: "" # e.g., "uv run trainer @ /app/k8s/prime-rl/examples/reverse-text/train.toml --output-dir /data/outputs"
|
||||
|
||||
# Helps reduce CUDA memory fragmentation with PyTorch allocator
|
||||
pytorchCudaAllocConf: "expandable_segments:True"
|
||||
|
||||
gpu:
|
||||
enabled: true
|
||||
count: 1
|
||||
|
||||
resources:
|
||||
requests:
|
||||
memory: "4Gi"
|
||||
cpu: "1"
|
||||
|
||||
service:
|
||||
enabled: true
|
||||
type: ClusterIP
|
||||
port: 8000
|
||||
ncclPort: 29501
|
||||
|
||||
env: []
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for trainer (requires metrics_server config)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows time for model loading
|
||||
startup:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 60 # 60 * 10s = 10 min max startup time
|
||||
timeoutSeconds: 30
|
||||
liveness:
|
||||
periodSeconds: 30
|
||||
failureThreshold: 6 # 6 * 30s = 3 min before restart
|
||||
timeoutSeconds: 30
|
||||
readiness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 30
|
||||
|
||||
# Additional configuration
|
||||
config:
|
||||
# Example name (used for labeling)
|
||||
example: "reverse-text"
|
||||
|
||||
# Secrets (optional)
|
||||
secrets:
|
||||
enabled: false
|
||||
name: prime-rl-secrets
|
||||
# wandbApiKey: ""
|
||||
# hfToken: ""
|
||||
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.shared import VLLMClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FrozenModelConfig(ClientConfig):
|
||||
class FrozenModelConfig(VLLMClientConfig):
|
||||
"""An externally hosted model behind an OpenAI-compatible endpoint: the
|
||||
client config plus the served model's ``name``.
|
||||
|
||||
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
|
||||
name: str
|
||||
"""Served model name, sent as the ``model`` field of every request."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
)
|
||||
return self
|
||||
base_url: str
|
||||
|
||||
|
||||
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
|
||||
|
||||
@@ -6,7 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
RunConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
@@ -14,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
@@ -43,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
@@ -55,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
client: ClientConfig = Field(default_factory=ClientConfig)
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
|
||||
@@ -21,7 +21,7 @@ class ServerConfig(BaseConfig):
|
||||
"""Port to bind to."""
|
||||
|
||||
liveness_timeout_seconds: float = Field(30.0, gt=0)
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. Health checks polling this endpoint should use a timeout at least this high."""
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (`vllm.config.lora.MaxLoRARanks`), excluding 1 so
|
||||
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
|
||||
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
|
||||
"vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
|
||||
# an adapter named like a served base model, so serve the base under another name.
|
||||
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
|
||||
namespace.served_model_name = [f"{self.vllm.model}-base"]
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
@@ -14,13 +14,13 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
@@ -40,7 +40,7 @@ class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
@@ -481,14 +481,11 @@ class CheckpointConfig(BaseConfig):
|
||||
keep_interval: int | None = Field(None, ge=1)
|
||||
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
|
||||
|
||||
skip_progress: bool = False
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
in-flight episode cap from engine KV capacity and learned per-env episode
|
||||
costs; these fields only bound and seed it."""
|
||||
in-flight episode cap from engine KV pressure; these fields only bound and
|
||||
seed it."""
|
||||
|
||||
initial_inflight: int | None = Field(None, ge=1)
|
||||
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
|
||||
|
||||
@@ -25,15 +25,7 @@ from prime_rl.configs.trainer import (
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_seq_len,
|
||||
validate_shared_tokenizer,
|
||||
validate_shared_wandb_config,
|
||||
)
|
||||
from prime_rl.utils.validation import propagate_shared_fields
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
@@ -333,15 +325,6 @@ class RLConfig(BaseConfig):
|
||||
sub.output_dir = run_dir
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_resume(self):
|
||||
"""Propagate the top-level resume onto the sub-configs."""
|
||||
if self.resume is None:
|
||||
return self
|
||||
self.trainer.resume = self.resume.model_copy()
|
||||
self.orchestrator.resume = self.resume.model_copy()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Default the W&B and Prime platform run names to ``run.name``.
|
||||
@@ -365,13 +348,70 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_configs(self):
|
||||
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
validate_shared_seq_len(self.trainer, self.orchestrator)
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
"""Cross-component constraints for values set per sub-config rather than through the
|
||||
shared fields (``propagate_shared_fields`` already rejects shared vs sub-config conflicts)."""
|
||||
trainer, orchestrator, inference = self.trainer, self.orchestrator, self.inference
|
||||
|
||||
def require_equal(name: str, values: dict[str, Any]) -> None:
|
||||
if len({repr(v) for v in values.values()}) > 1:
|
||||
found = ", ".join(f"{path}={value!r}" for path, value in values.items())
|
||||
raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.")
|
||||
|
||||
# The orchestrator queries the inference server it is paired with; without one, it
|
||||
# must match the trainer whose weights the external server receives.
|
||||
if inference is not None:
|
||||
require_equal(
|
||||
"model.name",
|
||||
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
|
||||
)
|
||||
else:
|
||||
require_equal(
|
||||
"model.name",
|
||||
{"trainer.model.name": trainer.model.name, "orchestrator.model.name": orchestrator.model.name},
|
||||
)
|
||||
# ``tokenizer.name`` / ``trust_remote_code`` may differ (e.g. FP8-quantized inference variants).
|
||||
chat_templates = {
|
||||
"trainer.tokenizer.chat_template": trainer.tokenizer.chat_template,
|
||||
"orchestrator.tokenizer.chat_template": orchestrator.tokenizer.chat_template,
|
||||
}
|
||||
if inference is not None:
|
||||
chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template
|
||||
require_equal("tokenizer.chat_template", chat_templates)
|
||||
require_equal(
|
||||
"max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps}
|
||||
)
|
||||
require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume})
|
||||
if trainer.model.seq_len < orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len "
|
||||
f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces."
|
||||
)
|
||||
if (trainer.ckpt is None) != (orchestrator.ckpt is None):
|
||||
raise ValueError(
|
||||
"Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]."
|
||||
)
|
||||
if trainer.ckpt and orchestrator.ckpt:
|
||||
require_equal(
|
||||
"ckpt.interval",
|
||||
{
|
||||
"trainer.ckpt.interval": trainer.ckpt.interval,
|
||||
"orchestrator.ckpt.interval": orchestrator.ckpt.interval,
|
||||
},
|
||||
)
|
||||
trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb
|
||||
if (trainer_wandb is None) != (orchestrator_wandb is None):
|
||||
raise ValueError(
|
||||
"W&B must be configured on both trainer and orchestrator, otherwise only one side's "
|
||||
"metrics are logged. Use the shared [monitors.wandb]."
|
||||
)
|
||||
if trainer_wandb and orchestrator_wandb:
|
||||
require_equal(
|
||||
"monitors.wandb.project",
|
||||
{
|
||||
"trainer.monitors.wandb.project": trainer_wandb.project,
|
||||
"orchestrator.monitors.wandb.project": orchestrator_wandb.project,
|
||||
},
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -555,17 +595,17 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
|
||||
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
@@ -283,6 +283,13 @@ class SFTConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.01
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = False
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import AfterValidator, Field, model_validator
|
||||
from verifiers.v1.configs.client import BaseClientConfig
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -212,22 +213,10 @@ class DynamoConfig(BaseConfig):
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
class ClientConfig(BaseClientConfig):
|
||||
wait_for_ready_timeout: int = 3600
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
|
||||
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
"""Static headers sent with every request."""
|
||||
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
@@ -238,6 +227,13 @@ class ClientConfig(BaseConfig):
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class VLLMClientConfig(ClientConfig):
|
||||
"""Client defaults for the live inference deployment managed by training."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
@@ -270,14 +266,6 @@ class HeartbeatConfig(BaseConfig):
|
||||
rate limit. Size it well under the monitor's period."""
|
||||
|
||||
|
||||
class MetricsServerConfig(BaseConfig):
|
||||
port: int = Field(8000, ge=1, le=65535)
|
||||
"""Port to expose metrics and health endpoints on."""
|
||||
|
||||
host: str = "0.0.0.0"
|
||||
"""Host to bind the server to."""
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
ResumeConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
@@ -23,6 +22,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
|
||||
DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"]
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
@@ -326,11 +326,14 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
dsa_backend: DSABackend = "tilelang"
|
||||
"""Kernels for the DSA sparse MLA attention (``glm_moe_dsa``, e.g. GLM-5). ``tilelang`` runs the TileLang forward and backward. ``cudnn_flashmla`` runs the FlashMLA sparse prefill forward with the cuDNN frontend CuTe-DSL backward; it needs the ``flash-mla`` extra and an SM90 GPU (SM100/SM103 are wired up but untested)."""
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
freeze_moe_router: bool = False
|
||||
"""Freeze MoE router parameters during training."""
|
||||
freeze_moe_router: bool | Literal["auto"] = "auto"
|
||||
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
|
||||
|
||||
lora: LoRAConfig | None = None
|
||||
"""LoRA configuration. If None, LoRA is disabled."""
|
||||
@@ -463,16 +466,6 @@ class BaseOptimizerConfig(BaseConfig):
|
||||
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
|
||||
|
||||
|
||||
class SGDConfig(BaseOptimizerConfig):
|
||||
type: Literal["sgd"] = "sgd"
|
||||
|
||||
nesterov: bool = True
|
||||
"""Use Nesterov momentum."""
|
||||
|
||||
momentum: float = 0.9
|
||||
"""SGD momentum factor."""
|
||||
|
||||
|
||||
class AdamWConfig(BaseOptimizerConfig):
|
||||
type: Literal["adamw"] = "adamw"
|
||||
|
||||
@@ -500,9 +493,7 @@ class SignSGDConfig(BaseOptimizerConfig):
|
||||
type: Literal["sign_sgd"] = "sign_sgd"
|
||||
|
||||
|
||||
OptimizerConfig: TypeAlias = Annotated[
|
||||
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
|
||||
]
|
||||
OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
@@ -518,9 +509,6 @@ class CheckpointConfig(BaseConfig):
|
||||
keep_interval: int | None = Field(None, ge=1)
|
||||
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
|
||||
|
||||
skip_progress: bool = False
|
||||
"""Skip loading the progress from checkpoint."""
|
||||
|
||||
skip_scheduler: bool = False
|
||||
"""Skip loading the scheduler from checkpoint."""
|
||||
|
||||
@@ -683,9 +671,6 @@ class TrainerConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
metrics_server: MetricsServerConfig | None = None
|
||||
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
|
||||
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
@@ -703,6 +688,13 @@ class TrainerConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.0
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = True
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from typing import Any
|
||||
|
||||
|
||||
def propagate_shared_fields(data: Any) -> Any:
|
||||
@@ -128,6 +124,8 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"inference.vllm.chat_template",
|
||||
)
|
||||
|
||||
propagate("resume", "trainer.resume", "orchestrator.resume")
|
||||
|
||||
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
|
||||
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
|
||||
|
||||
@@ -147,7 +145,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# - shared ``[tokenizer] chat_template`` (already filled all three above,
|
||||
# this re-fill is a no-op via fill-if-absent), and
|
||||
# - ``[trainer.tokenizer] chat_template`` set directly without shared
|
||||
# (only path that reaches inference; ``validate_shared_tokenizer``
|
||||
# (only path that reaches inference; ``RLConfig.validate_shared_configs``
|
||||
# would otherwise complain about the missing inference value).
|
||||
trainer_chat_template = get("trainer.tokenizer.chat_template")
|
||||
if trainer_chat_template is not None:
|
||||
@@ -190,115 +188,3 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
raise ValueError("\n".join(lines))
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def validate_shared_ckpt_config(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.ckpt and not orchestrator.ckpt:
|
||||
raise ValueError(
|
||||
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
|
||||
)
|
||||
if orchestrator.ckpt and not trainer.ckpt:
|
||||
raise ValueError(
|
||||
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
|
||||
)
|
||||
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
|
||||
raise ValueError(
|
||||
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
|
||||
)
|
||||
if trainer.resume != orchestrator.resume:
|
||||
raise ValueError(
|
||||
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_model_name(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
# Orchestrator must match inference (it queries the inference server)
|
||||
if inference is not None:
|
||||
if inference.vllm.model != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
"The orchestrator queries the inference server and must use the same model name."
|
||||
)
|
||||
return
|
||||
|
||||
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
|
||||
return
|
||||
if trainer.model.name != orchestrator.model.name:
|
||||
raise ValueError(
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_wandb_config(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Trainer W&B config is specified, but orchestrator W&B config is not. "
|
||||
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
|
||||
raise ValueError(
|
||||
"Orchestrator W&B config is specified, but trainer W&B config is not. "
|
||||
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
|
||||
"or use [monitors.wandb] to configure both at once."
|
||||
)
|
||||
if trainer.monitors.wandb and orchestrator.monitors.wandb:
|
||||
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
|
||||
raise ValueError(
|
||||
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_max_steps(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.max_steps != orchestrator.max_steps:
|
||||
raise ValueError(
|
||||
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_seq_len(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
) -> None:
|
||||
if trainer.model.seq_len < orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
|
||||
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_tokenizer(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
# Validate chat_template is consistent across all components.
|
||||
# We only check chat_template (not name/trust_remote_code) because those
|
||||
# are auto-derived from model names which may legitimately differ (e.g.
|
||||
# when inference uses an FP8 quantized variant of the same model).
|
||||
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
|
||||
raise ValueError(
|
||||
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
|
||||
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
|
||||
f"Use the shared [tokenizer] config to set chat_template for both."
|
||||
)
|
||||
if inference is not None:
|
||||
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
|
||||
raise ValueError(
|
||||
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
|
||||
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
|
||||
f"Use the shared [tokenizer] config to set chat_template for all components."
|
||||
)
|
||||
|
||||
+16
-12
@@ -11,13 +11,12 @@ dependencies = [
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"numpy>=2.2.6",
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.8.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"prime-runs[train]>=0.1.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -32,8 +31,6 @@ dependencies = [
|
||||
"verifiers[harbor]>=0.3.2.dev158",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
]
|
||||
|
||||
@@ -56,12 +53,14 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.30.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.31.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
"dion ; sys_platform == 'linux'",
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
# DSA sparse MLA backward kernel (CuTe DSL); >=1.29 matches the pinned CUTLASS DSL 4.7.
|
||||
"nvidia-cudnn-frontend>=1.30.0 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
@@ -91,13 +90,15 @@ disagg = [
|
||||
"deep-ep ; sys_platform == 'linux'",
|
||||
"deep-gemm ; sys_platform == 'linux'",
|
||||
"nixl ; sys_platform == 'linux'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
sonic-moe = ["sonic-moe ; sys_platform == 'linux'"]
|
||||
# FlashMLA sparse prefill forward for `model.dsa_backend = "cudnn_flashmla"` (sm_90a + sm_100f).
|
||||
# FlashMLA is not on PyPI and only an x86_64 wheel is published.
|
||||
flash-mla = ["flash-mla ; sys_platform == 'linux' and platform_machine == 'x86_64'"]
|
||||
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
|
||||
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
|
||||
kernels = [
|
||||
@@ -111,12 +112,10 @@ all = [
|
||||
"prime-rl[sonic-moe]",
|
||||
"prime-rl[flash-attn-3]",
|
||||
"prime-rl[flash-attn-cute]",
|
||||
"prime-rl[flash-mla]",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
mamba-ssm = [
|
||||
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
|
||||
]
|
||||
dev = [
|
||||
"ipykernel>=6.29.5",
|
||||
"ipywidgets>=8.1.7",
|
||||
@@ -148,7 +147,7 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
@@ -230,6 +229,8 @@ requires-dist = [
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
tokenspeed-mla = false
|
||||
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
|
||||
flashinfer-python = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
@@ -253,6 +254,7 @@ deep-gemm = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
flash-mla = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
@@ -278,8 +280,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -293,6 +295,8 @@ prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.0-6f48176/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
# FlashMLA nv_dev @ b7643bd built against torch 2.13.0+cu130 (see the release notes for the recipe).
|
||||
flash-mla = { url = "https://github.com/NovaSky-AI/skyrl-wheels/releases/download/cu13torch2.13-flashmla-b7643bd/flash_mla-1.0.0%2Bcu.13.0.torch.2.13.b7643bd-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
@@ -53,8 +53,8 @@ describe_tag() {
|
||||
sed -E 's/-[0-9]+-g[0-9a-f]+$//' <<< "$1"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
local dir="$root/deps/verifiers"
|
||||
standard_git_version() {
|
||||
local dir="$1"
|
||||
local desc tag distance
|
||||
|
||||
[ -d "$dir" ] || return 1
|
||||
@@ -64,6 +64,14 @@ verifiers_git_version() {
|
||||
next_patch_dev_version "$tag" "$distance"
|
||||
}
|
||||
|
||||
verifiers_git_version() {
|
||||
standard_git_version "$root/deps/verifiers"
|
||||
}
|
||||
|
||||
pydantic_config_git_version() {
|
||||
standard_git_version "$root/deps/pydantic-config"
|
||||
}
|
||||
|
||||
renderers_git_version() {
|
||||
local dir="$root/deps/renderers"
|
||||
local desc tag distance version
|
||||
@@ -111,22 +119,27 @@ resolve_version() {
|
||||
|
||||
verifiers_version="$(resolve_version verifiers VERIFIERS_PRETEND_VERSION verifiers_git_version)"
|
||||
renderers_version="$(resolve_version renderers RENDERERS_PRETEND_VERSION renderers_git_version)"
|
||||
pydantic_config_version="$(resolve_version prime-pydantic-config PYDANTIC_CONFIG_PRETEND_VERSION pydantic_config_git_version)"
|
||||
|
||||
printf 'Resolved verifiers pretend version: %s\n' "$verifiers_version" >&2
|
||||
printf 'Resolved renderers pretend version: %s\n' "$renderers_version" >&2
|
||||
printf 'Resolved pydantic-config pretend version: %s\n' "$pydantic_config_version" >&2
|
||||
|
||||
case "$mode" in
|
||||
shell)
|
||||
printf "export VERIFIERS_PRETEND_VERSION='%s'\n" "$verifiers_version"
|
||||
printf "export RENDERERS_PRETEND_VERSION='%s'\n" "$renderers_version"
|
||||
printf "export PYDANTIC_CONFIG_PRETEND_VERSION='%s'\n" "$pydantic_config_version"
|
||||
;;
|
||||
github-output)
|
||||
printf 'verifiers=%s\n' "$verifiers_version"
|
||||
printf 'renderers=%s\n' "$renderers_version"
|
||||
printf 'pydantic_config=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
env)
|
||||
printf 'VERIFIERS_PRETEND_VERSION=%s\n' "$verifiers_version"
|
||||
printf 'RENDERERS_PRETEND_VERSION=%s\n' "$renderers_version"
|
||||
printf 'PYDANTIC_CONFIG_PRETEND_VERSION=%s\n' "$pydantic_config_version"
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown output mode: %s\n' "$mode" >&2
|
||||
|
||||
@@ -113,8 +113,7 @@ HEAVY_PINS_PY
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
|
||||
--group mamba-ssm )
|
||||
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def editable_paths(root: Path) -> list[Path]:
|
||||
lock = tomllib.loads((root / "uv.lock").read_text())
|
||||
paths = set()
|
||||
for package in lock["package"]:
|
||||
source = package["source"]
|
||||
if "directory" in source:
|
||||
raise ValueError(f"Non-editable local package: {package['name']}")
|
||||
if "editable" not in source:
|
||||
continue
|
||||
path = (root / source["editable"]).resolve()
|
||||
if not path.is_relative_to(root):
|
||||
raise ValueError(f"Editable package outside the application: {path}")
|
||||
paths.add(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def set_fallback_version(pyproject: Path, version: str) -> None:
|
||||
if not re.fullmatch(r"[0-9][A-Za-z0-9.+-]*", version):
|
||||
raise ValueError(f"Invalid package version: {version!r}")
|
||||
content, count = re.subn(
|
||||
r'(?m)^fallback-version = "[^"]*"$', f'fallback-version = "{version}"', pyproject.read_text()
|
||||
)
|
||||
if count != 1:
|
||||
raise ValueError(f"Expected one fallback-version in {pyproject}")
|
||||
pyproject.write_text(content)
|
||||
|
||||
|
||||
def copy_installation_artifacts(venv: Path, baseline: set[Path], output: Path) -> None:
|
||||
# The runtime supplies the interpreter and third-party environment.
|
||||
for directory in (venv / "bin", venv / "lib/python3.12/site-packages"):
|
||||
for path in directory.iterdir():
|
||||
relative = path.relative_to(venv)
|
||||
if relative in baseline:
|
||||
continue
|
||||
target = output / ".venv" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.is_dir():
|
||||
shutil.copytree(path, target, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
||||
else:
|
||||
shutil.copy2(path, target)
|
||||
|
||||
|
||||
def application_layer(root: Path, output: Path) -> None:
|
||||
if output.is_relative_to(root):
|
||||
raise ValueError("The output directory must be outside the application")
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
venv = root / ".venv"
|
||||
if venv.exists() or venv.is_symlink():
|
||||
raise FileExistsError(venv)
|
||||
versions = {
|
||||
"deps/verifiers": "VERIFIERS_PRETEND_VERSION",
|
||||
"deps/renderers": "RENDERERS_PRETEND_VERSION",
|
||||
"deps/pydantic-config": "PYDANTIC_CONFIG_PRETEND_VERSION",
|
||||
}
|
||||
for path, variable in versions.items():
|
||||
set_fallback_version(root / path / "pyproject.toml", os.environ[variable])
|
||||
|
||||
subprocess.run(["uv", "venv", "--python", "/usr/bin/python3.12", str(venv)], check=True)
|
||||
baseline = {path.relative_to(venv) for path in venv.rglob("*")}
|
||||
command = ["uv", "pip", "install", "--python", str(venv / "bin/python"), "--no-deps"]
|
||||
for path in editable_paths(root):
|
||||
command.extend(["--editable", str(path)])
|
||||
subprocess.run(command, check=True, cwd=root)
|
||||
|
||||
shutil.copytree(root, output, ignore=shutil.ignore_patterns(".venv", ".git", "__pycache__", "*.pyc"))
|
||||
copy_installation_artifacts(venv, baseline, output)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build a source and editable-package Docker layer")
|
||||
parser.add_argument("root", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
application_layer(args.root.resolve(), args.output.resolve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,80 @@
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def dependency_fingerprint(root: Path) -> str:
|
||||
inputs = [root / path for path in ("Dockerfile.cuda", ".dockerignore", "uv.lock", "scripts/docker_dependencies.py")]
|
||||
for directory, children, files in os.walk(root):
|
||||
children[:] = [name for name in children if name not in {".git", ".venv", "outputs"}]
|
||||
if "pyproject.toml" in files:
|
||||
inputs.append(Path(directory) / "pyproject.toml")
|
||||
digest = hashlib.sha256()
|
||||
for path in sorted(inputs):
|
||||
name = path.relative_to(root).as_posix().encode()
|
||||
content = path.read_bytes()
|
||||
digest.update(len(name).to_bytes(8, "big"))
|
||||
digest.update(name)
|
||||
digest.update(len(content).to_bytes(8, "big"))
|
||||
digest.update(content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def registry_digest(image: str) -> str | None:
|
||||
registry, _, reference = image.partition("/")
|
||||
if registry != "ghcr.io":
|
||||
raise ValueError("Dependency images must use ghcr.io")
|
||||
repository, separator, tag = reference.rpartition(":")
|
||||
if not separator or not repository or not tag:
|
||||
raise ValueError("Expected ghcr.io/<owner>/<image>:<tag>")
|
||||
|
||||
query = urlencode({"service": registry, "scope": f"repository:{repository}:pull"})
|
||||
headers = {}
|
||||
if token := os.environ.get("GH_TOKEN"):
|
||||
credentials = f"{os.environ['GITHUB_ACTOR']}:{token}".encode()
|
||||
headers["Authorization"] = f"Basic {base64.b64encode(credentials).decode()}"
|
||||
request = Request(f"https://{registry}/token?{query}", headers=headers)
|
||||
with urlopen(request, timeout=30) as response:
|
||||
token = json.load(response)["token"]
|
||||
request = Request(
|
||||
f"https://{registry}/v2/{repository}/manifests/{tag}",
|
||||
headers={
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json",
|
||||
},
|
||||
method="HEAD",
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=30) as response:
|
||||
digest = response.headers["Docker-Content-Digest"]
|
||||
if not digest or not digest.startswith("sha256:"):
|
||||
raise ValueError(f"Missing or invalid image digest for {image}")
|
||||
return digest
|
||||
except HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Fingerprint and resolve Docker dependency images")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
fingerprint = commands.add_parser("fingerprint")
|
||||
fingerprint.add_argument("root", type=Path)
|
||||
resolve = commands.add_parser("resolve")
|
||||
resolve.add_argument("image")
|
||||
args = parser.parse_args()
|
||||
if args.command == "fingerprint":
|
||||
print(dependency_fingerprint(args.root.resolve()))
|
||||
else:
|
||||
print(registry_digest(args.image) or "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
|
||||
"scroll",
|
||||
(e) => {
|
||||
if (!e.target.matches?.("#replay-output") || !replay) return;
|
||||
// top and bottom coincide when the output fits; keep the mode Home/End chose
|
||||
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
|
||||
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
|
||||
replay.followOutput = atBottom;
|
||||
$("#replay-top")?.classList.toggle("active", !atBottom);
|
||||
|
||||
@@ -34,10 +34,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import (
|
||||
@@ -49,9 +45,6 @@ from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
|
||||
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -49,64 +47,6 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
original_post_init = VllmConfig.__post_init__
|
||||
|
||||
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
|
||||
return
|
||||
|
||||
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
|
||||
kv_transfer_config = config.kv_transfer_config
|
||||
return (
|
||||
config.model_config is not None
|
||||
and config.model_config.enable_return_routed_experts
|
||||
and kv_transfer_config is not None
|
||||
and kv_transfer_config.kv_connector == "NixlConnector"
|
||||
and kv_transfer_config.is_kv_transfer_instance
|
||||
)
|
||||
|
||||
def _post_init(config: VllmConfig):
|
||||
if not _is_nixl_routed_experts_pd_config(config):
|
||||
return original_post_init(config)
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
# remains rejected by prime-rl config validation.
|
||||
config.model_config.enable_return_routed_experts = False
|
||||
try:
|
||||
return original_post_init(config)
|
||||
finally:
|
||||
config.model_config.enable_return_routed_experts = True
|
||||
|
||||
_post_init._prime_rl_allows_nixl_routed_experts = True
|
||||
VllmConfig.__post_init__ = _post_init
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
|
||||
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
base_name = module_name.rsplit(".", 1)[-1]
|
||||
# Case for expert lora weights.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
if unexpected_modules:
|
||||
|
||||
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
# vLLM captures sampling masks and routed experts only on the V2 model runner.
|
||||
# setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant — the base model name, which
|
||||
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
|
||||
the base-model match, so requests keep addressing one stable name. If a future
|
||||
vLLM rejects registering an adapter under a served model name, fall back to a
|
||||
distinct constant adapter name set once at startup.) vLLM's native loader
|
||||
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
|
||||
that makes the worker re-read the new weights during ``add_lora``, reusing the
|
||||
existing ``lora_int_id``.
|
||||
changes per policy version; the name is constant — the model name every client
|
||||
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
|
||||
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
|
||||
we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
|
||||
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
|
||||
@@ -17,10 +17,6 @@ else:
|
||||
class FileSystemWeightUpdateWorker(Worker):
|
||||
"""vLLM worker extension for updating weights in-place using shared filesystem."""
|
||||
|
||||
def init_broadcaster(self) -> None:
|
||||
"""Initialize the broadcaster."""
|
||||
...
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
@@ -55,7 +55,6 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType, AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -50,9 +50,8 @@ class Algorithm:
|
||||
annotated traces into transport samples only after admission.
|
||||
"""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
def __init__(self, config: AlgoConfig, clients: InferenceClient):
|
||||
self.action_loss_type = config.action_loss_type
|
||||
self.clients = clients
|
||||
self.connected: InferenceClient | None = None
|
||||
|
||||
@@ -74,7 +73,3 @@ class Algorithm:
|
||||
"""Run rollout-local scoring when the episode has trainable traces."""
|
||||
if any(True for _ in iter_trainable_traces([episode])):
|
||||
await self.score_episode(episode)
|
||||
|
||||
async def finalize_group(self, episodes: list[vf.Episode]) -> None:
|
||||
"""Run group-relative scoring over the native episodes."""
|
||||
await self.score_group(episodes)
|
||||
|
||||
@@ -24,8 +24,6 @@ class OPDAlgorithm(Algorithm):
|
||||
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
|
||||
advantage stream; ``group_size`` only fans out sampling."""
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.teacher = config.teacher
|
||||
|
||||
@@ -31,8 +31,6 @@ class OPSDAlgorithm(Algorithm):
|
||||
multimodal prompts and any number of turns. No scalar advantage is
|
||||
assigned."""
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.demo_key = config.demo_key
|
||||
|
||||
@@ -10,5 +10,3 @@ class SFTDistillAlgorithm(Algorithm):
|
||||
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
|
||||
every sampled token. A curriculum can reject results using reward or any
|
||||
other finalized rollout data."""
|
||||
|
||||
action_loss_type = "ce"
|
||||
|
||||
@@ -5,8 +5,11 @@ from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, SamplingMask, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
@@ -858,3 +861,32 @@ def prepare_batch(
|
||||
batches_per_gpu[worker_idx].extend(worker_batches)
|
||||
|
||||
return batches_per_gpu
|
||||
|
||||
|
||||
class BatchPacker:
|
||||
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
|
||||
|
||||
def __init__(self, config: OrchestratorConfig):
|
||||
self.seq_len = config.seq_len
|
||||
self.num_train_workers = config.num_train_workers
|
||||
self.pad_to_multiple_of = config.pad_to_multiple_of
|
||||
try:
|
||||
model_config = AutoConfig.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
|
||||
)
|
||||
except Exception as e:
|
||||
get_logger().warning(
|
||||
f"Could not load model config for {config.model.name} ({e}) - "
|
||||
"packing balances by token count instead of estimated FLOPs"
|
||||
)
|
||||
model_config = None
|
||||
self.bin_cost = build_bin_cost(model_config)
|
||||
|
||||
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
|
||||
return prepare_batch(
|
||||
rollouts=samples,
|
||||
seq_len=self.seq_len,
|
||||
num_train_workers=self.num_train_workers,
|
||||
bin_cost=self.bin_cost,
|
||||
pad_to_multiple_of=self.pad_to_multiple_of,
|
||||
)
|
||||
|
||||
@@ -55,19 +55,16 @@ class CheckpointManager:
|
||||
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
|
||||
get_logger().debug(f"Loading checkpoint from {state_file}")
|
||||
start = time.perf_counter()
|
||||
if self.config.skip_progress:
|
||||
get_logger().info("Skipping progress and train source loading from checkpoint")
|
||||
else:
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
saved: Progress = state["progress"]
|
||||
for key, value in asdict(saved).items():
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name in state["train_source"]["envs"]:
|
||||
if name in train_source.curricula:
|
||||
get_logger().info(f"Resumed curriculum state for env {name}")
|
||||
with open(state_file, "rb") as f:
|
||||
state = torch.load(f, weights_only=False)
|
||||
saved: Progress = state["progress"]
|
||||
for key, value in asdict(saved).items():
|
||||
if hasattr(progress, key):
|
||||
setattr(progress, key, value)
|
||||
train_source.load_state_dict(state["train_source"])
|
||||
for name in state["train_source"]["envs"]:
|
||||
if name in train_source.curricula:
|
||||
get_logger().info(f"Resumed curriculum state for env {name}")
|
||||
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
@@ -12,40 +11,19 @@ from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI
|
||||
from renderers import RendererConfig
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
|
||||
from verifiers.v1.clients.base import build_async_openai
|
||||
from verifiers.v1.configs.client import (
|
||||
BaseClientConfig,
|
||||
EvalClientConfig,
|
||||
TrainClientConfig,
|
||||
resolve_api_key,
|
||||
resolve_headers,
|
||||
)
|
||||
|
||||
from prime_rl.configs.eval import PRIME_INFERENCE_URL
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def resolve_api_key(api_key_var: str) -> str:
|
||||
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
|
||||
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
|
||||
api_key = os.environ.get(api_key_var)
|
||||
if not api_key and api_key_var == "PRIME_API_KEY":
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
api_key = PrimeConfig().api_key
|
||||
return api_key or "EMPTY"
|
||||
|
||||
|
||||
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
"""The static headers plus those read from the environment. A Prime Inference client
|
||||
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
|
||||
like the verifiers client: a team's internal models are served only under it."""
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
|
||||
headers["X-Prime-Team-ID"] = team_id
|
||||
return headers
|
||||
|
||||
|
||||
class PrefillScorer:
|
||||
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
|
||||
a single OpenAI client from the pool's train client config."""
|
||||
@@ -55,14 +33,8 @@ class PrefillScorer:
|
||||
|
||||
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
|
||||
if self._client is None:
|
||||
# Build the OpenAI client straight from the config fields — works for any
|
||||
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
|
||||
# for these chat-completions teacher configs.
|
||||
self._client = AsyncOpenAI(
|
||||
base_url=config.base_url,
|
||||
api_key=resolve_api_key(config.api_key_var),
|
||||
default_headers=config.headers or None,
|
||||
)
|
||||
# Prefill scoring uses the SDK even when generation uses the eval relay.
|
||||
self._client = build_async_openai(config)
|
||||
return await prefill_logprobs(self._client, model, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -274,10 +246,7 @@ def setup_client(
|
||||
"renderer": renderer_config,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
}
|
||||
headers = resolve_headers(client_config)
|
||||
return config_cls(
|
||||
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
|
||||
)
|
||||
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -290,8 +259,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
|
||||
|
||||
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
|
||||
headers = resolve_headers(client_config)
|
||||
api_key = resolve_api_key(client_config.api_key_var)
|
||||
config = client_config.model_copy(update={"base_url": base_url})
|
||||
headers = resolve_headers(config)
|
||||
api_key = resolve_api_key(config)
|
||||
if api_key != "EMPTY":
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
@@ -324,7 +294,9 @@ async def maybe_check_has_model(
|
||||
f"{result.text[:300]}"
|
||||
)
|
||||
models = body["data"]
|
||||
if not any(model["id"] == model_name for model in models):
|
||||
# A LoRA server lists the model name only once the adapter is loaded; until then
|
||||
# the base model (served as ``<model>-base``) carries it as its ``root``.
|
||||
if not any(model_name in (model["id"], model.get("root")) for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ class ConcurrencyController:
|
||||
|
||||
# ── inbound hooks ────────────────────────────────────────────────────────
|
||||
|
||||
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
|
||||
def record_episode(self, tokens: int) -> None:
|
||||
"""One completed unit (from the dispatcher). Advances the turnover
|
||||
clock and, while the last poll was green, grows the cap — so growth
|
||||
is paced by the pipeline itself at any concurrency scale."""
|
||||
|
||||
@@ -143,7 +143,7 @@ class Dispatcher:
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
|
||||
on_episode_complete: Callable[[int], None] | None = None,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.progress = progress
|
||||
@@ -157,7 +157,7 @@ class Dispatcher:
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.run_id = run_id
|
||||
self.run_name = run_name
|
||||
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
|
||||
# Called with ``total_tokens`` per completed episode
|
||||
self.on_episode_complete = on_episode_complete
|
||||
|
||||
# Starting value of the dynamic cap (the concurrency controller moves
|
||||
@@ -694,9 +694,7 @@ class Dispatcher:
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(
|
||||
meta.env_name, meta.kind, episode.num_total_tokens, time.monotonic() - meta.started_at
|
||||
)
|
||||
self.on_episode_complete(episode.num_total_tokens)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
def complete_group_member(self, meta: InflightEpisode, group: GroupState | None) -> int:
|
||||
|
||||
@@ -38,6 +38,7 @@ from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.batch import BatchPacker
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient, setup_admin_plane
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
@@ -47,11 +48,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes, dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.packing import BatchPacker
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
@@ -78,12 +74,8 @@ from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
from prime_rl.utils.pathing import get_broadcast_dir, get_config_dir, resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
# Wall-clock budget for post-training cleanup; force-exit if graceful
|
||||
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
|
||||
@@ -250,8 +242,7 @@ class Orchestrator:
|
||||
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
|
||||
# themselves are restored below, once the envs are loaded.
|
||||
# trainer. The curricula themselves are restored below, once the envs are loaded.
|
||||
if self.resume_step is not None:
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming from step {self.resume_step}")
|
||||
@@ -298,9 +289,8 @@ class Orchestrator:
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
# A LoRA run's adapter is registered under the base model name: the
|
||||
# single adapter shadows it (vLLM resolves lora_requests before the
|
||||
# base-model match), so requests keep addressing one stable name.
|
||||
# A LoRA run's adapter is registered under the model name clients send;
|
||||
# the inference server serves the base model as ``<model>-base``.
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class BatchPacker:
|
||||
"""Bin-packs a step's training samples into one micro-batch list per trainer DP rank."""
|
||||
|
||||
def __init__(self, config: OrchestratorConfig):
|
||||
self.seq_len = config.seq_len
|
||||
self.num_train_workers = config.num_train_workers
|
||||
self.pad_to_multiple_of = config.pad_to_multiple_of
|
||||
try:
|
||||
model_config = AutoConfig.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.tokenizer.trust_remote_code
|
||||
)
|
||||
except Exception as e:
|
||||
get_logger().warning(
|
||||
f"Could not load model config for {config.model.name} ({e}) - "
|
||||
"packing balances by token count instead of estimated FLOPs"
|
||||
)
|
||||
model_config = None
|
||||
self.bin_cost = build_bin_cost(model_config)
|
||||
|
||||
def pack(self, samples: list[TrainingSample]) -> list[list[MicroBatch]]:
|
||||
return prepare_batch(
|
||||
rollouts=samples,
|
||||
seq_len=self.seq_len,
|
||||
num_train_workers=self.num_train_workers,
|
||||
bin_cost=self.bin_cost,
|
||||
pad_to_multiple_of=self.pad_to_multiple_of,
|
||||
)
|
||||
@@ -1,115 +0,0 @@
|
||||
from typing import Any, Optional, TypedDict, Union
|
||||
|
||||
import openai.types.chat
|
||||
from openai.types.chat.chat_completion import ChatCompletion, Choice
|
||||
from openai.types.chat.chat_completion_assistant_message_param import (
|
||||
Audio,
|
||||
ContentArrayOfContentPart,
|
||||
)
|
||||
from openai.types.chat.chat_completion_content_part_param import ChatCompletionContentPartParam
|
||||
from openai.types.chat.chat_completion_content_part_text_param import ChatCompletionContentPartTextParam
|
||||
from openai.types.chat.chat_completion_developer_message_param import ChatCompletionDeveloperMessageParam
|
||||
from openai.types.chat.chat_completion_function_message_param import ChatCompletionFunctionMessageParam
|
||||
from openai.types.chat.chat_completion_message import FunctionCall
|
||||
from openai.types.chat.chat_completion_message_tool_call_union_param import ChatCompletionMessageToolCallUnionParam
|
||||
from openai.types.chat.chat_completion_system_message_param import ChatCompletionSystemMessageParam
|
||||
from openai.types.chat.chat_completion_user_message_param import ChatCompletionUserMessageParam
|
||||
from typing_extensions import Literal, Required
|
||||
|
||||
|
||||
def monkey_patch_oai_iterable_types():
|
||||
"""
|
||||
This monkey patch is necessary to avoid Pydantic validating fields using
|
||||
typing.Iterable (e.g. in multimodal or tool call messages) lazily which
|
||||
leads to tokenization errors, for more info see
|
||||
https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
|
||||
"""
|
||||
|
||||
class ModdedChatCompletionDeveloperMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["developer"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionSystemMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["system"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionUserMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartParam]]]
|
||||
role: Required[Literal["user"]]
|
||||
name: str
|
||||
|
||||
class ModdedChatCompletionAssistantMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
role: Required[Literal["assistant"]]
|
||||
audio: Optional[Audio]
|
||||
content: Union[str, list[ContentArrayOfContentPart], None]
|
||||
function_call: Optional[FunctionCall]
|
||||
name: str
|
||||
refusal: Optional[str]
|
||||
tool_calls: list[ChatCompletionMessageToolCallUnionParam]
|
||||
|
||||
class ModdedChatCompletionToolMessageParam(TypedDict, total=False):
|
||||
"""Same as openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam, but replacing typing.Iterable with list to not mess up Pydantic."""
|
||||
|
||||
content: Required[Union[str, list[ChatCompletionContentPartTextParam]]]
|
||||
role: Required[Literal["tool"]]
|
||||
tool_call_id: Required[str]
|
||||
|
||||
# Patch OAI types
|
||||
openai.types.chat.chat_completion_developer_message_param.ChatCompletionDeveloperMessageParam = (
|
||||
ModdedChatCompletionDeveloperMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_system_message_param.ChatCompletionSystemMessageParam = (
|
||||
ModdedChatCompletionSystemMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_user_message_param.ChatCompletionUserMessageParam = (
|
||||
ModdedChatCompletionUserMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_assistant_message_param.ChatCompletionAssistantMessageParam = (
|
||||
ModdedChatCompletionAssistantMessageParam
|
||||
)
|
||||
openai.types.chat.chat_completion_tool_message_param.ChatCompletionToolMessageParam = (
|
||||
ModdedChatCompletionToolMessageParam
|
||||
)
|
||||
|
||||
openai.types.chat.chat_completion_message_param.ChatCompletionMessageParam = Union[
|
||||
ChatCompletionDeveloperMessageParam,
|
||||
ChatCompletionSystemMessageParam,
|
||||
ChatCompletionUserMessageParam,
|
||||
ModdedChatCompletionAssistantMessageParam,
|
||||
ModdedChatCompletionToolMessageParam,
|
||||
ChatCompletionFunctionMessageParam,
|
||||
]
|
||||
|
||||
|
||||
def monkey_patch_chat_completion_logprobs():
|
||||
"""
|
||||
At large batch sizes and context, constructing OAI's Pydantic model
|
||||
ChatCompletion with logprobs is causing heavy CPU overhead (~200ms per
|
||||
object at 32K context, which translates to >10min overhead at 4K batch
|
||||
size). This function monkey-patches the OAI type and verifiers'
|
||||
post-processing utils to avoid validating the complex logprobs field.
|
||||
"""
|
||||
|
||||
class ChoiceAny(Choice):
|
||||
"""Same as openai.types.chat.chat_completion.Choice, but without type validation for logprobs field."""
|
||||
|
||||
logprobs: Optional[Any] = None
|
||||
|
||||
class ModdedChatCompletion(ChatCompletion):
|
||||
"""Same as openai.types.chat.chat_completion.ChatCompletion, but using ChoiceAny instead of Choice."""
|
||||
|
||||
choices: list[ChoiceAny] # type: ignore
|
||||
|
||||
# Patch OAI types
|
||||
openai.types.chat.chat_completion.Choice = ChoiceAny
|
||||
openai.types.chat.chat_completion.ChatCompletion = ModdedChatCompletion
|
||||
@@ -242,7 +242,7 @@ class TrainSink:
|
||||
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
if survivors:
|
||||
await env.algorithm.finalize_group(group)
|
||||
await env.algorithm.score_group(group)
|
||||
admitted = self._admit(group) if group else False
|
||||
if not survivors or not admitted:
|
||||
self.pending_episodes.extend(group, admitted=admitted)
|
||||
|
||||
@@ -27,7 +27,7 @@ from prime_rl.trainer.models.fusions import (
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -16,6 +16,7 @@ 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 CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
@@ -125,23 +126,26 @@ def freeze_vision_encoder(model: nn.Module, override_attr: str | None = None) ->
|
||||
logger.info(f"Froze {num_frozen} parameters in vision encoder")
|
||||
|
||||
|
||||
def iter_moe_blocks(model: nn.Module) -> Iterator[MoE]:
|
||||
"""Yield the MoE MLP of each decoder layer, skipping dense layers."""
|
||||
for layer in get_language_model(model).layers:
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
if isinstance(mlp, MoE):
|
||||
yield mlp
|
||||
|
||||
|
||||
def freeze_moe_router(model: nn.Module) -> None:
|
||||
"""Freeze MoE router parameters to maintain stable routing during training."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_frozen = 0
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
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):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen == 0:
|
||||
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
|
||||
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
# No-op for non-MoE models: freeze_moe_router=True is the RL default.
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
@@ -150,16 +154,12 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
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):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.to(torch.float32)
|
||||
if isinstance(moe.router, TokenChoiceTopKRouter):
|
||||
moe.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
|
||||
# No-op for non-MoE models: moe_router_dtype='float32' is the default,
|
||||
# so absence of MoE routers is the common case, not an error.
|
||||
@@ -177,13 +177,10 @@ def get_full_offload_dtype_policy(
|
||||
if config.moe_router_dtype != "float32":
|
||||
return 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):
|
||||
for param in mlp.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
return policy
|
||||
|
||||
|
||||
@@ -215,14 +212,10 @@ def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
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):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
if num_routers == 0:
|
||||
raise ValueError("No MoE routers found to force-balance. Is this a MoE model?")
|
||||
@@ -248,13 +241,7 @@ def get_load_balance_stats(
|
||||
"""
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
block_mlps = []
|
||||
for transformer_block in language_model.layers:
|
||||
# This is necessary for models that have mixed dense layers
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
|
||||
block_mlps.append(block_mlp)
|
||||
block_mlps = list(iter_moe_blocks(model))
|
||||
if not block_mlps:
|
||||
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
|
||||
|
||||
@@ -333,7 +320,7 @@ def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
|
||||
|
||||
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
|
||||
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
|
||||
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
|
||||
if tokens_per_expert.numel() == 0:
|
||||
return {}
|
||||
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
|
||||
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
|
||||
@@ -365,6 +352,7 @@ 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.dsa_backend = config.dsa_backend
|
||||
if config.index_cache is not None:
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
@@ -828,12 +816,41 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
)
|
||||
|
||||
|
||||
# Int args whose value changes between calls. torch.compile treats an int arg as a constant and recompiles
|
||||
# whenever it changes, and every other rank waits in collectives until that rank finishes recompiling. Listed
|
||||
# here, an arg is symbolic from the first compile instead.
|
||||
DYNAMIC_INT_ARGS = (
|
||||
# Longest document in the packed row. FlashAttention uses it to size the attention launch grid.
|
||||
"max_seqlen",
|
||||
)
|
||||
|
||||
|
||||
def mark_dynamic_int_args() -> None:
|
||||
"""Add DYNAMIC_INT_ARGS to torch.compiler.config.dynamic_sources, keeping entries already set."""
|
||||
sources = [source for source in torch.compiler.config.dynamic_sources.split(",") if source]
|
||||
for arg in DYNAMIC_INT_ARGS:
|
||||
# Matches the arg passed directly (L['max_seqlen']) or through a wrapper's kwargs (L['kwargs']['max_seqlen']).
|
||||
pattern = rf".*\['{arg}'\]"
|
||||
if pattern not in sources:
|
||||
sources.append(pattern)
|
||||
torch.compiler.config.dynamic_sources = ",".join(sources)
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
torch._dynamo.config.capture_scalar_outputs = True
|
||||
mark_dynamic_int_args()
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
layer = language_model.layers[layer_id]
|
||||
if isinstance(layer, CheckpointWrapper) and any(
|
||||
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
|
||||
):
|
||||
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
|
||||
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
|
||||
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
|
||||
layer = layer._checkpoint_wrapped_module
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
@@ -994,14 +1011,15 @@ def setup_model(
|
||||
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
|
||||
)
|
||||
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
if loading_from_checkpoint_later:
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
|
||||
@@ -15,9 +15,9 @@ from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
@@ -87,30 +87,25 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
4: flash_attn_4_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: AfmoeAttentionConfig, flash_attn_version: int = 4):
|
||||
super().__init__(config)
|
||||
self._flash_attn_version = flash_attn_version
|
||||
self.func = self._funcs[flash_attn_version]
|
||||
self._flash_attn_call = self.func
|
||||
if self._flash_attn_version == 4:
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
kwargs: dict = {"causal": True}
|
||||
if self.sliding_window is not None:
|
||||
kwargs["window_size"] = (self.sliding_window - 1, 0)
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
if self._flash_attn_version == 4:
|
||||
out, _ = self.func(q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, **kwargs)
|
||||
else:
|
||||
out = self.func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
|
||||
return out
|
||||
|
||||
def forward(
|
||||
|
||||
@@ -61,8 +61,8 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
num_experts_per_tok: Number of routed experts activated per token.
|
||||
n_routed_experts: Total number of routed experts.
|
||||
n_shared_experts: Number of always-on shared experts.
|
||||
scoring_func: Router activation. Only `sqrtsoftplus` is implemented; any other
|
||||
value is rejected when the MoE layer is built.
|
||||
scoring_func: Router score function, passed to the shared router: `sqrtsoftplus`
|
||||
(V4's checkpoints), `sigmoid`, `softmax` or `topk_softmax`.
|
||||
topk_method: Router top-k selection. Only `noaux_tc` (aux-loss-free bias correction) is
|
||||
implemented; the field is carried because vLLM gates `e_score_correction_bias` on it.
|
||||
norm_topk_prob: Whether to renormalize the top-k routing probabilities.
|
||||
|
||||
@@ -6,96 +6,15 @@ selection with a frozen token-id lookup but keeps the learned gating weights.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.layers.activations import ClampedSilu
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class ClampedSwiglu:
|
||||
"""SwiGLU with both branches clamped, as in HF's `DeepseekV4Experts`.
|
||||
|
||||
Structurally an `Activation`, but with `limit` as instance state: V4 reads its clamp
|
||||
off `config.swiglu_limit`, while the shared `ActivationDispatch` holds stateless
|
||||
classes keyed by name and so has nowhere to put a per-model number.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None, "V4's routed experts are gated"
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class DeepseekV4Router(TokenChoiceTopKRouter):
|
||||
"""Token-choice router scored with `sqrt(softplus(.))`, V4's only scoring function.
|
||||
|
||||
`TokenChoiceTopKRouter.forward` picks its scoring function from an inline
|
||||
`if/elif/else: raise` chain with no hook to extend, and `"sqrtsoftplus"` is outside
|
||||
the `ScoreFuncType` it accepts, so the whole method is restated below. Only the
|
||||
scoring line is new: the `routed_experts` bypass, the selection bias, the
|
||||
normalization, the scaling and the per-expert token count are the base class's,
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, routed_experts: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
if self.fp32_gate:
|
||||
gate_bias = self.gate.bias.float() if self.gate.bias is not None else None
|
||||
logits = F.linear(x.float(), self.gate.weight.float(), gate_bias)
|
||||
else:
|
||||
logits = self.gate(x)
|
||||
|
||||
# Scoring runs in float32 to avoid loss explosion, as in the base class. HF scores
|
||||
# in the input dtype instead, so bf16 activations drift from HF by ~1e-3 here.
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
|
||||
# NOTE: the selection bias only steers selection. The gating value top_scores is
|
||||
# still derived from the original scores.
|
||||
if routed_experts is not None:
|
||||
top_scores = scores.gather(dim=1, index=routed_experts)
|
||||
selected_experts_indices = routed_experts
|
||||
elif self.force_balanced:
|
||||
num_tokens = scores.shape[0]
|
||||
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
|
||||
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
else:
|
||||
selection_scores = scores
|
||||
if self.selection_bias is not None:
|
||||
selection_scores = selection_scores + self.selection_bias
|
||||
_, selected_experts_indices = torch.topk(selection_scores, k=self.top_k, dim=1, sorted=self.topk_sorted)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
|
||||
with torch.no_grad():
|
||||
selected_probability_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
|
||||
routing_confidence_sum = selected_probability_mass.sum()
|
||||
|
||||
if self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
top_scores = top_scores * self.route_scale
|
||||
|
||||
num_tokens_per_expert = torch.histc(
|
||||
selected_experts_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
).to(torch.int64)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
|
||||
class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
class DeepseekV4HashRouter(TokenChoiceTopKRouter):
|
||||
"""A bootstrap layer's router: selection is a frozen token-id lookup, gating still learned.
|
||||
|
||||
`tid2eid` replaces the top-k of the scores with `tid2eid[token_id]`, read from the checkpoint
|
||||
@@ -105,73 +24,9 @@ class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
unbuilt, keeping the state dict aligned with HF's.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: str,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
vocab_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
dim=dim,
|
||||
num_experts=num_experts,
|
||||
top_k=top_k,
|
||||
score_func=score_func,
|
||||
route_norm=route_norm,
|
||||
route_scale=route_scale,
|
||||
selection_bias=False,
|
||||
)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4Experts(GroupedExperts):
|
||||
"""Routed experts with V4's clamped SwiGLU.
|
||||
|
||||
The shared `GroupedExperts` already stores the stacked `gate_proj`/`up_proj`/`down_proj`
|
||||
that the on-disk per-expert `w1`/`w2`/`w3` convert into, and its `forward` reaches the
|
||||
activation through `self.activation`, so only that attribute and the initialization
|
||||
spread differ from the base class.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, hidden_dim: int, num_experts: int, swiglu_limit: float) -> None:
|
||||
super().__init__(dim, hidden_dim, num_experts, expert_type="gated")
|
||||
self.activation = ClampedSwiglu(swiglu_limit)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# Both halves of HF's fused gate_up_proj are drawn from the same std=0.02
|
||||
# distribution, so gate and up match that here despite being separate tensors.
|
||||
# The base class scales up_proj by init_std instead.
|
||||
nn.init.trunc_normal_(self.gate_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.up_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class DeepseekV4MLP(FeedForward):
|
||||
"""Dense SwiGLU MLP with V4's clamp, used as the MoE layer's shared expert.
|
||||
|
||||
The shared `FeedForward` already names its projections the way HF's `LlamaMLP` (which
|
||||
HF's `DeepseekV4MLP` subclasses) does, and initializes them the same way, so only the
|
||||
activation changes: gate and up are clamped before the SwiGLU. Unlike the routed
|
||||
experts they are separate tensors here, so there is nothing to chunk.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
# `FeedForward` builds its projections without a bias whatever `bias` says.
|
||||
assert not config.mlp_bias, "mlp_bias is not supported by the shared `FeedForward`"
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.limit = config.swiglu_limit
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x).clamp(max=self.limit)
|
||||
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
|
||||
return self.down_proj(F.silu(gate) * up)
|
||||
def __init__(self, *, vocab_size: int, **router_kwargs) -> None:
|
||||
super().__init__(**router_kwargs, selection_bias=False)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, self.top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4MoE(MoE):
|
||||
@@ -190,13 +45,9 @@ class DeepseekV4MoE(MoE):
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
assert config.hidden_act == "silu", (
|
||||
f"the routed experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
f"the experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
)
|
||||
if config.scoring_func != "sqrtsoftplus":
|
||||
raise ValueError(
|
||||
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
|
||||
)
|
||||
|
||||
assert not config.mlp_bias, "mlp_bias is not supported"
|
||||
is_hash = layer_idx < config.num_hash_layers
|
||||
|
||||
router_kwargs = dict(
|
||||
@@ -212,17 +63,22 @@ class DeepseekV4MoE(MoE):
|
||||
router = (
|
||||
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
|
||||
if is_hash
|
||||
else DeepseekV4Router(**router_kwargs, selection_bias=True)
|
||||
else TokenChoiceTopKRouter(**router_kwargs, selection_bias=True)
|
||||
)
|
||||
experts = DeepseekV4Experts(
|
||||
activation = ClampedSilu(config.swiglu_limit)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
swiglu_limit=config.swiglu_limit,
|
||||
activation=activation,
|
||||
)
|
||||
# HF sizes its shared expert at `moe_intermediate_size` regardless of
|
||||
# `n_shared_experts`, which therefore only decides whether one exists at all.
|
||||
shared_expert = DeepseekV4MLP(config) if config.n_shared_experts > 0 else None
|
||||
shared_expert = (
|
||||
FeedForward(dim=config.hidden_size, hidden_dim=config.moe_intermediate_size, activation=activation)
|
||||
if config.n_shared_experts > 0
|
||||
else None
|
||||
)
|
||||
|
||||
super().__init__(
|
||||
router=router,
|
||||
@@ -235,6 +91,11 @@ class DeepseekV4MoE(MoE):
|
||||
self.layer_idx = layer_idx
|
||||
self.is_hash = is_hash
|
||||
|
||||
def init_weights(self, init_std: float, buffer_device: torch.device) -> None:
|
||||
super().init_weights(init_std, buffer_device)
|
||||
# HF draws both halves of its fused gate_up_proj from std=0.02; the shared init uses init_std for up.
|
||||
nn.init.trunc_normal_(self.experts.up_proj, mean=0.0, std=0.02)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -23,7 +23,6 @@ from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfig
|
||||
@@ -89,7 +88,6 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
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))
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
|
||||
@@ -10,7 +10,6 @@ from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
|
||||
@@ -42,6 +41,7 @@ def _sparse_mla_attention_args(config: GlmMoeDsaConfig, layer_idx: int) -> Spars
|
||||
index_topk=config.index_topk,
|
||||
use_index_cache=getattr(config, "use_index_cache", False),
|
||||
skip_topk=_index_cache_skip_topk(config, layer_idx),
|
||||
dsa_backend=getattr(config, "dsa_backend", "tilelang"),
|
||||
)
|
||||
|
||||
|
||||
@@ -87,7 +87,6 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
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))
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
|
||||
@@ -4,6 +4,7 @@ import torch
|
||||
import torch.distributed as dist
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.configs.trainer import DSABackend
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
@@ -30,6 +31,7 @@ class SparseMlaAttentionArgs:
|
||||
index_n_heads: int
|
||||
index_head_dim: int
|
||||
index_topk: int
|
||||
dsa_backend: DSABackend
|
||||
use_index_cache: bool = False
|
||||
skip_topk: bool = False
|
||||
|
||||
@@ -230,7 +232,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
position_embeddings_full=position_embeddings,
|
||||
)
|
||||
|
||||
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.args.dsa_backend, 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)
|
||||
|
||||
@@ -13,10 +13,14 @@ except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import math
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
from prime_rl.configs.trainer import DSABackend
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def preprocess(
|
||||
@@ -276,8 +280,32 @@ def bwd(
|
||||
return sparse_mla_bwd_kernel
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::sparse_mla_backward", mutates_args=())
|
||||
def sparse_mla_backward(
|
||||
_CUDNN_SM100_CAPABILITIES = ((10, 0), (10, 3))
|
||||
|
||||
|
||||
def cudnn_backward_arch(q: torch.Tensor, kv: torch.Tensor) -> str | None:
|
||||
"""The cuDNN DSA backward variant for this device ("sm90" / "sm100"), or None if unsupported."""
|
||||
if kv.shape[2] != 1:
|
||||
return None
|
||||
capability = torch.cuda.get_device_capability(q.device)
|
||||
if capability[0] == 9:
|
||||
return "sm90"
|
||||
if capability in _CUDNN_SM100_CAPABILITIES:
|
||||
return "sm100"
|
||||
return None
|
||||
|
||||
|
||||
def flat_kv_indices(indices: torch.Tensor, S_kv: int) -> torch.Tensor:
|
||||
"""Global indices into the batch-flattened KV, with sentinel / out-of-range indices as -1.
|
||||
|
||||
`indices` is [B, S, kv_group, topk]; valid entries live in [0, S_kv - 1) (see sparse_mla_fwd).
|
||||
"""
|
||||
B = indices.shape[0]
|
||||
batch_offset = torch.arange(B, device=indices.device, dtype=indices.dtype).view(B, 1, 1, 1) * S_kv
|
||||
return torch.where(indices <= S_kv - 2, indices + batch_offset, -1)
|
||||
|
||||
|
||||
def tilelang_sparse_mla_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
@@ -286,20 +314,13 @@ def sparse_mla_backward(
|
||||
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()
|
||||
"""TileLang backward; takes a natural-log LSE."""
|
||||
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
|
||||
assert kv.shape[0] == B
|
||||
H, dim_plus_tail_dim = q.shape[2:]
|
||||
kv_group = kv.shape[2]
|
||||
D = 512
|
||||
D_tail = dim_plus_tail_dim - D
|
||||
topk = indices.shape[-1]
|
||||
assert indices.shape == (B, S, kv_group, topk)
|
||||
assert lse.shape == (B, S, H)
|
||||
|
||||
preprocess_kernel = preprocess(H, D)
|
||||
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
|
||||
@@ -307,9 +328,82 @@ def sparse_mla_backward(
|
||||
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse * math.log2(math.e), delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
return dq, dkv
|
||||
|
||||
|
||||
def cudnn_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,
|
||||
arch: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""cuDNN-frontend CuTe-DSL DSA backward (single KV head with K=V).
|
||||
|
||||
The cuDNN kernels take flat (tokens, ...) tensors with global indices, skip
|
||||
negative indices (no KV load, no dKV atomics) and expect a natural-log LSE.
|
||||
"""
|
||||
B, S, H, D_qk = q.shape
|
||||
S_kv = kv.shape[1]
|
||||
topk = indices.shape[-1]
|
||||
args = (
|
||||
q.view(B * S, H, D_qk),
|
||||
kv.view(B * S_kv, D_qk),
|
||||
out.view(B * S, H, -1),
|
||||
grad_out.contiguous().view(B * S, H, -1),
|
||||
lse.view(B * S, H),
|
||||
)
|
||||
flat_indices = flat_kv_indices(indices, S_kv).view(B * S, topk)
|
||||
if arch == "sm90":
|
||||
from cudnn.deepseek_sparse_attention.sparse_attention_backward._interface_sm90 import flash_attn_bwd_sm90
|
||||
|
||||
dq, dkv = flash_attn_bwd_sm90(*args, softmax_scale=sm_scale, topk_idxs=flat_indices)
|
||||
else:
|
||||
# Untested: no SM100 hardware has run this path. A -inf sink leaves the softmax unchanged.
|
||||
from cudnn.deepseek_sparse_attention.sparse_attention_backward._interface_sm100 import flash_attn_bwd_sm100
|
||||
|
||||
no_sink = torch.full((H,), float("-inf"), dtype=torch.float32, device=q.device)
|
||||
dq, dkv, _ = flash_attn_bwd_sm100(*args, no_sink, flat_indices, softmax_scale=sm_scale)
|
||||
return dq.view_as(q), dkv.view_as(kv)
|
||||
|
||||
|
||||
@torch.library.custom_op(
|
||||
"prime_rl::sparse_mla_backward",
|
||||
mutates_args=(),
|
||||
schema="(Tensor q, Tensor kv, Tensor out, Tensor grad_out, Tensor indices, Tensor lse, str backend, float? sm_scale=None) -> (Tensor, Tensor)",
|
||||
)
|
||||
def sparse_mla_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
backend: DSABackend,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Sparse MLA backward for the `backend` route (see `sparse_mla`); `lse` is natural-log."""
|
||||
assert q.is_contiguous()
|
||||
assert kv.is_contiguous()
|
||||
assert indices.is_contiguous()
|
||||
assert lse.is_contiguous()
|
||||
B, S, H, dim_plus_tail_dim = q.shape
|
||||
_, S_kv, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim_plus_tail_dim
|
||||
assert kv.shape[0] == B
|
||||
topk = indices.shape[-1]
|
||||
assert indices.shape == (B, S, kv_group, topk)
|
||||
assert lse.shape == (B, S, H)
|
||||
|
||||
if backend == "cudnn_flashmla":
|
||||
dq, dkv = cudnn_sparse_mla_backward(q, kv, out, grad_out, indices, lse, sm_scale, cudnn_backward_arch(q, kv))
|
||||
else:
|
||||
dq, dkv = tilelang_sparse_mla_backward(q, kv, out, grad_out, indices, lse, sm_scale)
|
||||
return dq, dkv
|
||||
|
||||
|
||||
@@ -321,6 +415,7 @@ def _sparse_mla_backward_fake(
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
backend: DSABackend,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(kv)
|
||||
|
||||
@@ -13,11 +13,17 @@ except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import math
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_backward
|
||||
from prime_rl.configs.trainer import DSABackend
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import (
|
||||
flat_kv_indices,
|
||||
sparse_mla_backward,
|
||||
)
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
@@ -186,17 +192,52 @@ def sparse_mla_fwd(
|
||||
return main
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::sparse_mla", mutates_args=())
|
||||
def flashmla_sparse_mla_forward(
|
||||
q: torch.Tensor, kv: torch.Tensor, indices: torch.Tensor, sm_scale: float, d_v: int
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""FlashMLA sparse prefill forward; returns a natural-log LSE."""
|
||||
from flash_mla import flash_mla_sparse_fwd
|
||||
|
||||
B, S, H, D_qk = q.shape
|
||||
S_kv, kv_group = kv.shape[1:3]
|
||||
topk = indices.shape[-1]
|
||||
# Shortest prefix holding every valid index, so the kernel skips the sentinel tail
|
||||
# (the indexer sorts valid indices first); invalid entries inside it are -1.
|
||||
positions = torch.arange(1, topk + 1, device=indices.device, dtype=torch.int32)
|
||||
topk_length = torch.where(indices <= S_kv - 2, positions, 0).amax(-1).view(B * S)
|
||||
out, _max_logits, lse = flash_mla_sparse_fwd(
|
||||
q.view(B * S, H, D_qk),
|
||||
kv.view(B * S_kv, kv_group, D_qk),
|
||||
flat_kv_indices(indices, S_kv).view(B * S, kv_group, topk),
|
||||
sm_scale,
|
||||
d_v,
|
||||
topk_length=topk_length,
|
||||
)
|
||||
return out.view(B, S, H, d_v), lse.view(B, S, H)
|
||||
|
||||
|
||||
@torch.library.custom_op(
|
||||
"prime_rl::sparse_mla",
|
||||
mutates_args=(),
|
||||
schema="(Tensor q, Tensor kv, Tensor indices, str backend, float? sm_scale=None, SymInt d_v=512, SymInt block_I=64, SymInt num_stages=2, SymInt threads=256) -> (Tensor, Tensor)",
|
||||
)
|
||||
def sparse_mla(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
backend: DSABackend,
|
||||
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]:
|
||||
"""Sparse MLA attention over the top-k `indices`; returns the output and its natural-log LSE.
|
||||
|
||||
`backend` picks the kernels for the forward and (via autograd) the backward:
|
||||
``tilelang`` is TileLang for both; ``cudnn_flashmla`` is FlashMLA forward + cuDNN backward
|
||||
(SM90; SM100 / SM103 untested).
|
||||
"""
|
||||
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
|
||||
@@ -209,19 +250,26 @@ def sparse_mla(
|
||||
_, _, _, topk = indices.shape
|
||||
assert indices.shape == (batch, seq_len, kv_group, topk)
|
||||
|
||||
kernel = sparse_mla_fwd(
|
||||
heads,
|
||||
dim,
|
||||
tail_dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
block_I=block_I,
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices)
|
||||
if backend == "cudnn_flashmla":
|
||||
if sm_scale is None:
|
||||
sm_scale = dim_plus_tail_dim**-0.5
|
||||
out, lse = flashmla_sparse_mla_forward(q, kv, indices, sm_scale, d_v)
|
||||
else:
|
||||
kernel = sparse_mla_fwd(
|
||||
heads,
|
||||
dim,
|
||||
tail_dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
block_I=block_I,
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices)
|
||||
# The TileLang kernel returns a base-2 LSE.
|
||||
lse = lse * math.log(2.0)
|
||||
return out, lse
|
||||
|
||||
|
||||
@@ -230,6 +278,7 @@ def _sparse_mla_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
backend: DSABackend,
|
||||
sm_scale: float | None = None,
|
||||
d_v: int = 512,
|
||||
block_I: int = 64,
|
||||
@@ -240,10 +289,11 @@ def _sparse_mla_fake(
|
||||
|
||||
|
||||
def _sparse_mla_setup_context(ctx, inputs, output) -> None:
|
||||
q, kv, indices, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
|
||||
q, kv, indices, backend, 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.backend = backend
|
||||
ctx.mark_non_differentiable(lse)
|
||||
|
||||
|
||||
@@ -256,9 +306,10 @@ def _sparse_mla_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.
|
||||
grad_out,
|
||||
indices,
|
||||
lse.detach(),
|
||||
ctx.backend,
|
||||
ctx.sm_scale,
|
||||
)
|
||||
return dq, dkv, None, None, None, None, None, None
|
||||
return dq, dkv, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
sparse_mla.register_autograd(_sparse_mla_autograd_backward, setup_context=_sparse_mla_setup_context)
|
||||
|
||||
@@ -18,6 +18,19 @@ class ClampedSwiglu(Activation):
|
||||
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
|
||||
|
||||
|
||||
class ClampedSilu(Activation):
|
||||
"""SwiGLU with the gate clamped to `max=limit` and up to `[-limit, limit]` (DeepSeek V4)."""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class Relu2(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -13,14 +13,19 @@ from .rotary_emb import apply_rotary_pos_emb
|
||||
# flash-attention-2
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward, _flash_attn_varlen_forward
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
_flash_attn_varlen_backward = _flash_attn_varlen_forward = None # type: ignore
|
||||
|
||||
# flash-attention-3
|
||||
try:
|
||||
from flash_attn_interface import _flash_attn_backward as _flash_attn_3_bwd
|
||||
from flash_attn_interface import _flash_attn_forward as _flash_attn_3_fwd
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
_flash_attn_3_bwd = _flash_attn_3_fwd = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
@@ -30,9 +35,11 @@ except ImportError:
|
||||
_flash_attn_bwd = _flash_attn_fwd = None # type: ignore
|
||||
|
||||
|
||||
# FA4's flash_attn_varlen_func is a Python autograd.Function that Dynamo cannot trace. Inside a
|
||||
# checkpointed block that graph break drops the whole block to eager, so FA4 is exposed as an
|
||||
# opaque custom op instead, which also lets selective activation checkpointing save its output.
|
||||
# Each FlashAttention version's flash_attn_varlen_func is a Python autograd.Function that Dynamo
|
||||
# cannot trace (FA2 and FA3 also reject the same cu_seqlens tensor passed as both cu_seqlens_q and
|
||||
# cu_seqlens_k). Inside a checkpointed block that graph break drops the whole block to eager, so
|
||||
# each version is exposed as an opaque custom op instead, which also lets selective activation
|
||||
# checkpointing save its output.
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_4_varlen", mutates_args=())
|
||||
def _flash_attn_4_varlen(
|
||||
q: torch.Tensor,
|
||||
@@ -40,6 +47,8 @@ def _flash_attn_4_varlen(
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -50,6 +59,8 @@ def _flash_attn_4_varlen(
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
@@ -59,7 +70,7 @@ def _flash_attn_4_varlen(
|
||||
|
||||
|
||||
@_flash_attn_4_varlen.register_fake
|
||||
def _(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
@@ -75,6 +86,8 @@ def _flash_attn_4_varlen_backward(
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -91,19 +104,24 @@ def _flash_attn_4_varlen_backward(
|
||||
window_size_right=window_size_right,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_4_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right = inputs
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size_left, window_size_right = (
|
||||
inputs
|
||||
)
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.max_seqlen = (max_seqlen_q, max_seqlen_k)
|
||||
ctx.causal = causal
|
||||
ctx.window_size = (window_size_left, window_size_right)
|
||||
|
||||
@@ -111,9 +129,9 @@ def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
def _flash_attn_4_varlen_autograd(ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
dq, dk, dv = _flash_attn_4_varlen_backward(
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, ctx.causal, *ctx.window_size
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, *ctx.max_seqlen, ctx.causal, *ctx.window_size
|
||||
)
|
||||
return dq, dk, dv, None, None, None, None, None
|
||||
return dq, dk, dv, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_4_varlen.register_autograd(_flash_attn_4_varlen_autograd, setup_context=_flash_attn_4_varlen_setup_context)
|
||||
@@ -126,11 +144,264 @@ def flash_attn_4_varlen_op(
|
||||
*,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None = None,
|
||||
max_seqlen_k: int | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int | None, int | None] = (None, None),
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Drop-in for FA4's ``flash_attn_varlen_func`` as called by ``FlashAttention``, routed through the custom op."""
|
||||
return _flash_attn_4_varlen(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size[0], window_size[1])
|
||||
return _flash_attn_4_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size[0], window_size[1]
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen", mutates_args=())
|
||||
def _flash_attn_3_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
out, lse, _, _ = _flash_attn_3_fwd(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out, lse
|
||||
|
||||
|
||||
@_flash_attn_3_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen_backward", mutates_args=())
|
||||
def _flash_attn_3_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_3_bwd(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
dq=dq,
|
||||
dk=dk,
|
||||
dv=dv,
|
||||
softmax_scale=softmax_scale,
|
||||
is_causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_3_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
# FA2's public flash_attn_varlen_func pads the head dim to a multiple of 8 around its kernels; these ops call
|
||||
# the kernels directly, so they pad the same way.
|
||||
def pad_head_dim_to_multiple_of_8_for_fa2(t: torch.Tensor) -> torch.Tensor:
|
||||
head_dim = t.shape[-1]
|
||||
if head_dim % 8 == 0:
|
||||
return t
|
||||
return torch.nn.functional.pad(t, [0, 8 - head_dim % 8])
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen", mutates_args=())
|
||||
def _flash_attn_2_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
q, k, v = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (q, k, v))
|
||||
out_padded, lse, _, _ = _flash_attn_varlen_forward(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out_padded[..., :head_dim], lse
|
||||
|
||||
|
||||
# FA2's kernel allocates its outputs with empty_like on the padded inputs, so the fakes keep their strides and padding.
|
||||
@_flash_attn_2_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
out = torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(q))[..., :head_dim]
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen_backward", mutates_args=())
|
||||
def _flash_attn_2_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
dout, q, k, v, out = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (dout, q, k, v, out))
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_varlen_backward(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
dq,
|
||||
dk,
|
||||
dv,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size_left,
|
||||
window_size_right,
|
||||
0.0,
|
||||
None,
|
||||
False,
|
||||
)
|
||||
return dq[..., :head_dim], dk[..., :head_dim], dv[..., :head_dim]
|
||||
|
||||
|
||||
@_flash_attn_2_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
return tuple(torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(t))[..., :head_dim] for t in (q, k, v))
|
||||
|
||||
|
||||
def _flash_attn_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, *scalar_args = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.scalar_args = scalar_args
|
||||
|
||||
|
||||
def _flash_attn_varlen_autograd(backward_op, ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
dq, dk, dv = backward_op(dout.contiguous(), *ctx.saved_tensors, *ctx.scalar_args)
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_2_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_2_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
_flash_attn_3_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_3_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
|
||||
|
||||
def flash_attn_2_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA2's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_2_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def flash_attn_3_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA3's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_3_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -158,8 +429,8 @@ class FlashAttention(nn.Module):
|
||||
supported_fusions = {"qkv": fuse_qkv_projections}
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
|
||||
ExpertType = Literal["gated", "non_gated"]
|
||||
|
||||
@@ -17,14 +17,14 @@ class FeedForward(nn.Module):
|
||||
hidden_dim: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) if expert_type == "gated" else None
|
||||
self.up_proj = nn.Linear(dim, hidden_dim, bias=bias)
|
||||
self.down_proj = nn.Linear(hidden_dim, dim, bias=bias)
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x) if self.gate_proj is not None else None
|
||||
|
||||
@@ -13,11 +13,11 @@ from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, ExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
|
||||
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax", "sqrtsoftplus"]
|
||||
|
||||
|
||||
@torch.library.custom_op(
|
||||
@@ -76,7 +76,7 @@ class GroupedExperts(nn.Module):
|
||||
num_experts: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
compute: ExpertCompute | None = None,
|
||||
):
|
||||
@@ -93,7 +93,7 @@ class GroupedExperts(nn.Module):
|
||||
self.up_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias else None
|
||||
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, dim)) if bias else None
|
||||
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
if expert_type == "non_gated":
|
||||
self.supported_fusions = {}
|
||||
self.set_compute(compute or BF16ExpertCompute())
|
||||
@@ -136,8 +136,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim (int): Dimension of input tokens.
|
||||
num_experts (int): Number of experts in each moe layer.
|
||||
top_k (int): Number of experts each token will be routed to in token-choice routing.
|
||||
score_func (Literal["softmax", "sigmoid", "topk_softmax"]): Score transform. ``topk_softmax``
|
||||
selects experts from the logits and normalizes only the selected logits.
|
||||
score_func (ScoreFuncType): Score transform. ``topk_softmax`` selects experts from the logits
|
||||
and normalizes only the selected logits. ``sqrtsoftplus`` is DeepSeek V4's ``sqrt(softplus(.))``.
|
||||
route_norm (bool): Whether to normalize the routing scores when using sigmoid.
|
||||
route_scale (float): Scaling factor applied to the routing scores.
|
||||
gate_bias (bool): Whether the gate has a trainable logit bias.
|
||||
@@ -151,7 +151,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: Literal["softmax", "sigmoid", "topk_softmax"],
|
||||
score_func: ScoreFuncType,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
*,
|
||||
@@ -214,6 +214,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
scores = F.softmax(logits.float(), dim=1)
|
||||
elif self.score_func == "topk_softmax":
|
||||
scores = logits
|
||||
elif self.score_func == "sqrtsoftplus":
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown score function {self.score_func}")
|
||||
|
||||
|
||||
@@ -176,15 +176,15 @@ def substitute_ulysses_attn(
|
||||
|
||||
# Resolve flash kernel + version from attn_impl.
|
||||
if attn_impl == "flash_attention_4":
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_4_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
elif attn_impl == "flash_attention_3":
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_3_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 3
|
||||
else:
|
||||
from flash_attn import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_2_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 2
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ from transformers.modeling_outputs import (
|
||||
from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
|
||||
from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
@@ -71,7 +70,6 @@ class LlamaDecoderLayer(GradientCheckpointingLayer):
|
||||
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))
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
|
||||
@@ -6,9 +6,9 @@ from torch import nn
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
|
||||
@@ -69,9 +69,9 @@ class Qwen3_5VisionMLP(nn.Module):
|
||||
|
||||
class Qwen3_5VisionAttention(nn.Module):
|
||||
FLASH_ATTENTION_FUNCTIONS = {
|
||||
"flash_attention_2": flash_attn_varlen_func,
|
||||
"flash_attention_3": flash_attn_3_varlen_func,
|
||||
"flash_attention_4": flash_attn_4_varlen_func,
|
||||
"flash_attention_2": flash_attn_2_varlen_op,
|
||||
"flash_attention_3": flash_attn_3_varlen_op,
|
||||
"flash_attention_4": flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
|
||||
@@ -3,7 +3,7 @@ import torch.distributed as dist
|
||||
from dion import Muon
|
||||
from torch import nn
|
||||
from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.optim import SGD, AdamW, Optimizer
|
||||
from torch.optim import AdamW, Optimizer
|
||||
|
||||
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
|
||||
from prime_rl.trainer.models.fusions import get_model_packed_parameters
|
||||
@@ -117,14 +117,6 @@ def _create_optimizer(
|
||||
# param at load time, mismatching the saved state). Muon filters internally below.
|
||||
trainable_params = [p for _, p in named_params if p.requires_grad]
|
||||
match config.type:
|
||||
case "sgd":
|
||||
return SGD(
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
momentum=config.momentum,
|
||||
nesterov=config.nesterov,
|
||||
)
|
||||
case "adamw":
|
||||
return AdamW(
|
||||
params=trainable_params,
|
||||
|
||||
@@ -68,11 +68,11 @@ from prime_rl.trainer.world import get_world
|
||||
from prime_rl.trainer.lora import get_lora_state
|
||||
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
@clean_exit
|
||||
@@ -102,19 +102,6 @@ def train(config: TrainerConfig):
|
||||
logger.info("Initializing heartbeat")
|
||||
heart = Heartbeat(config.heartbeat)
|
||||
|
||||
# Setup metrics server (full on master, health-only on other nodes' local rank 0)
|
||||
metrics_server = None
|
||||
health_server = None
|
||||
if config.metrics_server is not None and world.local_rank == 0:
|
||||
if world.is_master:
|
||||
logger.info(f"Initializing metrics server on port {config.metrics_server.port}")
|
||||
metrics_server = MetricsServer(config.metrics_server)
|
||||
metrics_server.start()
|
||||
else:
|
||||
logger.info(f"Initializing health server on port {config.metrics_server.port}")
|
||||
health_server = HealthServer(config.metrics_server.port, config.metrics_server.host)
|
||||
health_server.start()
|
||||
|
||||
# Set precision
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds),
|
||||
@@ -721,20 +708,6 @@ def train(config: TrainerConfig):
|
||||
disk_metrics["step"] = progress.step
|
||||
asyncio.run(monitors.log(disk_metrics, step=progress.step))
|
||||
|
||||
# Update Prometheus metrics if configured
|
||||
if metrics_server is not None:
|
||||
metrics_server.update(
|
||||
step=progress.step,
|
||||
loss=tensor_stats["loss/mean"],
|
||||
throughput=throughput,
|
||||
grad_norm=grad_norm.item() if grad_norm is not None else None,
|
||||
peak_memory_gib=peak_memory,
|
||||
learning_rate=current_lr,
|
||||
mfu=mfu,
|
||||
entropy=tensor_stats.get("entropy/all/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
|
||||
)
|
||||
|
||||
# Send heartbeat if configured
|
||||
if heart is not None:
|
||||
heart.beat()
|
||||
@@ -764,12 +737,6 @@ def train(config: TrainerConfig):
|
||||
logger.success("RL trainer finished")
|
||||
asyncio.run(monitors.finalize())
|
||||
|
||||
# Stop metrics/health server if configured
|
||||
if metrics_server is not None:
|
||||
metrics_server.stop()
|
||||
if health_server is not None:
|
||||
health_server.stop()
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for RL trainer. Run using `uv run trainer`"""
|
||||
|
||||
@@ -210,13 +210,12 @@ def train(config: SFTConfig):
|
||||
model,
|
||||
[optimizer],
|
||||
scheduler if not skip.skip_scheduler else None,
|
||||
progress if not skip.skip_progress else None,
|
||||
progress,
|
||||
dataloader=dataloader if not skip.skip_dataloader else None,
|
||||
path=resume_dir / "trainer" if resume_dir is not None else None,
|
||||
)
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
if not skip.skip_progress:
|
||||
progress.step += 1
|
||||
progress.step += 1
|
||||
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
|
||||
if skip.skip_scheduler:
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
|
||||
@@ -143,11 +143,12 @@ def setup_logger(
|
||||
if json_logging and tag:
|
||||
logger = logger.bind(tag=tag)
|
||||
|
||||
# diagnose=False: repr()-ing frame locals that hold multi-GB tensors makes a crash look like a hang.
|
||||
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
|
||||
if json_logging:
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True)
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True, diagnose=False)
|
||||
else:
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True)
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True, diagnose=False)
|
||||
if log_file is not None:
|
||||
# The console format carries raw ANSI codes; the file gets a plain layout.
|
||||
logger.add(
|
||||
@@ -155,6 +156,7 @@ def setup_logger(
|
||||
format="{time:HH:mm:ss} {level: >7} " + f"{tag_prefix}{{message}}",
|
||||
level=log_level.upper(),
|
||||
colorize=False,
|
||||
diagnose=False,
|
||||
)
|
||||
|
||||
# Disable critical logging
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
"""Prometheus metrics server for trainer observability.
|
||||
|
||||
Exposes training metrics at /metrics in Prometheus format.
|
||||
Also exposes /health endpoint for Kubernetes liveness probes.
|
||||
Runs in a background thread to avoid blocking the training loop.
|
||||
"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from loguru import logger
|
||||
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, Gauge, generate_latest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.shared import MetricsServerConfig
|
||||
|
||||
|
||||
class HealthServer:
|
||||
"""Lightweight HTTP server exposing /health for Kubernetes liveness probes.
|
||||
|
||||
Can be subclassed to add additional endpoints (e.g., MetricsServer).
|
||||
"""
|
||||
|
||||
def __init__(self, port: int, host: str = "0.0.0.0"):
|
||||
self.port = port
|
||||
self.host = host
|
||||
self._server: HTTPServer | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._started = False
|
||||
|
||||
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
|
||||
"""Create the request handler class. Override to add endpoints."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/health":
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"ok\n")
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
return Handler
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the server in a background thread."""
|
||||
if self._started:
|
||||
logger.warning(f"{self.__class__.__name__} already started")
|
||||
return
|
||||
|
||||
self._server = HTTPServer((self.host, self.port), self._make_handler())
|
||||
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
self._started = True
|
||||
logger.info(f"Health server started at http://{self.host}:{self.port}/health")
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the server and release the port."""
|
||||
if self._server is not None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=5.0)
|
||||
self._server = None
|
||||
self._thread = None
|
||||
self._started = False
|
||||
logger.info(f"{self.__class__.__name__} stopped")
|
||||
|
||||
|
||||
class MetricsServer(HealthServer):
|
||||
"""Prometheus metrics server extending HealthServer with /metrics endpoint.
|
||||
|
||||
Uses an isolated CollectorRegistry to avoid global state pollution.
|
||||
Disabled by default - enable by setting `metrics_server` in trainer config.
|
||||
"""
|
||||
|
||||
def __init__(self, config: "MetricsServerConfig"):
|
||||
super().__init__(config.port, config.host)
|
||||
self.config = config
|
||||
|
||||
self._registry = CollectorRegistry()
|
||||
self._step = Gauge("trainer_step", "Current training step", registry=self._registry)
|
||||
self._loss = Gauge("trainer_loss", "Current training loss", registry=self._registry)
|
||||
self._throughput = Gauge(
|
||||
"trainer_throughput_tokens_per_sec", "Training throughput in tokens/sec", registry=self._registry
|
||||
)
|
||||
self._last_step_ts = Gauge(
|
||||
"trainer_last_step_timestamp_seconds", "Unix timestamp of last step", registry=self._registry
|
||||
)
|
||||
self._grad_norm = Gauge("trainer_grad_norm", "Gradient norm", registry=self._registry)
|
||||
self._peak_mem = Gauge("trainer_peak_memory_gib", "Peak GPU memory in GiB", registry=self._registry)
|
||||
self._lr = Gauge("trainer_learning_rate", "Current learning rate", registry=self._registry)
|
||||
self._mfu = Gauge("trainer_mfu_percent", "Model FLOPS utilization %", registry=self._registry)
|
||||
self._entropy = Gauge("trainer_entropy", "Mean entropy", registry=self._registry)
|
||||
self._mismatch_kl = Gauge(
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
|
||||
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
|
||||
"""Create handler with /metrics and /health endpoints."""
|
||||
registry = self._registry
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/metrics":
|
||||
self._handle_metrics()
|
||||
elif self.path == "/health":
|
||||
self._handle_health()
|
||||
else:
|
||||
self.send_response(404)
|
||||
self.end_headers()
|
||||
|
||||
def _handle_metrics(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", CONTENT_TYPE_LATEST)
|
||||
self.end_headers()
|
||||
self.wfile.write(generate_latest(registry))
|
||||
|
||||
def _handle_health(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"ok\n")
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
return Handler
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the metrics server in a background thread."""
|
||||
if self._started:
|
||||
logger.warning("Metrics server already started")
|
||||
return
|
||||
|
||||
self._server = HTTPServer((self.host, self.port), self._make_handler())
|
||||
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
||||
self._thread.start()
|
||||
self._started = True
|
||||
logger.info(f"Metrics server started at http://{self.host}:{self.port}/metrics")
|
||||
logger.info(f"Health endpoint available at http://{self.host}:{self.port}/health")
|
||||
|
||||
def update(
|
||||
self,
|
||||
step: int,
|
||||
loss: float,
|
||||
throughput: float,
|
||||
grad_norm: float | None,
|
||||
peak_memory_gib: float,
|
||||
learning_rate: float,
|
||||
mfu: float = 0.0,
|
||||
entropy: float = 0.0,
|
||||
mismatch_kl: float = 0.0,
|
||||
) -> None:
|
||||
"""Update metrics after a training step."""
|
||||
self._step.set(step)
|
||||
self._loss.set(loss)
|
||||
self._throughput.set(throughput)
|
||||
if grad_norm is not None:
|
||||
self._grad_norm.set(grad_norm)
|
||||
self._peak_mem.set(peak_memory_gib)
|
||||
self._lr.set(learning_rate)
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
@@ -2,33 +2,14 @@ import asyncio
|
||||
import functools
|
||||
import importlib
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
import wandb
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# TODO: Change all imports to use utils.pathing
|
||||
# ruff: noqa: F401
|
||||
from prime_rl.utils.pathing import (
|
||||
get_all_ckpt_steps,
|
||||
get_batch_dir,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
get_eval_dir,
|
||||
get_file_monitor_dir,
|
||||
get_log_dir,
|
||||
get_step_path,
|
||||
resolve_latest_ckpt_step,
|
||||
sync_wait_for_path,
|
||||
wait_for_path,
|
||||
)
|
||||
|
||||
|
||||
def import_object(dotted_path: str) -> Any:
|
||||
"""Import an object from a dotted path like 'my_module.submodule.MyClass'."""
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
@@ -46,14 +45,6 @@ def cleanup_zombies():
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def free_port() -> int:
|
||||
"""Fixture to get a free port per tests"""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def user() -> str:
|
||||
"""Fixture for current user from environment for test session."""
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
|
||||
|
||||
|
||||
class _StubTokenizer:
|
||||
def get_added_vocab(self):
|
||||
return {}
|
||||
|
||||
def encode(self, text, **_kwargs):
|
||||
return text
|
||||
|
||||
|
||||
def _request_tools():
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _tokenizer():
|
||||
from vllm.tokenizers import deepseek_v4
|
||||
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
|
||||
|
||||
|
||||
def _render(messages, tools):
|
||||
return _tokenizer().apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=False,
|
||||
thinking=True,
|
||||
reasoning_effort="low",
|
||||
)
|
||||
|
||||
|
||||
def _reference(messages):
|
||||
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
|
||||
|
||||
|
||||
def test_request_tools_attach_to_first_existing_system_without_mutation():
|
||||
messages = [
|
||||
{"role": "user", "content": "This may precede the system message."},
|
||||
{"role": "system", "content": "You are helpful.", "tools": []},
|
||||
{"role": "system", "content": "A later system message."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
]
|
||||
snapshot = copy.deepcopy(messages)
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
expected_messages = messages.copy()
|
||||
expected_messages[1] = {**messages[1], "tools": tools}
|
||||
assert prompt == _reference(expected_messages)
|
||||
assert prompt.count("## Tools") == 1
|
||||
assert messages == snapshot
|
||||
|
||||
|
||||
def test_request_tools_synthesize_system_only_when_none_exists():
|
||||
messages = [{"role": "user", "content": "Weather in Paris?"}]
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -93,6 +93,8 @@ def test_setup_client_creates_renderer_client():
|
||||
base_url="http://worker-a:8000/v1",
|
||||
api_key_var="PRIME_API_KEY",
|
||||
headers={"X-Test": "test"},
|
||||
headers_from_env={"X-Token": "PROVIDER_TOKEN"},
|
||||
timeout={"read": 12},
|
||||
)
|
||||
|
||||
renderer_settings = Qwen3VLRendererConfig()
|
||||
@@ -108,6 +110,8 @@ def test_setup_client_creates_renderer_client():
|
||||
assert client.base_url == "http://worker-a:8000/v1"
|
||||
assert "X-data-parallel-rank" not in client.headers
|
||||
assert client.headers["X-Test"] == "test"
|
||||
assert client.headers_from_env == {"X-Token": "PROVIDER_TOKEN"}
|
||||
assert client.timeout.read == 12
|
||||
|
||||
|
||||
def test_check_health_retries_non_success_status():
|
||||
|
||||
@@ -18,6 +18,9 @@ from prime_rl.configs.orchestrator import (
|
||||
ScheduledEvalConfig,
|
||||
TrainConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
ModelConfig as OrchestratorModelConfig,
|
||||
)
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.trainer import ModelConfig as TrainerModelConfig
|
||||
@@ -37,14 +40,11 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/`, `examples/` or `k8s/`."""
|
||||
"""Any TOML file inside `configs/` or `examples/`."""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
# The k8s example configs are mounted into the chart's containers verbatim, so a
|
||||
# stale key there breaks a deploy with nothing else to catch it.
|
||||
k8s_files = list(Path("k8s").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files + k8s_files
|
||||
return config_files + example_files
|
||||
|
||||
|
||||
def can_parse(config_cls: type, args: list[str]) -> bool:
|
||||
@@ -343,6 +343,16 @@ def test_moe_router_dtype_auto_resolves_per_trainer():
|
||||
assert config_cls.model_validate({"model": {"moe_router_dtype": dtype}}).model.moe_router_dtype == dtype
|
||||
|
||||
|
||||
def test_freeze_moe_router_auto_resolves_per_trainer():
|
||||
"""``freeze_moe_router='auto'`` (the default) freezes the router for RL, not SFT; explicit values are kept."""
|
||||
assert TrainerConfig.model_validate({}).model.freeze_moe_router is True
|
||||
assert SFTConfig.model_validate({}).model.freeze_moe_router is False
|
||||
|
||||
for config_cls in (TrainerConfig, SFTConfig):
|
||||
for freeze in (True, False):
|
||||
assert config_cls.model_validate({"model": {"freeze_moe_router": freeze}}).model.freeze_moe_router is freeze
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
|
||||
@@ -357,13 +367,12 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon"])
|
||||
def test_full_optimizer_offload_requires_supported_optimizer(config_cls, optimizer_type):
|
||||
def test_full_optimizer_offload_requires_supported_optimizer(config_cls):
|
||||
with pytest.raises(ValidationError, match="Full optimizer offload only supports AdamW and SignSGD"):
|
||||
config_cls.model_validate(
|
||||
{
|
||||
"model": {"optim_cpu_offload": False, "full_offload": True},
|
||||
"optim": {"type": optimizer_type, "max_norm": None},
|
||||
"optim": {"type": "muon", "max_norm": None},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -397,6 +406,36 @@ def test_resolved_json_roundtrips_explicit_none(tmp_path):
|
||||
assert reloaded == config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_class,source_args,expected_url,expected_key",
|
||||
[
|
||||
(
|
||||
EvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"https://configured.pinference.ai/api/v1",
|
||||
"PRIME_API_KEY",
|
||||
),
|
||||
(
|
||||
SFTOnlineEvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"http://localhost:8000/v1",
|
||||
"VLLM_API_KEY",
|
||||
),
|
||||
(OrchestratorModelConfig, [], "http://localhost:8000/v1", "VLLM_API_KEY"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("overrides", [[], ["--client.skip-model-check"], ["--client.wait-for-ready-timeout", "10"]])
|
||||
def test_client_defaults_survive_partial_overrides(
|
||||
monkeypatch, config_class, source_args, expected_url, expected_key, overrides
|
||||
):
|
||||
monkeypatch.setenv("PRIME_INFERENCE_URL", "https://configured.pinference.ai/api/v1")
|
||||
config = cli(config_class, args=source_args + overrides)
|
||||
assert config.client.base_url == expected_url
|
||||
assert config.client.api_key_var == expected_key
|
||||
reloaded = config_class.model_validate_json(config.model_dump_json())
|
||||
assert reloaded.client == config.client
|
||||
|
||||
|
||||
def test_env_algo_inherits_the_group_algo():
|
||||
config = OrchestratorConfig.model_validate(
|
||||
{
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class AfmoeConfig(PretrainedConfig):
|
||||
"""
|
||||
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).
|
||||
"""
|
||||
|
||||
model_type = "afmoe"
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_hidden_layers: int = 32,
|
||||
vocab_size: int = 200192,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 6144,
|
||||
moe_intermediate_size=1408,
|
||||
num_dense_layers=1,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=None,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=16384,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-5,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
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,
|
||||
load_balance_coeff: float | None = None,
|
||||
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,
|
||||
pad_token_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_dense_layers = num_dense_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
|
||||
# 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.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
|
||||
self.sliding_window = sliding_window
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
self.layer_types = [
|
||||
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
layer_type_validation(self.layer_types)
|
||||
|
||||
# muP specific
|
||||
self.mup_enabled = mup_enabled
|
||||
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["AfmoeConfig"]
|
||||
@@ -1,645 +0,0 @@
|
||||
from typing import Callable, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.cache_utils import Cache, DynamicCache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
from transformers.masking_utils import (
|
||||
create_causal_mask,
|
||||
create_sliding_window_causal_mask,
|
||||
)
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import (
|
||||
MoeCausalLMOutputWithPast,
|
||||
MoeModelOutputWithPast,
|
||||
)
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
try:
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
except:
|
||||
from configuration_afmoe import AfmoeConfig
|
||||
|
||||
|
||||
class AfmoeRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: AfmoeConfig, device=None):
|
||||
super().__init__()
|
||||
# BC: "rope_type" was originally "type"
|
||||
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
||||
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
self.rope_type = "default"
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
|
||||
self.config = config
|
||||
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
||||
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.original_inv_freq = self.inv_freq
|
||||
|
||||
def compute_default_rope_parameters(self, config=None, device=None, seq_len=None, layer_type=None):
|
||||
"""Required by transformers 5.0.0 for weight initialization when rope_type is 'default'."""
|
||||
cfg = config or self.config
|
||||
cfg.standardize_rope_params()
|
||||
rope_params = cfg.rope_parameters[layer_type] if layer_type is not None else cfg.rope_parameters
|
||||
base = rope_params["rope_theta"]
|
||||
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
inv_freq = 1.0 / (
|
||||
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
||||
)
|
||||
return inv_freq, 1.0
|
||||
|
||||
def _dynamic_frequency_update(self, position_ids, device):
|
||||
"""
|
||||
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
||||
1 - growing beyond the cached sequence length (allow scaling)
|
||||
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
||||
"""
|
||||
seq_len = torch.max(position_ids) + 1
|
||||
if seq_len > self.max_seq_len_cached: # growth
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = seq_len
|
||||
|
||||
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
||||
# This .to() is needed if the model has been moved to a device after being initialized (because
|
||||
# the buffer is automatically moved, but not the original copy)
|
||||
self.original_inv_freq = self.original_inv_freq.to(device)
|
||||
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = self.original_max_seq_len
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, x, position_ids):
|
||||
if "dynamic" in self.rope_type:
|
||||
self._dynamic_frequency_update(position_ids, device=x.device)
|
||||
|
||||
# Core RoPE block
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
||||
device_type = x.device.type
|
||||
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False):
|
||||
freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
|
||||
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
||||
cos = cos * self.attention_scaling
|
||||
sin = sin * self.attention_scaling
|
||||
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
"""Rotates half the hidden dims of the input."""
|
||||
x1 = x[..., : x.shape[-1] // 2]
|
||||
x2 = x[..., x.shape[-1] // 2 :]
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
"""Applies Rotary Position Embedding to the query and key tensors.
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
position_ids (`torch.Tensor`, *optional*):
|
||||
Deprecated and unused.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
||||
"""
|
||||
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
||||
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
||||
"""
|
||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class AfmoeRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, eps: float):
|
||||
"""
|
||||
AfmoeRMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
**kwargs,
|
||||
):
|
||||
key_states = repeat_kv(key, module.num_key_value_groups)
|
||||
value_states = repeat_kv(value, module.num_key_value_groups)
|
||||
|
||||
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
||||
if attention_mask is not None:
|
||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||
attn_weights = attn_weights + causal_mask
|
||||
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||
attn_output = torch.matmul(attn_weights, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
return attn_output, attn_weights
|
||||
|
||||
|
||||
class AfmoeMLP(nn.Module):
|
||||
def __init__(self, config, intermediate_size=None):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.intermediate_size = intermediate_size or config.intermediate_size
|
||||
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
||||
self.act_fn = ACT2FN[config.hidden_act]
|
||||
|
||||
def forward(self, x):
|
||||
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
|
||||
|
||||
class AfmoeTokenChoiceRouter(nn.Module):
|
||||
"""Token-choice top-K router for MoE routing."""
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.num_experts = config.num_experts
|
||||
self.score_func = config.score_func
|
||||
self.route_norm = config.route_norm
|
||||
self.route_scale = config.route_scale
|
||||
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
||||
|
||||
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
|
||||
_, _, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
scores = self.gate(hidden_states)
|
||||
|
||||
# Apply scoring function in float32 for stability
|
||||
if self.score_func == "sigmoid":
|
||||
scores = torch.sigmoid(scores.to(torch.float32))
|
||||
else:
|
||||
scores = F.softmax(scores.to(torch.float32), dim=-1)
|
||||
|
||||
if expert_bias is not None:
|
||||
_, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts)
|
||||
else:
|
||||
top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
|
||||
|
||||
# Normalize weights if using sigmoid
|
||||
if self.score_func == "sigmoid" and self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
|
||||
top_scores = top_scores * self.route_scale
|
||||
return top_scores, selected_experts
|
||||
|
||||
|
||||
class AfmoeMoE(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.router = AfmoeTokenChoiceRouter(config)
|
||||
|
||||
self.shared_experts = None
|
||||
if config.num_shared_experts > 0:
|
||||
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
|
||||
self.experts = nn.ModuleList(
|
||||
[AfmoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
|
||||
)
|
||||
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
|
||||
|
||||
def forward(self, hidden_states):
|
||||
batch_size, seq_len, hidden_dim = hidden_states.shape
|
||||
hidden_states_flat = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
# Get routing decisions
|
||||
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
|
||||
|
||||
# Process through shared experts
|
||||
if self.shared_experts is not None:
|
||||
shared_output = self.shared_experts(hidden_states_flat)
|
||||
else:
|
||||
shared_output = torch.zeros_like(hidden_states_flat)
|
||||
|
||||
# Reorder tokens by expert for efficient processing
|
||||
token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
|
||||
top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
|
||||
token_to_expert = selected_experts.view(-1)[token_indices_sorted]
|
||||
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
||||
|
||||
# Gather input tokens
|
||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
|
||||
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
|
||||
|
||||
routed_output = torch.zeros_like(routed_input)
|
||||
for expert_id in range(self.config.num_experts):
|
||||
mask = token_to_expert == expert_id
|
||||
if mask.any():
|
||||
expert_input = routed_input[mask]
|
||||
expert_out = self.experts[expert_id](expert_input)
|
||||
routed_output[mask] = expert_out
|
||||
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
|
||||
|
||||
# Scatter back to original positions
|
||||
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
|
||||
|
||||
return output.view(batch_size, seq_len, hidden_dim)
|
||||
|
||||
|
||||
class AfmoeAttention(nn.Module):
|
||||
"""Multi-headed attention with local/global pattern and gating."""
|
||||
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.num_key_value_heads = config.num_key_value_heads
|
||||
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
||||
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
|
||||
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
|
||||
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
past_key_value: Optional[Cache] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.Tensor:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
gate_states = self.gate_proj(hidden_states)
|
||||
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
if self.is_local_attention:
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
if past_key_value is not None:
|
||||
cache_kwargs = {"cache_position": cache_position}
|
||||
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
||||
|
||||
attention_interface: Callable = eager_attention_forward
|
||||
if self.config._attn_implementation != "eager":
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||
|
||||
output, _ = attention_interface(
|
||||
self,
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask=attention_mask,
|
||||
dropout=0.0 if not self.training else self.attention_dropout,
|
||||
scaling=self.scaling,
|
||||
sliding_window=self.sliding_window,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
output = output.view(*input_shape, -1).contiguous()
|
||||
output = output * F.sigmoid(gate_states)
|
||||
return self.o_proj(output)
|
||||
|
||||
|
||||
class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_idx = layer_idx
|
||||
|
||||
self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
|
||||
self.attention_type = config.layer_types[layer_idx]
|
||||
|
||||
# Dual normalization for attention
|
||||
self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# Dual normalization for FFN
|
||||
self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# MoE or dense FFN
|
||||
self.moe_enabled = layer_idx >= config.num_dense_layers
|
||||
if self.moe_enabled:
|
||||
self.mlp = AfmoeMoE(config)
|
||||
else:
|
||||
self.mlp = AfmoeMLP(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Cache] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
|
||||
# Self Attention with dual normalization
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_value,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# FFN with dual normalization
|
||||
residual = hidden_states
|
||||
hidden_states = self.pre_mlp_layernorm(hidden_states)
|
||||
|
||||
if self.moe_enabled:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
else:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
|
||||
hidden_states = self.post_mlp_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class AfmoePreTrainedModel(PreTrainedModel):
|
||||
config_class = AfmoeConfig
|
||||
base_model_prefix = "model"
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_keep_in_fp32_modules = [
|
||||
"input_layernorm",
|
||||
"post_attention_layernorm",
|
||||
"pre_mlp_layernorm",
|
||||
"post_mlp_layernorm",
|
||||
"q_norm",
|
||||
"k_norm",
|
||||
"norm",
|
||||
]
|
||||
_supports_sdpa = True
|
||||
_supports_attention_backend = True
|
||||
supports_gradient_checkpointing = True
|
||||
|
||||
|
||||
class AfmoeModel(AfmoePreTrainedModel):
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
|
||||
def __init__(self, config: AfmoeConfig):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if use_cache and past_key_values is None:
|
||||
past_key_values = DynamicCache()
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if cache_position is None:
|
||||
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
cache_position = torch.arange(
|
||||
past_seen_tokens,
|
||||
past_seen_tokens + inputs_embeds.shape[1],
|
||||
device=inputs_embeds.device,
|
||||
)
|
||||
if position_ids is None:
|
||||
position_ids = cache_position.unsqueeze(0)
|
||||
|
||||
# It may already have been prepared by e.g. `generate`
|
||||
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"cache_position": cache_position,
|
||||
"past_key_values": past_key_values,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
# Apply muP input scaling if enabled
|
||||
if self.config.mup_enabled:
|
||||
hidden_states = hidden_states * (self.config.hidden_size**0.5)
|
||||
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_values,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=past_key_values,
|
||||
)
|
||||
|
||||
|
||||
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_rep"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = AfmoeModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
# Initialize weights and apply final processing
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def get_output_embeddings(self):
|
||||
return self.lm_head
|
||||
|
||||
def set_output_embeddings(self, new_embeddings):
|
||||
self.lm_head = new_embeddings
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
|
||||
outputs: MoeModelOutputWithPast = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
# Only compute necessary logits
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
||||
|
||||
loss = None
|
||||
if labels is not None:
|
||||
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
||||
|
||||
return MoeCausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=outputs.hidden_states,
|
||||
attentions=outputs.attentions,
|
||||
router_logits=outputs.router_logits,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AfmoeForCausalLM",
|
||||
"AfmoeModel",
|
||||
"AfmoePreTrainedModel",
|
||||
]
|
||||
@@ -1,183 +0,0 @@
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeForCausalLM as PrimeRLAfmoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models.afmoe_hf_modeling.configuration_afmoe import AfmoeConfig
|
||||
from tests.unit.train.models.afmoe_hf_modeling.modeling_afmoe import (
|
||||
AfmoeForCausalLM as HFAfmoeForCausalLM,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.skip(reason="HF afmoe model does not support flash attention 2")]
|
||||
|
||||
|
||||
def get_model_pairs():
|
||||
hf_config = AfmoeConfig(
|
||||
architectures=["AfmoeForCausalLM"],
|
||||
attention_dropout=0.0,
|
||||
global_attn_every_n_layers=2,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
hidden_size=256,
|
||||
initializer_range=0.02,
|
||||
intermediate_size=512,
|
||||
layer_types=[
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
],
|
||||
load_balance_coeff=0.001,
|
||||
max_position_embeddings=512,
|
||||
moe_intermediate_size=128,
|
||||
mup_enabled=True,
|
||||
n_group=1,
|
||||
num_attention_heads=4,
|
||||
num_dense_layers=2,
|
||||
num_expert_groups=1,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
num_hidden_layers=4,
|
||||
num_key_value_heads=2,
|
||||
num_limited_groups=1,
|
||||
num_shared_experts=1,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_scaling=None,
|
||||
rope_theta=10000.0,
|
||||
route_norm=True,
|
||||
route_scale=2.826,
|
||||
score_func="sigmoid",
|
||||
sliding_window=128,
|
||||
tie_word_embeddings=False,
|
||||
topk_group=1,
|
||||
use_cache=True,
|
||||
use_grouped_mm=False,
|
||||
vocab_size=256,
|
||||
)
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
assert set(prime_state_keys) - set(state_dict.keys()) == set()
|
||||
return hf_model, prime_model
|
||||
|
||||
|
||||
class _IdentityMLP(nn.Identity):
|
||||
def forward(self, x, **kwargs):
|
||||
return super().forward(x)
|
||||
|
||||
|
||||
def test_afmoe_attn_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
for layer in hf_model.model.layers:
|
||||
layer.mlp = nn.Identity()
|
||||
for layer in prime_model.model.layers:
|
||||
layer.mlp = _IdentityMLP()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe_mlp_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
# HF AfmoeAttention.forward() returns a single tensor
|
||||
def identity_attn_hf(hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
||||
return hidden_states
|
||||
|
||||
# PrimeRL attention returns a tuple (output, attn_weights)
|
||||
def identity_attn_prime(hidden_states: torch.Tensor, *args, **kwargs) -> tuple[torch.Tensor, None]:
|
||||
return hidden_states, None
|
||||
|
||||
for layer in hf_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_hf
|
||||
for layer in prime_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_prime
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFAfmoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids=position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_afmoe()
|
||||
@@ -5,9 +5,8 @@ import torch.nn.functional as F
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
|
||||
from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model
|
||||
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ClampedSilu
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, GroupedGemmExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
@@ -69,7 +68,7 @@ def test_unselected_moe_uses_bf16_without_loading_compute_backend(selection, com
|
||||
pytest.param(GroupedExperts, {"activation": "relu2"}, True, "standard SwiGLU", id="relu2"),
|
||||
pytest.param(GroupedExperts, {"activation": "clamped_swiglu"}, True, "standard SwiGLU", id="clamped-swiglu"),
|
||||
pytest.param(GroupedExperts, {"bias": True}, True, "bias-free", id="bias"),
|
||||
pytest.param(DeepseekV4Experts, {"swiglu_limit": 10.0}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
pytest.param(GroupedExperts, {"activation": ClampedSilu(10.0)}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
],
|
||||
)
|
||||
def test_set_compute_validates_sonic_expert_structure(expert_cls, kwargs, fused, error):
|
||||
|
||||
@@ -5,7 +5,7 @@ from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from prime_rl.trainer.models import cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
|
||||
@@ -160,95 +160,6 @@ def test_fused_vs_vanilla_integration():
|
||||
torch.testing.assert_close(fused_out["entropy"], vanilla_entropy, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
@pytest.mark.gpu
|
||||
@pytest.mark.skip(reason="Produces NaNs in bf16 with FA3; needs investigation")
|
||||
def test_full_model_fused_vs_vanilla():
|
||||
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
|
||||
torch.manual_seed(123)
|
||||
|
||||
# Create tiny Qwen3 model for fast testing
|
||||
config = Qwen3Config(
|
||||
hidden_size=128,
|
||||
intermediate_size=256,
|
||||
max_position_embeddings=512,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=32,
|
||||
num_hidden_layers=2,
|
||||
vocab_size=1000,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_theta=10000.0,
|
||||
attention_bias=False,
|
||||
)
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
# Create two identical models
|
||||
model_vanilla = Qwen3ForCausalLM._from_config(config)
|
||||
model_fused = Qwen3ForCausalLM._from_config(config)
|
||||
|
||||
# Share weights between models
|
||||
model_fused.load_state_dict(model_vanilla.state_dict())
|
||||
|
||||
# Wrap with different LM heads
|
||||
inject_prime_lm_head(model_vanilla, chunk_size=None) # Vanilla
|
||||
inject_prime_lm_head(model_fused, chunk_size=32) # Fused with chunking
|
||||
|
||||
# Setup optimizers
|
||||
optimizer_vanilla = torch.optim.AdamW(model_vanilla.parameters(), lr=1e-4)
|
||||
optimizer_fused = torch.optim.AdamW(model_fused.parameters(), lr=1e-4)
|
||||
|
||||
# Run a few training steps
|
||||
num_steps = 3
|
||||
batch_size, seq_len = 2, 64
|
||||
temp_value = 1.5
|
||||
|
||||
for step in range(num_steps):
|
||||
# Generate random batch
|
||||
with torch.device("cuda"):
|
||||
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
|
||||
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
|
||||
temperature = torch.full((batch_size, seq_len), temp_value, dtype=torch.float32, device="cuda")
|
||||
seq_lens = torch.tensor([seq_len])
|
||||
|
||||
# Vanilla forward (returns logits, compute logprobs/entropy using RL train functions)
|
||||
optimizer_vanilla.zero_grad()
|
||||
out_vanilla = cast_float_and_contiguous(
|
||||
model_vanilla(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_vanilla.get("logprobs") is None:
|
||||
assert out_vanilla.get("logits") is not None
|
||||
logits = out_vanilla["logits"] / temp_value
|
||||
out_vanilla["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_vanilla["entropy"] = compute_entropy(logits)
|
||||
loss_vanilla = -out_vanilla["logprobs"].mean()
|
||||
loss_vanilla.backward()
|
||||
optimizer_vanilla.step()
|
||||
|
||||
# Fused forward (returns logprobs and entropy directly)
|
||||
optimizer_fused.zero_grad()
|
||||
out_fused = cast_float_and_contiguous(
|
||||
model_fused(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_fused.get("logprobs") is None:
|
||||
assert out_fused.get("logits") is not None
|
||||
logits = out_fused["logits"] / temp_value
|
||||
out_fused["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_fused["entropy"] = compute_entropy(logits)
|
||||
loss_fused = -out_fused["logprobs"].mean()
|
||||
loss_fused.backward()
|
||||
optimizer_fused.step()
|
||||
|
||||
# Compare outputs (should be very close since models started identical)
|
||||
torch.testing.assert_close(out_fused["logprobs"], out_vanilla["logprobs"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(out_fused["entropy"], out_vanilla["entropy"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(loss_fused, loss_vanilla, rtol=1e-3, atol=1e-4)
|
||||
|
||||
# After training, weights should still be close (optimizer steps should be similar)
|
||||
for (name_v, param_v), (name_f, param_f) in zip(model_vanilla.named_parameters(), model_fused.named_parameters()):
|
||||
if "lm_head" not in name_v: # Compare non-lm_head params
|
||||
torch.testing.assert_close(param_f, param_v, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
def test_fused_lm_head_correct_shift():
|
||||
"""
|
||||
End-to-end test that the fused LM head with shifted labels, after shift_tensor_right,
|
||||
|
||||
@@ -69,61 +69,6 @@ def test_model_with_position_ids(model):
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Sequence packing for Qwen not working.")
|
||||
@pytest.mark.parametrize("correct_position_ids", [True, False])
|
||||
def test_model_with_sequence_packing(model, correct_position_ids):
|
||||
"""
|
||||
The goal of this test is to check that the sequence packing works correctly.
|
||||
|
||||
The idea is that is to check that the logits is the same when doing
|
||||
|
||||
[B, seq] and doing [1, B*seq] with the proper masking.
|
||||
|
||||
"""
|
||||
if model.config.attn != "flash_attention_2":
|
||||
pytest.skip("Test only works with flash attention")
|
||||
|
||||
model = model.to("cuda")
|
||||
inputs = [0, 1, 2, 3]
|
||||
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.Tensor(inputs).repeat(1, 1).int().to("cuda")
|
||||
outputs = model(input_ids=inputs_ids, seq_lens=torch.tensor([len(inputs)], device="cuda"))
|
||||
output_base = outputs["logits"]
|
||||
|
||||
assert output_base.shape == (1, len(inputs), model.config.vocab_size)
|
||||
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.Tensor(inputs + inputs).repeat(1, 1).int().to("cuda")
|
||||
if correct_position_ids:
|
||||
position_ids = torch.Tensor([0, 1, 2, 3, 0, 1, 2, 3]).repeat(1, 1).int().to("cuda")
|
||||
# should work
|
||||
else:
|
||||
position_ids = torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7]).repeat(1, 1).int().to("cuda")
|
||||
# should fail
|
||||
outputs = model(
|
||||
input_ids=inputs_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([len(inputs), len(inputs)], device="cuda"),
|
||||
)
|
||||
outputs_packed = outputs["logits"]
|
||||
|
||||
assert outputs_packed.shape == (1, 2 * len(inputs), model.config.vocab_size)
|
||||
|
||||
output_packed_left = outputs_packed[:, : len(inputs), :]
|
||||
output_packed_right = outputs_packed[:, len(inputs) :, :]
|
||||
|
||||
assert output_packed_left.shape == output_base.shape == output_packed_right.shape
|
||||
|
||||
if correct_position_ids:
|
||||
torch.testing.assert_close(output_packed_left, output_base)
|
||||
torch.testing.assert_close(output_packed_right, output_base)
|
||||
else:
|
||||
torch.testing.assert_close(output_packed_left, output_base)
|
||||
with pytest.raises(AssertionError):
|
||||
torch.testing.assert_close(output_packed_right, output_base)
|
||||
|
||||
|
||||
def test_moe_custom_impl():
|
||||
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="flash_attention_2")
|
||||
model = get_model(config)
|
||||
@@ -136,19 +81,3 @@ def test_moe_custom_impl():
|
||||
logits = outputs["logits"]
|
||||
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="need special token for meta stuff in ci")
|
||||
@pytest.mark.parametrize("model_name", ["meta-llama/Llama-3.2-1B-Instruct"])
|
||||
def test_model_forward_custom_impl(model_name):
|
||||
config = ModelConfig(name=model_name, attn="flash_attention_2")
|
||||
model = get_model(config)
|
||||
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
model = model.to("cuda")
|
||||
with torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
|
||||
outputs = model(input_ids=inputs_ids, seq_lens=torch.tensor([SEQ_LEN], device="cuda"))
|
||||
logits = outputs["logits"]
|
||||
|
||||
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import multiprocessing as mp
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.inference.vllm.worker.nccl import NCCLWeightBroadcastReceiver
|
||||
from prime_rl.transports.weights.nccl import NCCLBroadcaster
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
@pytest.mark.skip(reason="Skipping NCCL broadcast as it fail only in ci")
|
||||
def test_nccl_broadcast(free_port):
|
||||
host = "localhost"
|
||||
free_port = free_port()
|
||||
|
||||
def send():
|
||||
device = torch.device(f"cuda:{0}")
|
||||
nccl_broadcast = NCCLBroadcaster(host=host, port=free_port, rank=0, world_size=2, device=device, timeout=10)
|
||||
|
||||
class SubModel(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.layers = torch.nn.ModuleList([torch.nn.Linear(10, 10) for _ in range(10)])
|
||||
|
||||
def forward(self, x):
|
||||
for layer in self.layers:
|
||||
x = layer(x)
|
||||
return x
|
||||
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.model = SubModel()
|
||||
|
||||
def forward(self, x):
|
||||
return self.model(x)
|
||||
|
||||
model = Model().to(device)
|
||||
for param in model.parameters():
|
||||
param.data = torch.ones_like(param.data)
|
||||
|
||||
nccl_broadcast.send(model)
|
||||
|
||||
def receive():
|
||||
device = torch.device(f"cuda:{1}")
|
||||
nccl_broadcast = NCCLWeightBroadcastReceiver(
|
||||
host=host, port=free_port, rank=1, world_size=2, device=device, timeout=10
|
||||
)
|
||||
|
||||
for key, value in nccl_broadcast.receive_state_dict():
|
||||
assert value.allclose(torch.ones_like(value))
|
||||
|
||||
processes = [mp.Process(target=send), mp.Process(target=receive)]
|
||||
|
||||
for process in processes:
|
||||
process.start()
|
||||
|
||||
for process in processes:
|
||||
process.join()
|
||||
assert process.exitcode == 0, f"Process {process.name} exited with code {process.exitcode}"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user