Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3587b285f5 | ||
|
|
f3827c4ed2 | ||
|
|
93a0fe0d6b | ||
|
|
db2c00e9ed | ||
|
|
4250d895bc | ||
|
|
78bc69ccc4 | ||
|
|
81052082a9 | ||
|
|
b9c0bfe87b | ||
|
|
51879014fc | ||
|
|
52e985ae9d | ||
|
|
63b3e85864 | ||
|
|
7133f8f8f2 | ||
|
|
b029ef253e | ||
|
|
eae8bd9462 | ||
|
|
c8af127357 | ||
|
|
2b688edcf6 | ||
|
|
883b8f32c5 | ||
|
|
407e8ba223 | ||
|
|
cf9962c13b |
+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
-77
@@ -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,50 +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 --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 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 --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);
|
||||
@@ -184,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
|
||||
|
||||
@@ -262,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
|
||||
@@ -282,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"
|
||||
@@ -303,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
|
||||
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"]
|
||||
|
||||
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`.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,9 +481,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."""
|
||||
|
||||
|
||||
class ConcurrencyConfig(BaseConfig):
|
||||
"""Adaptive in-flight concurrency control. The orchestrator sizes the
|
||||
|
||||
@@ -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``."""
|
||||
|
||||
@@ -22,6 +22,7 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
|
||||
DSABackend: TypeAlias = Literal["tilelang", "cudnn_flashmla"]
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
@@ -325,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."""
|
||||
@@ -462,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"
|
||||
|
||||
@@ -499,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):
|
||||
@@ -517,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."""
|
||||
|
||||
@@ -699,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
-5
@@ -16,7 +16,7 @@ dependencies = [
|
||||
"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",
|
||||
@@ -53,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'",
|
||||
@@ -94,6 +96,9 @@ 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 = [
|
||||
@@ -107,6 +112,7 @@ all = [
|
||||
"prime-rl[sonic-moe]",
|
||||
"prime-rl[flash-attn-3]",
|
||||
"prime-rl[flash-attn-cute]",
|
||||
"prime-rl[flash-mla]",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
@@ -141,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",
|
||||
@@ -223,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 —
|
||||
@@ -246,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 }
|
||||
@@ -271,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'" },
|
||||
@@ -286,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,7 +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 )
|
||||
--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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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,7 +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.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
@@ -242,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}")
|
||||
@@ -290,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,
|
||||
)
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -41,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"),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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])
|
||||
@@ -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
|
||||
@@ -340,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"):
|
||||
@@ -354,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},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -394,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}"
|
||||
@@ -17,26 +17,28 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
verifiers = false
|
||||
prime-pydantic-config = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
prime-traces = false
|
||||
vllm-router = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
dion = false
|
||||
fastokens = false
|
||||
prime-runs = false
|
||||
flash-attn-3 = false
|
||||
prime-tunnel = false
|
||||
deep-gemm = false
|
||||
prime-evals = false
|
||||
torchao = false
|
||||
tokenspeed-mla = false
|
||||
flash-mla = false
|
||||
flashinfer-python = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
nixl-cu13 = false
|
||||
deep-ep = false
|
||||
prime-sandboxes = false
|
||||
renderers = false
|
||||
prime-kernels = false
|
||||
prime = false
|
||||
prime-evals = false
|
||||
prime-kernels = false
|
||||
prime-pydantic-config = false
|
||||
prime-runs = false
|
||||
prime-sandboxes = false
|
||||
prime-traces = false
|
||||
prime-tunnel = false
|
||||
renderers = false
|
||||
tokenspeed-mla = false
|
||||
torchao = false
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
|
||||
[manifest]
|
||||
members = [
|
||||
@@ -1860,9 +1862,17 @@ dependencies = [
|
||||
{ name = "transformers" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flash-mla"
|
||||
version = "1.0.0+cu.13.0.torch.2.13.b7643bd"
|
||||
source = { 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" }
|
||||
wheels = [
|
||||
{ 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", hash = "sha256:0bdb32340979c739659b305537dbe0445ba9f3148a4ce2f97f4fd170887c01e4" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flashinfer-python"
|
||||
version = "0.6.18.post1"
|
||||
version = "0.7.0.post1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -1870,6 +1880,7 @@ dependencies = [
|
||||
{ name = "cuda-python" },
|
||||
{ name = "cuda-tile" },
|
||||
{ name = "einops" },
|
||||
{ name = "nccl-extensions" },
|
||||
{ name = "nccl4py" },
|
||||
{ name = "ninja" },
|
||||
{ name = "numpy" },
|
||||
@@ -1882,9 +1893,9 @@ dependencies = [
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "tqdm" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/ad/7e/a756567c193b2af546f98c08158505e998c2dd4a7f8fc6fe6c72105dce8b/flashinfer_python-0.6.18.post1.tar.gz", hash = "sha256:1ebfb8ff3fa3a896e5abbd0dec123a5f3e3734029871349dad6968b252b82097", size = 13294037, upload-time = "2026-09-05T03:26:09.049Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/14/b0/2f27f2645056b0e671b3bcf8a934e73ed89ca5c5df9ebe651f21c0d218e2/flashinfer_python-0.7.0.post1.tar.gz", hash = "sha256:2e67b38a9af1d4eedff96f7f5d79c6a4d9f0f97cb4a30f71e4ffd717f1ad9af4", size = 26061698, upload-time = "2026-09-29T23:34:14.797Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/3f/bd0a74bfbb4f3813bfe61267ff696fb229ab70c0f1f44848287221928c95/flashinfer_python-0.6.18.post1-py3-none-any.whl", hash = "sha256:adb6d2952b47131138e108bd2999b1fe18b71f1a4c0b2684f168753db9563991", size = 18348022, upload-time = "2026-09-05T03:26:06.084Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/00/7d/16237087a2af99086ef4ae9808dff9b24f0a4db4cfd673233836821a32e0/flashinfer_python-0.7.0.post1-py3-none-any.whl", hash = "sha256:c7adf826568d61fc1b7d3aadd4cae387a35a138bfc08e2deca2f34ecfa280716", size = 33659854, upload-time = "2026-09-29T23:34:11.137Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2450,23 +2461,22 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "humming-kernels"
|
||||
version = "0.1.12"
|
||||
version = "0.1.16"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-bindings" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "numpy" },
|
||||
{ name = "nvidia-ml-py" },
|
||||
{ name = "safetensors" },
|
||||
{ name = "tabulate" },
|
||||
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
|
||||
{ name = "tqdm" },
|
||||
{ name = "triton" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/93/b9/53797fff4b1b31b4567453a365646d724469b1bb0d76c07f8746617d0cb6/humming_kernels-0.1.12.tar.gz", hash = "sha256:c96c37c95f74379067d2d2d0c5154d12ee9a8cfa29a7c3370a7f3e34f207ca72", size = 259323, upload-time = "2026-07-31T14:28:23.124Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/70/d2/e286acb9f594f998bbc2d99617966a4f01a603c699d829793a86a42c2440/humming_kernels-0.1.16.tar.gz", hash = "sha256:a5356a63c4adf6c16c46f541749dec90fc2d49cf29ebc33ac05e23c744731809", size = 317590, upload-time = "2026-09-22T02:41:16.516Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/58/0f/01f871dc26f8d7e1683df9464890d48cfd5c4e46c4a264d7ee0868749197/humming_kernels-0.1.12-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:988e8b9da41e3679ae2816bdfb51acab53c05cc56254b5ca98e847f4efcf24fd", size = 318019, upload-time = "2026-07-31T14:28:19.925Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/a2/f96912ee7d68f56e61c15555657ffa057b8afbaa21241c63342b5969bb74/humming_kernels-0.1.12-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:cd3ef712a93f3a9075ea99de2c72bcd3ec89dab3759b3a248d869f5507b60331", size = 322656, upload-time = "2026-07-31T14:28:21.511Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/47/43794faeb47fe2067bef5c7d830fac4244bf872625b0bfddf116fd7a0a0d/humming_kernels-0.1.16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:fa1a86e31fc3c0fede5bceb3dc2f088e6bdda636a8f405fd71def853f12049e1", size = 417732, upload-time = "2026-09-22T02:41:12.611Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a2/7f/08aad5a947d549aa21af5b93e711aad3d5689d39e8439c7fa72eab9773de/humming_kernels-0.1.16-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:683212692f5e1339961e4322aff1ba116523e2681b2aafeaf7c081bc4e1f5627", size = 426040, upload-time = "2026-09-22T02:41:14.541Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -3801,6 +3811,22 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/b6/e7cdde7b8e90d5dff25b622f95833ef26567ad184c977278b93a1cbd5717/narwhals-2.22.0-py3-none-any.whl", hash = "sha256:1421797ede01789cc1537619dbc3f36f840737240f748fdb24a60a0225fc80be", size = 453815, upload-time = "2026-06-01T13:34:34.127Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nccl-extensions"
|
||||
version = "0.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cuda-core" },
|
||||
{ name = "cuda-pathfinder" },
|
||||
{ name = "nccl4py" },
|
||||
{ name = "numpy" },
|
||||
{ name = "packaging" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/24/77/a02842f3e7d6aef181733f94d313a1ff4b3db2726e2c067d7946e8f34cc3/nccl_extensions-0.1.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d85e203e284b50dad3846d6fb0d35560378537689f23d92a16c67f7d854025d7", size = 22282239, upload-time = "2026-09-02T15:38:26.362Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f3/3c/b043c1f8ca2766d48e30e9cc5a0d65d51aef77e3a8d18dbbaa95fd5386e2/nccl_extensions-0.1.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:54d46bee108f0bc18cdc35dbe17bba6452d6a38a270fa5e8ccde03267460fa87", size = 22589285, upload-time = "2026-09-02T15:38:53.213Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nccl4py"
|
||||
version = "0.4.1"
|
||||
@@ -4045,11 +4071,15 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "nvidia-cudnn-frontend"
|
||||
version = "1.25.0"
|
||||
version = "1.30.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
{ name = "nvidia-cutlass-dsl" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/28/0f/df39a194f2529093db737d43cc4cbf594c6a79712a09aa104b999e4d95d4/nvidia_cudnn_frontend-1.25.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09e6e1bc48ce1235743f89d8ea699c52b3008fd6dae7f2ecadb744bebf272a2b", size = 3263306, upload-time = "2026-06-10T21:07:48.093Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/03/65/3b45941d8a22128b971e910f2e9af6bf5ef453e92cc329c56b6eb53c53de/nvidia_cudnn_frontend-1.25.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a94a72d736bd79eb35f451aaf26d9493778e02ecabccc92c05425508c9e7a83", size = 3414884, upload-time = "2026-06-10T21:08:08.603Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e4/53/07836d9f74f1416a8768530d428c155f67d7728f283bce3a9b3096b7e18f/nvidia_cudnn_frontend-1.30.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:279d227a226429288ae9e4e88db744ce144ae69605f63a286dc84ae180869a6e", size = 8631629, upload-time = "2026-09-23T03:44:15.265Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ee/95/c92076af7561e6e43da1ee3ac4155202dcd3876e5b999ff0dea5754eb3d2/nvidia_cudnn_frontend-1.30.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5dda72db38ea0c39f158ebffa9596eefab21ce7cc6a12824490ab8b6cb60e76d", size = 8797507, upload-time = "2026-09-23T03:44:35.051Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4551,6 +4581,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/e5/4d2d8af06f788329b4f78f8cc3679bb395392fcaa1e4d8d3c33e85308fa4/orjson-3.11.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:71e63adb0e1f1ed5d9e168f50a91ceb93ae6420731d222dc7da5c69409aa47aa", size = 136943, upload-time = "2026-05-06T15:10:14.405Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oss-harmony"
|
||||
version = "0.0.11"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/43/88/ca56e5b17df4763bbb552c7be3abe432b51db3c51f6327a3848b88ad7c08/oss_harmony-0.0.11.tar.gz", hash = "sha256:ccad467b71d61490df1f2204b7a064990833338615ac135536c5b3a8e2d03a15", size = 2198780, upload-time = "2026-05-13T20:49:11.767Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/e9/0b33d4c592e1422c9faeaf1cfe10731328ecf3504e900dc7921109affd55/oss_harmony-0.0.11-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f1f74ef7f8be32fa1dcfe1644839af5f0873acce78b5668c2aa39f26d83218ff", size = 3493239, upload-time = "2026-05-13T20:48:49.588Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/89/68/001d7429a692b2db0c03bd49b756f834716b64afc0bbbece96824e8f0af8/oss_harmony-0.0.11-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d877c6b526cdbdf55068bae8f05c60398e929c9e296c7f69a1d533339708be80", size = 3567858, upload-time = "2026-05-13T20:48:57.904Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4b/c9/720aed1527d87f82e07a7f35c3c81c6d9198a8d1223bdbd298b3c66a72db/oss_harmony-0.0.11-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:036505bfb39c6b50edcf717349518d269bb375207f7f8e95f517e938b8f2e0c8", size = 3695703, upload-time = "2026-05-13T20:49:02.857Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/9a/ad24d20ea1e8b3167744f5d357d48a116086258ca58540986a0896781864/oss_harmony-0.0.11-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0d1545203973abb3002dcc6c5cffd14ca4a376b655c14ce190c78eb6aaf5f6fd", size = 3807882, upload-time = "2026-05-13T20:49:09.767Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "outlines-core"
|
||||
version = "0.2.14"
|
||||
@@ -4983,11 +5028,13 @@ all = [
|
||||
{ name = "flash-attn-3", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux'" },
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "quack-kernels", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
@@ -5001,8 +5048,8 @@ all = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { 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' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { 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' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.2", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm-router", version = "0.2.2", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
@@ -5032,6 +5079,9 @@ flash-attn-3 = [
|
||||
flash-attn-cute = [
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux'" },
|
||||
]
|
||||
flash-mla = [
|
||||
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
]
|
||||
gpu = [
|
||||
{ name = "dion", marker = "sys_platform == 'linux'" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux'" },
|
||||
@@ -5039,6 +5089,7 @@ gpu = [
|
||||
{ name = "modelexpress", marker = "sys_platform == 'linux'" },
|
||||
{ name = "mooncake-transfer-engine", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux'" },
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux'" },
|
||||
{ name = "ring-flash-attn", marker = "sys_platform == 'linux'" },
|
||||
{ name = "tilelang" },
|
||||
@@ -5050,8 +5101,8 @@ gpu = [
|
||||
{ name = "torchdata", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchtitan", marker = "sys_platform == 'linux'" },
|
||||
{ name = "torchvision", marker = "sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.30.0", source = { 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' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "vllm", version = "0.31.0", source = { 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' and sys_platform == 'linux'" },
|
||||
]
|
||||
kernels = [
|
||||
{ name = "prime-kernels", version = "0.1.0+cu130torch2.13.0", source = { 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 != 'x86_64' and sys_platform == 'linux'" },
|
||||
@@ -5094,6 +5145,7 @@ requires-dist = [
|
||||
{ name = "flash-attn-3", marker = "sys_platform == 'linux' and extra == 'flash-attn-3'", index = "https://download.pytorch.org/whl/test/cu130" },
|
||||
{ name = "flash-attn-4", marker = "sys_platform == 'linux' and extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=0251105" },
|
||||
{ name = "flash-linear-attention", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "flash-mla", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == '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" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "mamba-ssm", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/state-spaces/mamba?rev=f577286" },
|
||||
@@ -5103,6 +5155,7 @@ requires-dist = [
|
||||
{ name = "nixl", marker = "sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "nixl-cu13", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = "==0.10.1" },
|
||||
{ name = "numpy", specifier = ">=2.2.6" },
|
||||
{ name = "nvidia-cudnn-frontend", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=1.30.0" },
|
||||
{ name = "nvidia-ml-py", marker = "sys_platform == 'linux' and extra == 'gpu'", specifier = ">=12.575.51" },
|
||||
{ name = "openai", specifier = ">=1.106.1" },
|
||||
{ name = "orjson", specifier = ">=3.11.0" },
|
||||
@@ -5115,11 +5168,12 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["flash-attn"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["flash-attn-3"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["flash-attn-cute"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["flash-mla"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["sonic-moe"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.4" },
|
||||
{ name = "prometheus-client", specifier = ">=0.20.0" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
@@ -5145,16 +5199,16 @@ requires-dist = [
|
||||
{ name = "uvicorn", marker = "extra == 'dashboard'", specifier = ">=0.30" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.30.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", specifier = ">=0.31.0" },
|
||||
{ name = "vllm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'gpu'", url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl" },
|
||||
{ name = "vllm-router", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
|
||||
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ name = "wandb-workspaces", specifier = ">=0.4.3" },
|
||||
]
|
||||
provides-extras = ["gpu", "dashboard", "dynamo", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "quack", "sonic-moe", "kernels", "all"]
|
||||
provides-extras = ["gpu", "dashboard", "dynamo", "flash-attn", "flash-attn-3", "flash-attn-cute", "disagg", "quack", "sonic-moe", "flash-mla", "kernels", "all"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
@@ -5192,15 +5246,15 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-runs"
|
||||
version = "0.1.3"
|
||||
version = "0.1.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-traces" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3f/ba/3d38aeafc0ef885eef7b99bbe26fe350b4248af8d3fa89d4ca8a249f0f04/prime_runs-0.1.3.tar.gz", hash = "sha256:181ab1c720ed9113abbf3719ba6863c9ee23c55309101c0b7f4021ff9dafbe20", size = 65541, upload-time = "2026-09-17T15:31:42.319Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6c/de/6fb503ce854315d096982b79340b02eb5a978b139a7c719d39df77e7f211/prime_runs-0.1.4.tar.gz", hash = "sha256:f06c2bc7db28f0ed99ca6b06aa5186245ca94009872eb861ab0be7cff25484bd", size = 67282, upload-time = "2026-10-08T00:23:59.354Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6e/93/5fff685470a6cb12fc93192432951a081de70e271aef1cebc506fba4ccc5/prime_runs-0.1.3-py3-none-any.whl", hash = "sha256:86c3d5183ed5848854a194233b4a9451deabea56a9063771244c5c54c00d69df", size = 45087, upload-time = "2026-09-17T15:31:40.913Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/51/8f300ac057c95afa9df591172b2e8374743afdeeae300771fd78c91a5f75/prime_runs-0.1.4-py3-none-any.whl", hash = "sha256:f33b477c2d53eca08524a3d469810943eee31af8f60ceffc38ef2b9c90596d1b", size = 46253, upload-time = "2026-10-08T00:23:57.736Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -7791,8 +7845,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
version = "0.31.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -7830,12 +7884,12 @@ dependencies = [
|
||||
{ name = "nvidia-cutlass-dsl" },
|
||||
{ name = "nvtx" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "opencv-python-headless" },
|
||||
{ name = "opentelemetry-api" },
|
||||
{ name = "opentelemetry-exporter-otlp" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai" },
|
||||
{ name = "oss-harmony" },
|
||||
{ name = "outlines-core" },
|
||||
{ name = "partial-json-parser" },
|
||||
{ name = "pillow" },
|
||||
@@ -7874,7 +7928,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:eb3e11bab695d085098579a6eda2d602419adec3826ebfbcce9a3ffa543eb62e" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:56edd19c798510b6da5ae4dd38b3bdf55ea7ae261b339a906df006dc3faf751d" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -7896,10 +7950,10 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.7.0.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.16" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
|
||||
@@ -7921,7 +7975,6 @@ requires-dist = [
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
{ name = "opentelemetry-api", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
@@ -7931,6 +7984,7 @@ requires-dist = [
|
||||
{ name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", specifier = ">=0.4.1" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", marker = "extra == 'otel'", specifier = ">=0.4.1" },
|
||||
{ name = "oss-harmony", specifier = ">=0.0.11" },
|
||||
{ name = "outlines-core", specifier = "==0.2.14" },
|
||||
{ name = "pandas", marker = "extra == 'bench'" },
|
||||
{ name = "partial-json-parser" },
|
||||
@@ -7938,7 +7992,8 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine != 's390x'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine == 's390x'", specifier = "==7.36.1" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
{ name = "pybase64" },
|
||||
@@ -7973,19 +8028,19 @@ requires-dist = [
|
||||
{ name = "torchcodec", specifier = ">=0.14" },
|
||||
{ name = "torchvision", specifier = "==0.28.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=5.10.4" },
|
||||
{ name = "transformers", specifier = ">=5.10.4,<5.18.0" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = "==0.2.7" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.1" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "deepstream", "flashinfer", "b12x", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
[[package]]
|
||||
name = "vllm"
|
||||
version = "0.30.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
version = "0.31.0"
|
||||
source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
@@ -8023,12 +8078,12 @@ dependencies = [
|
||||
{ name = "nvidia-cutlass-dsl" },
|
||||
{ name = "nvtx" },
|
||||
{ name = "openai" },
|
||||
{ name = "openai-harmony" },
|
||||
{ name = "opencv-python-headless" },
|
||||
{ name = "opentelemetry-api" },
|
||||
{ name = "opentelemetry-exporter-otlp" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai" },
|
||||
{ name = "oss-harmony" },
|
||||
{ name = "outlines-core" },
|
||||
{ name = "partial-json-parser" },
|
||||
{ name = "pillow" },
|
||||
@@ -8067,7 +8122,7 @@ dependencies = [
|
||||
{ name = "xgrammar" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ef52ee58c410ead0b8afb190838fa4cbcb52075596f67862a03859d984966ac4" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:39132b433967f0962d03d8a5f633b9bee6b32708f566c7d5637b79f8d0ef3433" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -8089,10 +8144,10 @@ requires-dist = [
|
||||
{ name = "fastsafetensors", specifier = ">=0.3.3" },
|
||||
{ name = "fastsafetensors", marker = "extra == 'fastsafetensors'", specifier = ">=0.3.3" },
|
||||
{ name = "filelock", specifier = ">=3.16.1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.6.18.post1" },
|
||||
{ name = "flashinfer-python", specifier = "==0.7.0.post1" },
|
||||
{ name = "helion", marker = "extra == 'helion'", specifier = "==1.4.0" },
|
||||
{ name = "huggingface-hub", specifier = ">=1.31.0" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.12" },
|
||||
{ name = "humming-kernels", extras = ["cu13"], specifier = "==0.1.16" },
|
||||
{ name = "ijson" },
|
||||
{ name = "instanttensor", specifier = ">=0.1.9" },
|
||||
{ name = "instanttensor", marker = "extra == 'instanttensor'", specifier = ">=0.1.9" },
|
||||
@@ -8114,7 +8169,6 @@ requires-dist = [
|
||||
{ name = "nvidia-deepstream-videodecode-cu13", marker = "extra == 'deepstream'", specifier = ">=9.0.2" },
|
||||
{ name = "nvtx", specifier = "==0.2.15" },
|
||||
{ name = "openai", specifier = ">=2.25.0" },
|
||||
{ name = "openai-harmony", specifier = ">=0.0.3" },
|
||||
{ name = "opencv-python-headless", specifier = ">=4.13.0" },
|
||||
{ name = "opentelemetry-api", specifier = ">=1.27.0" },
|
||||
{ name = "opentelemetry-api", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
@@ -8124,6 +8178,7 @@ requires-dist = [
|
||||
{ name = "opentelemetry-sdk", marker = "extra == 'otel'", specifier = ">=1.26.0" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", specifier = ">=0.4.1" },
|
||||
{ name = "opentelemetry-semantic-conventions-ai", marker = "extra == 'otel'", specifier = ">=0.4.1" },
|
||||
{ name = "oss-harmony", specifier = ">=0.0.11" },
|
||||
{ name = "outlines-core", specifier = "==0.2.14" },
|
||||
{ name = "pandas", marker = "extra == 'bench'" },
|
||||
{ name = "partial-json-parser" },
|
||||
@@ -8131,7 +8186,8 @@ requires-dist = [
|
||||
{ name = "plotly", marker = "extra == 'bench'" },
|
||||
{ name = "prometheus-client", specifier = ">=0.18.0" },
|
||||
{ name = "prometheus-fastapi-instrumentator", specifier = ">=8.0.0" },
|
||||
{ name = "protobuf", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine != 's390x'", specifier = ">=5.29.6,!=6.30.*,!=6.31.*,!=6.32.*,!=6.33.0.*,!=6.33.1.*,!=6.33.2.*,!=6.33.3.*,!=6.33.4.*" },
|
||||
{ name = "protobuf", marker = "platform_machine == 's390x'", specifier = "==7.36.1" },
|
||||
{ name = "psutil" },
|
||||
{ name = "py-cpuinfo" },
|
||||
{ name = "pybase64" },
|
||||
@@ -8166,12 +8222,12 @@ requires-dist = [
|
||||
{ name = "torchcodec", specifier = ">=0.14" },
|
||||
{ name = "torchvision", specifier = "==0.28.0" },
|
||||
{ name = "tqdm" },
|
||||
{ name = "transformers", specifier = ">=5.10.4" },
|
||||
{ name = "transformers", specifier = ">=5.10.4,<5.18.0" },
|
||||
{ name = "typing-extensions", specifier = ">=4.10" },
|
||||
{ name = "vllm-gguf-plugin", marker = "extra == 'extra-quant'", specifier = ">=0.0.2" },
|
||||
{ name = "watchfiles" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = ">=0.2.1,<1.0.0" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.0" },
|
||||
{ name = "xgrammar", marker = "platform_machine == 'aarch64' or platform_machine == 'arm64' or platform_machine == 'ppc64le' or platform_machine == 's390x' or platform_machine == 'x86_64'", specifier = "==0.2.7" },
|
||||
{ name = "zentorch", marker = "extra == 'zen'", specifier = "==2.13.0.1" },
|
||||
]
|
||||
provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttensor", "runai", "audio", "video", "deepstream", "flashinfer", "b12x", "helion", "grpc", "otel", "extra-quant"]
|
||||
|
||||
@@ -8473,7 +8529,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "xgrammar"
|
||||
version = "0.2.1"
|
||||
version = "0.2.7"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi" },
|
||||
@@ -8484,10 +8540,10 @@ dependencies = [
|
||||
{ name = "triton", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d8/ea/6394caddd078d33772070eefaaf77cb0a826a3047b908b688dece7d040b5/xgrammar-0.2.1.tar.gz", hash = "sha256:4c48c251b75d211e9ffa7f4f4ac8b5b0164f89fd5f0d1883ad7ff4554922030d", size = 2427065, upload-time = "2026-05-17T21:39:26.576Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/81/e8/21a1661542d541c3c11e56062a213f6405824845a7fc8d3874447d5c6775/xgrammar-0.2.7.tar.gz", hash = "sha256:7674afeee5e6eff9672627b62d5ab0aa2347ea51674f4d78a5c160029f92bc3e", size = 2663916, upload-time = "2026-09-15T15:51:07.444Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/44/60/7c6194b66e043f36a7fbdbf7e6e0e4c94b151f7e53ad1b197f53e711f5d1/xgrammar-0.2.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9e8dd9853958a263b4015ce79133a0ff4eaa9d22ef781fb2350c7dfc40c2c012", size = 44218929, upload-time = "2026-05-17T21:37:56.155Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/96/4b/327b3cf702b685a2be28d15490faa4beeac00c4fbcf9bb2d7db0fda32931/xgrammar-0.2.1-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cbc6014dc1c92fc317b14519121c8163fe35fd934179e5a45d83f780ff231826", size = 44678489, upload-time = "2026-05-17T21:38:00.791Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/35/5d56e9dbe6f0ccefebcb5212b7ded0af17bec7f2d148dd6403c7d247d063/xgrammar-0.2.7-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2df1a2292f6b1c5cdc4b176ef2f22c58a837ac99fd854d93856160f31f14a4b0", size = 1113117, upload-time = "2026-09-15T15:50:26.492Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/f2/cb90cfbcca316b3fa98b0928ec989f3fb75f6439bc5269c5c2121d361301/xgrammar-0.2.7-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4397798f73512ab5abccbadf0a7b6aaf0753ccc4f3171c43b14c4d22df1ed28", size = 1265122, upload-time = "2026-09-15T15:50:28.098Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user