Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f87ebcc239 | ||
|
|
866c3e1438 | ||
|
|
c176840626 | ||
|
|
bb0c103f08 | ||
|
|
3fc28ddfb3 | ||
|
|
eaad03b9df | ||
|
|
70117046ac | ||
|
|
b2c6fe9aec | ||
|
|
66e1c2cb07 |
@@ -1,155 +0,0 @@
|
||||
name: Build Kernels
|
||||
|
||||
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
|
||||
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
|
||||
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
|
||||
# skill).
|
||||
#
|
||||
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
|
||||
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
|
||||
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
|
||||
#
|
||||
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "deps/prime-kernels"
|
||||
- ".gitmodules"
|
||||
- ".github/workflows/build_kernels.yaml"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
|
||||
required: false
|
||||
type: string
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Release tag to attach the wheels to. The release may still be a draft."
|
||||
required: false
|
||||
type: string
|
||||
ref:
|
||||
description: "Ref to build the kernels from. Empty = the caller's ref."
|
||||
required: false
|
||||
type: string
|
||||
|
||||
env:
|
||||
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
|
||||
# the job container image below must be edited alongside it (no env context there).
|
||||
CUDA_TAG: cu128
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build wheel (${{ matrix.arch }})
|
||||
# Uploading the wheels to a release needs write; on workflow_call the caller
|
||||
# must grant it too (tag-and-release.yaml does).
|
||||
permissions:
|
||||
contents: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- runner: image-builder
|
||||
arch: x86_64
|
||||
- runner: image-builder-arm-2204
|
||||
arch: aarch64
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
|
||||
steps:
|
||||
- name: Install build tooling
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
|
||||
- name: Init the kernels submodule
|
||||
run: |
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
git submodule update --init -- deps/prime-kernels
|
||||
|
||||
- name: Install uv
|
||||
run: |
|
||||
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
|
||||
uv --version
|
||||
|
||||
# The wheel only imports under the exact torch it was compiled against, so build
|
||||
# against the torch prime-rl resolves rather than whatever is newest today.
|
||||
- name: Create build environment
|
||||
env:
|
||||
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
|
||||
run: |
|
||||
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
|
||||
if [ -z "$TORCH_PIN" ]; then
|
||||
echo "Could not read torch's version from uv.lock" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Building against torch==$TORCH_PIN"
|
||||
uv venv --python 3.12 /tmp/build-env
|
||||
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
|
||||
|
||||
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
|
||||
# the wheel carries both in its local version.
|
||||
- name: Stamp ABI into the version
|
||||
run: |
|
||||
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
|
||||
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
|
||||
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
|
||||
grep '^version' deps/prime-kernels/pyproject.toml
|
||||
|
||||
- name: Build wheel
|
||||
env:
|
||||
VIRTUAL_ENV: /tmp/build-env
|
||||
CUDA_HOME: /usr/local/cuda
|
||||
PRIME_KERNELS_REQUIRE: "1"
|
||||
MAX_JOBS: "8"
|
||||
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
|
||||
|
||||
- name: Inspect wheel
|
||||
run: |
|
||||
ls -lh dist/
|
||||
/tmp/build-env/bin/python - <<'PY'
|
||||
import pathlib, zipfile
|
||||
wheel = next(pathlib.Path("dist").glob("*.whl"))
|
||||
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
|
||||
assert extensions, f"{wheel.name} contains no compiled kernels"
|
||||
print(wheel.name, *extensions, sep="\n ")
|
||||
PY
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: prime-kernels-${{ matrix.arch }}
|
||||
path: dist/*.whl
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Attach to release
|
||||
if: inputs.release_tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
# gh must not resolve the repo from the checkout: inside the container the
|
||||
# workspace is owned by another uid, which git rejects as dubious ownership.
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ inputs.release_tag }}
|
||||
run: |
|
||||
gh release upload "$TAG" dist/*.whl --clobber
|
||||
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
|
||||
WHEEL=$(basename dist/*.whl)
|
||||
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
|
||||
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -113,21 +113,8 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Wheels are attached while the release is still a draft, so it is never published without
|
||||
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
|
||||
# resolves to a wheel-less release would fall back to compiling CUDA from source.
|
||||
kernels-from-auto-tag:
|
||||
needs: auto-tag-on-main
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
|
||||
release-from-auto-tag:
|
||||
needs: [auto-tag-on-main, kernels-from-auto-tag]
|
||||
needs: auto-tag-on-main
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -219,17 +206,8 @@ jobs:
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
kernels-from-tag:
|
||||
needs: resolve-release
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/build_kernels.yaml
|
||||
with:
|
||||
release_tag: ${{ needs.resolve-release.outputs.tag }}
|
||||
ref: ${{ needs.resolve-release.outputs.tag }}
|
||||
|
||||
publish-release:
|
||||
needs: [resolve-release, kernels-from-tag]
|
||||
needs: resolve-release
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
+42
-22
@@ -6,7 +6,7 @@
|
||||
|
||||
# Every pyproject.toml + uv.lock, so the dependency sync below caches
|
||||
# independently of source edits.
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
|
||||
# .git is ~735 MB, changes every commit, and would land in the registry cache.
|
||||
COPY --exclude=.git . /ctx
|
||||
RUN mkdir -p /manifests \
|
||||
@@ -15,7 +15,7 @@ RUN mkdir -p /manifests \
|
||||
&& cp uv.lock /manifests/
|
||||
|
||||
# Build stage - multi-arch base (supports amd64 + arm64)
|
||||
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
|
||||
LABEL maintainer="prime intellect"
|
||||
LABEL repository="prime-rl"
|
||||
|
||||
@@ -150,8 +150,8 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu12-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
|
||||
fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
@@ -161,19 +161,42 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
|
||||
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
|
||||
FROM builder AS cuda-trim
|
||||
RUN find /usr/local/cuda-12.8/targets/*/lib \
|
||||
RUN find /usr/local/cuda-13.0/targets/*/lib \
|
||||
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
|
||||
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
|
||||
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
|
||||
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
|
||||
|
||||
# CUDA 13 runtime libs source
|
||||
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
|
||||
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
|
||||
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
|
||||
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
|
||||
# installed as one version-matched unit via AWS's official installer
|
||||
# rather than picking versions by hand. Do not substitute a host-mounted
|
||||
# copy of these libraries instead of building them in -- symbol-version
|
||||
# mismatches between a host's rdma-core and a container's can silently
|
||||
# break the NCCL plugin. --skip-kmod: containers share the host kernel and
|
||||
# must never build/load a kernel module themselves; the EFA driver is
|
||||
# expected to already be present on the host. --skip-limit-conf: ulimits
|
||||
# config doesn't apply inside a build. Same base OS as the runtime stage
|
||||
# below for glibc/rdma-core ABI compatibility.
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS efa-installer
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ARG EFA_INSTALLER_VERSION=1.47.0
|
||||
# One RUN: efa_installer.sh apt-get installs its own deps (pciutils,
|
||||
# libnl-3-200, tcl, ...) internally, so the package index has to survive
|
||||
# until after it runs. Purging /var/lib/apt/lists/* only at the very end
|
||||
# (not between the curl/tar deps and the installer invocation) keeps that
|
||||
# available.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl ca-certificates tar gzip \
|
||||
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
|
||||
-o /tmp/aws-efa-installer.tar.gz \
|
||||
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
|
||||
&& cd /tmp/aws-efa-installer \
|
||||
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
|
||||
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Runtime image
|
||||
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
|
||||
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
@@ -207,20 +230,12 @@ RUN apt-get update && apt-get install -y \
|
||||
&& apt-get clean autoclean \
|
||||
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
|
||||
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
|
||||
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
|
||||
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH="/usr/local/cuda/bin:${PATH}"
|
||||
|
||||
# CUDA 13 runtime libs for deep-gemm
|
||||
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
|
||||
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
|
||||
&& ldconfig \
|
||||
&& ldconfig -p | grep -q libcudart.so.13 \
|
||||
&& ldconfig -p | grep -q libnvrtc.so.13
|
||||
|
||||
|
||||
ARG USER_ID=1000
|
||||
ARG GROUP_ID=1000
|
||||
|
||||
@@ -252,6 +267,11 @@ COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packa
|
||||
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so /app/.venv/lib/python3.12/site-packages/
|
||||
COPY --from=builder /opt/ucx /opt/ucx
|
||||
|
||||
# EFA userspace stack from the dedicated stage above. Not added to
|
||||
# LD_LIBRARY_PATH here -- deployment configs opt into that only where
|
||||
# EFA is actually available, so this is inert everywhere else.
|
||||
COPY --from=efa-installer /opt/amazon /opt/amazon
|
||||
|
||||
# Copy and set up entrypoint script
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:50:40+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:35:31.543870+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
"time_taken": 295.5118532651104
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 20.802552047875178,
|
||||
"std": 0.16199364988631793,
|
||||
"min": 20.664358307416567,
|
||||
"max": 20.98082222151257
|
||||
"mean": 16.701924322664684,
|
||||
"std": 0.0999595293790186,
|
||||
"min": 16.586575698092034,
|
||||
"max": 16.763194274056005
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 2484.411208996455,
|
||||
"std": 19.346608946709658,
|
||||
"min": 2467.9069802355616,
|
||||
"max": 2505.7016937694384
|
||||
"mean": 1994.6806480062144,
|
||||
"std": 11.937986005933869,
|
||||
"min": 1980.9047701633856,
|
||||
"max": 2001.998007610024
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 52.79691480938345,
|
||||
"std": 0.4071756223542672,
|
||||
"min": 52.35017399210483,
|
||||
"max": 53.14720633160323
|
||||
"mean": 65.74198961785685,
|
||||
"std": 0.3962098986964774,
|
||||
"min": 65.49867434287444,
|
||||
"max": 66.19917749473825
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 11.728515625,
|
||||
"pct": 24.742767157118376
|
||||
"gib": 11.591145833333334,
|
||||
"pct": 24.45296844104
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-20
@@ -6,43 +6,46 @@
|
||||
"lora_rank": null,
|
||||
"seq_len": 65536,
|
||||
"ac": "Recompute",
|
||||
"selective_targets": null,
|
||||
"attention": "flash_attention_2",
|
||||
"output": "benchmark_result.json",
|
||||
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
|
||||
"dry_run": false,
|
||||
"timeout": 1500,
|
||||
"timeout": 600,
|
||||
"max_steps": 4,
|
||||
"micro_batches": 2,
|
||||
"ep": 1,
|
||||
"cp": 1,
|
||||
"fused_lm_head_token_chunk_size": 1024,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "c88d08fdf",
|
||||
"timestamp": "2026-06-24T22:55:54+00:00",
|
||||
"commit_sha": "7007d2ef",
|
||||
"timestamp": "2026-08-29T02:28:40.728120+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
"time_taken": 317.33935201819986
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 17.217465998339005,
|
||||
"std": 0.02905058130694137,
|
||||
"min": 17.19503698271855,
|
||||
"max": 17.250282374540514
|
||||
"mean": 15.880248465863398,
|
||||
"std": 0.005915779562921215,
|
||||
"min": 15.873443653590638,
|
||||
"max": 15.884167926432548
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 8225.003435798719,
|
||||
"std": 13.877833769765575,
|
||||
"min": 8214.288808538377,
|
||||
"max": 8240.68023789224
|
||||
"mean": 7586.197539502296,
|
||||
"std": 2.826043462792163,
|
||||
"min": 7582.946793757898,
|
||||
"max": 7588.069915881657
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 63.90305413212627,
|
||||
"std": 0.11015530079183487,
|
||||
"min": 63.77801387012005,
|
||||
"max": 63.985770548693836
|
||||
"mean": 69.21047159920757,
|
||||
"std": 0.022114607283211834,
|
||||
"min": 69.19065106380731,
|
||||
"max": 69.234325167723
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 6.298828125,
|
||||
"pct": 13.288163877053583
|
||||
"gib": 8.55078125,
|
||||
"pct": 18.038939985655993
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
|
||||
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
|
||||
|
||||
Forward and backward are timed separately, because only the forward is a kernel — the
|
||||
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
|
||||
grouped-mm reference. A speedup on the forward can be spent again on the backward.
|
||||
|
||||
uv run benchmarks/scripts/bench_fused_moe.py
|
||||
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
|
||||
|
||||
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
|
||||
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
|
||||
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
|
||||
parser.add_argument("--num-experts", type=int, default=64)
|
||||
parser.add_argument("--top-k", type=int, default=8)
|
||||
parser.add_argument("--iters", type=int, default=20)
|
||||
parser.add_argument("--warmup", type=int, default=5)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
|
||||
torch.manual_seed(0)
|
||||
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
|
||||
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
|
||||
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
|
||||
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
|
||||
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
|
||||
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
|
||||
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
|
||||
|
||||
|
||||
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
|
||||
x, w1, w2, w3, selected, top_scores = inputs
|
||||
if mode == "grouped_mm":
|
||||
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
|
||||
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
|
||||
|
||||
|
||||
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
|
||||
"""Median forward ms, median backward ms, peak MiB."""
|
||||
forward_ms, backward_ms = [], []
|
||||
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
|
||||
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
|
||||
for i in range(args.warmup + args.iters):
|
||||
for tensor in inputs[:4] + (inputs[5],):
|
||||
tensor.grad = None
|
||||
torch.cuda.synchronize()
|
||||
|
||||
start.record()
|
||||
out = run_forward(mode, inputs, args.num_experts)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
forward_ms.append(start.elapsed_time(end))
|
||||
|
||||
start.record()
|
||||
out.backward(grad_out)
|
||||
end.record()
|
||||
torch.cuda.synchronize()
|
||||
if i >= args.warmup:
|
||||
backward_ms.append(start.elapsed_time(end))
|
||||
|
||||
median = lambda values: sorted(values)[len(values) // 2]
|
||||
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
if not torch.cuda.is_available():
|
||||
raise SystemExit("no CUDA device")
|
||||
kernel = _load_fused_moe_kernel()
|
||||
for mxfp8 in (False, True):
|
||||
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
|
||||
if reason is not None:
|
||||
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
|
||||
|
||||
inputs = make_inputs(args)
|
||||
print(
|
||||
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
|
||||
f"experts={args.num_experts} top_k={args.top_k} "
|
||||
f"({args.iters} iters, {args.warmup} warmup, median)\n"
|
||||
)
|
||||
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
|
||||
|
||||
baseline = None
|
||||
for mode in MODES:
|
||||
forward, backward, peak = time_mode(mode, inputs, args)
|
||||
total = forward + backward
|
||||
baseline = baseline or total
|
||||
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -70,11 +70,6 @@ class BenchmarkConfig(BaseConfig):
|
||||
Field(description="Activation checkpointing type"),
|
||||
] = "Recompute"
|
||||
|
||||
selective_targets: Annotated[
|
||||
list[str] | None,
|
||||
Field(description="Selective activation checkpoint targets when ac=Selective"),
|
||||
] = None
|
||||
|
||||
attention: Annotated[
|
||||
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
|
||||
Field(description="Attention implementation"),
|
||||
@@ -160,8 +155,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
|
||||
cmd.append("--model.ac")
|
||||
elif config.ac == "Selective":
|
||||
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
|
||||
if config.selective_targets:
|
||||
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
|
||||
elif config.ac == "Offload":
|
||||
cmd.append("--model.ac-offloading")
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 26dafdc958...1f1e050ab0
Vendored
+1
-1
Submodule deps/prime-kernels updated: 2ceaf9eccb...3fb83eb7aa
Vendored
+1
-1
Submodule deps/renderers updated: cb82439137...9b47901de1
Vendored
+1
-1
Submodule deps/verifiers updated: b2e4e81577...e2103d6fb4
+29
-10
@@ -35,31 +35,50 @@ impl = "custom" # or "hf" to force the HF path
|
||||
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
|
||||
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
|
||||
|
||||
### Low-precision training
|
||||
|
||||
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
|
||||
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
|
||||
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
|
||||
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
|
||||
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
|
||||
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
|
||||
|
||||
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
|
||||
|
||||
- `type = "bf16"` (default)
|
||||
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
|
||||
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
|
||||
|
||||
```toml
|
||||
[trainer.model.quantization]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
enable_a2a = true
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "mxfp8"
|
||||
recipe = "mxfp8_rceil"
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "mxfp8"
|
||||
```
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
|
||||
|
||||
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
|
||||
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
|
||||
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
|
||||
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
|
||||
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
|
||||
|
||||
```toml
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "deepep"
|
||||
num_sms = 20
|
||||
token_chunk_size = 4096
|
||||
```
|
||||
|
||||
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
|
||||
|
||||
@@ -141,7 +160,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
|
||||
|
||||
```bash
|
||||
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
|
||||
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
|
||||
```
|
||||
|
||||
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
|
||||
|
||||
+12
-6
@@ -99,11 +99,14 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
ep_comm_backend = "torch" # or "deepep"
|
||||
ep = 8 # explicit EP degree; must divide num_experts
|
||||
|
||||
[trainer.model.moe.dispatch]
|
||||
type = "torch"
|
||||
transport = "bf16"
|
||||
```
|
||||
|
||||
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
|
||||
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
@@ -127,15 +130,18 @@ cp_style = "ulysses" # "ring"
|
||||
| `trainer.model.ac.mode = "selective"` | medium | small |
|
||||
| `trainer.model.ac_offloading` | extra | a bit more |
|
||||
|
||||
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
|
||||
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
|
||||
|
||||
```toml
|
||||
[trainer.model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
|
||||
```
|
||||
|
||||
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
|
||||
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
|
||||
|
||||
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
|
||||
|
||||
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
|
||||
|
||||
### Optimizer Offloading
|
||||
|
||||
|
||||
@@ -97,6 +97,9 @@ ep = 8
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
|
||||
[trainer.model.moe.compute]
|
||||
type = "deepgemm_fp8"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
|
||||
@@ -23,11 +23,8 @@ rank = 32
|
||||
alpha = 32
|
||||
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
|
||||
|
||||
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
|
||||
# raises CheckpointError; selective AC excluding routed_experts avoids that.
|
||||
[model.ac]
|
||||
mode = "selective"
|
||||
targets = ["norm", "attn_proj", "linear_attn"]
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
|
||||
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
"prime-pydantic-config>=0.4.3",
|
||||
"renderers>=0.1.10",
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
|
||||
@@ -462,7 +462,7 @@ class InferenceConfig(BaseConfig):
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
|
||||
|
||||
# Launcher-only fields
|
||||
|
||||
@@ -607,6 +607,18 @@ class InferenceConfig(BaseConfig):
|
||||
if not hasattr(namespace, "logprobs_mode"):
|
||||
namespace.logprobs_mode = "processed_logprobs"
|
||||
|
||||
# Always surface cached prompt tokens in `usage` — the router's
|
||||
# cache-discount billing counters parse them off /inference/v1/generate.
|
||||
if "enable_prompt_tokens_details" not in extra_fields:
|
||||
namespace.enable_prompt_tokens_details = True
|
||||
|
||||
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
|
||||
# `moe_router_dtype` off the HF config to pick the router logits dtype.
|
||||
if self.enable_fp32_router_logits:
|
||||
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
|
||||
hf_overrides.setdefault("moe_router_dtype", "float32")
|
||||
namespace.hf_overrides = hf_overrides
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
@@ -616,8 +628,6 @@ class InferenceConfig(BaseConfig):
|
||||
additional_config = getattr(namespace, "additional_config", None) or {}
|
||||
if self.enable_fp32_lm_head:
|
||||
additional_config["fp32_lm_head"] = True
|
||||
if self.enable_fp32_router_logits:
|
||||
additional_config["fp32_router_logits"] = True
|
||||
if additional_config:
|
||||
namespace.additional_config = additional_config
|
||||
|
||||
|
||||
@@ -324,7 +324,7 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
|
||||
@@ -21,7 +21,6 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
|
||||
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
|
||||
|
||||
|
||||
class GCConfig(BaseConfig):
|
||||
@@ -31,20 +30,13 @@ class GCConfig(BaseConfig):
|
||||
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
mode: Literal["full", "selective"] = "full"
|
||||
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
|
||||
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
|
||||
|
||||
freq: int = Field(1, ge=1)
|
||||
"""Apply activation checkpointing to every N layers."""
|
||||
|
||||
targets: list[str] = ["norm"]
|
||||
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_selective_targets(self):
|
||||
self.targets = list(dict.fromkeys(self.targets))
|
||||
if self.mode == "selective" and not self.targets:
|
||||
raise ValueError("Selective activation checkpointing requires at least one target.")
|
||||
return self
|
||||
targets: list[str] | None = None
|
||||
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
|
||||
|
||||
|
||||
class ActivationOffloadingConfig(BaseConfig):
|
||||
@@ -123,7 +115,7 @@ class LoRAConfig(BaseConfig):
|
||||
"fc1_latent_proj",
|
||||
"fc2_latent_proj",
|
||||
]
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
|
||||
|
||||
modules_to_save: list[str] = []
|
||||
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
|
||||
@@ -151,7 +143,7 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
# in BF16 on the trainer while inference quantized it to FP8, causing
|
||||
# hidden-state drift before the MoE router.
|
||||
r"mlp\.gate\.",
|
||||
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"in_proj_a",
|
||||
@@ -161,21 +153,80 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
|
||||
class FP8Config(BaseConfig):
|
||||
type: Literal["fp8"] = "fp8"
|
||||
enable_grouped_gemm: bool = True
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from DeepGEMM FP8 replacement."""
|
||||
|
||||
|
||||
class MXFP8Config(BaseConfig):
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
enable_grouped_gemm: bool = True
|
||||
enable_a2a: bool = True
|
||||
"""MXFP8 recipe for dense linear modules."""
|
||||
|
||||
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
|
||||
"""Dense linear module names excluded from torchao MXFP8 replacement."""
|
||||
|
||||
|
||||
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BF16MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs in bfloat16."""
|
||||
|
||||
type: Literal["bf16"] = "bf16"
|
||||
|
||||
|
||||
class DeepGemmFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
|
||||
|
||||
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
|
||||
|
||||
|
||||
class MXFP8MoEComputeConfig(BaseConfig):
|
||||
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
|
||||
|
||||
type: Literal["mxfp8"] = "mxfp8"
|
||||
recipe: MXFP8Recipe = "mxfp8_rceil"
|
||||
"""MXFP8 expert-compute recipe."""
|
||||
|
||||
|
||||
MoEComputeConfig: TypeAlias = Annotated[
|
||||
BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class TorchMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with torch all-to-all collectives."""
|
||||
|
||||
type: Literal["torch"] = "torch"
|
||||
transport: Literal["bf16", "mxfp8"] = "bf16"
|
||||
"""Wire format for routed activations and their reverse-path gradients."""
|
||||
|
||||
|
||||
class DeepEPMoEDispatchConfig(BaseConfig):
|
||||
"""Dispatch and combine routed tokens with DeepEP."""
|
||||
|
||||
type: Literal["deepep"] = "deepep"
|
||||
num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated to DeepEP communication kernels."""
|
||||
|
||||
token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Optional chunk size used to pipeline dispatch with local expert compute."""
|
||||
|
||||
|
||||
MoEDispatchConfig: TypeAlias = Annotated[
|
||||
TorchMoEDispatchConfig | DeepEPMoEDispatchConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class MoERuntimeConfig(BaseConfig):
|
||||
"""Independent routed-expert compute and token-dispatch choices."""
|
||||
|
||||
compute: MoEComputeConfig = BF16MoEComputeConfig()
|
||||
dispatch: MoEDispatchConfig = TorchMoEDispatchConfig()
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
@@ -213,14 +264,8 @@ class ModelConfig(BaseModelConfig):
|
||||
ep: int | Literal["auto"] = "auto"
|
||||
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
|
||||
|
||||
ep_comm_backend: EPCommBackend = "torch"
|
||||
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
|
||||
|
||||
deepep_num_sms: int = Field(20, ge=1)
|
||||
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
|
||||
|
||||
deepep_token_chunk_size: int | None = Field(None, ge=1)
|
||||
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
|
||||
moe: MoERuntimeConfig = MoERuntimeConfig()
|
||||
"""Routed-expert compute and token-dispatch runtime."""
|
||||
|
||||
cp: int = 1
|
||||
"""Context parallelism degree. 1 disables CP."""
|
||||
@@ -240,12 +285,6 @@ class ModelConfig(BaseModelConfig):
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
moe_fused_kernel: bool = False
|
||||
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
|
||||
|
||||
quantization: QuantizationConfig | None = None
|
||||
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
@@ -301,12 +340,6 @@ class ModelConfig(BaseModelConfig):
|
||||
self.ac = ActivationCheckpointConfig()
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def selective_ac_only_with_custom_impl(self):
|
||||
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cpu_offload_mutual_exclusion(self):
|
||||
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
|
||||
@@ -332,19 +365,18 @@ class ModelConfig(BaseModelConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
def validate_moe_runtime(self):
|
||||
if self.ep == 1:
|
||||
return self
|
||||
|
||||
if isinstance(self.ep, int) and self.ep <= 1:
|
||||
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def mxfp8_only_with_torch_ep_backend(self):
|
||||
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
|
||||
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
|
||||
compute = self.moe.compute
|
||||
dispatch = self.moe.dispatch
|
||||
if isinstance(dispatch, DeepEPMoEDispatchConfig):
|
||||
if isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
|
||||
elif dispatch.transport == "mxfp8":
|
||||
if not isinstance(compute, MXFP8MoEComputeConfig):
|
||||
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -644,7 +676,7 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
warnings.warn(
|
||||
"Gradient clipping is not compatible with DeepEP. "
|
||||
"Automatically setting optim.max_norm to None (disabled).",
|
||||
|
||||
+57
-33
@@ -27,7 +27,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"renderers>=0.1.10",
|
||||
"renderers[multimodal]>=0.1.11",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
@@ -49,11 +49,11 @@ prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
gpu = [
|
||||
"torch>=2.9.0 ; sys_platform == 'linux'",
|
||||
"torch>=2.13.0 ; sys_platform == 'linux'",
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.26.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.28.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
@@ -61,20 +61,21 @@ gpu = [
|
||||
"tilelang>=0.1.8 ; sys_platform == 'linux'",
|
||||
"flash-linear-attention ; sys_platform == 'linux'",
|
||||
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
|
||||
"torchao>=0.17.0 ; sys_platform == 'linux'",
|
||||
"torchao>=0.18.0 ; sys_platform == 'linux'",
|
||||
"modelexpress==0.3.0 ; sys_platform == 'linux'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
]
|
||||
dashboard = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn>=0.30",
|
||||
]
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
|
||||
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
|
||||
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
|
||||
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
|
||||
# trainer/model.py).
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
|
||||
|
||||
@@ -85,7 +86,7 @@ disagg = [
|
||||
"deep-ep ; sys_platform == 'linux'",
|
||||
"deep-gemm ; sys_platform == 'linux'",
|
||||
"nixl ; sys_platform == 'linux'",
|
||||
"nixl-cu12 ; sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
|
||||
"vllm-router ; sys_platform == 'linux'",
|
||||
]
|
||||
gpt-oss = [
|
||||
@@ -135,13 +136,17 @@ environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'aarch64'",
|
||||
"sys_platform == 'darwin' and platform_machine == 'arm64'",
|
||||
]
|
||||
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
|
||||
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
|
||||
# See: https://github.com/pytorch/pytorch/issues/166122
|
||||
override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.6.2",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"torch>=2.13.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
@@ -178,13 +183,30 @@ version = "0.3.0"
|
||||
requires-dist = [
|
||||
"grpcio>=1.66.2",
|
||||
"huggingface_hub>=0.20.0",
|
||||
"nixl[cu12]",
|
||||
"nixl",
|
||||
"numpy>=1.24.0",
|
||||
"protobuf>=5.27.0,<7.0.0",
|
||||
"pydantic>=2.0.0",
|
||||
"torch>=2.6.0",
|
||||
]
|
||||
|
||||
# NIXL publishes its CUDA 12 package as a base dependency even when the
|
||||
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nixl"
|
||||
version = "0.10.1"
|
||||
requires-dist = ["nixl-cu13==0.10.1"]
|
||||
|
||||
# CUTLASS DSL has the same CUDA 12 default. vLLM requests its CUDA 13 extra,
|
||||
# so resolve that variant without installing both runtime packages.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
requires-dist = [
|
||||
"nvidia-cutlass-dsl-libs-base==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
@@ -210,7 +232,7 @@ vllm-router = false
|
||||
dion = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
nixl-cu13 = false
|
||||
torchao = false
|
||||
prime-kernels = false
|
||||
|
||||
@@ -221,36 +243,38 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
torch = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchvision = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torchaudio = [{ index = "pytorch-cu128", marker = "sys_platform == 'linux'" }]
|
||||
torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchvision = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchaudio = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
|
||||
torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
flash_attn_3 = { index = "pytorch-cu130-test" }
|
||||
|
||||
[tool.uv.extra-build-dependencies]
|
||||
flash-attn = [{ requirement = "torch", match-runtime = true }]
|
||||
@@ -261,13 +285,13 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
name = "pytorch-cu130"
|
||||
url = "https://download.pytorch.org/whl/cu130"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
name = "pytorch-cu130-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu130"
|
||||
explicit = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
|
||||
#
|
||||
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
|
||||
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
|
||||
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
|
||||
# and is what `pyproject.toml` consumes by default; this script is for
|
||||
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
|
||||
#
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh # build + install in-place
|
||||
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: d30fc36)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
|
||||
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if already installed at the right version
|
||||
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
|
||||
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
|
||||
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
|
||||
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Auto-detect CUDA version
|
||||
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
|
||||
if [ -z "$CUDA_VERSION" ]; then
|
||||
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CUDA_MAJOR="${CUDA_VERSION%%.*}"
|
||||
CUDA_MINOR="${CUDA_VERSION#*.}"
|
||||
CUDA_MINOR="${CUDA_MINOR%%.*}"
|
||||
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
|
||||
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " Building DeepGEMM (${SHORT_REF})"
|
||||
echo " CUDA: ${CUDA_VERSION}"
|
||||
echo "================================================================"
|
||||
|
||||
TMPDIR=$(mktemp -d)
|
||||
cleanup() { rm -rf "$TMPDIR"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
|
||||
cd "$TMPDIR/DeepGEMM"
|
||||
git checkout "$DEEPGEMM_GIT_REF"
|
||||
git submodule update --init --recursive
|
||||
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
if [ -n "$WHEEL_DIR" ]; then
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Wheel built:"
|
||||
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
|
||||
else
|
||||
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
|
||||
echo ""
|
||||
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
|
||||
fi
|
||||
|
||||
echo "================================================================"
|
||||
echo " DeepGEMM build complete"
|
||||
echo "================================================================"
|
||||
@@ -1,170 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install DeepEP kernels for expert-parallel disaggregated inference.
|
||||
#
|
||||
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
|
||||
# Required for disaggregated prefill/decode deployments with expert parallelism.
|
||||
#
|
||||
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
|
||||
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
|
||||
#
|
||||
# Prerequisites:
|
||||
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
|
||||
# - For multi-node: IBGDA driver configured (see --configure-drivers)
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_ep_kernels.sh
|
||||
#
|
||||
# Options:
|
||||
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
|
||||
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
|
||||
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
|
||||
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPEP_COMMIT_HASH="73b6ea4"
|
||||
NVSHMEM_VER="3.3.24"
|
||||
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
|
||||
CONFIGURE_DRIVERS=0
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--workspace) WORKSPACE="$2"; shift 2 ;;
|
||||
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
|
||||
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
|
||||
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
|
||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Skip if DeepEP is already installed
|
||||
if python -c "import deep_ep" 2>/dev/null; then
|
||||
echo "DeepEP already installed, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
|
||||
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
|
||||
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
|
||||
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
|
||||
|
||||
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
|
||||
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
|
||||
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
|
||||
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
|
||||
exit 1
|
||||
fi
|
||||
export CUDA_HOME
|
||||
|
||||
# Verify versions actually match
|
||||
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
|
||||
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
|
||||
|
||||
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
|
||||
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
|
||||
case "$GPU_NAME" in
|
||||
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
|
||||
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
|
||||
*)
|
||||
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
|
||||
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
|
||||
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
export TORCH_CUDA_ARCH_LIST
|
||||
|
||||
echo "================================================================"
|
||||
echo " Installing DeepEP kernels"
|
||||
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
|
||||
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
|
||||
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
|
||||
echo " NVSHMEM: ${NVSHMEM_VER}"
|
||||
echo " Workspace: ${WORKSPACE}"
|
||||
echo "================================================================"
|
||||
|
||||
mkdir -p "$WORKSPACE"
|
||||
|
||||
# ── Step 1: Install build deps ────────────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Installing build dependencies ---"
|
||||
cd "$REPO_ROOT"
|
||||
uv pip install cmake ninja
|
||||
|
||||
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
|
||||
|
||||
ARCH=$(uname -m)
|
||||
case "${ARCH,,}" in
|
||||
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
|
||||
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
|
||||
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
NVSHMEM_DIR="$WORKSPACE/nvshmem"
|
||||
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
|
||||
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
|
||||
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
|
||||
|
||||
echo "Downloading ${NVSHMEM_URL}"
|
||||
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
|
||||
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
|
||||
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
|
||||
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
|
||||
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
|
||||
else
|
||||
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
|
||||
fi
|
||||
|
||||
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
|
||||
export NVSHMEM_DIR
|
||||
|
||||
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
|
||||
echo ""
|
||||
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
|
||||
|
||||
DEEPEP_DIR="$WORKSPACE/DeepEP"
|
||||
if [ ! -d "$DEEPEP_DIR/.git" ]; then
|
||||
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
|
||||
fi
|
||||
|
||||
cd "$DEEPEP_DIR"
|
||||
git fetch origin
|
||||
git checkout "$DEEPEP_COMMIT_HASH"
|
||||
|
||||
WHEEL_DIR="$REPO_ROOT/deps"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
|
||||
echo ""
|
||||
echo "--- DeepEP wheel built at: $WHEEL ---"
|
||||
|
||||
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
|
||||
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
|
||||
echo ""
|
||||
echo "--- Configuring IBGDA drivers (requires sudo) ---"
|
||||
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
|
||||
if command -v update-initramfs &> /dev/null; then
|
||||
sudo update-initramfs -u
|
||||
elif command -v dracut &> /dev/null; then
|
||||
sudo dracut --force
|
||||
else
|
||||
echo "No supported initramfs update tool found." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo ""
|
||||
echo "IBGDA configured. Please REBOOT the system to apply changes."
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "================================================================"
|
||||
echo " DeepEP installation complete"
|
||||
echo " NVSHMEM: ${NVSHMEM_DIR}"
|
||||
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
|
||||
echo "================================================================"
|
||||
@@ -98,7 +98,6 @@ ARCH_PRESETS = {
|
||||
first_k_dense_replace=1,
|
||||
norm_topk_prob=True,
|
||||
use_qk_norm=False,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=151329,
|
||||
eos_token_id=[151329, 151336, 151338],
|
||||
),
|
||||
@@ -127,7 +126,6 @@ ARCH_PRESETS = {
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
use_grouped_mm=False,
|
||||
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
|
||||
),
|
||||
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
|
||||
@@ -173,7 +171,6 @@ ARCH_PRESETS = {
|
||||
num_experts_per_tok=4,
|
||||
mlp_layer_types=["dense"] + ["sparse"] * 11,
|
||||
moe_routed_scaling_factor=2.5,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=9,
|
||||
bos_token_id=2,
|
||||
eos_token_id=[2, 24],
|
||||
|
||||
+15
-4
@@ -66,13 +66,24 @@ Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
The `disagg` extra installs the prebuilt DeepEP wheel pinned in `[tool.uv.sources]`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_ep_kernels.sh
|
||||
uv sync --extra disagg
|
||||
```
|
||||
|
||||
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
|
||||
The prime-kernels repository owns source builds for DeepEP, DeepGEMM, and TorchAO. Use
|
||||
its scripts when a local rebuild is required:
|
||||
|
||||
```bash
|
||||
git submodule update --init deps/prime-kernels
|
||||
bash deps/prime-kernels/scripts/install_ep_kernels.sh --wheel-dir /tmp/prime-kernels-wheels
|
||||
uv pip install --reinstall --no-deps /tmp/prime-kernels-wheels/deep_ep-*.whl
|
||||
```
|
||||
|
||||
The build needs a CUDA toolkit whose version matches torch. Set
|
||||
`TORCH_CUDA_ARCH_LIST` when the build host has no GPU or when the wheel must support
|
||||
more than the local GPU architecture.
|
||||
|
||||
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
|
||||
|
||||
@@ -91,4 +102,4 @@ Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, s
|
||||
- `pyproject.toml` — dependencies, extras, dependency groups
|
||||
- `uv.lock` — pinned lockfile (refresh with `uv sync --all-extras`)
|
||||
- `scripts/install.sh` — bootstrap installer
|
||||
- `scripts/install_ep_kernels.sh` — DeepEP build script
|
||||
- `deps/prime-kernels/scripts/` — native wheel build scripts
|
||||
|
||||
+48
-50
@@ -10,13 +10,13 @@ CUDA kernels live in their own monorepo,
|
||||
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
|
||||
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
|
||||
package: one folder per kernel, holding the
|
||||
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
|
||||
kernel's Python surface and, for compiled kernels, its C++/CUDA sources under `csrc/`, all declared in the single
|
||||
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
|
||||
is initialized.
|
||||
|
||||
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
|
||||
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
|
||||
compiled extensions to it.
|
||||
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit for local
|
||||
source builds and a prime-kernels release for installs. prime-kernels builds and publishes
|
||||
its own wheels. prime-rl stays a pure-Python wheel; never add compiled extensions to it.
|
||||
|
||||
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
|
||||
already covers it — prime-rl lints none of it.
|
||||
@@ -38,15 +38,18 @@ it once at startup rather than failing a run halfway through. `unavailable_reaso
|
||||
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
|
||||
wants; `is_available` is just that call compared to `None`.
|
||||
|
||||
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
|
||||
tcgen05, reached through `model.moe_fused_kernel=true`.
|
||||
`flash_moe` is a compiled fused MoE forward kernel (bf16 + mxfp8) on Blackwell
|
||||
tcgen05. Its trainer integration is dormant. `mxfp8_moe` is a Python-only registered
|
||||
kernel package for MXFP8 grouped GEMM and torch EP transport on SM100; it owns the
|
||||
MoE-specific torchao-derived orchestration and exports explicit BF16 boundaries instead
|
||||
of tensor-subclass interception.
|
||||
|
||||
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
|
||||
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
|
||||
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
|
||||
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
|
||||
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
|
||||
a change in both repos.
|
||||
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`. When the trainer integration
|
||||
is restored, call this once during setup so an unsupported model fails before training rather
|
||||
than mid-step. Never hardcode a `128` on this side: then every requirement change is a change
|
||||
in both repos.
|
||||
|
||||
## Building locally
|
||||
|
||||
@@ -72,14 +75,15 @@ The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels
|
||||
|
||||
1. Commit the sources under `prime_kernels/<name>/csrc/`.
|
||||
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
|
||||
`arch`, `cxx-std`; paths are relative to the kernel folder.
|
||||
`arch`, `cxx-std`; paths are relative to the kernel folder. A vendored Python kernel
|
||||
uses `python-only = true`, may declare import checks in `requires`, and omits compiled
|
||||
extension fields.
|
||||
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
|
||||
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
|
||||
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
|
||||
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
|
||||
used in training also needs `torch.library.register_autograd`, since a schema carries
|
||||
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
|
||||
of its own.)
|
||||
no backward. `flash_moe` is forward only and currently has no trainer integration.
|
||||
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
|
||||
|
||||
Rules the build assumes:
|
||||
@@ -112,69 +116,63 @@ Then, in order:
|
||||
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
|
||||
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
|
||||
numbers, not a build error, and prime-rl's call sites have to absorb it.
|
||||
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
|
||||
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
|
||||
forward and its hand-written backward against the grouped-mm expert path; it is
|
||||
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
|
||||
on a machine the kernel was built for.
|
||||
- Rebuild and re-run the kernel repository's numerical coverage plus every PrimeRL runtime
|
||||
path that calls the changed kernel; the ABI is not checked for you.
|
||||
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
|
||||
new code only reaches users once a release rebuilds the wheels and the pin below moves.
|
||||
|
||||
## Prebuilt wheels
|
||||
|
||||
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
|
||||
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
|
||||
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
|
||||
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
|
||||
The [prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels) repository owns
|
||||
`build_kernels.yaml`. It builds `prime-kernels`, `deep-ep`, `deep-gemm`, and `torchao` for
|
||||
x86_64 and aarch64. It publishes the wheels as prime-kernels release assets.
|
||||
|
||||
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
|
||||
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
|
||||
bumps would build no wheels.
|
||||
|
||||
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
|
||||
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
|
||||
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
|
||||
Run that workflow in prime-kernels for each torch or CUDA bump:
|
||||
|
||||
```bash
|
||||
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
|
||||
gh workflow run build_kernels.yaml \
|
||||
--repo PrimeIntellect-ai/prime-kernels \
|
||||
-f release_tag=vX.Y.Z
|
||||
```
|
||||
|
||||
The wheel version carries the ABI it was built against, e.g.
|
||||
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
|
||||
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
|
||||
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
|
||||
`prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl`. It imports only under
|
||||
that exact torch and CUDA ABI. prime-kernels CI controls the build dependency pins.
|
||||
|
||||
### Pinning installs at the prebuilt wheels
|
||||
|
||||
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
|
||||
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
|
||||
the extra may take, since a sync must never compile:
|
||||
`[tool.uv.sources]`. deep-ep, deep-gemm, torchao, and vLLM use the same pattern. A sync must
|
||||
never compile these packages:
|
||||
|
||||
```toml
|
||||
[tool.uv.sources]
|
||||
prime-kernels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
```
|
||||
|
||||
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
|
||||
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
|
||||
its job summary. Then `uv lock`.
|
||||
The wheels are prime-kernels release assets. Get the exact names before you move all pins:
|
||||
|
||||
The pin necessarily trails by one release: a release's own assets do not exist until that
|
||||
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
|
||||
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
|
||||
pin whose torch no longer matches the lock fails at import, not at install.
|
||||
```bash
|
||||
gh release view vX.Y.Z \
|
||||
--repo PrimeIntellect-ai/prime-kernels \
|
||||
--json assets
|
||||
```
|
||||
|
||||
Then run `uv lock`.
|
||||
|
||||
Move the pin when a kernel, torch, or CUDA pin changes. A stale pin ships stale kernels. A
|
||||
torch ABI mismatch fails at import, not at install.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
|
||||
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
|
||||
wheel imports only under the torch it was compiled against.
|
||||
- Keep the torch floor in prime-kernels aligned with prime-rl. The wheel imports only under
|
||||
the torch version it was compiled against.
|
||||
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
|
||||
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
|
||||
metadata and does not.
|
||||
- A fresh clone without the submodule still installs and trains — only the source build needs
|
||||
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
|
||||
published with kernels silently skipped.
|
||||
- A fresh prime-rl clone without the submodule still installs and trains. Only a local source
|
||||
build needs it. prime-kernels CI sets `PRIME_KERNELS_REQUIRE=1`, so a release cannot omit
|
||||
kernels silently.
|
||||
|
||||
@@ -207,7 +207,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
@@ -233,8 +232,11 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if envs.VLLM_USE_V2_MODEL_RUNNER:
|
||||
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"The V2 model runner does not support routed experts capture - "
|
||||
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
@@ -609,32 +611,6 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_harmony_stop_token_propagation():
|
||||
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
|
||||
|
||||
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
|
||||
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
|
||||
ignores them, using only self.stop_token_ids (which defaults to []).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/22519
|
||||
"""
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
|
||||
|
||||
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
|
||||
|
||||
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
|
||||
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
|
||||
# Merge harmony stop tokens from default_sampling_params
|
||||
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
|
||||
if default_stop_ids:
|
||||
existing = set(params.stop_token_ids or [])
|
||||
merged = list(existing | set(default_stop_ids))
|
||||
params.stop_token_ids = merged
|
||||
return params
|
||||
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
@@ -717,45 +693,6 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
|
||||
@@ -10,11 +10,11 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
|
||||
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
|
||||
# stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
# Router replay needs the V1 GPU model runner: V2 silently never captures
|
||||
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
|
||||
# setdefault so it stays overridable.
|
||||
if config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -20,17 +20,13 @@ from prime_rl.utils.logger import get_logger
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
|
||||
@@ -3,22 +3,20 @@
|
||||
vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing and server-side ``max_tokens``
|
||||
defaulting. We subclass it for the bits still missing from the upstream handler:
|
||||
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
|
||||
defaulting and ``usage`` reporting. We subclass it for the bits still missing
|
||||
from the upstream handler:
|
||||
|
||||
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
|
||||
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
|
||||
now does this too; we keep the equivalent path for the DP-replicated
|
||||
inference servers prime-RL runs.
|
||||
1. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
|
||||
objects (the form the PD router can merge and the renderers parse) instead
|
||||
of upstream's single ``.npy`` base64 string.
|
||||
|
||||
2. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
|
||||
source fork.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
|
||||
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
|
||||
``get_max_tokens``); we keep an equivalent guard so callers that omit
|
||||
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
|
||||
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
|
||||
parses ``request.kv_transfer_params`` but never threads it into the engine,
|
||||
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
|
||||
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
|
||||
cut — drop the bridge once we pin a release that includes it.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
routed_experts: dict[str, Any] | None = None
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact
|
||||
# ``{data, shape, start, dtype}`` object the PD router merges and the
|
||||
# renderers parse.
|
||||
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=choices,
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
|
||||
instance, which means an unset ``max_tokens`` is indistinguishable from
|
||||
an explicit ``max_tokens=16`` once the request reaches the handler —
|
||||
both surface as ``sampling_params.max_tokens == 16``. We re-read the
|
||||
cached body to recover that distinction. When we can't (no raw_request,
|
||||
non-JSON body, or read error), pessimistically assume the client did
|
||||
set it so we never clobber an explicit value.
|
||||
"""
|
||||
if raw_request is None:
|
||||
return True
|
||||
try:
|
||||
body = await raw_request.json()
|
||||
except Exception:
|
||||
return True
|
||||
if not isinstance(body, dict):
|
||||
return True
|
||||
sp = body.get("sampling_params")
|
||||
return isinstance(sp, dict) and "max_tokens" in sp
|
||||
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
|
||||
|
||||
Computed lazily because ``custom_init_app_state`` swaps in this
|
||||
subclass via ``object.__new__`` + ``__dict__.update`` (so our
|
||||
``__init__`` never runs).
|
||||
"""
|
||||
diff = self.model_config.get_diff_sampling_param()
|
||||
mc = self.model_config
|
||||
override = (
|
||||
diff.get("max_tokens")
|
||||
if mc.generation_config not in ("auto", "vllm")
|
||||
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
|
||||
# in case a downstream caller ever sets the attribute to ``None``
|
||||
# (``getattr``'s default only fires when the attribute is missing,
|
||||
# not when it exists with a ``None`` value).
|
||||
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
|
||||
)
|
||||
return diff, override
|
||||
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
|
||||
|
||||
async def serve_tokens(
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
# (c) dispatch to our overridden response builder so ``routed_experts``
|
||||
# makes it into the JSON.
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
return error_check_ret
|
||||
|
||||
if self.engine_client.errored:
|
||||
raise self.engine_client.dead_error
|
||||
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
model_name = self.models.model_name(lora_request)
|
||||
|
||||
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
|
||||
request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = request_metadata
|
||||
|
||||
# Build the engine input — features-aware (MM) or text-only fallback.
|
||||
# Identical to upstream so we keep tracking it.
|
||||
if features := request.features:
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItem,
|
||||
MultiModalKwargsItems,
|
||||
PlaceholderRange,
|
||||
)
|
||||
|
||||
mm_placeholders = {
|
||||
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
|
||||
for modality, ranges in features.mm_placeholders.items()
|
||||
}
|
||||
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
|
||||
if features.kwargs_data is not None:
|
||||
for modality, items in features.kwargs_data.items():
|
||||
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
|
||||
else:
|
||||
for modality, hashes in features.mm_hashes.items():
|
||||
mm_kwargs[modality] = [None] * len(hashes)
|
||||
engine_input = mm_input(
|
||||
prompt_token_ids=request.token_ids,
|
||||
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
|
||||
mm_hashes=features.mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
cache_salt=request.cache_salt,
|
||||
)
|
||||
else:
|
||||
(engine_input,) = await self.online_renderer.preprocess_completion(
|
||||
request,
|
||||
prompt_input=request.token_ids,
|
||||
prompt_embeds=None,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
|
||||
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
|
||||
# engine's KV connector picks the params up.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Upstream parses ``request.kv_transfer_params`` but never threads it
|
||||
# into the engine, so decode receives an empty NIXL handshake and
|
||||
# re-prefills the prompt locally (~100x slower under concurrency).
|
||||
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
|
||||
# connector picks the params up. Fixed upstream by vllm#42644 (merged
|
||||
# after 0.28.0) — drop once we pin a release that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = sampling_params.extra_args or {}
|
||||
extra = request.sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
request.sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
|
||||
# ``ServingTokens`` now does this too; kept here so callers that omit
|
||||
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
|
||||
# default.
|
||||
if not await _client_set_max_tokens(raw_request):
|
||||
diff_sp, override = self._max_tokens_defaults
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
max_model_len=self.model_config.max_model_len,
|
||||
max_tokens=None,
|
||||
input_length=len(request.token_ids),
|
||||
default_sampling_params=diff_sp,
|
||||
override_max_tokens=override,
|
||||
)
|
||||
|
||||
if self.force_no_detokenize:
|
||||
sampling_params.detokenize = False
|
||||
if request.stream:
|
||||
sampling_params.output_kind = RequestOutputKind.DELTA
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
engine_input,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
result_generator = self.engine_client.generate(
|
||||
engine_input,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=self._get_data_parallel_rank(raw_request),
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
# Streaming path: defer to upstream — prime-RL's renderer client
|
||||
# only consumes the full response, so adding routed_experts to the
|
||||
# streaming choice schema is unnecessary churn.
|
||||
return self.serve_tokens_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
return await self.serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
return await super().serve_tokens(request, raw_request)
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
start = request.sampling_params.routed_experts_prompt_start
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=start,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -3,7 +3,6 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_fp32_router_logits,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
@@ -21,6 +20,3 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -33,7 +33,6 @@ OVERVIEW_NAME = "overview"
|
||||
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
|
||||
# dynamic, so also a regex) — and each section builder prepends its own.
|
||||
COMMON_METRICS = [
|
||||
"all/dispatch_failure/mean",
|
||||
"effective/num_total_tokens/mean",
|
||||
"effective/num_turns/mean",
|
||||
"effective/num_branches/mean",
|
||||
|
||||
@@ -854,10 +854,9 @@ class Orchestrator:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Dispatch Failure``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, an episode error came from the environment, and a dispatch failure produced no episode)."""
|
||||
``Error``, ``Cancelled``, and ``Ratio`` describe the step's full arrival window. Over the
|
||||
shipped set they are 0/0/share-of-shipped by construction, so the window is the only scope
|
||||
where they carry signal. A cancellation is a pipeline decision, not a rollout failure."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -866,16 +865,13 @@ class Orchestrator:
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
|
||||
num_attempts = len(episodes) + len(batch.failures)
|
||||
dispatch_failure_rate = len(batch.failures) / num_attempts if num_attempts else 0.0
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Dispatch Failure {dispatch_failure_rate:.1%} | "
|
||||
f"Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
@@ -884,10 +880,7 @@ class Orchestrator:
|
||||
|
||||
window_by_env = episodes.by_env()
|
||||
shipped_by_env = effective.by_env()
|
||||
failures_by_env: dict[str, list[DispatchFailure]] = {}
|
||||
for failure in batch.failures:
|
||||
failures_by_env.setdefault(failure.env_name, []).append(failure)
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env) | set(failures_by_env))
|
||||
env_names = sorted(set(window_by_env) | set(shipped_by_env))
|
||||
name_width = max((len(name) for name in env_names), default=0)
|
||||
lines = [head]
|
||||
for env_name in env_names:
|
||||
@@ -895,15 +888,11 @@ class Orchestrator:
|
||||
env_eff_pool = shipped_by_env.get(env_name, TrainEpisodes())
|
||||
env_eff = env_eff_pool.metrics
|
||||
ratio = (pool.num_traces / n_generated) if n_generated else 0.0
|
||||
env_failures = failures_by_env.get(env_name, [])
|
||||
env_attempts = len(pool) + len(env_failures)
|
||||
env_failure_rate = len(env_failures) / env_attempts if env_attempts else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Dispatch Failure {env_failure_rate:.1%} | "
|
||||
f"Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Whole-block activation checkpointing with an operator-based policy."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from functools import partial
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointImpl, checkpoint_wrapper
|
||||
from torch.utils.checkpoint import (
|
||||
SAC_IGNORED_OPS,
|
||||
CheckpointPolicy,
|
||||
SelectiveCheckpointContext,
|
||||
create_selective_checkpoint_contexts,
|
||||
)
|
||||
|
||||
from prime_rl.configs.trainer import ActivationCheckpointConfig
|
||||
|
||||
# FSDP's replay-specific hooks emit a different number of profiler markers.
|
||||
SAC_IGNORED_OPS.update(
|
||||
{
|
||||
torch.ops.profiler._record_function_enter.default,
|
||||
torch.ops.profiler._record_function_enter_new.default,
|
||||
torch.ops.profiler._record_function_exit.default,
|
||||
torch.ops.profiler._record_function_exit._RecordFunction,
|
||||
}
|
||||
)
|
||||
|
||||
# Adapted from TorchTitan's whole-block selective activation checkpointing policy.
|
||||
# These targets and the CUDA-to-CPU copy rule are correctness requirements. They
|
||||
# must remain active when custom targets replace the default selective targets.
|
||||
MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
|
||||
MANDATORY_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::topk",
|
||||
"prime_rl::record_moe_routing_statistics",
|
||||
}
|
||||
)
|
||||
|
||||
DEFAULT_SELECTIVE_SAVE_NAMESPACES = frozenset(
|
||||
{
|
||||
"_c10d_functional",
|
||||
"flash_attn",
|
||||
"flash_attn_3",
|
||||
"prime_rl_collectives",
|
||||
"prime_rl_ring",
|
||||
}
|
||||
)
|
||||
DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::_efficient_attention_forward",
|
||||
"aten::_flash_attention_forward",
|
||||
"aten::_scaled_dot_product_attention_math",
|
||||
"aten::_scaled_dot_product_cudnn_attention",
|
||||
"aten::_scaled_dot_product_efficient_attention",
|
||||
"aten::_scaled_dot_product_flash_attention",
|
||||
"aten::_scaled_dot_product_flash_attention_for_cpu",
|
||||
"aten::_scaled_dot_product_fused_attention_overrideable",
|
||||
"aten::_scaled_grouped_mm",
|
||||
"aten::_scaled_mm",
|
||||
"aten::_scaled_mm_v2",
|
||||
"aten::_grouped_mm",
|
||||
"aten::addmm",
|
||||
"aten::bmm",
|
||||
"aten::convolution",
|
||||
"aten::linear",
|
||||
"aten::mm",
|
||||
"prime_rl::fp8_blockwise_mm",
|
||||
"prime_rl::grouped_fp8_gemm",
|
||||
"prime_rl::sparse_mla",
|
||||
}
|
||||
)
|
||||
# An operation target matches one qualified operator name, while a namespace
|
||||
# target matches every operation registered in that namespace.
|
||||
DEFAULT_SELECTIVE_TARGETS = DEFAULT_SELECTIVE_SAVE_NAMESPACES | DEFAULT_SELECTIVE_SAVE_OPERATIONS
|
||||
|
||||
|
||||
# PyTorch calls checkpoint policies with the dispatched operation's operands.
|
||||
# Keyword operands let us distinguish CUDA-to-CPU copies from other _to_copy calls.
|
||||
def _mandatory_checkpoint_policy(
|
||||
_context: SelectiveCheckpointContext,
|
||||
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> CheckpointPolicy:
|
||||
if operation.namespace in MANDATORY_SAVE_NAMESPACES or operation.name() in MANDATORY_SAVE_OPERATIONS:
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
|
||||
if operation.name() == "aten::_to_copy":
|
||||
device = kwargs.get("device")
|
||||
if isinstance(device, torch.device) and device.type == "cpu":
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
|
||||
return CheckpointPolicy.PREFER_RECOMPUTE
|
||||
|
||||
|
||||
def _selective_checkpoint_policy(
|
||||
context: SelectiveCheckpointContext,
|
||||
operation: torch._ops.OpOverload | torch._ops.HigherOrderOperator,
|
||||
*args,
|
||||
targets: frozenset[str] = DEFAULT_SELECTIVE_TARGETS,
|
||||
**kwargs,
|
||||
) -> CheckpointPolicy:
|
||||
runtime_policy = _mandatory_checkpoint_policy(context, operation, *args, **kwargs)
|
||||
if runtime_policy is CheckpointPolicy.MUST_SAVE:
|
||||
return runtime_policy
|
||||
if operation.namespace in targets or operation.name() in targets:
|
||||
return CheckpointPolicy.MUST_SAVE
|
||||
return CheckpointPolicy.PREFER_RECOMPUTE
|
||||
|
||||
|
||||
def get_activation_checkpoint_wrapper(config: ActivationCheckpointConfig) -> Callable[[nn.Module], nn.Module]:
|
||||
if config.mode == "full":
|
||||
policy = _mandatory_checkpoint_policy
|
||||
else:
|
||||
targets = DEFAULT_SELECTIVE_TARGETS if config.targets is None else frozenset(config.targets)
|
||||
policy = partial(_selective_checkpoint_policy, targets=targets)
|
||||
|
||||
return partial(
|
||||
checkpoint_wrapper,
|
||||
checkpoint_impl=CheckpointImpl.NO_REENTRANT,
|
||||
context_fn=partial(create_selective_checkpoint_contexts, policy),
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_SELECTIVE_SAVE_NAMESPACES",
|
||||
"DEFAULT_SELECTIVE_SAVE_OPERATIONS",
|
||||
"DEFAULT_SELECTIVE_TARGETS",
|
||||
"MANDATORY_SAVE_NAMESPACES",
|
||||
"MANDATORY_SAVE_OPERATIONS",
|
||||
"get_activation_checkpoint_wrapper",
|
||||
]
|
||||
@@ -1,3 +1,3 @@
|
||||
from prime_rl.trainer.distributed.expert_parallel import DeepEPExpertParallel, MXFP8AllToAllExpertParallel, get_ep_group
|
||||
from prime_rl.trainer.distributed.expert_parallel import ExpertWeightParallel
|
||||
|
||||
__all__ = ["DeepEPExpertParallel", "MXFP8AllToAllExpertParallel", "get_ep_group"]
|
||||
__all__ = ["ExpertWeightParallel"]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
"""Autograd and compile-friendly distributed collectives."""
|
||||
|
||||
import prime_kernels
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_to_all_single", mutates_args=())
|
||||
def _all_to_all_single(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
) -> torch.Tensor:
|
||||
output_split_list = output_splits.tolist()
|
||||
input_split_list = input_splits.tolist()
|
||||
output = x.new_empty((sum(output_split_list), *x.shape[1:]))
|
||||
dist.all_to_all_single(
|
||||
output,
|
||||
x.contiguous(),
|
||||
output_split_list,
|
||||
input_split_list,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@_all_to_all_single.register_fake
|
||||
def _all_to_all_single_fake(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
) -> torch.Tensor:
|
||||
output_size = torch.library.get_ctx().new_dynamic_size()
|
||||
return x.new_empty((output_size, *x.shape[1:]))
|
||||
|
||||
|
||||
def _all_to_all_setup_context(ctx, inputs, output) -> None:
|
||||
_, output_splits, input_splits, group_name = inputs
|
||||
ctx.save_for_backward(output_splits, input_splits)
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
def _all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
output_splits, input_splits = ctx.saved_tensors
|
||||
return (
|
||||
_all_to_all_single(
|
||||
grad_output,
|
||||
input_splits,
|
||||
output_splits,
|
||||
ctx.group_name,
|
||||
),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_all_to_all_single.register_autograd(_all_to_all_backward, setup_context=_all_to_all_setup_context)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_to_all_single_equal", mutates_args=())
|
||||
def _all_to_all_single_equal(x: torch.Tensor, group_name: str) -> torch.Tensor:
|
||||
output = x.new_empty(x.shape)
|
||||
dist.all_to_all_single(
|
||||
output,
|
||||
x.contiguous(),
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
@_all_to_all_single_equal.register_fake
|
||||
def _all_to_all_single_equal_fake(x: torch.Tensor, group_name: str) -> torch.Tensor:
|
||||
return x.new_empty(x.shape)
|
||||
|
||||
|
||||
def _all_to_all_equal_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
return _all_to_all_single_equal(grad_output, ctx.group_name), None
|
||||
|
||||
|
||||
def _all_to_all_equal_setup_context(ctx, inputs, output) -> None:
|
||||
_, group_name = inputs
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
_all_to_all_single_equal.register_autograd(
|
||||
_all_to_all_equal_backward,
|
||||
setup_context=_all_to_all_equal_setup_context,
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::mxfp8_all_to_all", mutates_args=())
|
||||
def _mxfp8_all_to_all(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
quantized: bool,
|
||||
) -> torch.Tensor:
|
||||
kernel = prime_kernels.load("mxfp8_moe")
|
||||
operation = kernel.all_to_all_dispatch if quantized else kernel.all_to_all_combine
|
||||
return operation(
|
||||
x,
|
||||
output_splits.tolist(),
|
||||
input_splits.tolist(),
|
||||
dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
|
||||
|
||||
@_mxfp8_all_to_all.register_fake
|
||||
def _mxfp8_all_to_all_fake(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group_name: str,
|
||||
quantized: bool,
|
||||
) -> torch.Tensor:
|
||||
output_size = torch.library.get_ctx().new_dynamic_size()
|
||||
return x.new_empty((output_size, *x.shape[1:]))
|
||||
|
||||
|
||||
def _mxfp8_all_to_all_setup_context(ctx, inputs, output) -> None:
|
||||
_, output_splits, input_splits, group_name, quantized = inputs
|
||||
ctx.save_for_backward(output_splits, input_splits)
|
||||
ctx.group_name = group_name
|
||||
ctx.quantized = quantized
|
||||
|
||||
|
||||
def _mxfp8_all_to_all_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None, None]:
|
||||
output_splits, input_splits = ctx.saved_tensors
|
||||
return (
|
||||
_mxfp8_all_to_all(
|
||||
grad_output,
|
||||
input_splits,
|
||||
output_splits,
|
||||
ctx.group_name,
|
||||
not ctx.quantized,
|
||||
),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_mxfp8_all_to_all.register_autograd(
|
||||
_mxfp8_all_to_all_backward,
|
||||
setup_context=_mxfp8_all_to_all_setup_context,
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::all_gather", mutates_args=())
|
||||
def _all_gather(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
gathered = x.movedim(dim, 0).contiguous()
|
||||
output = gathered.new_empty((gathered.shape[0] * group_size, *gathered.shape[1:]))
|
||||
dist.all_gather_into_tensor(
|
||||
output,
|
||||
gathered,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
|
||||
@_all_gather.register_fake
|
||||
def _all_gather_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
shape = list(x.shape)
|
||||
shape[dim] *= group_size
|
||||
return x.new_empty(shape)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_collectives::reduce_scatter_sum", mutates_args=())
|
||||
def _reduce_scatter_sum(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
scattered = x.movedim(dim, 0).contiguous()
|
||||
output = scattered.new_empty((scattered.shape[0] // group_size, *scattered.shape[1:]))
|
||||
dist.reduce_scatter_tensor(
|
||||
output,
|
||||
scattered,
|
||||
group=dist.distributed_c10d._resolve_process_group(group_name),
|
||||
)
|
||||
return output.movedim(0, dim).contiguous()
|
||||
|
||||
|
||||
@_reduce_scatter_sum.register_fake
|
||||
def _reduce_scatter_sum_fake(x: torch.Tensor, dim: int, group_size: int, group_name: str) -> torch.Tensor:
|
||||
shape = list(x.shape)
|
||||
shape[dim] //= group_size
|
||||
return x.new_empty(shape)
|
||||
|
||||
|
||||
def _collective_setup_context(ctx, inputs, output) -> None:
|
||||
_, dim, group_size, group_name = inputs
|
||||
ctx.dim = dim
|
||||
ctx.group_size = group_size
|
||||
ctx.group_name = group_name
|
||||
|
||||
|
||||
def _all_gather_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
return (
|
||||
_reduce_scatter_sum(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _reduce_scatter_backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None, None]:
|
||||
return (
|
||||
_all_gather(grad_output, ctx.dim, ctx.group_size, ctx.group_name),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
_all_gather.register_autograd(_all_gather_backward, setup_context=_collective_setup_context)
|
||||
_reduce_scatter_sum.register_autograd(_reduce_scatter_backward, setup_context=_collective_setup_context)
|
||||
|
||||
|
||||
def all_to_all_single(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _all_to_all_single(x, output_splits, input_splits, group.group_name)
|
||||
|
||||
|
||||
def all_to_all_single_equal(x: torch.Tensor, group: ProcessGroup) -> torch.Tensor:
|
||||
return _all_to_all_single_equal(x, group.group_name)
|
||||
|
||||
|
||||
def mxfp8_all_to_all_dispatch(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, True)
|
||||
|
||||
|
||||
def mxfp8_all_to_all_combine(
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
group: ProcessGroup,
|
||||
) -> torch.Tensor:
|
||||
return _mxfp8_all_to_all(x, output_splits, input_splits, group.group_name, False)
|
||||
|
||||
|
||||
def all_gather(x: torch.Tensor, dim: int, group: ProcessGroup) -> torch.Tensor:
|
||||
return _all_gather(x, dim, group.size(), group.group_name)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"all_gather",
|
||||
"all_to_all_single",
|
||||
"all_to_all_single_equal",
|
||||
"mxfp8_all_to_all_combine",
|
||||
"mxfp8_all_to_all_dispatch",
|
||||
]
|
||||
@@ -1,15 +1,28 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
import torch
|
||||
from deep_ep import Buffer
|
||||
from deep_ep.utils import EventHandle, EventOverlap
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import (
|
||||
ExpertFunction,
|
||||
PermutationState,
|
||||
TokenDispatcherBase,
|
||||
permute_for_grouped_gemm,
|
||||
unpermute_from_grouped_gemm,
|
||||
)
|
||||
|
||||
_buffer: Buffer | None = None
|
||||
_handle_cache: dict[int, object] = {}
|
||||
_combine_backward_handles: dict[int, object] = {}
|
||||
# The custom-op schema can carry only the dispatcher ID; weak values avoid extending dispatcher lifetimes.
|
||||
_combine_dispatchers: WeakValueDictionary[int, DeepEPTokenDispatcher] = WeakValueDictionary()
|
||||
_pending_dispatch_events: dict[int, EventOverlap] = {}
|
||||
_handle_counter = 0
|
||||
_pending_combine_event: EventOverlap | None = None
|
||||
_deepep_cuda_ops_registered = False
|
||||
_deepep_cuda_lib: torch.library.Library | None = None
|
||||
|
||||
@@ -37,10 +50,13 @@ def register_deepep_cuda_ops() -> None:
|
||||
"Tensor is_token_in_rank, Tensor num_tokens_per_expert) "
|
||||
"-> (Tensor, Tensor, Tensor, Tensor, Tensor)"
|
||||
)
|
||||
_deepep_cuda_lib.define("combine(Tensor x, Tensor handle_id, int dispatcher_id) -> Tensor")
|
||||
|
||||
torch.library.impl(_deepep_cuda_lib, "dispatch", "CUDA")(_dispatch_op_impl)
|
||||
torch.library.impl(_deepep_cuda_lib, "combine", "CUDA")(_combine_op_impl)
|
||||
|
||||
torch.library.register_autograd("deepep::dispatch", _dispatch_backward, setup_context=_dispatch_setup_context)
|
||||
torch.library.register_autograd("deepep::combine", _combine_backward, setup_context=_combine_setup_context)
|
||||
|
||||
_deepep_cuda_ops_registered = True
|
||||
|
||||
@@ -113,57 +129,53 @@ def _dispatch_backward(
|
||||
return grad_x, None, grad_topk_weights, None, None, None, None
|
||||
|
||||
|
||||
class _DeepEPCombine(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, handle_id: torch.Tensor) -> torch.Tensor:
|
||||
global _pending_combine_event
|
||||
def _combine_op_impl(x: torch.Tensor, handle_id: torch.Tensor, dispatcher_id: int) -> torch.Tensor:
|
||||
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
|
||||
handle_key = handle_id.item()
|
||||
handle = _handle_cache.pop(handle_key, None)
|
||||
assert handle is not None, f"Handle not found for handle_id={handle_key}"
|
||||
|
||||
assert _buffer is not None, "DeepEP buffer must be initialized before combine."
|
||||
handle = _handle_cache.pop(handle_id.item(), None)
|
||||
assert handle is not None, f"Handle not found for handle_id={handle_id.item()}"
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
combined, _, after_event = _buffer.combine(
|
||||
x=x,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
_pending_combine_event = after_event
|
||||
ctx.handle = handle
|
||||
return combined
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None]:
|
||||
handle = ctx.handle
|
||||
assert handle is not None, "Handle not found in DeepEP combine backward."
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
grad_x, _, _, _, _, after_event = _buffer.dispatch(
|
||||
x=grad_combined,
|
||||
topk_idx=None,
|
||||
topk_weights=None,
|
||||
num_tokens_per_rank=None,
|
||||
num_tokens_per_rdma_rank=None,
|
||||
is_token_in_rank=None,
|
||||
num_tokens_per_expert=None,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
after_event.current_stream_wait()
|
||||
return grad_x, None
|
||||
previous_event = _new_event_overlap()
|
||||
combined, _, after_event = _buffer.combine(
|
||||
x=x,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
dispatcher = _combine_dispatchers.get(dispatcher_id)
|
||||
assert dispatcher is not None, "DeepEP dispatcher was released before combine completed."
|
||||
dispatcher._pending_combine_events.append(after_event)
|
||||
if x.requires_grad:
|
||||
_combine_backward_handles[handle_key] = handle
|
||||
return combined
|
||||
|
||||
|
||||
@torch.compiler.disable()
|
||||
def sync_combine() -> None:
|
||||
global _pending_combine_event
|
||||
def _combine_setup_context(ctx, inputs, output) -> None:
|
||||
_, handle_id, _ = inputs
|
||||
ctx.handle = _combine_backward_handles.pop(handle_id.item(), None)
|
||||
|
||||
if _pending_combine_event is not None:
|
||||
_pending_combine_event.current_stream_wait()
|
||||
_pending_combine_event = None
|
||||
|
||||
def _combine_backward(ctx, grad_combined: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
handle = ctx.handle
|
||||
assert handle is not None, "Handle not found in DeepEP combine backward."
|
||||
|
||||
previous_event = _new_event_overlap()
|
||||
grad_x, _, _, _, _, after_event = _buffer.dispatch(
|
||||
x=grad_combined,
|
||||
topk_idx=None,
|
||||
topk_weights=None,
|
||||
num_tokens_per_rank=None,
|
||||
num_tokens_per_rdma_rank=None,
|
||||
is_token_in_rank=None,
|
||||
num_tokens_per_expert=None,
|
||||
handle=handle,
|
||||
previous_event=previous_event,
|
||||
async_finish=True,
|
||||
allocate_on_comm_stream=True,
|
||||
)
|
||||
after_event.current_stream_wait()
|
||||
return grad_x, None, None
|
||||
|
||||
|
||||
@torch.compiler.disable()
|
||||
@@ -235,14 +247,6 @@ def _unpermute_tokens(
|
||||
return output_hidden_states
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DispatchState:
|
||||
handle_id: torch.Tensor
|
||||
permuted_indices: torch.Tensor
|
||||
num_recv_tokens: int
|
||||
permuted_scores: torch.Tensor | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingDispatchState:
|
||||
hidden_states: torch.Tensor
|
||||
@@ -295,50 +299,177 @@ def dispatch_tokens_async(
|
||||
)
|
||||
|
||||
|
||||
def finalize_dispatch_tokens(pending_state: _PendingDispatchState) -> tuple[torch.Tensor, torch.Tensor, _DispatchState]:
|
||||
_sync_dispatch(pending_state.handle_id)
|
||||
@dataclass(frozen=True)
|
||||
class DeepEPDispatchState:
|
||||
handle_id: torch.Tensor
|
||||
deep_ep_permuted_indices: torch.Tensor
|
||||
num_received_tokens: int
|
||||
scores_after_experts: torch.Tensor | None
|
||||
grouped_gemm_permutation: PermutationState
|
||||
|
||||
hidden_states = pending_state.hidden_states
|
||||
num_recv_tokens = hidden_states.shape[0]
|
||||
hidden_states, permuted_scores, permuted_indices = _permute_tokens(
|
||||
hidden_states,
|
||||
pending_state.dispatched_indices,
|
||||
pending_state.dispatched_scores,
|
||||
)
|
||||
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
|
||||
|
||||
if pending_state.score_before_experts and permuted_scores is not None:
|
||||
hidden_states = (hidden_states.to(torch.float32) * permuted_scores.to(torch.float32).reshape(-1, 1)).to(
|
||||
hidden_states.dtype
|
||||
class DeepEPTokenDispatcher(TokenDispatcherBase[DeepEPDispatchState]):
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
num_experts: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
num_sms: int,
|
||||
token_chunk_size: int | None,
|
||||
) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.num_local_experts = num_experts // group.size()
|
||||
self.group = group
|
||||
self.token_chunk_size = token_chunk_size
|
||||
self._pending_combine_events: list[EventOverlap] = []
|
||||
self._dispatcher_id = id(self)
|
||||
_combine_dispatchers[self._dispatcher_id] = self
|
||||
self._concatenate_stream: torch.cuda.Stream | None = None
|
||||
self._output_event: torch.cuda.Event | None = None
|
||||
configure_num_sms(num_sms)
|
||||
|
||||
def _finalize_dispatch(
|
||||
self, pending_state: _PendingDispatchState
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
|
||||
_sync_dispatch(pending_state.handle_id)
|
||||
|
||||
hidden_states = pending_state.hidden_states
|
||||
num_received_tokens = hidden_states.shape[0]
|
||||
hidden_states, permuted_scores, deep_ep_permuted_indices = _permute_tokens(
|
||||
hidden_states,
|
||||
pending_state.dispatched_indices,
|
||||
pending_state.dispatched_scores,
|
||||
)
|
||||
permuted_scores_for_state = None
|
||||
else:
|
||||
permuted_scores_for_state = permuted_scores
|
||||
num_tokens_per_expert = pending_state.num_tokens_per_expert.to(hidden_states.device)
|
||||
|
||||
state = _DispatchState(
|
||||
handle_id=pending_state.handle_id,
|
||||
permuted_indices=permuted_indices,
|
||||
num_recv_tokens=num_recv_tokens,
|
||||
permuted_scores=permuted_scores_for_state,
|
||||
)
|
||||
return hidden_states, num_tokens_per_expert, state
|
||||
if pending_state.score_before_experts:
|
||||
hidden_states = (hidden_states.float() * permuted_scores.float().reshape(-1, 1)).to(hidden_states.dtype)
|
||||
scores_after_experts = None
|
||||
else:
|
||||
scores_after_experts = permuted_scores
|
||||
|
||||
|
||||
def combine_tokens(hidden_states: torch.Tensor, state: _DispatchState) -> torch.Tensor:
|
||||
if state.permuted_scores is not None:
|
||||
hidden_states = (hidden_states.to(torch.float32) * state.permuted_scores.to(torch.float32).reshape(-1, 1)).to(
|
||||
hidden_states.dtype
|
||||
hidden_states, num_tokens_per_expert, grouped_gemm_permutation = permute_for_grouped_gemm(
|
||||
hidden_states,
|
||||
num_tokens_per_expert,
|
||||
experts_per_rank=self.num_local_experts,
|
||||
num_ranks=1,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
hidden_states = _unpermute_tokens(hidden_states, state.permuted_indices, state.num_recv_tokens)
|
||||
return _DeepEPCombine.apply(hidden_states, state.handle_id)
|
||||
state = DeepEPDispatchState(
|
||||
handle_id=pending_state.handle_id,
|
||||
deep_ep_permuted_indices=deep_ep_permuted_indices,
|
||||
num_received_tokens=num_received_tokens,
|
||||
scores_after_experts=scores_after_experts,
|
||||
grouped_gemm_permutation=grouped_gemm_permutation,
|
||||
)
|
||||
return hidden_states, num_tokens_per_expert, state
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DeepEPDispatchState]:
|
||||
pending_state = dispatch_tokens_async(
|
||||
x,
|
||||
selected_experts_indices,
|
||||
top_scores,
|
||||
num_experts=self.num_experts,
|
||||
group=self.group,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
return self._finalize_dispatch(pending_state)
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: DeepEPDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.grouped_gemm_permutation)
|
||||
if state.scores_after_experts is not None:
|
||||
routed_output = (routed_output.float() * state.scores_after_experts.float().reshape(-1, 1)).to(
|
||||
routed_output.dtype
|
||||
)
|
||||
routed_output = _unpermute_tokens(
|
||||
routed_output,
|
||||
state.deep_ep_permuted_indices,
|
||||
state.num_received_tokens,
|
||||
)
|
||||
combined = torch.ops.deepep.combine(routed_output, state.handle_id, self._dispatcher_id)
|
||||
return combined
|
||||
|
||||
def _run_dispatched_chunk(
|
||||
self,
|
||||
pending_state: _PendingDispatchState,
|
||||
experts: ExpertFunction,
|
||||
) -> torch.Tensor:
|
||||
hidden_states, num_tokens_per_expert, dispatch_state = self._finalize_dispatch(pending_state)
|
||||
routed_output = experts(hidden_states, num_tokens_per_expert)
|
||||
return self.combine(routed_output, dispatch_state)
|
||||
|
||||
@torch.compiler.disable()
|
||||
def _synchronize_combines(self) -> None:
|
||||
for event in self._pending_combine_events:
|
||||
event.current_stream_wait()
|
||||
self._pending_combine_events.clear()
|
||||
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor:
|
||||
if self.token_chunk_size is None:
|
||||
chunk_ranges = [(0, x.shape[0])]
|
||||
else:
|
||||
chunk_ranges = [
|
||||
(start, min(start + self.token_chunk_size, x.shape[0]))
|
||||
for start in range(0, x.shape[0], self.token_chunk_size)
|
||||
]
|
||||
|
||||
pending_states = (
|
||||
dispatch_tokens_async(
|
||||
x[start:end],
|
||||
selected_experts_indices[start:end],
|
||||
top_scores[start:end],
|
||||
num_experts=self.num_experts,
|
||||
group=self.group,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
for start, end in chunk_ranges
|
||||
)
|
||||
|
||||
pending_state = next(pending_states)
|
||||
routed_outputs: list[torch.Tensor] = []
|
||||
for next_pending_state in pending_states:
|
||||
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
|
||||
pending_state = next_pending_state
|
||||
routed_outputs.append(self._run_dispatched_chunk(pending_state, experts))
|
||||
if len(routed_outputs) == 1:
|
||||
return routed_outputs[0]
|
||||
|
||||
if self._concatenate_stream is None:
|
||||
self._concatenate_stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(self._concatenate_stream):
|
||||
self._synchronize_combines()
|
||||
output = torch.cat(routed_outputs, dim=0)
|
||||
self._output_event = self._concatenate_stream.record_event()
|
||||
return output
|
||||
|
||||
def synchronize(self) -> None:
|
||||
if self._output_event is not None:
|
||||
torch.cuda.current_stream().wait_event(self._output_event)
|
||||
self._output_event = None
|
||||
return
|
||||
self._synchronize_combines()
|
||||
|
||||
|
||||
register_deepep_cuda_ops()
|
||||
|
||||
__all__ = [
|
||||
"combine_tokens",
|
||||
"configure_num_sms",
|
||||
"DeepEPTokenDispatcher",
|
||||
"dispatch_tokens_async",
|
||||
"finalize_dispatch_tokens",
|
||||
"sync_combine",
|
||||
]
|
||||
|
||||
@@ -1,87 +1,14 @@
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from torch.distributed import ProcessGroup
|
||||
from torch.distributed.distributed_c10d import _resolve_process_group
|
||||
from torch.distributed.tensor import DeviceMesh, Shard, distribute_module, distribute_tensor
|
||||
from torch.distributed.tensor.parallel import ParallelStyle
|
||||
from torchao.prototype.moe_training.ep import a2a_combine_hp_fwd_mxfp8_bwd, a2a_dispatch_mxfp8_fwd_hp_bwd
|
||||
from torchao.prototype.mx_formats.mx_tensor import MXTensor
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
|
||||
|
||||
class _MXFP8Dispatch(torch.autograd.Function):
|
||||
class ExpertWeightParallel(ParallelStyle):
|
||||
@staticmethod
|
||||
def forward(ctx, routed_input, output_splits, input_splits, group_name):
|
||||
mx_routed_input = a2a_dispatch_mxfp8_fwd_hp_bwd(routed_input, output_splits, input_splits, group_name)
|
||||
ctx.input_splits = input_splits
|
||||
ctx.output_splits = output_splits
|
||||
ctx.group = _resolve_process_group(group_name)
|
||||
return mx_routed_input.dequantize(routed_input.dtype)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
grad_input = grad_output.new_empty((sum(ctx.input_splits),) + tuple(grad_output.shape[1:]))
|
||||
dist.all_to_all_single(
|
||||
grad_input, grad_output.contiguous(), ctx.input_splits, ctx.output_splits, group=ctx.group
|
||||
)
|
||||
return grad_input, None, None, None
|
||||
|
||||
|
||||
class _DequantMXGradInBwd(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x, hp_dtype):
|
||||
ctx.hp_dtype = hp_dtype
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
if isinstance(grad_output, MXTensor):
|
||||
grad_output = grad_output.dequantize(ctx.hp_dtype)
|
||||
return grad_output, None
|
||||
|
||||
|
||||
class MXFP8AllToAllExpertParallel(ExpertParallel):
|
||||
def _token_dispatch(self, mod, inputs, device_mesh):
|
||||
routed_input, num_tokens_per_expert = inputs
|
||||
with torch.no_grad():
|
||||
num_tokens_per_expert_group = num_tokens_per_expert.new_empty(num_tokens_per_expert.shape[0])
|
||||
dist.all_to_all_single(num_tokens_per_expert_group, num_tokens_per_expert, group=device_mesh.get_group())
|
||||
self.input_splits = num_tokens_per_expert.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
|
||||
self.output_splits = num_tokens_per_expert_group.view(device_mesh.shape[0], -1).sum(dim=1).tolist()
|
||||
routed_input = _MXFP8Dispatch.apply(
|
||||
routed_input, self.output_splits, self.input_splits, device_mesh.get_group().group_name
|
||||
)
|
||||
return routed_input, num_tokens_per_expert_group
|
||||
|
||||
def _token_combine(self, mod, routed_output, device_mesh):
|
||||
routed_output = _DequantMXGradInBwd.apply(routed_output, routed_output.dtype)
|
||||
return a2a_combine_hp_fwd_mxfp8_bwd(
|
||||
routed_output,
|
||||
self.input_splits,
|
||||
self.output_splits,
|
||||
device_mesh.get_group().group_name,
|
||||
)
|
||||
|
||||
|
||||
class DeepEPExpertParallel(ParallelStyle):
|
||||
"""Expert-parallel style backed by DeepEP dispatch/combine.
|
||||
|
||||
Only handles weight sharding (Shard(0) on expert dim) and stores the EP
|
||||
process group on the module. PrimeRL drives DeepEP dispatch/combine from
|
||||
`MoE.forward()` so communication stays outside the selective-AC checkpoint
|
||||
boundary while local expert matmuls remain checkpointable.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _partition_fn(name: str, mod: nn.Module, device_mesh: DeviceMesh) -> None:
|
||||
for param_name, param in mod.named_parameters(recurse=False):
|
||||
mod.register_parameter(param_name, nn.Parameter(distribute_tensor(param, device_mesh, [Shard(0)])))
|
||||
mod._ep_group = device_mesh.get_group()
|
||||
def _partition_fn(_name: str, module: nn.Module, device_mesh: DeviceMesh) -> None:
|
||||
for parameter_name, parameter in module.named_parameters(recurse=False):
|
||||
sharded = distribute_tensor(parameter, device_mesh, [Shard(0)])
|
||||
module.register_parameter(parameter_name, nn.Parameter(sharded))
|
||||
|
||||
def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module:
|
||||
return distribute_module(module, device_mesh, partition_fn=self._partition_fn)
|
||||
|
||||
|
||||
def get_ep_group(experts: nn.Module) -> ProcessGroup:
|
||||
return experts._ep_group
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import Generic, Protocol, TypeVar
|
||||
|
||||
import torch
|
||||
from torch.distributed import ProcessGroup
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import (
|
||||
all_to_all_single,
|
||||
all_to_all_single_equal,
|
||||
mxfp8_all_to_all_combine,
|
||||
mxfp8_all_to_all_dispatch,
|
||||
)
|
||||
|
||||
|
||||
class ExpertFunction(Protocol):
|
||||
def __call__(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor: ...
|
||||
|
||||
|
||||
class TokenDispatcher(Protocol):
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor: ...
|
||||
|
||||
def synchronize(self) -> None: ...
|
||||
|
||||
|
||||
DispatchState = TypeVar("DispatchState")
|
||||
|
||||
|
||||
class TokenDispatcherBase(ABC, Generic[DispatchState]):
|
||||
def __init__(self, num_experts: int, token_group_alignment: int) -> None:
|
||||
self.num_experts = num_experts
|
||||
self.token_group_alignment = token_group_alignment
|
||||
|
||||
@abstractmethod
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, DispatchState]: ...
|
||||
|
||||
@abstractmethod
|
||||
def combine(self, routed_output: torch.Tensor, state: DispatchState) -> torch.Tensor: ...
|
||||
|
||||
def run(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
experts: ExpertFunction,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> torch.Tensor:
|
||||
routed_input, num_tokens_per_expert, state = self.dispatch(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
score_before_experts=score_before_experts,
|
||||
)
|
||||
routed_output = experts(routed_input, num_tokens_per_expert)
|
||||
return self.combine(routed_output, state)
|
||||
|
||||
def synchronize(self) -> None:
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PermutationState:
|
||||
input_shape: torch.Size
|
||||
permuted_indices: torch.Tensor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LocalDispatchState:
|
||||
num_tokens: int
|
||||
token_indices_experts_sorted: torch.Tensor
|
||||
scores_after_experts: torch.Tensor | None
|
||||
permutation: PermutationState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TorchDispatchState(LocalDispatchState):
|
||||
input_splits: torch.Tensor
|
||||
output_splits: torch.Tensor
|
||||
|
||||
|
||||
def permute_for_grouped_gemm(
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert_group: torch.Tensor,
|
||||
*,
|
||||
experts_per_rank: int,
|
||||
num_ranks: int,
|
||||
alignment: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, PermutationState]:
|
||||
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
|
||||
|
||||
max_len = x.shape[0] + experts_per_rank * alignment
|
||||
max_len = (max_len + alignment - 1) // alignment * alignment
|
||||
with torch.no_grad():
|
||||
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
|
||||
num_tokens_per_expert_group,
|
||||
experts_per_rank,
|
||||
num_ranks,
|
||||
max_len,
|
||||
alignment,
|
||||
use_cpu=x.device.type == "cpu",
|
||||
)
|
||||
|
||||
x = torch.vstack((x, x.new_zeros((1, x.shape[-1]))))
|
||||
state = PermutationState(input_shape=x.shape, permuted_indices=permuted_indices)
|
||||
return x[permuted_indices], num_tokens_per_expert, state
|
||||
|
||||
|
||||
def unpermute_from_grouped_gemm(x: torch.Tensor, state: PermutationState) -> torch.Tensor:
|
||||
output = x.new_empty(state.input_shape)
|
||||
output[state.permuted_indices] = x
|
||||
return output[:-1]
|
||||
|
||||
|
||||
def _local_reorder(
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
flattened_experts = selected_experts_indices.reshape(-1)
|
||||
num_tokens_per_expert = torch.histc(
|
||||
flattened_experts.float(),
|
||||
bins=num_experts,
|
||||
min=0,
|
||||
max=num_experts,
|
||||
).to(torch.int64)
|
||||
token_indices_experts_sorted = torch.argsort(flattened_experts, stable=True)
|
||||
top_scores_experts_sorted = top_scores.reshape(-1)[token_indices_experts_sorted]
|
||||
token_indices_experts_sorted = token_indices_experts_sorted // top_k
|
||||
routed_input = x[token_indices_experts_sorted]
|
||||
return routed_input, token_indices_experts_sorted, top_scores_experts_sorted, num_tokens_per_expert
|
||||
|
||||
|
||||
def _scatter_routed_output(
|
||||
routed_output: torch.Tensor,
|
||||
*,
|
||||
num_tokens: int,
|
||||
token_indices_experts_sorted: torch.Tensor,
|
||||
scores_after_experts: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
if scores_after_experts is not None:
|
||||
routed_output = (routed_output.float() * scores_after_experts.reshape(-1, 1)).to(routed_output.dtype)
|
||||
|
||||
dim = routed_output.shape[-1]
|
||||
output = routed_output.new_zeros((num_tokens, dim))
|
||||
routed_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
return output.scatter_add(0, routed_indices, routed_output)
|
||||
|
||||
|
||||
class LocalTokenDispatcher(TokenDispatcherBase[LocalDispatchState]):
|
||||
def __init__(self, num_experts: int, top_k: int, token_group_alignment: int) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.top_k = top_k
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, LocalDispatchState]:
|
||||
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
num_experts=self.num_experts,
|
||||
top_k=self.top_k,
|
||||
)
|
||||
scores_after_experts = None
|
||||
if score_before_experts:
|
||||
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
|
||||
else:
|
||||
scores_after_experts = sorted_scores
|
||||
|
||||
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
|
||||
routed_input,
|
||||
num_tokens_per_expert,
|
||||
experts_per_rank=self.num_experts,
|
||||
num_ranks=1,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
state = LocalDispatchState(
|
||||
num_tokens=x.shape[0],
|
||||
token_indices_experts_sorted=token_indices,
|
||||
scores_after_experts=scores_after_experts,
|
||||
permutation=permutation,
|
||||
)
|
||||
return routed_input, num_tokens_per_expert, state
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: LocalDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
|
||||
return _scatter_routed_output(
|
||||
routed_output,
|
||||
num_tokens=state.num_tokens,
|
||||
token_indices_experts_sorted=state.token_indices_experts_sorted,
|
||||
scores_after_experts=state.scores_after_experts,
|
||||
)
|
||||
|
||||
|
||||
class TorchTokenDispatcher(TokenDispatcherBase[TorchDispatchState]):
|
||||
def __init__(
|
||||
self,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
) -> None:
|
||||
super().__init__(num_experts, token_group_alignment)
|
||||
self.top_k = top_k
|
||||
self.group = group
|
||||
|
||||
def _dispatch_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return all_to_all_single(x, output_splits, input_splits, self.group)
|
||||
|
||||
def _combine_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return all_to_all_single(x, output_splits, input_splits, self.group)
|
||||
|
||||
def dispatch(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
top_scores: torch.Tensor,
|
||||
selected_experts_indices: torch.Tensor,
|
||||
*,
|
||||
score_before_experts: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, TorchDispatchState]:
|
||||
routed_input, token_indices, sorted_scores, num_tokens_per_expert = _local_reorder(
|
||||
x,
|
||||
top_scores,
|
||||
selected_experts_indices,
|
||||
num_experts=self.num_experts,
|
||||
top_k=self.top_k,
|
||||
)
|
||||
scores_after_experts = None
|
||||
if score_before_experts:
|
||||
routed_input = (routed_input.float() * sorted_scores.reshape(-1, 1)).to(x.dtype)
|
||||
else:
|
||||
scores_after_experts = sorted_scores
|
||||
|
||||
ep_degree = self.group.size()
|
||||
with torch.no_grad():
|
||||
num_tokens_per_expert_group = all_to_all_single_equal(num_tokens_per_expert, self.group)
|
||||
input_splits = num_tokens_per_expert.view(ep_degree, -1).sum(dim=1)
|
||||
output_splits = num_tokens_per_expert_group.view(ep_degree, -1).sum(dim=1)
|
||||
|
||||
routed_input = self._dispatch_tokens(routed_input, output_splits, input_splits)
|
||||
experts_per_rank = self.num_experts // ep_degree
|
||||
routed_input, num_tokens_per_expert, permutation = permute_for_grouped_gemm(
|
||||
routed_input,
|
||||
num_tokens_per_expert_group,
|
||||
experts_per_rank=experts_per_rank,
|
||||
num_ranks=ep_degree,
|
||||
alignment=self.token_group_alignment,
|
||||
)
|
||||
state = TorchDispatchState(
|
||||
num_tokens=x.shape[0],
|
||||
token_indices_experts_sorted=token_indices,
|
||||
scores_after_experts=scores_after_experts,
|
||||
permutation=permutation,
|
||||
input_splits=input_splits,
|
||||
output_splits=output_splits,
|
||||
)
|
||||
return routed_input, num_tokens_per_expert, state
|
||||
|
||||
def combine(self, routed_output: torch.Tensor, state: TorchDispatchState) -> torch.Tensor:
|
||||
routed_output = unpermute_from_grouped_gemm(routed_output, state.permutation)
|
||||
routed_output = self._combine_tokens(routed_output, state.input_splits, state.output_splits)
|
||||
return _scatter_routed_output(
|
||||
routed_output,
|
||||
num_tokens=state.num_tokens,
|
||||
token_indices_experts_sorted=state.token_indices_experts_sorted,
|
||||
scores_after_experts=state.scores_after_experts,
|
||||
)
|
||||
|
||||
|
||||
class MXFP8TorchTokenDispatcher(TorchTokenDispatcher):
|
||||
def __init__(
|
||||
self,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
token_group_alignment: int,
|
||||
group: ProcessGroup,
|
||||
) -> None:
|
||||
super().__init__(num_experts, top_k, token_group_alignment, group)
|
||||
|
||||
def _dispatch_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return mxfp8_all_to_all_dispatch(x, output_splits, input_splits, self.group)
|
||||
|
||||
def _combine_tokens(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
output_splits: torch.Tensor,
|
||||
input_splits: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return mxfp8_all_to_all_combine(x, output_splits, input_splits, self.group)
|
||||
@@ -18,7 +18,7 @@ from prime_rl.trainer.models.layers.lora.multi_moe import (
|
||||
MultiLoRAGroupedExperts,
|
||||
MultiLoRANonGatedGroupedExperts,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -156,8 +156,8 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
|
||||
target_modules = []
|
||||
|
||||
for name, module in model.named_modules():
|
||||
# Check if module is Linear or one of the supported expert classes
|
||||
if not isinstance(module, (nn.Linear, GroupedExperts, NonGatedGroupedExperts, GptOssGroupedExperts)):
|
||||
# Check if module is Linear or a supported expert class
|
||||
if not isinstance(module, (nn.Linear, GroupedExperts)):
|
||||
continue
|
||||
|
||||
for pattern in target_patterns:
|
||||
@@ -224,6 +224,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
lora_state = setup_lora_state(config, torch.device("cuda", get_world().local_rank))
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
lora_state.register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
|
||||
uses_gpt_oss_moe_adapter = (
|
||||
isinstance(model, PreTrainedModelPrimeRL) and getattr(model.config, "model_type", None) == "gpt_oss"
|
||||
)
|
||||
|
||||
from torch.distributed.fsdp import FSDPModule
|
||||
|
||||
@@ -256,25 +259,13 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
)
|
||||
# Handle GroupedExperts (MoE)
|
||||
elif isinstance(base_module, GroupedExperts):
|
||||
lora_module = MultiLoRAGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle NonGatedGroupedExperts (relu2 experts used by NemotronH's LatentMoE)
|
||||
elif isinstance(base_module, NonGatedGroupedExperts):
|
||||
lora_module = MultiLoRANonGatedGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle GptOssGroupedExperts (gpt-oss fused gate_up + biases)
|
||||
elif isinstance(base_module, GptOssGroupedExperts):
|
||||
lora_module = MultiLoRAGptOssGroupedExperts(
|
||||
if uses_gpt_oss_moe_adapter:
|
||||
wrapper = MultiLoRAGptOssGroupedExperts
|
||||
elif base_module.gate_proj is not None:
|
||||
wrapper = MultiLoRAGroupedExperts
|
||||
else:
|
||||
wrapper = MultiLoRANonGatedGroupedExperts
|
||||
lora_module = wrapper(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=1,
|
||||
@@ -284,7 +275,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
else:
|
||||
logger.warning(
|
||||
f"Module {module_name} is type {type(base_module).__name__}, "
|
||||
f"expected nn.Linear, GroupedExperts, NonGatedGroupedExperts, or GptOssGroupedExperts. Skipping."
|
||||
"expected nn.Linear or GroupedExperts. Skipping."
|
||||
)
|
||||
continue
|
||||
|
||||
|
||||
+48
-157
@@ -15,13 +15,10 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
@@ -32,10 +29,9 @@ from prime_rl.configs.trainer import (
|
||||
FP8Config,
|
||||
ModelConfig,
|
||||
MXFP8Config,
|
||||
QuantizationConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.trainer.distributed import DeepEPExpertParallel, MXFP8AllToAllExpertParallel
|
||||
from prime_rl.trainer.activation_checkpointing import get_activation_checkpoint_wrapper
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
AutoModelForCausalLMPrimeRL,
|
||||
@@ -46,16 +42,11 @@ from prime_rl.trainer.models import (
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE, TokenChoiceTopKRouter, _load_fused_moe_kernel
|
||||
from prime_rl.trainer.models.layers.mxfp8_grouped_gemm import apply_mxfp8_moe_grouped_gemm
|
||||
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
|
||||
from prime_rl.trainer.models.layers.mxfp8_linear import replace_linear_with_mxfp8_linear
|
||||
from prime_rl.trainer.moe_runtime import configure_moe_runtime
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -403,8 +394,8 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
if mlp is None:
|
||||
continue
|
||||
|
||||
# Custom implementation: MoE/LatentMoE class with router attribute
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
# Custom implementation
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
@@ -431,7 +422,7 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
@@ -443,39 +434,6 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Running {num_routers} MoE router gates in fp32")
|
||||
|
||||
|
||||
def apply_fused_moe_kernel(model: nn.Module, quantization: QuantizationConfig | None) -> None:
|
||||
"""
|
||||
Route MoE routed-expert compute through the our fused bf16/mxfp8 MoE CUDA kernel.
|
||||
Forward runs the kernel, backward recomputes the reference grouped-mm path.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_moe_layers = 0
|
||||
|
||||
# MXFP8 with grouped GEMM is the one setting that quantizes the experts themselves, so this also picks the MXFP8 kernel."""
|
||||
dtype = "mxfp8" if isinstance(quantization, MXFP8Config) and quantization.enable_grouped_gemm else "bf16"
|
||||
kernel = _load_fused_moe_kernel()
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
if mlp.score_before_experts:
|
||||
raise ValueError(
|
||||
"model.moe_fused_kernel=true requires MoE layers with score_before_experts=false, because the fused kernel applies the routing scores to the expert outputs."
|
||||
)
|
||||
_, hidden_dim, dim = mlp.experts.w1.shape
|
||||
reason = kernel.unsupported_shape_reason(dim, hidden_dim, mxfp8=dtype == "mxfp8")
|
||||
if reason is not None:
|
||||
raise ValueError(f"model.moe_fused_kernel=true does not support this model: {reason}")
|
||||
mlp.fused_kernel = dtype
|
||||
num_moe_layers += 1
|
||||
|
||||
if num_moe_layers == 0:
|
||||
raise ValueError("model.moe_fused_kernel=true but no MoE layers found. Is this a custom-impl MoE model?")
|
||||
|
||||
logger.info(f"Using the fused {dtype} MoE kernel for {num_moe_layers} MoE layers")
|
||||
|
||||
|
||||
def get_full_offload_dtype_policy(
|
||||
model: nn.Module,
|
||||
config: ModelConfig,
|
||||
@@ -489,7 +447,7 @@ def get_full_offload_dtype_policy(
|
||||
language_model = get_language_model(model)
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
@@ -527,7 +485,7 @@ def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
@@ -544,20 +502,6 @@ def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
|
||||
|
||||
def configure_moe_ep_backend(model: nn.Module, config: ModelConfig) -> None:
|
||||
backend = config.ep_comm_backend
|
||||
if backend == "deepep":
|
||||
from prime_rl.trainer.distributed.deepep import configure_num_sms
|
||||
|
||||
configure_num_sms(config.deepep_num_sms)
|
||||
language_model = get_language_model(model)
|
||||
for transformer_block in language_model.layers:
|
||||
if not isinstance(transformer_block.mlp, (MoE, LatentMoE)):
|
||||
continue
|
||||
transformer_block.mlp.set_ep_comm_backend(backend)
|
||||
transformer_block.mlp.set_deepep_token_chunk_size(config.deepep_token_chunk_size)
|
||||
|
||||
|
||||
def get_load_balance_stats(
|
||||
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
|
||||
) -> dict[str, Tensor | None]:
|
||||
@@ -647,13 +591,6 @@ def get_model(
|
||||
subconfig = getattr(model_config, subconfig_key, None)
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
# MoEArgs.fp8 (read via getattr(config, "fp8") in the modeling files) gates the
|
||||
# DeepGEMM FP8 grouped GEMM. MXFP8 grouped GEMM is applied by wrapping the expert
|
||||
# weights with torchao (see apply_quantization), so it leaves this flag False and
|
||||
# the experts keep calling torch._grouped_mm — which the wrapper tensor intercepts.
|
||||
model_config.fp8 = isinstance(config.quantization, FP8Config) and config.quantization.enable_grouped_gemm
|
||||
|
||||
if config.index_cache is not None:
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
@@ -855,12 +792,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
|
||||
for transformer_block in transformer_layers:
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if parallel_dims.ep_enabled and block_mlp is not None and isinstance(block_mlp, MoE):
|
||||
fully_shard(block_mlp.experts, mesh=dp_mod_ep_mesh, **fsdp_config)
|
||||
|
||||
block_mlp.experts.set_gradient_divide_factor(parallel_dims.fsdp_gradient_divide_factor)
|
||||
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if config.moe_router_dtype == "float32" and isinstance(block_mlp, MoE):
|
||||
# Own FSDP unit with an fp32 policy so the gate weight is not cast to
|
||||
# bf16 for forward and its gradients reduce in fp32.
|
||||
fully_shard(
|
||||
@@ -923,7 +860,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
for transformer_block, next_transformer_block in zip(transformer_blocks, next_transformer_blocks):
|
||||
if next_transformer_block is not None:
|
||||
next_mlp = getattr(next_transformer_block, "mlp", None)
|
||||
if next_mlp is not None and isinstance(next_mlp, (MoE, LatentMoE)):
|
||||
if next_mlp is not None and isinstance(next_mlp, MoE):
|
||||
prefetch_modules = [next_transformer_block]
|
||||
if isinstance(next_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(next_mlp.router)
|
||||
@@ -940,15 +877,23 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
prev_transformer_blocks = reversed_transformer_blocks[1:] + [None]
|
||||
|
||||
if language_model.norm is not None and model.lm_head is not None and len(language_model.layers) > 0:
|
||||
last_transformer_block = reversed_transformer_blocks[0]
|
||||
prefetch_modules = [last_transformer_block]
|
||||
last_mlp = getattr(last_transformer_block, "mlp", None)
|
||||
if last_mlp is not None and isinstance(last_mlp, MoE):
|
||||
prefetch_modules.append(last_mlp.experts)
|
||||
if isinstance(last_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(last_mlp.router)
|
||||
|
||||
if shard_norm_and_lm_head:
|
||||
model.lm_head.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
|
||||
model.lm_head.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
else:
|
||||
model.set_modules_to_backward_prefetch([reversed_transformer_blocks[0]])
|
||||
model.set_modules_to_backward_prefetch(prefetch_modules)
|
||||
|
||||
for transformer_block, prev_transformer_block in zip(reversed_transformer_blocks, prev_transformer_blocks):
|
||||
if prev_transformer_block is not None:
|
||||
prev_mlp = getattr(prev_transformer_block, "mlp", None)
|
||||
if prev_mlp is not None and isinstance(prev_mlp, (MoE, LatentMoE)):
|
||||
if prev_mlp is not None and isinstance(prev_mlp, MoE):
|
||||
prefetch_modules = [prev_transformer_block, prev_mlp.experts]
|
||||
if isinstance(prev_mlp.router, FSDPModule):
|
||||
prefetch_modules.append(prev_mlp.router)
|
||||
@@ -994,6 +939,9 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
|
||||
model_keys = dict.fromkeys(model.state_dict().keys())
|
||||
|
||||
if source_path.name == "prime" and not (source_path / ".prime-v1").is_file():
|
||||
raise RuntimeError(f"PrimeRL conversion cache {source_path} is missing the required .prime-v1 marker")
|
||||
|
||||
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
|
||||
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
|
||||
|
||||
@@ -1009,6 +957,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
snapshot_state_dict = load_state_dict(source_path)
|
||||
model.convert_to_prime(snapshot_state_dict)
|
||||
save_state_dict(snapshot_state_dict, snapshot_path)
|
||||
(snapshot_path / ".prime-v1").touch()
|
||||
del snapshot_state_dict
|
||||
|
||||
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
|
||||
@@ -1027,6 +976,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
|
||||
# All ranks wait for master rank to finish conversion
|
||||
torch.distributed.barrier()
|
||||
if (
|
||||
isinstance(model, PreTrainedModelPrimeRL)
|
||||
and snapshot_path.name == "prime"
|
||||
and not (snapshot_path / ".prime-v1").is_file()
|
||||
):
|
||||
raise RuntimeError(f"PrimeRL conversion cache {snapshot_path} is missing the required .prime-v1 marker")
|
||||
|
||||
logger.info(f"Loading weights using HF DCP from {snapshot_path}")
|
||||
load_dcp_start_time = time.perf_counter()
|
||||
@@ -1079,7 +1034,9 @@ def can_reinit_empty_buffers(model: nn.Module):
|
||||
if not (name.startswith("model.layers.") and name.endswith("mlp.tokens_per_expert"))
|
||||
]
|
||||
buffer_names = [
|
||||
name for name in buffer_names if not (name.startswith("model.layers.") and name.endswith("mlp.expert_bias"))
|
||||
name
|
||||
for name in buffer_names
|
||||
if not (name.startswith("model.layers.") and name.endswith("mlp.router.selection_bias"))
|
||||
]
|
||||
# HF standard transformer model
|
||||
if len(buffer_names) == 1 and buffer_names[0] == "model.rotary_emb.inv_freq":
|
||||
@@ -1139,50 +1096,20 @@ def reshard_module(model: nn.Module):
|
||||
|
||||
|
||||
def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
target_list = sorted(frozenset(ac_config.targets))
|
||||
selective_layers = 0
|
||||
full_layers = 0
|
||||
fallback_layer_types: set[str] = set()
|
||||
model_supported_targets: set[str] = set()
|
||||
wrap_block = get_activation_checkpoint_wrapper(ac_config)
|
||||
checkpointed_layers = 0
|
||||
|
||||
for layer_id, (layer_name, transformer_block) in enumerate(language_model.layers.named_children()):
|
||||
if layer_id % ac_config.freq != 0:
|
||||
continue
|
||||
|
||||
if ac_config.mode == "selective" and supports_selective_activation_checkpointing(transformer_block):
|
||||
model_supported_targets.update(get_supported_targets(transformer_block))
|
||||
set_selective_activation_checkpointing(transformer_block, target_list)
|
||||
selective_layers += 1
|
||||
else:
|
||||
if ac_config.mode == "selective":
|
||||
fallback_layer_types.add(type(transformer_block).__name__)
|
||||
transformer_block = checkpoint_wrapper(transformer_block, preserve_rng_state=False)
|
||||
full_layers += 1
|
||||
language_model.layers.register_module(layer_name, wrap_block(transformer_block))
|
||||
checkpointed_layers += 1
|
||||
|
||||
language_model.layers.register_module(layer_name, transformer_block)
|
||||
|
||||
if ac_config.mode == "selective":
|
||||
unsupported_targets = frozenset(target_list) - model_supported_targets
|
||||
if unsupported_targets:
|
||||
raise ValueError(
|
||||
f"Selective activation checkpoint targets {sorted(unsupported_targets)} are not supported "
|
||||
f"by the selected model layers. Supported targets across the model: {sorted(model_supported_targets)}"
|
||||
)
|
||||
if fallback_layer_types:
|
||||
logger.warning(
|
||||
"Selective activation checkpointing is not supported for layer types "
|
||||
f"{sorted(fallback_layer_types)}; falling back to full checkpointing for those layers."
|
||||
)
|
||||
logger.info(
|
||||
"Applied selective activation checkpointing "
|
||||
f"(freq={ac_config.freq}, targets={target_list}, selective_layers={selective_layers}, "
|
||||
f"full_fallback_layers={full_layers})"
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(f"Applied activation checkpointing (freq={ac_config.freq})")
|
||||
get_logger().info(
|
||||
f"Applied {ac_config.mode} activation checkpointing to {checkpointed_layers} layers (freq={ac_config.freq})"
|
||||
)
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
@@ -1195,13 +1122,9 @@ def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
|
||||
|
||||
def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
"""Swap dense linears and MoE expert GEMMs to the configured low-precision path.
|
||||
"""Swap dense linear modules to the configured low-precision path.
|
||||
|
||||
Runs after the LM head is injected but before LoRA / EP / FSDP so the swapped
|
||||
modules and wrapped parameters are picked up by the later parallelisms. The
|
||||
FP8 grouped GEMM (DeepGEMM) is gated separately via ``model_config.fp8`` since
|
||||
it lives inside the modeling code; here we only handle the dense-linear swap
|
||||
and the torchao MXFP8 expert-weight wrapping.
|
||||
Routed-expert compute is configured independently by ``model.moe.compute``.
|
||||
"""
|
||||
quant = config.quantization
|
||||
if quant is None:
|
||||
@@ -1211,33 +1134,11 @@ def apply_quantization(model: nn.Module, config: ModelConfig) -> None:
|
||||
replace_linear_with_fp8_blockwise_linear(model, ignore_modules=quant.ignore_patterns)
|
||||
elif isinstance(quant, MXFP8Config):
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability < (10, 0):
|
||||
if capability != (10, 0):
|
||||
raise ValueError(
|
||||
f"MXFP8 quantization requires SM100 (Blackwell) or newer, but device is SM{capability[0]}{capability[1]}."
|
||||
f"MXFP8 quantization requires SM100 (Blackwell), but device is SM{capability[0]}{capability[1]}."
|
||||
)
|
||||
replace_linear_with_mxfp8_linear(model, recipe=quant.recipe, ignore_modules=quant.ignore_patterns)
|
||||
if quant.enable_grouped_gemm:
|
||||
apply_mxfp8_moe_grouped_gemm(model, recipe=quant.recipe)
|
||||
|
||||
|
||||
def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims):
|
||||
language_model = get_language_model(model)
|
||||
for transformer_block in language_model.layers:
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is not None and isinstance(block_mlp, (MoE, LatentMoE)):
|
||||
if config.ep_comm_backend == "torch":
|
||||
quant = config.quantization
|
||||
if isinstance(quant, MXFP8Config) and quant.enable_a2a:
|
||||
parallelize_plan = MXFP8AllToAllExpertParallel()
|
||||
else:
|
||||
parallelize_plan = ExpertParallel()
|
||||
else:
|
||||
parallelize_plan = DeepEPExpertParallel()
|
||||
parallelize_module(
|
||||
block_mlp.experts,
|
||||
device_mesh=parallel_dims.get_mesh("ep"),
|
||||
parallelize_plan=parallelize_plan,
|
||||
)
|
||||
|
||||
|
||||
def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None:
|
||||
@@ -1266,7 +1167,7 @@ def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None:
|
||||
|
||||
def _reset_runtime_moe_buffers(model: nn.Module) -> None:
|
||||
for module in model.modules():
|
||||
if isinstance(module, (MoE, LatentMoE)) and module.tokens_per_expert.device.type != "meta":
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
|
||||
|
||||
@@ -1330,7 +1231,6 @@ def setup_model(
|
||||
|
||||
# 1. We load to meta device by default
|
||||
model = get_model(config, device=torch.device("meta"), dtype=DTYPE_MAP[config.optimization_dtype])
|
||||
configure_moe_ep_backend(model, config)
|
||||
|
||||
possible_to_load_to_meta = can_reinit_empty_buffers(model)
|
||||
|
||||
@@ -1343,7 +1243,6 @@ def setup_model(
|
||||
if not possible_to_load_to_meta:
|
||||
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
|
||||
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
|
||||
configure_moe_ep_backend(model, config)
|
||||
|
||||
lm_head_chunk_size: int | None = None
|
||||
if isinstance(config.fused_lm_head_token_chunk_size, int):
|
||||
@@ -1361,14 +1260,6 @@ def setup_model(
|
||||
if config.moe_router_dtype == "float32":
|
||||
apply_fp32_moe_router(model)
|
||||
|
||||
if config.moe_fused_kernel:
|
||||
if parallel_dims.ep_enabled:
|
||||
raise ValueError(
|
||||
"model.moe_fused_kernel=true requires ep=1: the fused kernel bypasses the EP "
|
||||
"all-to-all and indexes experts with global ids."
|
||||
)
|
||||
apply_fused_moe_kernel(model, config.quantization)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
@@ -1377,8 +1268,8 @@ def setup_model(
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
configure_moe_runtime(model, config, parallel_dims)
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, config, parallel_dims)
|
||||
# EP replaces params with DTensors that default to requires_grad=True,
|
||||
# re-freeze base params that LoRA froze earlier.
|
||||
if config.lora is not None:
|
||||
|
||||
@@ -37,21 +37,16 @@ class AfmoeConfig(PretrainedConfig):
|
||||
num_experts=64,
|
||||
num_experts_per_tok=6,
|
||||
num_shared_experts=2,
|
||||
num_expert_groups=1,
|
||||
num_limited_groups=1,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts: bool = False,
|
||||
load_balance_coeff: float = 5e-4,
|
||||
use_grouped_mm: bool = True,
|
||||
global_attn_every_n_layers=4,
|
||||
sliding_window=1024,
|
||||
mup_enabled=False,
|
||||
layer_types=None,
|
||||
attention_dropout: float = 0.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
@@ -71,18 +66,13 @@ class AfmoeConfig(PretrainedConfig):
|
||||
# MoE specific
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts = num_experts
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.num_expert_groups = num_expert_groups
|
||||
self.num_limited_groups = num_limited_groups
|
||||
self.score_func = score_func
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.score_before_experts = score_before_experts
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
# Attention specific
|
||||
self.attention_dropout = attention_dropout
|
||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
AFMoE specifics:
|
||||
|
||||
* Per-layer MLP prefix is ``model.layers.{i}.mlp``.
|
||||
* The router shares its name between HF and prime, so it is *not* renamed.
|
||||
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to prime
|
||||
``shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on the prime side).
|
||||
* The router gate shares its name between HF and prime, while HF
|
||||
``mlp.expert_bias`` maps to PrimeRL ``mlp.router.selection_bias``.
|
||||
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to PrimeRL
|
||||
``shared_expert.{gate,down,up}_proj.weight``.
|
||||
* Routed experts: HF per-expert ``experts.{e}.{gate,down,up}_proj.weight`` stack
|
||||
into prime ``experts.{w1,w2,w3}`` along dim 0 (no fused gate_up layout).
|
||||
into PrimeRL ``experts.{gate,down,up}_proj`` along dim 0.
|
||||
* Prime-only runtime buffers ``mlp.tokens_per_expert`` and ``mlp.reorderer.*``
|
||||
are dropped on the way back to HF.
|
||||
"""
|
||||
@@ -21,8 +22,9 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}.mlp"
|
||||
ops.append(Rename(f"{p}.expert_bias", f"{p}.router.selection_bias"))
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Stack(stacked=f"{p}.experts.{wn}", item=f"{p}.experts.{{e}}.{hf_proj}.weight"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
|
||||
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
@@ -82,18 +82,6 @@ class AfmoeAttentionBase(nn.Module):
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def output_proj(
|
||||
self,
|
||||
attn_output: torch.Tensor,
|
||||
gate_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
input_shape = gate_states.shape[:-1]
|
||||
if attn_output.dim() == 4:
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
|
||||
class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
@@ -125,21 +113,14 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
def attn_projections(
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -159,25 +140,10 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
return query_states, key_states, value_states, gate_states
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
query_states, key_states, value_states, gate_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
return self.output_proj(attn_output, gate_states), None
|
||||
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate_states)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
AFMOE_ATTN_IMPL2CLASS = {
|
||||
@@ -242,28 +208,38 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
self.post_mlp_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
self.moe_enabled = layer_idx >= config.num_dense_layers
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=config.num_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func=config.score_func,
|
||||
route_norm=config.route_norm,
|
||||
route_scale=config.route_scale,
|
||||
score_before_experts=getattr(config, "score_before_experts", False),
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.num_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.num_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -325,7 +301,7 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -213,24 +213,6 @@ class SplitConcat(ConvOp):
|
||||
sd[self.combined] = torch.cat(tensors, dim=self.dim)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Synthetic(ConvOp):
|
||||
"""A prime-only tensor with no HF counterpart, created on forward and
|
||||
dropped on backward (e.g. NemotronH's dummy ``experts.w3`` of shape (0,)).
|
||||
|
||||
``factory`` builds the tensor from the current state dict (so it can match
|
||||
device/dtype of a sibling)."""
|
||||
|
||||
prime: str
|
||||
factory: Callable[[StateDict], Tensor]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
sd[self.prime] = self.factory(sd)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
sd.pop(self.prime, None)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MapValue(ConvOp):
|
||||
"""Apply a value transform to one key. ``forward`` runs HF->prime,
|
||||
@@ -314,11 +296,11 @@ def key_present(name: str) -> Callable[[StateDict], bool]:
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Shared composition helper for Llama-style routed experts (prime w1=gate,
|
||||
# w2=down, w3=up). Used by several models' converting_<model>.py.
|
||||
# Shared composition helper for Llama-style routed experts (prime gate_proj=gate,
|
||||
# down_proj=down, up_proj=up). Used by several models' converting_<model>.py.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GATE_DOWN_UP = (("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj"))
|
||||
GATE_DOWN_UP = (("gate_proj", "gate_proj"), ("down_proj", "down_proj"), ("up_proj", "up_proj"))
|
||||
|
||||
|
||||
def routed_experts_op(
|
||||
@@ -335,14 +317,14 @@ def routed_experts_op(
|
||||
Per-expert HF weights <-> stacked prime tensors is a :class:`Stack` per
|
||||
proj. ``hf_experts``/``prime_experts`` are the (relative) expert container
|
||||
names (e.g. ``mlp.experts`` / ``block_sparse_moe.experts``); ``proj_order``
|
||||
maps prime ``wN`` to the HF per-expert proj name.
|
||||
maps prime projection names to the HF per-expert proj name.
|
||||
|
||||
With ``fused`` set, the transformers-v5 fused ``gate_up_proj`` input is also
|
||||
accepted: a :class:`Conditional` on its presence splits it (dim 1) into
|
||||
w1/w3 and renames ``down_proj`` -> w2; otherwise the per-expert ``Stack``s
|
||||
run. Prime always stores split w1/w2/w3, so the backward path always goes
|
||||
through the per-expert ``Stack`` unstack (the fused key is absent in prime,
|
||||
so the conditional takes the else branch)."""
|
||||
gate_proj/up_proj and renames ``down_proj``; otherwise the per-expert
|
||||
``Stack``s run. Prime always stores split gate/down/up projections, so the
|
||||
backward path always goes through the per-expert ``Stack`` unstack (the
|
||||
fused key is absent in prime, so the conditional takes the else branch)."""
|
||||
stacks = [
|
||||
Stack(
|
||||
stacked=f"{prefix}.{prime_experts}.{wn}",
|
||||
@@ -356,9 +338,12 @@ def routed_experts_op(
|
||||
fused_then = [
|
||||
SplitConcat(
|
||||
combined=gate_up,
|
||||
parts=[(f"{prefix}.{prime_experts}.w1", None), (f"{prefix}.{prime_experts}.w3", None)],
|
||||
parts=[
|
||||
(f"{prefix}.{prime_experts}.gate_proj", None),
|
||||
(f"{prefix}.{prime_experts}.up_proj", None),
|
||||
],
|
||||
dim=1,
|
||||
),
|
||||
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.w2"),
|
||||
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.down_proj"),
|
||||
]
|
||||
return Conditional(key_present(gate_up), then=fused_then, else_=stacks)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import warnings
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
@@ -97,10 +95,6 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
Number of routed experts.
|
||||
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
||||
Scaling factor or routed experts.
|
||||
n_group (`int`, *optional*, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, *optional*, defaults to 1):
|
||||
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
||||
first_k_dense_replace (`int`, *optional*, defaults to 1):
|
||||
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
||||
\--k dense layers--/
|
||||
@@ -128,9 +122,9 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
@@ -165,12 +159,9 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
n_shared_experts=1,
|
||||
n_routed_experts=128,
|
||||
routed_scaling_factor=1.0,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
first_k_dense_replace=1,
|
||||
norm_topk_prob=True,
|
||||
use_qk_norm=False,
|
||||
use_grouped_mm=True,
|
||||
pad_token_id=None,
|
||||
**kwargs,
|
||||
):
|
||||
@@ -196,18 +187,12 @@ class Glm4MoeConfig(PretrainedConfig):
|
||||
# MoE arguments
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
|
||||
@@ -4,15 +4,14 @@ GLM-4 MoE specifics:
|
||||
|
||||
* Router: HF ``mlp.gate.weight`` -> prime ``mlp.router.gate.weight``.
|
||||
* Expert bias: HF ``mlp.gate.e_score_correction_bias`` -> prime
|
||||
``mlp.expert_bias``.
|
||||
``mlp.router.selection_bias``.
|
||||
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
|
||||
stack into prime ``mlp.experts.{w1,w2,w3}`` along dim 0; the fused
|
||||
stack into prime ``mlp.experts.{gate,down,up}_proj`` along dim 0; the fused
|
||||
transformers-v5 ``mlp.experts.gate_up_proj`` / ``down_proj`` layout is also
|
||||
accepted on the way in (split along dim 1).
|
||||
* Shared experts: HF ``mlp.shared_experts.{gate,down,up}_proj.weight`` map to
|
||||
prime ``mlp.shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on prime; this
|
||||
is a plain rename forward). On the way back to HF, GLM strips a leading
|
||||
singleton dim from each shared-expert tensor when present
|
||||
prime ``mlp.shared_expert.{gate,down,up}_proj.weight``. On the way back to HF,
|
||||
GLM strips a leading singleton dim from each shared-expert tensor when present
|
||||
(:class:`~prime_rl.trainer.models.conversion_ops.SqueezeLeading`,
|
||||
backward-only).
|
||||
* Prime-only runtime buffer ``mlp.tokens_per_expert`` is dropped on the way
|
||||
@@ -42,7 +41,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
|
||||
p = f"model.layers.{layer_idx}.mlp"
|
||||
ops: list[ConvOp] = [
|
||||
Rename(f"{p}.gate.weight", f"{p}.router.gate.weight"),
|
||||
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.expert_bias"),
|
||||
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.router.selection_bias"),
|
||||
routed_experts_op(
|
||||
f"model.layers.{layer_idx}",
|
||||
hf_experts="mlp.experts",
|
||||
@@ -55,7 +54,7 @@ def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
|
||||
# restored the HF key, so it precedes the Rename in the forward list
|
||||
# (apply_prime_to_hf plays the chain in reverse).
|
||||
ops.append(SqueezeLeading(f"{p}.shared_experts.{hf_proj}.weight"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
return ops
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfi
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import conversion_chain
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
@@ -55,27 +55,36 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
num_shared_experts=config.n_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if layer_idx >= config.first_k_dense_replace:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.n_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -126,7 +135,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
return name.endswith("mlp.router.selection_bias")
|
||||
|
||||
def _init_weights(self, module):
|
||||
super()._init_weights(module)
|
||||
@@ -140,7 +149,7 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
"""Check if the state dict contains MoE layers in PrimeRL training format."""
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import warnings
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
@@ -56,10 +54,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
Dimension of value heads.
|
||||
qk_nope_head_dim (`int`, defaults to 192):
|
||||
Dimension of query/key heads that don't use rotary position embeddings.
|
||||
n_group (`int`, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, defaults to 1):
|
||||
Number of selected groups per token.
|
||||
num_experts_per_tok (`int`, defaults to 8):
|
||||
Number of active experts per token.
|
||||
first_k_dense_replace (`int`, defaults to 3):
|
||||
@@ -101,8 +95,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
field is absent from the config).
|
||||
topk_method (`str`, defaults to `"noaux_tc"`):
|
||||
MoE routing top-k method used by GLM-5 checkpoints.
|
||||
use_grouped_mm (`bool`, defaults to `True`):
|
||||
Whether to use grouped matrix multiplication for MoE.
|
||||
"""
|
||||
|
||||
model_type = "glm_moe_dsa"
|
||||
@@ -111,9 +103,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
@@ -141,8 +133,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
qk_nope_head_dim=192,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
num_experts_per_tok=8,
|
||||
first_k_dense_replace=3,
|
||||
norm_topk_prob=True,
|
||||
@@ -169,7 +159,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
indexer_types=None,
|
||||
scoring_func="sigmoid",
|
||||
topk_method="noaux_tc",
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
@@ -194,8 +183,6 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.first_k_dense_replace = first_k_dense_replace
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
@@ -226,12 +213,8 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.indexer_types = indexer_types
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
|
||||
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
|
||||
# overwrite self.head_dim and break the rotary embedding dimension.
|
||||
|
||||
@@ -90,13 +90,13 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
|
||||
expert_bias_key = f"{prefix}.mlp.expert_bias"
|
||||
if expert_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[expert_bias_key])
|
||||
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
|
||||
if selection_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
|
||||
|
||||
w1_key = f"{prefix}.mlp.experts.w1"
|
||||
w2_key = f"{prefix}.mlp.experts.w2"
|
||||
w3_key = f"{prefix}.mlp.experts.w3"
|
||||
w1_key = f"{prefix}.mlp.experts.gate_proj"
|
||||
w2_key = f"{prefix}.mlp.experts.down_proj"
|
||||
w3_key = f"{prefix}.mlp.experts.up_proj"
|
||||
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
|
||||
w1 = state_dict[w1_key]
|
||||
w2 = state_dict[w2_key]
|
||||
@@ -124,9 +124,9 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = w13
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = w2
|
||||
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.w1"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.w2"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.w3"
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
|
||||
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
|
||||
sw1 = state_dict[sw1_key]
|
||||
sw2 = state_dict[sw2_key]
|
||||
|
||||
@@ -20,7 +20,7 @@ from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
@@ -56,27 +56,36 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.n_routed_experts,
|
||||
num_shared_experts=config.n_shared_experts,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if layer_idx >= config.first_k_dense_replace:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
shared_expert = None
|
||||
if config.n_shared_experts > 0:
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size * config.n_shared_experts,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=shared_expert,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -136,7 +145,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
return name.endswith("mlp.router.selection_bias")
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
@@ -144,7 +153,7 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -10,11 +10,9 @@ from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla
|
||||
except ImportError:
|
||||
sparse_mla_fwd_interface = None # type: ignore
|
||||
sparse_mla_bwd = None # type: ignore
|
||||
sparse_mla = None # type: ignore
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -36,23 +34,6 @@ class SparseMlaAttentionArgs:
|
||||
skip_topk: bool = False
|
||||
|
||||
|
||||
class _SparseMLA(torch.autograd.Function):
|
||||
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, q, kv, indices, sm_scale):
|
||||
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, do):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
def apply_rope_interleave_single(
|
||||
t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
@@ -177,7 +158,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
|
||||
def attn_projections(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
def mla_latents(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
|
||||
@@ -224,15 +205,6 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
assert sparse_kv.shape[1] == s_full + 1
|
||||
return sparse_q, sparse_kv, w_v
|
||||
|
||||
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
return torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
|
||||
def output_proj(self, attn_output: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
attn_output = self._mla_unabsorb(attn_output, w_v)
|
||||
batch_size, total_tokens = attn_output.shape[:2]
|
||||
attn_output = attn_output.reshape(batch_size, total_tokens, -1)
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -241,7 +213,7 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
ke: torch.Tensor | None = None,
|
||||
cached_indices: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
|
||||
q_latent, k_compressed_normed, k_rope = self.mla_latents(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
@@ -268,6 +240,9 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
position_embeddings_full=position_embeddings,
|
||||
)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out, _ = sparse_mla(sparse_q, sparse_kv, indices, self.scaling)
|
||||
out = torch.einsum("bshk,hdk->bshd", out, w_v)
|
||||
batch_size, total_tokens = out.shape[:2]
|
||||
out = out.reshape(batch_size, total_tokens, -1)
|
||||
cached_indices = indices if self.use_index_cache else None
|
||||
return self.output_proj(out, w_v), cached_indices
|
||||
return self.o_proj(out), cached_indices
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Re-export HF's GptOssConfig so the parameter naming and rope/sliding-window defaults
|
||||
# stay in sync with upstream. We don't need to subclass it: the only PrimeRL-specific
|
||||
# behavior lives in modeling_gpt_oss.py (custom MoE for LoRA detection).
|
||||
# behavior lives in the model and checkpoint conversion modules.
|
||||
from transformers.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
|
||||
__all__ = ["GptOssConfig"]
|
||||
|
||||
@@ -1,27 +1,58 @@
|
||||
"""State-dict conversion for GPT-OSS.
|
||||
|
||||
The custom prime-rl GPT-OSS implementation mirrors HuggingFace's parameter naming
|
||||
exactly (gate_up_proj/gate_up_proj_bias/down_proj/down_proj_bias plus router.weight
|
||||
and router.bias as nn.Parameters). So loading the unsloth BF16 checkpoint requires
|
||||
no key conversion - HF and prime formats are identical for this model.
|
||||
"""
|
||||
"""HF <-> PrimeRL weight conversion for GPT-OSS."""
|
||||
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename
|
||||
|
||||
|
||||
class GptOssExperts(ConvOp):
|
||||
def __init__(self, prefix: str) -> None:
|
||||
self.prefix = prefix
|
||||
|
||||
def hf_to_prime(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_up_name = f"{self.prefix}.gate_up_proj"
|
||||
gate_up = state_dict.pop(gate_up_name)
|
||||
gate_up_bias = state_dict.pop(f"{self.prefix}.gate_up_proj_bias")
|
||||
state_dict[f"{self.prefix}.gate_proj"] = gate_up[..., ::2].transpose(-2, -1)
|
||||
state_dict[f"{self.prefix}.up_proj"] = gate_up[..., 1::2].transpose(-2, -1)
|
||||
state_dict[f"{self.prefix}.gate_proj_bias"] = gate_up_bias[..., ::2]
|
||||
state_dict[f"{self.prefix}.up_proj_bias"] = gate_up_bias[..., 1::2]
|
||||
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
|
||||
|
||||
def prime_to_hf(self, state_dict: dict[str, Tensor]) -> None:
|
||||
gate_name = f"{self.prefix}.gate_proj"
|
||||
gate = state_dict.pop(gate_name).transpose(-2, -1)
|
||||
up = state_dict.pop(f"{self.prefix}.up_proj").transpose(-2, -1)
|
||||
gate_bias = state_dict.pop(f"{self.prefix}.gate_proj_bias")
|
||||
up_bias = state_dict.pop(f"{self.prefix}.up_proj_bias")
|
||||
state_dict[f"{self.prefix}.gate_up_proj"] = gate.new_empty((*gate.shape[:-1], 2 * gate.shape[-1]))
|
||||
state_dict[f"{self.prefix}.gate_up_proj"][..., ::2] = gate
|
||||
state_dict[f"{self.prefix}.gate_up_proj"][..., 1::2] = up
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"] = gate_bias.new_empty(
|
||||
(*gate_bias.shape[:-1], 2 * gate_bias.shape[-1])
|
||||
)
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., ::2] = gate_bias
|
||||
state_dict[f"{self.prefix}.gate_up_proj_bias"][..., 1::2] = up_bias
|
||||
state_dict[f"{self.prefix}.down_proj"] = state_dict[f"{self.prefix}.down_proj"].transpose(-2, -1)
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict)
|
||||
|
||||
|
||||
def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
# Prime format equals HF format for GPT-OSS, so we never claim to be a separate
|
||||
# prime format - this disables the auto-conversion path in load_dcp_from_hf and
|
||||
# lets DCP load HF safetensors directly.
|
||||
return False
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
# HF and prime layouts coincide for GPT-OSS, so the conversion is the identity.
|
||||
return []
|
||||
operations: list[ConvOp] = []
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
prefix = f"model.layers.{layer_idx}.mlp"
|
||||
operations.extend(
|
||||
[
|
||||
Rename(f"{prefix}.router.weight", f"{prefix}.router.gate.weight"),
|
||||
Rename(f"{prefix}.router.bias", f"{prefix}.router.gate.bias"),
|
||||
GptOssExperts(f"{prefix}.experts"),
|
||||
]
|
||||
)
|
||||
return operations
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
# GPT-OSS model with PrimeRL custom MoE.
|
||||
#
|
||||
# This file mirrors HuggingFace's modeling_gpt_oss.py but swaps the experts module for
|
||||
# `GptOssGroupedExperts` so the LoRA detection logic in `prime_rl/trainer/lora.py` can
|
||||
# find and adapt the expert weights. Attention, rotary embedding, and RMSNorm are reused
|
||||
# from HF as-is - they correctly handle attention sinks and gpt-oss's split-rotate RoPE.
|
||||
# GPT-OSS model with PrimeRL grouped experts. Attention, rotary embedding, and
|
||||
# RMSNorm are reused from HuggingFace.
|
||||
|
||||
from typing import Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
@@ -31,101 +26,11 @@ from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
is_prime_state_dict,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts
|
||||
|
||||
|
||||
class GptOssTopKRouter(nn.Module):
|
||||
"""Token-choice top-k router matching HF's GptOssTopKRouter parameter naming.
|
||||
|
||||
Stores `weight` (num_experts, hidden_size) and `bias` (num_experts) as raw nn.Parameters
|
||||
so the unsloth BF16 checkpoint loads with no key conversion. Returns the same outputs as
|
||||
`TokenChoiceTopKRouter` so the surrounding MoE plumbing matches the rest of the repo.
|
||||
"""
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.hidden_size = config.hidden_size
|
||||
self.weight = nn.Parameter(torch.empty(self.num_experts, self.hidden_size))
|
||||
self.bias = nn.Parameter(torch.empty(self.num_experts))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""x: (T, hidden). Returns (top_scores, top_indices, num_tokens_per_expert).
|
||||
|
||||
Matches HF's softmax-after-topk semantics: we softmax the top-k logits only,
|
||||
not the full distribution.
|
||||
"""
|
||||
logits = F.linear(x, self.weight, self.bias) # (T, num_experts)
|
||||
top_logits, top_indices = torch.topk(logits, self.top_k, dim=-1)
|
||||
top_scores = F.softmax(top_logits, dim=-1, dtype=top_logits.dtype)
|
||||
num_tokens_per_expert = torch.histc(
|
||||
top_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
)
|
||||
return top_scores, top_indices, num_tokens_per_expert
|
||||
|
||||
def init_weights(self, init_std: float):
|
||||
nn.init.trunc_normal_(self.weight, mean=0.0, std=init_std)
|
||||
nn.init.zeros_(self.bias)
|
||||
|
||||
|
||||
class GptOssMoE(nn.Module):
|
||||
"""GPT-OSS sparse MLP: top-k router + grouped experts with biases.
|
||||
|
||||
Wraps `GptOssGroupedExperts` (which expects pre-permuted tokens + num_tokens_per_expert)
|
||||
with the standard MoE permute/unpermute pipeline. Routing weights are applied AFTER
|
||||
the expert computation, matching HF's `routing_weights[token_idx, top_k_pos]` index_add.
|
||||
"""
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
|
||||
# current FP8 grouped-GEMM path doesn't model that yet.
|
||||
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.router = GptOssTopKRouter(config)
|
||||
self.experts = GptOssGroupedExperts(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
num_experts=self.num_experts,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
bs, slen, dim = hidden_states.shape
|
||||
x = hidden_states.reshape(-1, dim) # (T, dim)
|
||||
|
||||
top_scores, top_indices, num_tokens_per_expert = self.router(x)
|
||||
# top_scores, top_indices: (T, top_k)
|
||||
|
||||
# Sort tokens by expert. Each token contributes top_k entries (one per chosen expert).
|
||||
flat_expert_indices = top_indices.reshape(-1) # (T*top_k,)
|
||||
sorted_perm = torch.argsort(flat_expert_indices, stable=True) # (T*top_k,)
|
||||
# token id of each (token, k) entry, in expert-sorted order
|
||||
token_indices_experts_sorted = sorted_perm // self.top_k
|
||||
# routing weight for each (token, k) entry, in expert-sorted order
|
||||
top_scores_experts_sorted = top_scores.reshape(-1)[sorted_perm]
|
||||
|
||||
# Gather inputs for each expert in expert-sorted order
|
||||
gather_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
routed_input = torch.gather(x, dim=0, index=gather_indices) # (T*top_k, dim)
|
||||
|
||||
routed_output = self.experts(routed_input, num_tokens_per_expert) # (T*top_k, dim)
|
||||
|
||||
# Apply routing weights post-experts (HF: weighted_output = out * routing_weights)
|
||||
routed_output = (routed_output.float() * top_scores_experts_sorted.reshape(-1, 1)).to(routed_output.dtype)
|
||||
|
||||
# Scatter-add back to original token positions
|
||||
out = torch.zeros_like(x)
|
||||
scatter_indices = token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim)
|
||||
out = out.scatter_add(dim=0, index=scatter_indices, src=routed_output)
|
||||
|
||||
out = out.reshape(bs, slen, dim)
|
||||
return out, top_scores # router_scores returned only for compatibility; trainer ignores
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
|
||||
|
||||
class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
@@ -133,7 +38,30 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
|
||||
self.mlp = GptOssMoE(config)
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.num_local_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func="topk_softmax",
|
||||
route_norm=False,
|
||||
route_scale=1.0,
|
||||
gate_bias=True,
|
||||
)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
num_experts=config.num_local_experts,
|
||||
expert_type="gated",
|
||||
activation="clamped_swiglu",
|
||||
bias=True,
|
||||
)
|
||||
self.mlp = MoE(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=None,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=None,
|
||||
)
|
||||
self.input_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = GptOssRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
@@ -162,7 +90,7 @@ class GptOssDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states, _ = self.mlp(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
@@ -276,11 +276,21 @@ def bwd(
|
||||
return sparse_mla_bwd_kernel
|
||||
|
||||
|
||||
def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
|
||||
@torch.library.custom_op("prime_rl::sparse_mla_backward", mutates_args=())
|
||||
def sparse_mla_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous()
|
||||
assert kv.is_contiguous()
|
||||
assert indices.is_contiguous()
|
||||
assert lse.is_contiguous()
|
||||
grad_out = grad_out.contiguous()
|
||||
B, S, H, dim_plus_tail_dim = q.shape
|
||||
_, S_kv, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim_plus_tail_dim
|
||||
@@ -295,9 +305,22 @@ def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
|
||||
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
|
||||
postprocess_kernel = postprocess(D, D_tail, kv_group)
|
||||
|
||||
delta = preprocess_kernel(o, do)
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, do, indices, lse, delta, dkv)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv
|
||||
|
||||
|
||||
@sparse_mla_backward.register_fake
|
||||
def _sparse_mla_backward_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(kv)
|
||||
|
||||
@@ -14,8 +14,11 @@ except Exception:
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_backward
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2, -1],
|
||||
@@ -183,7 +186,17 @@ def sparse_mla_fwd(
|
||||
return main
|
||||
|
||||
|
||||
def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64, num_stages=2, threads=256):
|
||||
@torch.library.custom_op("prime_rl::sparse_mla", mutates_args=())
|
||||
def sparse_mla(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
d_v: int = 512,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
|
||||
batch, seq_len, heads, dim_plus_tail_dim = q.shape
|
||||
_, seq_len_kv, kv_group, _ = kv.shape
|
||||
@@ -210,3 +223,42 @@ def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices)
|
||||
return out, lse
|
||||
|
||||
|
||||
@sparse_mla.register_fake
|
||||
def _sparse_mla_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
d_v: int = 512,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return q.new_empty((*q.shape[:-1], d_v)), q.new_empty(q.shape[:-1], dtype=torch.float32)
|
||||
|
||||
|
||||
def _sparse_mla_setup_context(ctx, inputs, output) -> None:
|
||||
q, kv, indices, sm_scale, _d_v, _block_I, _num_stages, _threads = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, kv, out, indices, lse)
|
||||
ctx.sm_scale = sm_scale
|
||||
ctx.mark_non_differentiable(lse)
|
||||
|
||||
|
||||
def _sparse_mla_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
|
||||
q, kv, out, indices, lse = ctx.saved_tensors
|
||||
dq, dkv = sparse_mla_backward(
|
||||
q.detach(),
|
||||
kv.detach(),
|
||||
out.detach(),
|
||||
grad_out,
|
||||
indices,
|
||||
lse.detach(),
|
||||
ctx.sm_scale,
|
||||
)
|
||||
return dq, dkv, None, None, None, None, None, None
|
||||
|
||||
|
||||
sparse_mla.register_autograd(_sparse_mla_autograd_backward, setup_context=_sparse_mla_setup_context)
|
||||
|
||||
@@ -21,12 +21,13 @@ class LagunaConfig(PretrainedConfig):
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
"layers.*.shared_expert.w1": "colwise",
|
||||
"layers.*.shared_expert.w2": "rowwise",
|
||||
"layers.*.shared_expert.w3": "colwise",
|
||||
"layers.*.mlp.shared_expert.gate_proj": "colwise",
|
||||
"layers.*.mlp.shared_expert.up_proj": "colwise",
|
||||
"layers.*.mlp.shared_expert.down_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
@@ -72,7 +73,6 @@ class LagunaConfig(PretrainedConfig):
|
||||
moe_apply_router_weight_on_input: bool = False,
|
||||
moe_router_logit_softcapping: float = 0.0,
|
||||
load_balance_coeff: float | None = 1e-3,
|
||||
use_grouped_mm: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
|
||||
@@ -107,7 +107,6 @@ class LagunaConfig(PretrainedConfig):
|
||||
self.moe_apply_router_weight_on_input = moe_apply_router_weight_on_input
|
||||
self.moe_router_logit_softcapping = moe_router_logit_softcapping
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
|
||||
@@ -5,14 +5,14 @@ Laguna specifics:
|
||||
* Router: HF ``mlp.gate.weight`` maps to prime ``mlp.router.gate.weight``.
|
||||
* Expert bias: the HF input is *either* ``mlp.experts.e_score_correction_bias``
|
||||
*or* ``mlp.gate.e_score_correction_bias`` (the former wins when both are
|
||||
present); it maps to prime ``mlp.expert_bias``. Backward always emits the
|
||||
present); it maps to prime ``mlp.router.selection_bias``. Backward always emits the
|
||||
canonical ``mlp.experts.e_score_correction_bias``.
|
||||
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
|
||||
*or* the fused ``mlp.experts.gate_up_proj`` / ``down_proj`` layout stack into
|
||||
prime ``mlp.experts.{w1,w2,w3}`` (w1=gate, w2=down, w3=up).
|
||||
prime ``mlp.experts.{gate,down,up}_proj``.
|
||||
* Shared expert: the HF input is *either* ``mlp.shared_expert.*`` *or*
|
||||
``mlp.shared_experts.*`` (singular wins); it maps to prime
|
||||
``shared_expert.{w1,w2,w3}.weight`` (no ``mlp.`` prefix, keeps ``.weight``).
|
||||
``mlp.shared_expert.{gate,down,up}_proj.weight``.
|
||||
Backward always emits the singular ``mlp.shared_expert.*``.
|
||||
* Prime-only ``mlp.tokens_per_expert`` is dropped on the way back to HF.
|
||||
"""
|
||||
@@ -41,14 +41,14 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
# the (always-singular) backward; the conditional adds the forward-only
|
||||
# `gate.` alternate, firing only when the canonical input is absent so it
|
||||
# matches the imperative's "experts wins" preference.
|
||||
ops.append(Rename(f"{p}.mlp.experts.e_score_correction_bias", f"{p}.mlp.expert_bias"))
|
||||
ops.append(Rename(f"{p}.mlp.experts.e_score_correction_bias", f"{p}.mlp.router.selection_bias"))
|
||||
ops.append(
|
||||
Conditional(
|
||||
predicate=lambda sd, p=p: (
|
||||
f"{p}.mlp.gate.e_score_correction_bias" in sd
|
||||
and f"{p}.mlp.experts.e_score_correction_bias" not in sd
|
||||
),
|
||||
then=[Rename(f"{p}.mlp.gate.e_score_correction_bias", f"{p}.mlp.expert_bias")],
|
||||
then=[Rename(f"{p}.mlp.gate.e_score_correction_bias", f"{p}.mlp.router.selection_bias")],
|
||||
)
|
||||
)
|
||||
|
||||
@@ -58,7 +58,7 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
# Shared expert. Base Renames handle the singular input + singular
|
||||
# backward; the conditional adds the forward-only plural alternate.
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.{hf_proj}.weight", f"{p}.mlp.shared_expert.{wn}.weight"))
|
||||
ops.append(
|
||||
Conditional(
|
||||
predicate=lambda sd, p=p: (
|
||||
@@ -66,7 +66,7 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
and f"{p}.mlp.shared_expert.gate_proj.weight" not in sd
|
||||
),
|
||||
then=[
|
||||
Rename(f"{p}.mlp.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight")
|
||||
Rename(f"{p}.mlp.shared_experts.{hf_proj}.weight", f"{p}.mlp.shared_expert.{wn}.weight")
|
||||
for wn, hf_proj in GATE_DOWN_UP
|
||||
],
|
||||
)
|
||||
|
||||
@@ -18,9 +18,10 @@ from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.converting_laguna import conversion_chain
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
|
||||
@@ -126,16 +127,39 @@ class LagunaFlashAttention(FlashAttention):
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
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 position_embeddings is not None:
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, self.num_heads, self.head_dim)
|
||||
if self.gating:
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
# per-head gates broadcast across head_dim; per-element gates are already
|
||||
@@ -171,32 +195,34 @@ class LagunaDecoderLayer(GradientCheckpointingLayer):
|
||||
if self.mlp_layer_type == "sparse":
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=0,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=config.moe_routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if config.moe_router_logit_softcapping:
|
||||
raise NotImplementedError("Laguna router logit softcapping is not supported by PrimeRL MoE yet.")
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
self.shared_expert = FeedForward(
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
expert_type=moe_args.expert_type,
|
||||
activation=moe_args.activation,
|
||||
),
|
||||
)
|
||||
else:
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.shared_expert = None
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -224,10 +250,6 @@ class LagunaDecoderLayer(GradientCheckpointingLayer):
|
||||
residual = hidden_states
|
||||
mlp_input = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(mlp_input, routed_experts=routed_experts)
|
||||
if self.shared_expert is not None:
|
||||
bs, slen, dim = hidden_states.shape
|
||||
shared_output = self.shared_expert(mlp_input.view(-1, dim)).view(bs, slen, dim)
|
||||
hidden_states = hidden_states + shared_output
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
@@ -257,7 +279,7 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
@@ -402,8 +424,8 @@ class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
if module.expert_bias is not None:
|
||||
module.expert_bias.zero_()
|
||||
if module.router.selection_bias is not None:
|
||||
module.router.selection_bias.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
from typing import Literal, Protocol
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class Activation(Protocol):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor: ...
|
||||
|
||||
|
||||
class ClampedSwiglu(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None
|
||||
gate = gate.clamp(max=7.0)
|
||||
up = up.clamp(min=-7.0, max=7.0)
|
||||
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
|
||||
|
||||
|
||||
class Relu2(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
if gate is not None:
|
||||
return F.relu(gate).square() * up
|
||||
return F.relu(up).square()
|
||||
|
||||
|
||||
class Silu(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
if gate is None:
|
||||
return F.silu(up)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
ActivationType = Literal["silu", "relu2", "clamped_swiglu"]
|
||||
|
||||
ActivationDispatch: dict[ActivationType, type[Activation]] = {
|
||||
"clamped_swiglu": ClampedSwiglu,
|
||||
"silu": Silu,
|
||||
"relu2": Relu2,
|
||||
}
|
||||
@@ -109,22 +109,13 @@ class FlashAttention(nn.Module):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
return out.contiguous().view(1, out.shape[0], -1)
|
||||
|
||||
def attn_projections(
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -157,28 +148,9 @@ class FlashAttention(nn.Module):
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
return query_states, key_states, value_states
|
||||
|
||||
def output_proj(self, attn_output: torch.Tensor) -> torch.Tensor:
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
attn_output = self.output_proj(attn_output)
|
||||
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
attn_output = out.contiguous().view(1, out.shape[0], -1)
|
||||
attn_output = self.o_proj(attn_output)
|
||||
return attn_output, None
|
||||
|
||||
|
||||
@@ -195,16 +167,7 @@ def substitute_ring_attn(
|
||||
attn_impl: str = "flash_attention_2",
|
||||
) -> None:
|
||||
"""Patch _compute_attention on FlashAttention variants to use ring attention."""
|
||||
from ring_flash_attn import llama3_flash_attn_varlen_func
|
||||
|
||||
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
|
||||
|
||||
if attn_impl == "flash_attention_4":
|
||||
ring_func = ring_fa4_varlen_func
|
||||
elif attn_impl == "flash_attention_3":
|
||||
ring_func = ring_fa3_varlen_func
|
||||
else:
|
||||
ring_func = llama3_flash_attn_varlen_func
|
||||
from .ring_attn import ring_varlen_attention
|
||||
|
||||
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
|
||||
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
|
||||
@@ -214,7 +177,7 @@ def substitute_ring_attn(
|
||||
if sliding_window is not None:
|
||||
window_size = (sliding_window - 1, 0)
|
||||
|
||||
out = ring_func(
|
||||
out = ring_varlen_attention(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
@@ -227,9 +190,8 @@ def substitute_ring_attn(
|
||||
window_size=window_size,
|
||||
group=process_group,
|
||||
heads_k_stride=heads_k_stride,
|
||||
attention_backend=attn_impl,
|
||||
)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
FlashAttention._compute_attention = _ring_compute_attention
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
"""Selective activation checkpointing hooks for custom decoder layers.
|
||||
|
||||
New model integration contract:
|
||||
|
||||
- `norm`: no explicit hook is required. Every child module whose type name
|
||||
contains `norm` is checkpointed through `forward()`.
|
||||
- `attn_proj`: expose `layer.self_attn.attn_projections(...)` for
|
||||
projection-side attention work before the core kernel, plus
|
||||
`layer.self_attn.output_proj(...)` for the post-attention output projection.
|
||||
This target is meant for attention-local work outside the main attention
|
||||
kernel, such as q/k/v projections, attention-local norms, RoPE, gating, and
|
||||
similar model-specific helpers.
|
||||
- `mla_up_proj`: expose `layer.self_attn.mla_up_proj(...)` when MLA-style
|
||||
up-projection work should be checkpointed separately from
|
||||
`attn_projections(...)`.
|
||||
- `mlp`: expose a dense `layer.mlp.forward(...)`. A module is treated as dense
|
||||
when it does not define `_run_routed_experts` or `tokens_per_expert`.
|
||||
- `routed_experts`: expose `layer.mlp._run_routed_experts(...)` for the MoE
|
||||
expert path, and optionally `layer.mlp._run_local_routed_experts(...)` when
|
||||
local expert compute is separated from dispatch/combine.
|
||||
- `linear_attn`: expose a token-mixer module on `layer.linear_attn` or
|
||||
`layer.mamba`, or reuse `layer.self_attn` when
|
||||
`layer.attention_type == "sliding_attention"`.
|
||||
|
||||
These hook names are an intentional public interface for custom model support,
|
||||
so new models should follow them directly rather than adding private aliases.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from functools import wraps
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
|
||||
SELECTIVE_AC_TARGETS = frozenset({"norm", "attn_proj", "mlp", "mla_up_proj", "routed_experts", "linear_attn"})
|
||||
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
|
||||
|
||||
|
||||
def _is_norm_module(module: nn.Module) -> bool:
|
||||
return "norm" in type(module).__name__.lower()
|
||||
|
||||
|
||||
def _should_checkpoint(module: nn.Module) -> bool:
|
||||
return torch.is_grad_enabled() and module.training
|
||||
|
||||
|
||||
def checkpoint_method(module: nn.Module, method_name: str) -> None:
|
||||
patched_methods = frozenset(getattr(module, _PATCHED_METHODS_ATTR, ()))
|
||||
if method_name in patched_methods:
|
||||
return
|
||||
|
||||
original = getattr(module, method_name)
|
||||
|
||||
@wraps(original)
|
||||
def checkpointed(*args, **kwargs):
|
||||
if not _should_checkpoint(module):
|
||||
return original(*args, **kwargs)
|
||||
|
||||
def fn(*checkpoint_args):
|
||||
return original(*checkpoint_args, **kwargs)
|
||||
|
||||
return checkpoint(fn, *args, use_reentrant=False, preserve_rng_state=False)
|
||||
|
||||
setattr(module, method_name, checkpointed)
|
||||
setattr(module, _PATCHED_METHODS_ATTR, patched_methods.union({method_name}))
|
||||
|
||||
|
||||
def _configure_norm_checkpointing(layer: nn.Module) -> None:
|
||||
for module in layer.modules():
|
||||
if module is layer or not _is_norm_module(module):
|
||||
continue
|
||||
checkpoint_method(module, "forward")
|
||||
|
||||
|
||||
def _is_dense_mlp(mlp: nn.Module) -> bool:
|
||||
return not hasattr(mlp, "_run_routed_experts") and not hasattr(mlp, "tokens_per_expert")
|
||||
|
||||
|
||||
def _supports_attn_proj(self_attn: nn.Module | None) -> bool:
|
||||
return self_attn is not None and hasattr(self_attn, "attn_projections") and hasattr(self_attn, "output_proj")
|
||||
|
||||
|
||||
def _get_linear_attn_module(layer: nn.Module) -> nn.Module | None:
|
||||
linear_attn = getattr(layer, "linear_attn", None)
|
||||
if linear_attn is not None:
|
||||
return linear_attn
|
||||
|
||||
mamba = getattr(layer, "mamba", None)
|
||||
if mamba is not None:
|
||||
return mamba
|
||||
|
||||
if getattr(layer, "attention_type", None) == "sliding_attention":
|
||||
return getattr(layer, "self_attn", None)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_supported_targets(layer: nn.Module) -> frozenset[str]:
|
||||
"""Infer which selective activation checkpoint targets a decoder layer supports."""
|
||||
supported_targets = {"norm"}
|
||||
self_attn = getattr(layer, "self_attn", None)
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
linear_attn = _get_linear_attn_module(layer)
|
||||
|
||||
if _supports_attn_proj(self_attn):
|
||||
supported_targets.add("attn_proj")
|
||||
if self_attn is not None and hasattr(self_attn, "mla_up_proj"):
|
||||
supported_targets.add("mla_up_proj")
|
||||
if mlp is not None and _is_dense_mlp(mlp):
|
||||
supported_targets.add("mlp")
|
||||
if mlp is not None and (hasattr(mlp, "_run_routed_experts") or hasattr(mlp, "_run_local_routed_experts")):
|
||||
supported_targets.add("routed_experts")
|
||||
if linear_attn is not None:
|
||||
supported_targets.add("linear_attn")
|
||||
|
||||
return frozenset(supported_targets)
|
||||
|
||||
|
||||
def set_selective_activation_checkpointing(layer: nn.Module, targets: Iterable[str]) -> None:
|
||||
target_set = frozenset(targets)
|
||||
invalid_targets = target_set - SELECTIVE_AC_TARGETS
|
||||
if invalid_targets:
|
||||
raise ValueError(f"Unsupported selective activation checkpoint targets: {sorted(invalid_targets)}")
|
||||
|
||||
enabled_targets = target_set & get_supported_targets(layer)
|
||||
self_attn = getattr(layer, "self_attn", None)
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
linear_attn = _get_linear_attn_module(layer)
|
||||
attn_proj_is_subsumed = "linear_attn" in enabled_targets and linear_attn is self_attn
|
||||
|
||||
if self_attn is not None and "attn_proj" in enabled_targets and not attn_proj_is_subsumed:
|
||||
checkpoint_method(self_attn, "attn_projections")
|
||||
checkpoint_method(self_attn, "output_proj")
|
||||
if self_attn is not None and "mla_up_proj" in enabled_targets:
|
||||
checkpoint_method(self_attn, "mla_up_proj")
|
||||
if mlp is not None and "mlp" in enabled_targets:
|
||||
checkpoint_method(mlp, "forward")
|
||||
if mlp is not None and "routed_experts" in enabled_targets:
|
||||
if hasattr(mlp, "_run_routed_experts"):
|
||||
checkpoint_method(mlp, "_run_routed_experts")
|
||||
if hasattr(mlp, "_run_local_routed_experts"):
|
||||
checkpoint_method(mlp, "_run_local_routed_experts")
|
||||
if linear_attn is not None and "linear_attn" in enabled_targets:
|
||||
checkpoint_method(linear_attn, "forward")
|
||||
if "norm" in enabled_targets:
|
||||
_configure_norm_checkpointing(layer)
|
||||
|
||||
|
||||
def supports_selective_activation_checkpointing(layer: nn.Module) -> bool:
|
||||
return type(layer).__module__.startswith("prime_rl.trainer.models.")
|
||||
@@ -19,33 +19,7 @@ import torch.distributed as dist
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
|
||||
|
||||
class _SeqToHeadParallel(torch.autograd.Function):
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
ctx.cp_group = cp_group
|
||||
ctx.cp_size = cp_size
|
||||
return _all_to_all_seq_to_head(x, cp_group, cp_size)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
return _all_to_all_head_to_seq(grad_output, ctx.cp_group, ctx.cp_size), None, None
|
||||
|
||||
|
||||
class _HeadToSeqParallel(torch.autograd.Function):
|
||||
"""[B, S, D/cp] -> [B, S/cp, D] via all-to-all."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
ctx.cp_group = cp_group
|
||||
ctx.cp_size = cp_size
|
||||
return _all_to_all_head_to_seq(x, cp_group, cp_size)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
return _all_to_all_seq_to_head(grad_output, ctx.cp_group, ctx.cp_size), None, None
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
|
||||
|
||||
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
@@ -60,8 +34,7 @@ def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
|
||||
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
|
||||
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
|
||||
output = torch.empty_like(x)
|
||||
dist.all_to_all_single(output, x, group=cp_group)
|
||||
output = all_to_all_single_equal(x, cp_group)
|
||||
# output[i] = data from rank i (its S_local tokens, our D_local slice)
|
||||
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
|
||||
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
|
||||
@@ -78,8 +51,7 @@ def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
|
||||
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
|
||||
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
|
||||
output = torch.empty_like(x)
|
||||
dist.all_to_all_single(output, x, group=cp_group)
|
||||
output = all_to_all_single_equal(x, cp_group)
|
||||
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
|
||||
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
|
||||
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
|
||||
@@ -87,12 +59,12 @@ def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_siz
|
||||
|
||||
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
|
||||
return _SeqToHeadParallel.apply(x, cp_group, cp_size)
|
||||
return _all_to_all_seq_to_head(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
|
||||
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
|
||||
return _all_to_all_head_to_seq(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def mamba_cp_forward(
|
||||
|
||||
@@ -2,13 +2,6 @@ from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
GROUP_ALIGNMENT,
|
||||
build_grouped_layout,
|
||||
@@ -33,6 +26,8 @@ def _compute_grad_weight(
|
||||
block_starts_tensor: torch.Tensor,
|
||||
aligned_ms: list[int],
|
||||
) -> torch.Tensor:
|
||||
import deep_gemm
|
||||
|
||||
is_sm100 = torch.cuda.get_device_capability(x.device)[0] >= 10
|
||||
if is_sm100:
|
||||
x_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
@@ -95,28 +90,104 @@ def _compute_grad_weight(
|
||||
return grad_weight.to(torch.bfloat16)
|
||||
|
||||
|
||||
class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
(
|
||||
total_m,
|
||||
@torch.library.custom_op("prime_rl::grouped_fp8_gemm", mutates_args=())
|
||||
def _grouped_fp8_gemm(x: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
|
||||
import deep_gemm
|
||||
|
||||
(
|
||||
total_m,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
_,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
out_padded = torch.empty((padded_total_m, weight.size(2)), device=x.device, dtype=x.dtype)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
x_fp8,
|
||||
weight_fp8,
|
||||
out_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
return unpack_rows_triton(
|
||||
out_padded,
|
||||
total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
|
||||
@_grouped_fp8_gemm.register_fake
|
||||
def _grouped_fp8_gemm_fake(x: torch.Tensor, weight: torch.Tensor, offs: torch.Tensor) -> torch.Tensor:
|
||||
return x.new_empty((x.shape[0], weight.shape[2]))
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::grouped_fp8_gemm_backward", mutates_args=())
|
||||
def _grouped_fp8_gemm_backward(
|
||||
grad_output: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
(
|
||||
_,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
grad_output = grad_output.contiguous()
|
||||
grad_x = torch.empty_like(x)
|
||||
grad_weight = torch.empty_like(weight)
|
||||
|
||||
if needs_grad_weight:
|
||||
grad_weight = _compute_grad_weight(
|
||||
x,
|
||||
grad_output,
|
||||
weight.shape,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
ks_tensor.tolist(),
|
||||
)
|
||||
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
x,
|
||||
if needs_grad_x:
|
||||
import deep_gemm
|
||||
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
@@ -125,118 +196,66 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
out_padded = torch.empty(
|
||||
(padded_total_m, weight.size(2)),
|
||||
device=x.device,
|
||||
dtype=x.dtype,
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(weight, use_ue8m0, GROUP_ALIGNMENT)
|
||||
grad_x_padded = torch.empty(
|
||||
(padded_total_m, weight.size(1)),
|
||||
device=grad_output.device,
|
||||
dtype=grad_output.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
x_fp8,
|
||||
weight_fp8,
|
||||
out_padded,
|
||||
dy_fp8,
|
||||
weight_dx_fp8,
|
||||
grad_x_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
out = unpack_rows_triton(
|
||||
out_padded,
|
||||
total_m,
|
||||
grad_x = unpack_rows_triton(
|
||||
grad_x_padded,
|
||||
x.size(0),
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
ctx.padded_total_m = padded_total_m
|
||||
ctx.aligned_ms = ks_tensor.tolist()
|
||||
ctx.save_for_backward(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
return out
|
||||
return grad_x, grad_weight
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor):
|
||||
(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = ctx.saved_tensors
|
||||
padded_total_m = ctx.padded_total_m
|
||||
aligned_ms = ctx.aligned_ms
|
||||
grad_output = grad_output.contiguous()
|
||||
|
||||
grad_x = grad_weight = None
|
||||
@_grouped_fp8_gemm_backward.register_fake
|
||||
def _grouped_fp8_gemm_backward_fake(
|
||||
grad_output: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(x), torch.empty_like(weight)
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
grad_weight = _compute_grad_weight(
|
||||
x,
|
||||
grad_output,
|
||||
weight.shape,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
aligned_ms,
|
||||
)
|
||||
|
||||
if ctx.needs_input_grad[0]:
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_x_padded = torch.empty(
|
||||
(padded_total_m, weight.size(1)),
|
||||
device=grad_output.device,
|
||||
dtype=grad_output.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
dy_fp8,
|
||||
weight_dx_fp8,
|
||||
grad_x_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
grad_x = unpack_rows_triton(
|
||||
grad_x_padded,
|
||||
x.size(0),
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
def _grouped_fp8_gemm_setup_context(ctx, inputs, output) -> None:
|
||||
x, weight, offs = inputs
|
||||
ctx.save_for_backward(x, weight, offs)
|
||||
|
||||
return grad_x, grad_weight, None
|
||||
|
||||
def _grouped_fp8_gemm_autograd_backward(ctx, grad_output: torch.Tensor):
|
||||
x, weight, offs = ctx.saved_tensors
|
||||
needs_grad_x, needs_grad_weight, _ = ctx.needs_input_grad
|
||||
grad_x, grad_weight = _grouped_fp8_gemm_backward(
|
||||
grad_output,
|
||||
x.detach(),
|
||||
weight.detach(),
|
||||
offs,
|
||||
needs_grad_x,
|
||||
needs_grad_weight,
|
||||
)
|
||||
return grad_x if needs_grad_x else None, grad_weight if needs_grad_weight else None, None
|
||||
|
||||
|
||||
_grouped_fp8_gemm.register_autograd(
|
||||
_grouped_fp8_gemm_autograd_backward,
|
||||
setup_context=_grouped_fp8_gemm_setup_context,
|
||||
)
|
||||
|
||||
|
||||
def grouped_fp8_gemm(
|
||||
@@ -254,4 +273,4 @@ def grouped_fp8_gemm(
|
||||
Returns:
|
||||
(M, N) output tensor in bfloat16.
|
||||
"""
|
||||
return _GroupedFP8Gemm.apply(x, weight, offs)
|
||||
return _grouped_fp8_gemm(x, weight, offs)
|
||||
|
||||
@@ -5,13 +5,6 @@ import re
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_tp_triton,
|
||||
per_block_cast_to_fp8_triton,
|
||||
@@ -22,64 +15,108 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
|
||||
x_shape = x.shape
|
||||
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
|
||||
@torch.library.custom_op("prime_rl::fp8_blockwise_mm", mutates_args=())
|
||||
def _fp8_blockwise_mm(x: torch.Tensor, weight: torch.Tensor, block_size: int) -> torch.Tensor:
|
||||
import deep_gemm
|
||||
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
|
||||
|
||||
ctx.save_for_backward(x_2d, weight)
|
||||
ctx.x_shape = x_shape
|
||||
ctx.block_size = block_size
|
||||
return out.reshape(*x_shape[:-1], out.size(-1))
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=torch.bfloat16)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
return out.reshape(*x.shape[:-1], out.size(-1))
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
x_2d, weight = ctx.saved_tensors
|
||||
block_size = ctx.block_size
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
@_fp8_blockwise_mm.register_fake
|
||||
def _fp8_blockwise_mm_fake(x: torch.Tensor, weight: torch.Tensor, block_size: int) -> torch.Tensor:
|
||||
return x.new_empty((*x.shape[:-1], weight.shape[0]), dtype=torch.bfloat16)
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
# deep_gemm.fp8_gemm_nt with recipe=(1, 1, 128) requires the K (token)
|
||||
# dim to be a multiple of 128. Zero-pad along the token axis so non-
|
||||
# aligned per-rank batches (from sequence packing) don't trip the kernel.
|
||||
M_tok = grad_output_2d.size(0)
|
||||
M_pad = (M_tok + block_size - 1) // block_size * block_size
|
||||
if M_pad != M_tok:
|
||||
pad_rows = M_pad - M_tok
|
||||
grad_output_2d_padded = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
|
||||
x_2d_padded = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, use_ue8m0, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, use_ue8m0, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
x_t_fp8,
|
||||
grad_weight_fp32,
|
||||
c=grad_weight_fp32,
|
||||
recipe=(1, 1, 128),
|
||||
)
|
||||
grad_weight = grad_weight_fp32.to(weight.dtype)
|
||||
|
||||
return grad_x, grad_weight, None, None
|
||||
@torch.library.custom_op("prime_rl::fp8_blockwise_mm_backward", mutates_args=())
|
||||
def _fp8_blockwise_mm_backward(
|
||||
grad_output: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
block_size: int,
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
import deep_gemm
|
||||
|
||||
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
grad_x = torch.empty_like(x)
|
||||
grad_weight = torch.empty_like(weight)
|
||||
|
||||
if needs_grad_x:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(x.shape)
|
||||
|
||||
if needs_grad_weight:
|
||||
# DeepGEMM's (1, 1, 128) recipe requires the token dimension to be aligned.
|
||||
num_tokens = grad_output_2d.size(0)
|
||||
padded_tokens = (num_tokens + block_size - 1) // block_size * block_size
|
||||
if padded_tokens != num_tokens:
|
||||
pad_rows = padded_tokens - num_tokens
|
||||
grad_output_2d = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
|
||||
x_2d = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d, use_ue8m0, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
x_t_fp8,
|
||||
grad_weight_fp32,
|
||||
c=grad_weight_fp32,
|
||||
recipe=(1, 1, 128),
|
||||
)
|
||||
grad_weight = grad_weight_fp32.to(weight.dtype)
|
||||
|
||||
return grad_x, grad_weight
|
||||
|
||||
|
||||
@_fp8_blockwise_mm_backward.register_fake
|
||||
def _fp8_blockwise_mm_backward_fake(
|
||||
grad_output: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
block_size: int,
|
||||
needs_grad_x: bool,
|
||||
needs_grad_weight: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(x), torch.empty_like(weight)
|
||||
|
||||
|
||||
def _fp8_blockwise_mm_setup_context(ctx, inputs, output) -> None:
|
||||
x, weight, block_size = inputs
|
||||
ctx.save_for_backward(x, weight)
|
||||
ctx.block_size = block_size
|
||||
|
||||
|
||||
def _fp8_blockwise_mm_autograd_backward(ctx, grad_output: torch.Tensor):
|
||||
x, weight = ctx.saved_tensors
|
||||
needs_grad_x, needs_grad_weight, _ = ctx.needs_input_grad
|
||||
grad_x, grad_weight = _fp8_blockwise_mm_backward(
|
||||
grad_output,
|
||||
x.detach(),
|
||||
weight.detach(),
|
||||
ctx.block_size,
|
||||
needs_grad_x,
|
||||
needs_grad_weight,
|
||||
)
|
||||
return grad_x if needs_grad_x else None, grad_weight if needs_grad_weight else None, None
|
||||
|
||||
|
||||
_fp8_blockwise_mm.register_autograd(
|
||||
_fp8_blockwise_mm_autograd_backward,
|
||||
setup_context=_fp8_blockwise_mm_setup_context,
|
||||
)
|
||||
|
||||
|
||||
class Float8BlockwiseLinear(nn.Linear):
|
||||
@@ -97,7 +134,7 @@ class Float8BlockwiseLinear(nn.Linear):
|
||||
self.block_size = block_size
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return _FP8BlockwiseMM.apply(x, self.weight, self.block_size, torch.bfloat16)
|
||||
return _fp8_blockwise_mm(x, self.weight, self.block_size)
|
||||
|
||||
@classmethod
|
||||
def from_linear(cls, mod: nn.Linear) -> "Float8BlockwiseLinear":
|
||||
@@ -119,7 +156,7 @@ def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: l
|
||||
|
||||
The default ignore list covers layers that should never be quantized:
|
||||
- lm_head
|
||||
- MoE routers and gates (router, mlp.gate., shared_expert_gate)
|
||||
- MoE routers and gates (router, mlp.gate., shared_expert.output_gate)
|
||||
- sparse-MLA scalar projection (weights_proj)
|
||||
- GLM-5.1 MTP head (eh_proj)
|
||||
- hybrid-Mamba projections (in_proj_a, in_proj_b)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
from dataclasses import dataclass
|
||||
from types import ModuleType
|
||||
from typing import Protocol
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
class GroupedGemm(Protocol):
|
||||
token_group_alignment: int
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
weight_t: torch.Tensor,
|
||||
*,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BF16GroupedGemm:
|
||||
token_group_alignment: int = 8
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
weight_t: torch.Tensor,
|
||||
*,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return torch._grouped_mm(x, weight_t, offs=offs)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeepGemmFP8GroupedGemm:
|
||||
token_group_alignment: int = 8
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
weight_t: torch.Tensor,
|
||||
*,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
|
||||
|
||||
return grouped_fp8_gemm(x, weight_t, offs)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MXFP8GroupedGemm:
|
||||
kernel: ModuleType
|
||||
high_precision_wgrad: bool
|
||||
token_group_alignment: int
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
weight_t: torch.Tensor,
|
||||
*,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.kernel.grouped_gemm(
|
||||
x,
|
||||
weight_t,
|
||||
offs,
|
||||
high_precision_wgrad=self.high_precision_wgrad,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,29 +1,42 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.activations import ACT2FN
|
||||
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
|
||||
ExpertType = Literal["gated", "non_gated"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class MLPConfig:
|
||||
hidden_size: int
|
||||
intermediate_size: int
|
||||
gate_act: str
|
||||
bias: bool
|
||||
class FeedForward(nn.Module):
|
||||
"""Dense feed-forward layer using the canonical projection names."""
|
||||
|
||||
|
||||
class MLP(nn.Module):
|
||||
def __init__(self, config: MLPConfig):
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
hidden_dim: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
bias: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.intermediate_size = 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.gate_act_fn = ACT2FN[config.gate_act]
|
||||
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]
|
||||
|
||||
def forward(self, x, routed_experts: torch.Tensor | None = None):
|
||||
down_proj = self.down_proj(self.gate_act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
return down_proj
|
||||
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
|
||||
up = self.up_proj(x)
|
||||
return self.down_proj(self.activation.apply(gate, up))
|
||||
|
||||
def init_weights(self, init_std: float = 0.02) -> None:
|
||||
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
|
||||
nn.init.trunc_normal_(first_projection.weight, mean=0.0, std=0.02)
|
||||
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
|
||||
for linear in remaining:
|
||||
nn.init.trunc_normal_(linear.weight, mean=0.0, std=init_std)
|
||||
for linear in (self.gate_proj, self.up_proj, self.down_proj):
|
||||
if linear is not None and linear.bias is not None:
|
||||
nn.init.zeros_(linear.bias)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,114 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchao.prototype.moe_training import conversion_utils as cu
|
||||
from torchao.prototype.moe_training import mxfp8_grouped_mm as tao_mxfp8_gmm
|
||||
from torchao.prototype.moe_training.config import MXFP8TrainingOpConfig, MXFP8TrainingRecipe
|
||||
from torchao.prototype.moe_training.kernels.mxfp8 import triton_mx_block_rearrange_2d_M_groups
|
||||
from torchao.prototype.moe_training.tensor import MXFP8TrainingWeightWrapperTensor
|
||||
from torchao.quantization.quant_api import quantize_
|
||||
from torchtitan.distributed.expert_parallel import set_token_group_alignment_size_m
|
||||
from torchtitan.experiments.kernels.moe import indices as tt_indices
|
||||
|
||||
from prime_rl.configs.trainer import MXFP8Recipe
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, NonGatedGroupedExperts
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
_MXFP8_TOKEN_GROUP_ALIGN: int = 32
|
||||
# torchao CUDA scale rearrange kernel supports at most 32 token groups,
|
||||
# the Triton variant has no such cap and produces the same swizzled layout, so fall back to it for wider MoEs
|
||||
_CUDA_REARRANGE_MAX_GROUPS: int = 32
|
||||
|
||||
# torchao's dim0 quantize Triton kernel indexes with int32 and corrupts mem when numel >= INT_MAX=2^31
|
||||
_QUANT_NUMEL_LIMIT: int = 1 << 31
|
||||
_QUANT_CHUNK_NUMEL: int = 1 << 30
|
||||
|
||||
|
||||
def _fallback_to_triton_rearrange_for_wide_moes() -> None:
|
||||
if getattr(tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda, "_prime_rl_wide_moe", False):
|
||||
return
|
||||
original = tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda
|
||||
|
||||
def mx_block_rearrange_2d_M_groups(
|
||||
scales_tensor: torch.Tensor, input_group_end_offsets: torch.Tensor, chunks_per_tb: int = 4
|
||||
) -> torch.Tensor:
|
||||
if input_group_end_offsets.shape[0] > _CUDA_REARRANGE_MAX_GROUPS:
|
||||
return triton_mx_block_rearrange_2d_M_groups(scales_tensor, input_group_end_offsets)
|
||||
return original(scales_tensor, input_group_end_offsets, chunks_per_tb)
|
||||
|
||||
mx_block_rearrange_2d_M_groups._prime_rl_wide_moe = True
|
||||
tao_mxfp8_gmm.mx_block_rearrange_2d_M_groups_cuda = mx_block_rearrange_2d_M_groups
|
||||
|
||||
|
||||
def _chunk_dim0_quantize_for_large_inputs() -> None:
|
||||
if getattr(tao_mxfp8_gmm.triton_to_mxfp8_dim0, "_prime_rl_chunked", False):
|
||||
return
|
||||
original = tao_mxfp8_gmm.triton_to_mxfp8_dim0
|
||||
|
||||
def triton_to_mxfp8_dim0(x: torch.Tensor, inner_block_size: int = 32, scaling_mode: str = "rceil") -> torch.Tensor:
|
||||
if x.ndim != 2 or x.numel() < _QUANT_NUMEL_LIMIT:
|
||||
return original(x, inner_block_size=inner_block_size, scaling_mode=scaling_mode)
|
||||
rows_per_chunk = max(1, _QUANT_CHUNK_NUMEL // x.shape[1])
|
||||
outs, scales = zip(
|
||||
*(
|
||||
original(chunk, inner_block_size=inner_block_size, scaling_mode=scaling_mode)
|
||||
for chunk in x.split(rows_per_chunk, dim=0)
|
||||
)
|
||||
)
|
||||
return torch.cat(outs, dim=0), torch.cat(scales, dim=0)
|
||||
|
||||
triton_to_mxfp8_dim0._prime_rl_chunked = True
|
||||
tao_mxfp8_gmm.triton_to_mxfp8_dim0 = triton_to_mxfp8_dim0
|
||||
|
||||
|
||||
def _relax_torchao_mxfp8_version_gate() -> None:
|
||||
if getattr(cu._get_tensor_cls_for_config, "_prime_rl_relaxed", False):
|
||||
return
|
||||
original = cu._get_tensor_cls_for_config
|
||||
|
||||
def _get_tensor_cls_for_config(config):
|
||||
if isinstance(config, MXFP8TrainingOpConfig):
|
||||
return MXFP8TrainingWeightWrapperTensor
|
||||
return original(config)
|
||||
|
||||
_get_tensor_cls_for_config._prime_rl_relaxed = True
|
||||
cu._get_tensor_cls_for_config = _get_tensor_cls_for_config
|
||||
|
||||
|
||||
def _align_permute_indices_buffer() -> None:
|
||||
"""
|
||||
Align the permuted index buffer to a multiple of alignment as the kernel requires rows % 32 = 0 and cols % 32 = 0.
|
||||
"""
|
||||
if getattr(tt_indices.generate_permute_indices, "_prime_rl_aligned", False):
|
||||
return
|
||||
original = tt_indices.generate_permute_indices
|
||||
|
||||
def generate_permute_indices(
|
||||
tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=False
|
||||
):
|
||||
al_mask = alignment - 1
|
||||
assert alignment > 0 and (alignment & al_mask) == 0
|
||||
max_len = (max_len + al_mask) & ~al_mask
|
||||
return original(tokens_per_expert_group, experts_per_rank, num_ranks, max_len, alignment, use_cpu=use_cpu)
|
||||
|
||||
generate_permute_indices._prime_rl_aligned = True
|
||||
tt_indices.generate_permute_indices = generate_permute_indices
|
||||
|
||||
|
||||
def apply_mxfp8_moe_grouped_gemm(model: nn.Module, recipe: MXFP8Recipe) -> None:
|
||||
_relax_torchao_mxfp8_version_gate()
|
||||
_align_permute_indices_buffer()
|
||||
_fallback_to_triton_rearrange_for_wide_moes()
|
||||
_chunk_dim0_quantize_for_large_inputs()
|
||||
set_token_group_alignment_size_m(_MXFP8_TOKEN_GROUP_ALIGN)
|
||||
op_config = MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe(recipe))
|
||||
|
||||
def filter_fn(module: nn.Module, fqn: str) -> bool:
|
||||
return isinstance(module, (GroupedExperts, NonGatedGroupedExperts))
|
||||
|
||||
quantize_(model, config=op_config, filter_fn=filter_fn)
|
||||
get_logger().info(
|
||||
f"Wrapped MoE expert weights with MXFP8 grouped GEMM (recipe={recipe}, "
|
||||
f"token_group_align={_MXFP8_TOKEN_GROUP_ALIGN})"
|
||||
)
|
||||
@@ -4,8 +4,8 @@ import re
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchao.prototype.moe_training.mxfp8_linear import _to_mxfp8_then_scaled_mm
|
||||
from torchao.prototype.mx_formats import ScaleCalculationMode
|
||||
from torchao.prototype.mx_formats.mx_linear import _to_mxfp8_then_scaled_mm
|
||||
from torchao.quantization.quantize_.common import KernelPreference
|
||||
|
||||
from prime_rl.configs.trainer import MXFP8Recipe
|
||||
|
||||
@@ -5,23 +5,10 @@ import prime_rl._compat # noqa: F401
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from ring_flash_attn.utils import AllGatherComm, get_default_args
|
||||
from ring_flash_attn.utils import AllGatherComm
|
||||
|
||||
|
||||
def _set_fa3_signature_params(params: dict, causal: bool, window_size: tuple[int, int]) -> None:
|
||||
if "is_causal" in params:
|
||||
params["is_causal"] = causal
|
||||
else:
|
||||
params["causal"] = causal
|
||||
|
||||
if "window_size" in params:
|
||||
params["window_size"] = window_size
|
||||
else:
|
||||
params["window_size_left"] = window_size[0]
|
||||
params["window_size_right"] = window_size[1]
|
||||
|
||||
|
||||
def _fa3_varlen_forward(
|
||||
def _flash_attention_forward(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
@@ -31,29 +18,74 @@ def _fa3_varlen_forward(
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
window_size: tuple[int, int],
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from flash_attn_interface import _flash_attn_forward
|
||||
if attention_backend == "flash_attention_2":
|
||||
from flash_attn.flash_attn_interface import _flash_attn_varlen_forward
|
||||
|
||||
params = get_default_args(_flash_attn_forward).copy()
|
||||
params.update(
|
||||
{
|
||||
"q": q,
|
||||
"k": k,
|
||||
"v": 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,
|
||||
}
|
||||
)
|
||||
_set_fa3_signature_params(params, causal, window_size)
|
||||
out, lse, _, _ = _flash_attn_forward(**params)
|
||||
return out, lse
|
||||
out, softmax_lse, _, _ = _flash_attn_varlen_forward(
|
||||
q=q,
|
||||
k=k,
|
||||
v=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,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size[0],
|
||||
window_size_right=window_size[1],
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
return_softmax=False,
|
||||
)
|
||||
return out, softmax_lse
|
||||
|
||||
if attention_backend == "flash_attention_3":
|
||||
from flash_attn_interface import _flash_attn_forward
|
||||
|
||||
out, softmax_lse, _, _ = _flash_attn_forward(
|
||||
q=q,
|
||||
k=k,
|
||||
v=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[0],
|
||||
window_size_right=window_size[1],
|
||||
)
|
||||
return out, softmax_lse
|
||||
|
||||
if attention_backend == "flash_attention_4":
|
||||
from flash_attn.cute.interface import _flash_attn_fwd
|
||||
|
||||
window_size_left = window_size[0] if window_size[0] != -1 else None
|
||||
window_size_right = window_size[1] if window_size[1] != -1 else None
|
||||
out, softmax_lse, _, _ = _flash_attn_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_lse=True,
|
||||
)
|
||||
return out, softmax_lse
|
||||
|
||||
raise ValueError(f"Unsupported ring attention backend: {attention_backend}")
|
||||
|
||||
|
||||
def _fa3_varlen_backward(
|
||||
def _flash_attention_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -69,217 +101,92 @@ def _fa3_varlen_backward(
|
||||
dv: torch.Tensor,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
window_size: tuple[int, int],
|
||||
attention_backend: str,
|
||||
) -> None:
|
||||
from flash_attn_interface import _flash_attn_backward
|
||||
if attention_backend == "flash_attention_2":
|
||||
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward
|
||||
|
||||
params = get_default_args(_flash_attn_backward).copy()
|
||||
params.update(
|
||||
{
|
||||
"dout": dout,
|
||||
"q": q,
|
||||
"k": k,
|
||||
"v": v,
|
||||
"out": out,
|
||||
"softmax_lse": softmax_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,
|
||||
}
|
||||
)
|
||||
_set_fa3_signature_params(params, causal, window_size)
|
||||
_flash_attn_backward(**params)
|
||||
_flash_attn_varlen_backward(
|
||||
dout=dout,
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
out=out,
|
||||
softmax_lse=softmax_lse,
|
||||
dq=dq,
|
||||
dk=dk,
|
||||
dv=dv,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
dropout_p=0.0,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size[0],
|
||||
window_size_right=window_size[1],
|
||||
softcap=0.0,
|
||||
alibi_slopes=None,
|
||||
deterministic=False,
|
||||
)
|
||||
return
|
||||
|
||||
if attention_backend == "flash_attention_3":
|
||||
from flash_attn_interface import _flash_attn_backward
|
||||
|
||||
_flash_attn_backward(
|
||||
dout=dout,
|
||||
q=q,
|
||||
k=k,
|
||||
v=v,
|
||||
out=out,
|
||||
softmax_lse=softmax_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[0],
|
||||
window_size_right=window_size[1],
|
||||
)
|
||||
return
|
||||
|
||||
if attention_backend == "flash_attention_4":
|
||||
from flash_attn.cute.interface import _flash_attn_bwd
|
||||
|
||||
window_size_left = window_size[0] if window_size[0] != -1 else None
|
||||
window_size_right = window_size[1] if window_size[1] != -1 else None
|
||||
_flash_attn_bwd(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
dout,
|
||||
softmax_lse,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
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,
|
||||
dq=dq,
|
||||
dk=dk,
|
||||
dv=dv,
|
||||
)
|
||||
return
|
||||
|
||||
raise ValueError(f"Unsupported ring attention backend: {attention_backend}")
|
||||
|
||||
|
||||
class _RingFA3Varlen(torch.autograd.Function):
|
||||
"""Ring attention using FA3 kernels with all-gather communication.
|
||||
|
||||
Mirrors the llama3_flash_attn_varlen pattern from ring-flash-attn but
|
||||
calls flash-attention-3 low-level forward/backward instead of FA2.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
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,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
group_name: str,
|
||||
window_size_left: int = -1,
|
||||
window_size_right: int = -1,
|
||||
) -> torch.Tensor:
|
||||
group = dist.group.WORLD
|
||||
for pg in dist.distributed_c10d._world.pg_map:
|
||||
if pg.group_name == group_name:
|
||||
group = pg
|
||||
break
|
||||
|
||||
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
|
||||
window_size = (window_size_left, window_size_right)
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
out_list = []
|
||||
lse_list = []
|
||||
|
||||
nheads = q.shape[1]
|
||||
total_k, nheads_k, head_dim = k.shape
|
||||
world_size = dist.get_world_size(group)
|
||||
|
||||
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
kv_buffer_copy = torch.empty_like(kv_buffer)
|
||||
comm = AllGatherComm(group)
|
||||
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
for i in range(0, nheads_k, heads_k_stride):
|
||||
comm.wait()
|
||||
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
|
||||
|
||||
if i < nheads_k - heads_k_stride:
|
||||
left = i + heads_k_stride
|
||||
right = left + heads_k_stride
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
|
||||
|
||||
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
|
||||
k_i = kv_buffer[0][local_k_slice]
|
||||
v_i = kv_buffer[1][local_k_slice]
|
||||
out_i, lse_i = _fa3_varlen_forward(
|
||||
q=q_i,
|
||||
k=k_i,
|
||||
v=v_i,
|
||||
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=window_size,
|
||||
)
|
||||
out_list.append(out_i)
|
||||
lse_list.append(lse_i)
|
||||
|
||||
out = torch.cat(out_list, dim=1)
|
||||
lse = torch.cat(lse_list, dim=-2)
|
||||
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.softmax_scale = softmax_scale
|
||||
ctx.max_seqlen_q = max_seqlen_q
|
||||
ctx.max_seqlen_k = max_seqlen_k
|
||||
ctx.local_k_slice = local_k_slice
|
||||
ctx.heads_k_stride = heads_k_stride
|
||||
ctx.causal = causal
|
||||
ctx.group_name = group_name
|
||||
ctx.window_size = window_size
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, dout: torch.Tensor):
|
||||
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
heads_k_stride = ctx.heads_k_stride
|
||||
local_k_slice = ctx.local_k_slice
|
||||
causal = ctx.causal
|
||||
|
||||
group = dist.group.WORLD
|
||||
for pg in dist.distributed_c10d._world.pg_map:
|
||||
if pg.group_name == ctx.group_name:
|
||||
group = pg
|
||||
break
|
||||
|
||||
nheads = q.shape[1]
|
||||
total_k, nheads_k, head_dim = k.shape
|
||||
world_size = dist.get_world_size(group)
|
||||
|
||||
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
kv_buffer_copy = torch.empty_like(kv_buffer)
|
||||
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
|
||||
kv_contiguous_buffer = None
|
||||
if heads_k_stride != nheads_k:
|
||||
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
|
||||
dq = torch.empty_like(q)
|
||||
dk = torch.empty_like(k)
|
||||
dv = torch.empty_like(v)
|
||||
|
||||
comm = AllGatherComm(group)
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
for i in range(0, nheads_k, heads_k_stride):
|
||||
dkv_buffer.zero_()
|
||||
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
|
||||
q_i = q[:, q_slice]
|
||||
dout_i = dout[:, q_slice]
|
||||
out_i = out[:, q_slice]
|
||||
dq_i = dq[:, q_slice]
|
||||
lse_i = softmax_lse[q_slice].contiguous()
|
||||
|
||||
comm.wait()
|
||||
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
|
||||
if i < nheads_k - heads_k_stride:
|
||||
left = i + heads_k_stride
|
||||
right = left + heads_k_stride
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
|
||||
|
||||
k_i = kv_buffer[0][local_k_slice]
|
||||
v_i = kv_buffer[1][local_k_slice]
|
||||
dk_i = dkv_buffer[0][local_k_slice]
|
||||
dv_i = dkv_buffer[1][local_k_slice]
|
||||
|
||||
_fa3_varlen_backward(
|
||||
dout=dout_i,
|
||||
q=q_i,
|
||||
k=k_i,
|
||||
v=v_i,
|
||||
out=out_i,
|
||||
softmax_lse=lse_i,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=ctx.max_seqlen_q,
|
||||
max_seqlen_k=ctx.max_seqlen_k,
|
||||
dq=dq_i,
|
||||
dk=dk_i,
|
||||
dv=dv_i,
|
||||
softmax_scale=ctx.softmax_scale,
|
||||
causal=causal,
|
||||
window_size=ctx.window_size,
|
||||
)
|
||||
|
||||
if heads_k_stride != nheads_k:
|
||||
dk_i = kv_contiguous_buffer[0]
|
||||
dv_i = kv_contiguous_buffer[1]
|
||||
else:
|
||||
dk_i = dk
|
||||
dv_i = dv
|
||||
|
||||
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
|
||||
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
|
||||
if heads_k_stride != nheads_k:
|
||||
dk[:, i : i + heads_k_stride] = dk_i
|
||||
dv[:, i : i + heads_k_stride] = dv_i
|
||||
|
||||
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
|
||||
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
|
||||
# window_size_left, window_size_right
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
def ring_fa3_varlen_func(
|
||||
@torch.library.custom_op("prime_rl_ring::attention", mutates_args=())
|
||||
def ring_attention_forward(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
@@ -287,36 +194,68 @@ def ring_fa3_varlen_func(
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
local_k_slice: slice,
|
||||
causal: bool,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
group: dist.ProcessGroup,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
return _RingFA3Varlen.apply(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
local_k_slice.start,
|
||||
local_k_slice.stop,
|
||||
heads_k_stride,
|
||||
causal,
|
||||
group.group_name,
|
||||
window_size[0],
|
||||
window_size[1],
|
||||
)
|
||||
causal: bool,
|
||||
group_name: str,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
group = dist.distributed_c10d._resolve_process_group(group_name)
|
||||
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
|
||||
window_size = (window_size_left, window_size_right)
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
|
||||
_, num_query_heads, _ = q.shape
|
||||
local_k_tokens, num_kv_heads, head_dim = k.shape
|
||||
world_size = group.size()
|
||||
gathered_kv_shape = (2, local_k_tokens * world_size, heads_k_stride, head_dim)
|
||||
gathered_kv = torch.empty(gathered_kv_shape, dtype=k.dtype, device=k.device)
|
||||
next_gathered_kv = torch.empty_like(gathered_kv)
|
||||
|
||||
communication = AllGatherComm(group)
|
||||
communication.all_gather(next_gathered_kv[0], k[:, :heads_k_stride].contiguous())
|
||||
communication.all_gather(next_gathered_kv[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
outputs = []
|
||||
softmax_lses = []
|
||||
query_heads_per_kv_head = num_query_heads // num_kv_heads
|
||||
for kv_head_start in range(0, num_kv_heads, heads_k_stride):
|
||||
communication.wait()
|
||||
gathered_kv, next_gathered_kv = next_gathered_kv, gathered_kv
|
||||
|
||||
next_kv_head_start = kv_head_start + heads_k_stride
|
||||
if next_kv_head_start < num_kv_heads:
|
||||
next_kv_head_stop = next_kv_head_start + heads_k_stride
|
||||
communication.all_gather(next_gathered_kv[0], k[:, next_kv_head_start:next_kv_head_stop].contiguous())
|
||||
communication.all_gather(next_gathered_kv[1], v[:, next_kv_head_start:next_kv_head_stop].contiguous())
|
||||
|
||||
query_head_start = kv_head_start * query_heads_per_kv_head
|
||||
query_head_stop = (kv_head_start + heads_k_stride) * query_heads_per_kv_head
|
||||
query_head_slice = slice(query_head_start, query_head_stop)
|
||||
out, softmax_lse = _flash_attention_forward(
|
||||
q=q[:, query_head_slice],
|
||||
k=gathered_kv[0][local_k_slice],
|
||||
v=gathered_kv[1][local_k_slice],
|
||||
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=window_size,
|
||||
attention_backend=attention_backend,
|
||||
)
|
||||
outputs.append(out)
|
||||
softmax_lses.append(softmax_lse)
|
||||
|
||||
return torch.cat(outputs, dim=1), torch.cat(softmax_lses, dim=-2)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# FA4 (flash_attn.cute) ring attention
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _fa4_varlen_forward(
|
||||
@ring_attention_forward.register_fake
|
||||
def _ring_attention_forward_fake(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
@@ -324,32 +263,20 @@ def _fa4_varlen_forward(
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
group_name: str,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
from flash_attn.cute.interface import _flash_attn_fwd
|
||||
|
||||
wl = window_size[0] if window_size[0] != -1 else None
|
||||
wr = window_size[1] if window_size[1] != -1 else None
|
||||
out, lse = _flash_attn_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=wl,
|
||||
window_size_right=wr,
|
||||
return_lse=True,
|
||||
)
|
||||
return out, lse
|
||||
return torch.empty_like(q), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
|
||||
|
||||
def _fa4_varlen_backward(
|
||||
@torch.library.custom_op("prime_rl_ring::attention_backward", mutates_args=())
|
||||
def ring_attention_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -360,221 +287,182 @@ def _fa4_varlen_backward(
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
dq: torch.Tensor,
|
||||
dk: torch.Tensor,
|
||||
dv: torch.Tensor,
|
||||
softmax_scale: float,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> None:
|
||||
from flash_attn.cute.interface import _flash_attn_bwd
|
||||
group_name: str,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
group = dist.distributed_c10d._resolve_process_group(group_name)
|
||||
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
|
||||
window_size = (window_size_left, window_size_right)
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
|
||||
wl = window_size[0] if window_size[0] != -1 else None
|
||||
wr = window_size[1] if window_size[1] != -1 else None
|
||||
_flash_attn_bwd(
|
||||
_, num_query_heads, _ = q.shape
|
||||
local_k_tokens, num_kv_heads, head_dim = k.shape
|
||||
world_size = group.size()
|
||||
gathered_kv_shape = (2, local_k_tokens * world_size, heads_k_stride, head_dim)
|
||||
gathered_kv = torch.empty(gathered_kv_shape, dtype=k.dtype, device=k.device)
|
||||
next_gathered_kv = torch.empty_like(gathered_kv)
|
||||
gathered_kv_grad = torch.empty_like(gathered_kv)
|
||||
local_kv_grad = (
|
||||
torch.empty((2, local_k_tokens, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
if heads_k_stride != num_kv_heads
|
||||
else None
|
||||
)
|
||||
dq = torch.empty_like(q)
|
||||
dk = torch.empty_like(k)
|
||||
dv = torch.empty_like(v)
|
||||
|
||||
communication = AllGatherComm(group)
|
||||
communication.all_gather(next_gathered_kv[0], k[:, :heads_k_stride].contiguous())
|
||||
communication.all_gather(next_gathered_kv[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
query_heads_per_kv_head = num_query_heads // num_kv_heads
|
||||
for kv_head_start in range(0, num_kv_heads, heads_k_stride):
|
||||
gathered_kv_grad.zero_()
|
||||
communication.wait()
|
||||
gathered_kv, next_gathered_kv = next_gathered_kv, gathered_kv
|
||||
|
||||
next_kv_head_start = kv_head_start + heads_k_stride
|
||||
if next_kv_head_start < num_kv_heads:
|
||||
next_kv_head_stop = next_kv_head_start + heads_k_stride
|
||||
communication.all_gather(next_gathered_kv[0], k[:, next_kv_head_start:next_kv_head_stop].contiguous())
|
||||
communication.all_gather(next_gathered_kv[1], v[:, next_kv_head_start:next_kv_head_stop].contiguous())
|
||||
|
||||
query_head_start = kv_head_start * query_heads_per_kv_head
|
||||
query_head_stop = (kv_head_start + heads_k_stride) * query_heads_per_kv_head
|
||||
query_head_slice = slice(query_head_start, query_head_stop)
|
||||
# FA2, FA3, and FA4 varlen kernels all return LSE as [heads, total_tokens].
|
||||
head_softmax_lse = softmax_lse[query_head_slice].contiguous()
|
||||
_flash_attention_backward(
|
||||
dout=dout[:, query_head_slice],
|
||||
q=q[:, query_head_slice],
|
||||
k=gathered_kv[0][local_k_slice],
|
||||
v=gathered_kv[1][local_k_slice],
|
||||
out=out[:, query_head_slice],
|
||||
softmax_lse=head_softmax_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[:, query_head_slice],
|
||||
dk=gathered_kv_grad[0][local_k_slice],
|
||||
dv=gathered_kv_grad[1][local_k_slice],
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size=window_size,
|
||||
attention_backend=attention_backend,
|
||||
)
|
||||
|
||||
if local_kv_grad is None:
|
||||
reduced_dk = dk
|
||||
reduced_dv = dv
|
||||
else:
|
||||
reduced_dk = local_kv_grad[0]
|
||||
reduced_dv = local_kv_grad[1]
|
||||
dist.reduce_scatter_tensor(reduced_dk, gathered_kv_grad[0], group=group)
|
||||
dist.reduce_scatter_tensor(reduced_dv, gathered_kv_grad[1], group=group)
|
||||
if local_kv_grad is not None:
|
||||
kv_head_stop = kv_head_start + heads_k_stride
|
||||
dk[:, kv_head_start:kv_head_stop] = reduced_dk
|
||||
dv[:, kv_head_start:kv_head_stop] = reduced_dv
|
||||
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@ring_attention_backward.register_fake
|
||||
def _ring_attention_backward_fake(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
softmax_lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
group_name: str,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
attention_backend: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
def _ring_attention_setup_context(ctx, inputs, output) -> None:
|
||||
(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
dout,
|
||||
softmax_lse,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=wl,
|
||||
window_size_right=wr,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
local_k_slice_start,
|
||||
local_k_slice_stop,
|
||||
heads_k_stride,
|
||||
causal,
|
||||
group_name,
|
||||
window_size_left,
|
||||
window_size_right,
|
||||
attention_backend,
|
||||
) = inputs
|
||||
out, softmax_lse = output
|
||||
ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.max_seqlen_q = max_seqlen_q
|
||||
ctx.max_seqlen_k = max_seqlen_k
|
||||
ctx.local_k_slice_start = local_k_slice_start
|
||||
ctx.local_k_slice_stop = local_k_slice_stop
|
||||
ctx.heads_k_stride = heads_k_stride
|
||||
ctx.causal = causal
|
||||
ctx.group_name = group_name
|
||||
ctx.window_size_left = window_size_left
|
||||
ctx.window_size_right = window_size_right
|
||||
ctx.attention_backend = attention_backend
|
||||
ctx.mark_non_differentiable(softmax_lse)
|
||||
|
||||
|
||||
def _ring_attention_autograd_backward(ctx, dout: torch.Tensor, _dsoftmax_lse: torch.Tensor | None):
|
||||
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
dq, dk, dv = ring_attention_backward(
|
||||
dout=dout.contiguous(),
|
||||
q=q.detach(),
|
||||
k=k.detach(),
|
||||
v=v.detach(),
|
||||
out=out.detach(),
|
||||
softmax_lse=softmax_lse.detach(),
|
||||
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,
|
||||
max_seqlen_q=ctx.max_seqlen_q,
|
||||
max_seqlen_k=ctx.max_seqlen_k,
|
||||
local_k_slice_start=ctx.local_k_slice_start,
|
||||
local_k_slice_stop=ctx.local_k_slice_stop,
|
||||
heads_k_stride=ctx.heads_k_stride,
|
||||
causal=ctx.causal,
|
||||
group_name=ctx.group_name,
|
||||
window_size_left=ctx.window_size_left,
|
||||
window_size_right=ctx.window_size_right,
|
||||
attention_backend=ctx.attention_backend,
|
||||
)
|
||||
return (dq, dk, dv) + (None,) * 12
|
||||
|
||||
|
||||
class _RingFA4Varlen(torch.autograd.Function):
|
||||
"""Ring attention using FA4 (flash_attn.cute) kernels with all-gather communication.
|
||||
|
||||
Mirrors _RingFA3Varlen but calls the FA4 low-level forward/backward.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
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,
|
||||
local_k_slice_start: int,
|
||||
local_k_slice_stop: int,
|
||||
heads_k_stride: int,
|
||||
causal: bool,
|
||||
group_name: str,
|
||||
window_size_left: int = -1,
|
||||
window_size_right: int = -1,
|
||||
) -> torch.Tensor:
|
||||
group = dist.group.WORLD
|
||||
for pg in dist.distributed_c10d._world.pg_map:
|
||||
if pg.group_name == group_name:
|
||||
group = pg
|
||||
break
|
||||
|
||||
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
|
||||
window_size = (window_size_left, window_size_right)
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
out_list = []
|
||||
lse_list = []
|
||||
|
||||
nheads = q.shape[1]
|
||||
total_k, nheads_k, head_dim = k.shape
|
||||
world_size = dist.get_world_size(group)
|
||||
|
||||
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
kv_buffer_copy = torch.empty_like(kv_buffer)
|
||||
comm = AllGatherComm(group)
|
||||
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
for i in range(0, nheads_k, heads_k_stride):
|
||||
comm.wait()
|
||||
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
|
||||
|
||||
if i < nheads_k - heads_k_stride:
|
||||
left = i + heads_k_stride
|
||||
right = left + heads_k_stride
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
|
||||
|
||||
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
|
||||
k_i = kv_buffer[0][local_k_slice]
|
||||
v_i = kv_buffer[1][local_k_slice]
|
||||
out_i, lse_i = _fa4_varlen_forward(
|
||||
q=q_i,
|
||||
k=k_i,
|
||||
v=v_i,
|
||||
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=window_size,
|
||||
)
|
||||
out_list.append(out_i)
|
||||
lse_list.append(lse_i)
|
||||
|
||||
out = torch.cat(out_list, dim=1)
|
||||
lse = torch.cat(lse_list, dim=-2)
|
||||
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.softmax_scale = softmax_scale
|
||||
ctx.max_seqlen_q = max_seqlen_q
|
||||
ctx.max_seqlen_k = max_seqlen_k
|
||||
ctx.local_k_slice = local_k_slice
|
||||
ctx.heads_k_stride = heads_k_stride
|
||||
ctx.causal = causal
|
||||
ctx.group_name = group_name
|
||||
ctx.window_size = window_size
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, dout: torch.Tensor):
|
||||
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
heads_k_stride = ctx.heads_k_stride
|
||||
local_k_slice = ctx.local_k_slice
|
||||
causal = ctx.causal
|
||||
|
||||
group = dist.group.WORLD
|
||||
for pg in dist.distributed_c10d._world.pg_map:
|
||||
if pg.group_name == ctx.group_name:
|
||||
group = pg
|
||||
break
|
||||
|
||||
nheads = q.shape[1]
|
||||
total_k, nheads_k, head_dim = k.shape
|
||||
world_size = dist.get_world_size(group)
|
||||
|
||||
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
kv_buffer_copy = torch.empty_like(kv_buffer)
|
||||
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
|
||||
kv_contiguous_buffer = None
|
||||
if heads_k_stride != nheads_k:
|
||||
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
|
||||
|
||||
dq = torch.empty_like(q)
|
||||
dk = torch.empty_like(k)
|
||||
dv = torch.empty_like(v)
|
||||
|
||||
comm = AllGatherComm(group)
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
|
||||
|
||||
for i in range(0, nheads_k, heads_k_stride):
|
||||
dkv_buffer.zero_()
|
||||
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
|
||||
q_i = q[:, q_slice]
|
||||
dout_i = dout[:, q_slice]
|
||||
out_i = out[:, q_slice]
|
||||
dq_i = dq[:, q_slice]
|
||||
lse_i = softmax_lse[q_slice].contiguous()
|
||||
|
||||
comm.wait()
|
||||
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
|
||||
if i < nheads_k - heads_k_stride:
|
||||
left = i + heads_k_stride
|
||||
right = left + heads_k_stride
|
||||
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
|
||||
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
|
||||
|
||||
k_i = kv_buffer[0][local_k_slice]
|
||||
v_i = kv_buffer[1][local_k_slice]
|
||||
dk_i = dkv_buffer[0][local_k_slice]
|
||||
dv_i = dkv_buffer[1][local_k_slice]
|
||||
|
||||
_fa4_varlen_backward(
|
||||
dout=dout_i,
|
||||
q=q_i,
|
||||
k=k_i,
|
||||
v=v_i,
|
||||
out=out_i,
|
||||
softmax_lse=lse_i,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=ctx.max_seqlen_q,
|
||||
max_seqlen_k=ctx.max_seqlen_k,
|
||||
dq=dq_i,
|
||||
dk=dk_i,
|
||||
dv=dv_i,
|
||||
softmax_scale=ctx.softmax_scale,
|
||||
causal=causal,
|
||||
window_size=ctx.window_size,
|
||||
)
|
||||
|
||||
if heads_k_stride != nheads_k:
|
||||
dk_i = kv_contiguous_buffer[0]
|
||||
dv_i = kv_contiguous_buffer[1]
|
||||
else:
|
||||
dk_i = dk
|
||||
dv_i = dv
|
||||
|
||||
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
|
||||
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
|
||||
if heads_k_stride != nheads_k:
|
||||
dk[:, i : i + heads_k_stride] = dk_i
|
||||
dv[:, i : i + heads_k_stride] = dv_i
|
||||
|
||||
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
|
||||
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
|
||||
# window_size_left, window_size_right
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
|
||||
ring_attention_forward.register_autograd(
|
||||
_ring_attention_autograd_backward,
|
||||
setup_context=_ring_attention_setup_context,
|
||||
)
|
||||
|
||||
|
||||
def ring_fa4_varlen_func(
|
||||
def ring_varlen_attention(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
@@ -586,21 +474,24 @@ def ring_fa4_varlen_func(
|
||||
causal: bool,
|
||||
heads_k_stride: int,
|
||||
group: dist.ProcessGroup,
|
||||
attention_backend: str,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
return _RingFA4Varlen.apply(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
local_k_slice.start,
|
||||
local_k_slice.stop,
|
||||
heads_k_stride,
|
||||
causal,
|
||||
group.group_name,
|
||||
window_size[0],
|
||||
window_size[1],
|
||||
out, _ = ring_attention_forward(
|
||||
q=q,
|
||||
k=k,
|
||||
v=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,
|
||||
local_k_slice_start=local_k_slice.start,
|
||||
local_k_slice_stop=local_k_slice.stop,
|
||||
heads_k_stride=heads_k_stride,
|
||||
causal=causal,
|
||||
group_name=group.group_name,
|
||||
window_size_left=window_size[0],
|
||||
window_size_right=window_size[1],
|
||||
attention_backend=attention_backend,
|
||||
)
|
||||
return out
|
||||
|
||||
@@ -37,7 +37,8 @@ from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.nn.functional as dist_nn
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_to_all_single_equal
|
||||
|
||||
# Populated by `update_ulysses_params` before each forward pass. Mirrors
|
||||
# ring_flash_attn's DATA_PARAMS pattern so the patched attention path can
|
||||
@@ -68,18 +69,11 @@ def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
|
||||
return t.repeat_interleave(cp_size // h, dim=1)
|
||||
|
||||
|
||||
@torch._dynamo.disable
|
||||
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
|
||||
|
||||
Splits the head dim into cp_size groups and exchanges them so each rank
|
||||
ends up with the full sequence but only H/cp_size heads. Differentiable.
|
||||
|
||||
Disabled for dynamo: the collective must execute eagerly so it is scheduled
|
||||
by the autograd engine in a consistent order across ranks, not reordered by
|
||||
the compiled backward graph. Otherwise FSDP's post_backward reduce-scatter
|
||||
and the all-to-all backward can interleave differently per rank, deadlocking
|
||||
NCCL (see PR #3186 job 1578).
|
||||
"""
|
||||
s_local, h, d = t.shape
|
||||
assert h % cp_size == 0, (
|
||||
@@ -90,14 +84,12 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
|
||||
|
||||
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
|
||||
t = t.reshape(s_local, cp_size, h_local, d).transpose(0, 1).contiguous()
|
||||
output = torch.empty_like(t)
|
||||
out = dist_nn.all_to_all_single(output, t, group=cp_group)
|
||||
out = all_to_all_single_equal(t, cp_group)
|
||||
# out[i] is the chunk that source-rank i had at position my_rank, i.e.
|
||||
# source-rank i's local sequence shard for *my* head slice.
|
||||
return out.reshape(cp_size * s_local, h_local, d)
|
||||
|
||||
|
||||
@torch._dynamo.disable
|
||||
def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
"""Inverse of `_all_to_all_seq_to_head`: [S_global, H_local, D] -> [S_local, H, D]."""
|
||||
s_global, h_local, d = t.shape
|
||||
@@ -106,8 +98,7 @@ def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
|
||||
h = h_local * cp_size
|
||||
|
||||
t = t.reshape(cp_size, s_local, h_local, d).contiguous()
|
||||
output = torch.empty_like(t)
|
||||
out = dist_nn.all_to_all_single(output, t, group=cp_group)
|
||||
out = all_to_all_single_equal(t, cp_group)
|
||||
# out[s']: original chunk for sequence-rank s' (which now becomes head-rank s').
|
||||
return out.transpose(0, 1).contiguous().reshape(s_local, h, d)
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ from transformers.utils.deprecation import deprecate_kwarg
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
@@ -62,13 +62,12 @@ class LlamaDecoderLayer(GradientCheckpointingLayer):
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
bias=config.mlp_bias,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
|
||||
@@ -44,8 +44,6 @@ class MiniMaxM2Config(PretrainedConfig):
|
||||
Type of QK normalization. "per_layer" means each head has its own scale.
|
||||
attention_bias (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use bias in attention projections.
|
||||
use_grouped_mm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use grouped matmul for experts.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m2"
|
||||
@@ -96,7 +94,6 @@ class MiniMaxM2Config(PretrainedConfig):
|
||||
output_router_logits=False,
|
||||
router_aux_loss_coef=0.001,
|
||||
router_jitter_noise=0.0,
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
@@ -138,9 +135,6 @@ class MiniMaxM2Config(PretrainedConfig):
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.qk_norm_type = qk_norm_type
|
||||
|
||||
# Training
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""HF<->prime weight conversion for MiniMax M2, as a declarative op chain.
|
||||
|
||||
Per layer: router ``block_sparse_moe.gate.weight`` <-> ``mlp.router.gate.weight``,
|
||||
the ``e_score_correction_bias`` <-> ``mlp.expert_bias``, and the routed experts
|
||||
(per-expert w1/w2/w3 ``nn.Linear`` <-> stacked w1/w2/w3). The prime-only runtime
|
||||
the ``e_score_correction_bias`` <-> ``mlp.router.selection_bias``, and the routed experts
|
||||
(per-expert w1/w2/w3 ``nn.Linear`` <-> stacked gate/down/up projections). The prime-only runtime
|
||||
buffer ``mlp.tokens_per_expert`` is dropped on the way to HF.
|
||||
"""
|
||||
|
||||
@@ -11,8 +11,8 @@ from __future__ import annotations
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, routed_experts_op
|
||||
|
||||
# HF stores per-expert projections under the literal names w1/w2/w3 (nn.Linear,
|
||||
# so each carries a `.weight` suffix); prime stacks them as w1/w2/w3.
|
||||
_MINIMAX_PROJ_ORDER = (("w1", "w1"), ("w2", "w2"), ("w3", "w3"))
|
||||
# so each carries a `.weight` suffix); PrimeRL uses canonical projection names.
|
||||
_MINIMAX_PROJ_ORDER = (("gate_proj", "w1"), ("down_proj", "w2"), ("up_proj", "w3"))
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
@@ -20,7 +20,7 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}"
|
||||
ops.append(Rename(f"{p}.block_sparse_moe.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
ops.append(Rename(f"{p}.block_sparse_moe.e_score_correction_bias", f"{p}.mlp.expert_bias"))
|
||||
ops.append(Rename(f"{p}.block_sparse_moe.e_score_correction_bias", f"{p}.mlp.router.selection_bias"))
|
||||
ops.append(
|
||||
routed_experts_op(
|
||||
p,
|
||||
|
||||
@@ -42,17 +42,21 @@ class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_local_experts,
|
||||
num_shared_experts=0,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func=config.scoring_func,
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=1e-3 if config.use_routing_bias else None,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
shared_expert=None,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -104,7 +108,7 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -6,7 +6,7 @@ class NemotronHConfig(PretrainedConfig):
|
||||
|
||||
The model architecture is defined by `layers_block_type`, a list where each element is
|
||||
one of "mamba", "attention", or "moe". The 120B model uses a pattern like MEMEMEM*EMEMEMEM*...
|
||||
(M=Mamba-2, E=LatentMoE, *=Attention) repeated across 88 layers.
|
||||
(M=Mamba-2, E=MoE with latent projections, *=Attention) repeated across 88 layers.
|
||||
|
||||
Args:
|
||||
vocab_size: Vocabulary size.
|
||||
@@ -46,8 +46,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
moe_latent_size: Latent projection size (None means use hidden_size).
|
||||
num_experts_per_tok: Top-k routing parameter.
|
||||
routed_scaling_factor: Scaling factor for routed expert outputs.
|
||||
n_group: Number of groups for expert routing.
|
||||
topk_group: Top-k group parameter.
|
||||
norm_topk_prob: Whether to normalize top-k probabilities.
|
||||
use_bias: Global bias setting.
|
||||
initializer_range: Standard deviation for weight initialization.
|
||||
@@ -55,7 +53,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
residual_in_fp32: Whether to keep residuals in fp32.
|
||||
rescale_prenorm_residual: Whether to rescale pre-norm residuals.
|
||||
load_balance_coeff: Auxiliary-loss-free load balancing coefficient.
|
||||
use_grouped_mm: Whether to use grouped MM for experts.
|
||||
"""
|
||||
|
||||
model_type = "nemotron_h"
|
||||
@@ -109,8 +106,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
moe_latent_size=None,
|
||||
num_experts_per_tok=2,
|
||||
routed_scaling_factor=1.0,
|
||||
n_group=1,
|
||||
topk_group=1,
|
||||
norm_topk_prob=True,
|
||||
# General training
|
||||
use_bias=False,
|
||||
@@ -120,7 +115,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
rescale_prenorm_residual=True,
|
||||
# PrimeRL training features
|
||||
load_balance_coeff=None,
|
||||
use_grouped_mm=True,
|
||||
# RoPE
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
@@ -191,8 +185,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
self.moe_latent_size = moe_latent_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
# General training config
|
||||
@@ -204,7 +196,6 @@ class NemotronHConfig(PretrainedConfig):
|
||||
|
||||
# PrimeRL training features
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
|
||||
@@ -5,14 +5,11 @@ split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
|
||||
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
|
||||
its per-tensor min on the way in (and intentionally *not* restored on the way
|
||||
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
|
||||
backward is the identity). Experts are up/down only (no gate); a dummy ``w3``
|
||||
of shape ``(0,)`` is synthesised for expert-parallel compatibility.
|
||||
backward is the identity). Experts are up/down only, with no gate projection.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
Conditional,
|
||||
ConvOp,
|
||||
@@ -21,47 +18,42 @@ from prime_rl.trainer.models.conversion_ops import (
|
||||
PrefixRename,
|
||||
Rename,
|
||||
Stack,
|
||||
Synthetic,
|
||||
key_present,
|
||||
)
|
||||
|
||||
|
||||
def _empty_w3(prefix: str):
|
||||
def factory(sd):
|
||||
w1 = f"{prefix}.mlp.experts.w1"
|
||||
device = sd[w1].device if w1 in sd else "cpu"
|
||||
return torch.empty(0, device=device)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
|
||||
return [
|
||||
# Router: gate.weight -> router.gate (note: prime drops the .weight),
|
||||
# Router gate and selection bias.
|
||||
# plus the load-balancing bias which is shifted by its min on the way in
|
||||
# and not undone on the way out (MapValue backward = identity).
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate"),
|
||||
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.e_score_correction_bias"),
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate.weight"),
|
||||
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.selection_bias"),
|
||||
MapValue(
|
||||
f"{prefix}.mlp.router.e_score_correction_bias",
|
||||
f"{prefix}.mlp.router.selection_bias",
|
||||
forward=lambda x: x - x.min(),
|
||||
backward=lambda x: x,
|
||||
),
|
||||
# Experts: w1=up, w2=down (no gate). HF is either per-expert weights or
|
||||
# Experts are up/down only. HF is either per-expert weights or
|
||||
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
|
||||
# per-expert (the predicate's HF key is absent in prime -> else branch).
|
||||
Conditional(
|
||||
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
|
||||
then=[
|
||||
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.w1"),
|
||||
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.w2"),
|
||||
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.up_proj"),
|
||||
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.down_proj"),
|
||||
],
|
||||
else_=[
|
||||
Stack(stacked=f"{prefix}.mlp.experts.w1", item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight"),
|
||||
Stack(stacked=f"{prefix}.mlp.experts.w2", item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight"),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.up_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight",
|
||||
),
|
||||
Stack(
|
||||
stacked=f"{prefix}.mlp.experts.down_proj",
|
||||
item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight",
|
||||
),
|
||||
],
|
||||
),
|
||||
Synthetic(f"{prefix}.mlp.experts.w3", factory=_empty_w3(prefix)),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
@@ -74,13 +66,13 @@ def _layer_op(prefix: str) -> ConvOp:
|
||||
namespace is disambiguated by which sub-key is present (and, on the way
|
||||
back, by which prime namespace is present, so the predicates work both
|
||||
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
|
||||
we didn't enumerate); MoE needs its specific ops (and the gated
|
||||
``Synthetic`` w3, which is why this is a Conditional rather than a plain
|
||||
catch-all)."""
|
||||
we didn't enumerate); MoE needs its specific ops."""
|
||||
is_attention = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
|
||||
)
|
||||
is_moe = lambda sd: f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate" in sd # noqa: E731
|
||||
is_moe = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate.weight" in sd
|
||||
)
|
||||
return Conditional(
|
||||
is_attention,
|
||||
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
|
||||
- Mamba-2 layers (using NemotronHMamba2Mixer from HF transformers)
|
||||
- LatentMoE layers (non-gated experts with latent projections)
|
||||
- MoE layers with non-gated experts and latent projections
|
||||
- Attention layers (using shared FlashAttention/SDPA from prime-rl)
|
||||
"""
|
||||
|
||||
@@ -23,7 +23,12 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
GroupedExperts,
|
||||
MoE,
|
||||
TokenChoiceTopKRouter,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
@@ -233,27 +238,65 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
class NemotronHMoE(MoE):
|
||||
def __init__(self, *, hidden_size: int, latent_size: int, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.fc1_latent_proj = nn.Linear(hidden_size, latent_size, bias=False)
|
||||
self.fc2_latent_proj = nn.Linear(latent_size, hidden_size, bias=False)
|
||||
|
||||
def prepare_expert_input(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc1_latent_proj(x)
|
||||
|
||||
def prepare_expert_output(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.fc2_latent_proj(x)
|
||||
|
||||
|
||||
class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
"""MoE layer: norm -> LatentMoE -> residual."""
|
||||
"""MoE layer with latent routed experts."""
|
||||
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
super().__init__()
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.layer_norm_epsilon))
|
||||
self.mlp = LatentMoE(
|
||||
effective_latent_dim = config.moe_latent_size if config.moe_latent_size is not None else config.hidden_size
|
||||
router = TokenChoiceTopKRouter(
|
||||
dim=config.hidden_size,
|
||||
latent_dim=config.moe_latent_size,
|
||||
moe_intermediate_size=config.moe_intermediate_size,
|
||||
shared_expert_intermediate_size=config.moe_shared_expert_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
n_group=config.n_group,
|
||||
topk_group=config.topk_group,
|
||||
norm_topk_prob=config.norm_topk_prob,
|
||||
routed_scaling_factor=config.routed_scaling_factor,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
score_func="sigmoid",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
selection_bias=True,
|
||||
topk_sorted=False,
|
||||
)
|
||||
router.fp32_gate = True
|
||||
experts = GroupedExperts(
|
||||
dim=effective_latent_dim,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_shared_expert_intermediate_size,
|
||||
expert_type="non_gated",
|
||||
activation=config.mlp_hidden_act,
|
||||
)
|
||||
moe_kwargs = dict(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=shared_expert,
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
)
|
||||
if config.moe_latent_size is None:
|
||||
self.mlp = MoE(**moe_kwargs)
|
||||
else:
|
||||
self.mlp = NemotronHMoE(
|
||||
hidden_size=config.hidden_size,
|
||||
latent_size=config.moe_latent_size,
|
||||
**moe_kwargs,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -336,7 +379,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.e_score_correction_bias"))
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
|
||||
|
||||
def _init_weights(self, module):
|
||||
std = self.config.initializer_range
|
||||
@@ -348,7 +391,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
module.weight.data.normal_(mean=0.0, std=std)
|
||||
if module.padding_idx is not None:
|
||||
module.weight.data[module.padding_idx].zero_()
|
||||
elif isinstance(module, (NonGatedGroupedExperts, NemotronHRouter)):
|
||||
elif isinstance(module, (GroupedExperts, TokenChoiceTopKRouter)):
|
||||
module.init_weights(std)
|
||||
|
||||
@classmethod
|
||||
@@ -359,7 +402,7 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mamba." in name
|
||||
or "mlp.experts.w1" in name
|
||||
or "mlp.experts.up_proj" in name
|
||||
or "self_attn." in name
|
||||
or "model.embed_tokens." in name
|
||||
or "model.norm." in name
|
||||
|
||||
@@ -13,7 +13,7 @@ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tu
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
@@ -52,13 +52,11 @@ class Qwen3DecoderLayer(GradientCheckpointingLayer):
|
||||
if self.layer_type == "sliding_attention":
|
||||
self.self_attn.sliding_window = config.sliding_window
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
Qwen3_5MoeGatedAttentionConfig,
|
||||
Qwen3_5MoeGatedDeltaNet,
|
||||
@@ -84,13 +84,11 @@ class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
|
||||
else:
|
||||
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
|
||||
@@ -50,7 +50,6 @@ class Qwen3_5MoeConfig(PretrainedConfig):
|
||||
layer_types=None,
|
||||
# PrimeRL additions
|
||||
load_balance_coeff=None,
|
||||
use_grouped_mm=True,
|
||||
pad_token_id=None,
|
||||
**kwargs,
|
||||
):
|
||||
@@ -100,7 +99,6 @@ class Qwen3_5MoeConfig(PretrainedConfig):
|
||||
|
||||
# PrimeRL additions
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""HF<->prime weight conversion for Qwen3.5-MoE, as a declarative op chain.
|
||||
|
||||
Per layer: router ``mlp.gate.weight`` <-> ``mlp.router.gate.weight``, the routed
|
||||
experts (per-expert gate/down/up <-> stacked w1/w2/w3, with the fused
|
||||
transformers-v5 ``gate_up_proj`` input also accepted), the shared expert
|
||||
(``mlp.shared_expert.{gate,down,up}_proj`` <-> ``shared_expert.{w1,w2,w3}``) and
|
||||
its gate (``mlp.shared_expert_gate`` <-> ``shared_expert_gate``).
|
||||
Per layer: the router and shared-expert output gate are nested under their
|
||||
PrimeRL modules, and routed experts use stacked canonical projections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,14 +15,8 @@ def _conversion_chain(config, model_prefix: str) -> list[ConvOp]:
|
||||
p = f"{model_prefix}.layers.{i}"
|
||||
# Router: mlp.gate.weight -> mlp.router.gate.weight
|
||||
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
# Routed experts: per-expert (gate/down/up) or fused gate_up_proj -> w1/w2/w3
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.mlp.shared_expert.output_gate.weight"))
|
||||
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
|
||||
# Shared expert: mlp.shared_expert.{gate,down,up}_proj.weight -> shared_expert.{w1,w2,w3}.weight
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.gate_proj.weight", f"{p}.shared_expert.w1.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.down_proj.weight", f"{p}.shared_expert.w2.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.up_proj.weight", f"{p}.shared_expert.w3.weight"))
|
||||
# Shared expert gate
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.shared_expert_gate.weight"))
|
||||
return ops
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,8 @@ from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_varlen_func,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
|
||||
from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_position_ids_for_cp
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
@@ -277,18 +278,6 @@ class Qwen3_5MoeGatedAttentionBase(nn.Module):
|
||||
self.q_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = Qwen3_5MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
def output_proj(
|
||||
self,
|
||||
attn_output: torch.Tensor,
|
||||
gate: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
input_shape = gate.shape[:-1]
|
||||
if attn_output.dim() == 4:
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate)
|
||||
return self.o_proj(attn_output)
|
||||
|
||||
|
||||
class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
"""Gated softmax attention using Flash Attention varlen functions."""
|
||||
@@ -325,21 +314,13 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
out = out[0]
|
||||
return out
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
|
||||
def attn_projections(
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -359,24 +340,10 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
|
||||
return query_states, key_states, value_states, gate
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
query_states, key_states, value_states, gate = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
return self.output_proj(attn_output, gate), None
|
||||
attn_output = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
|
||||
attn_output = attn_output.contiguous().view(*input_shape, -1)
|
||||
attn_output = attn_output * torch.sigmoid(gate)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
QWEN35MOE_ATTN_IMPL2CLASS = {
|
||||
@@ -421,6 +388,24 @@ def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
|
||||
return QWEN35MOE_ATTN_IMPL2CLASS[attn_impl](attn_config)
|
||||
|
||||
|
||||
class Qwen3_5MoeSharedExpert(FeedForward):
|
||||
def __init__(self, config: Qwen3_5MoeConfig) -> None:
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.output_gate = nn.Linear(config.hidden_size, 1, bias=False)
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
return torch.sigmoid(self.output_gate(x)) * super().forward(x, routed_experts)
|
||||
|
||||
def init_weights(self, init_std: float = 0.02) -> None:
|
||||
super().init_weights(init_std)
|
||||
nn.init.trunc_normal_(self.output_gate.weight, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
@@ -433,24 +418,23 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
elif self.layer_type == "full_attention":
|
||||
self.self_attn = _get_gated_attention(config)
|
||||
|
||||
# MoE: routed experts via shared MoE class (no shared experts in MoE itself)
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=0,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="softmax",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
|
||||
# Separate gated shared expert
|
||||
self.shared_expert = FeedForward(dim=config.hidden_size, hidden_dim=config.shared_expert_intermediate_size)
|
||||
self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=Qwen3_5MoeSharedExpert(config),
|
||||
)
|
||||
|
||||
# Layer norms with (1+weight) parameterization
|
||||
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
@@ -483,21 +467,9 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# MLP: routed experts + gated shared expert
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
|
||||
# Routed experts
|
||||
routed_output = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
|
||||
# Gated shared expert
|
||||
bs, slen, dim = hidden_states.shape
|
||||
hidden_flat = hidden_states.view(-1, dim)
|
||||
shared_output = self.shared_expert(hidden_flat)
|
||||
shared_output = F.sigmoid(self.shared_expert_gate(hidden_flat)) * shared_output
|
||||
shared_output = shared_output.view(bs, slen, dim)
|
||||
|
||||
hidden_states = residual + routed_output + shared_output
|
||||
hidden_states = residual + self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return hidden_states
|
||||
|
||||
|
||||
@@ -643,16 +615,11 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mlp.experts.1.up_proj" in name
|
||||
or "mlp.experts.gate_up_proj" in name
|
||||
or "mlp.shared_expert.gate_proj" in name
|
||||
for name in state_dict.keys()
|
||||
)
|
||||
return any("mlp.experts.1.up_proj" in name or "mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
@@ -927,16 +894,11 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mlp.experts.gate_up_proj" in name
|
||||
or "mlp.experts.1.up_proj" in name
|
||||
or "mlp.shared_expert.gate_proj" in name
|
||||
for name in state_dict
|
||||
)
|
||||
return any("mlp.experts.gate_up_proj" in name or "mlp.experts.1.up_proj" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Forward
|
||||
|
||||
@@ -126,9 +126,9 @@ class Qwen3MoeConfig(PretrainedConfig):
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.mlp.experts.*.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.*.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_proj": "colwise",
|
||||
"layers.*.mlp.experts.up_proj": "colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
@@ -168,7 +168,6 @@ class Qwen3MoeConfig(PretrainedConfig):
|
||||
router_aux_loss_coef=0.001,
|
||||
mlp_only_layers=None,
|
||||
load_balance_coeff=None,
|
||||
use_grouped_mm=True,
|
||||
pad_token_id=None,
|
||||
**kwargs,
|
||||
):
|
||||
@@ -202,7 +201,6 @@ class Qwen3MoeConfig(PretrainedConfig):
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
|
||||
@@ -29,7 +29,7 @@ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tu
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
@@ -60,29 +60,30 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=0,
|
||||
expert_type="gated",
|
||||
activation=config.hidden_act,
|
||||
score_func="softmax",
|
||||
route_norm=config.norm_topk_prob,
|
||||
route_scale=1.0,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
|
||||
if (layer_idx not in config.mlp_only_layers) and (
|
||||
config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0
|
||||
):
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
self.mlp = MoE.from_args(
|
||||
moe_args,
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
shared_expert=None,
|
||||
)
|
||||
else:
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.mlp = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
@@ -139,7 +140,7 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
"""Check if the state dict contains MoE layers in PrimeRL training format."""
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
return any("mlp.experts.gate_proj" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import importlib.util
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
|
||||
from prime_rl.configs.trainer import (
|
||||
BF16MoEComputeConfig,
|
||||
DeepEPMoEDispatchConfig,
|
||||
DeepGemmFP8MoEComputeConfig,
|
||||
ModelConfig,
|
||||
MoERuntimeConfig,
|
||||
MXFP8MoEComputeConfig,
|
||||
TorchMoEDispatchConfig,
|
||||
)
|
||||
from prime_rl.trainer.distributed.expert_parallel import ExpertWeightParallel
|
||||
from prime_rl.trainer.distributed.token_dispatcher import (
|
||||
LocalTokenDispatcher,
|
||||
MXFP8TorchTokenDispatcher,
|
||||
TorchTokenDispatcher,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.grouped_gemm import (
|
||||
BF16GroupedGemm,
|
||||
DeepGemmFP8GroupedGemm,
|
||||
GroupedGemm,
|
||||
MXFP8GroupedGemm,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def _resolve_grouped_gemm(config: ModelConfig) -> GroupedGemm:
|
||||
compute = config.moe.compute
|
||||
if isinstance(compute, BF16MoEComputeConfig):
|
||||
return BF16GroupedGemm()
|
||||
if isinstance(compute, DeepGemmFP8MoEComputeConfig):
|
||||
if importlib.util.find_spec("deep_gemm") is None:
|
||||
raise RuntimeError("DeepGEMM FP8 expert compute requires the deep-gemm package.")
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability < (9, 0):
|
||||
raise RuntimeError(
|
||||
f"DeepGEMM FP8 expert compute requires SM90 or newer, but this device is SM{capability[0]}{capability[1]}."
|
||||
)
|
||||
return DeepGemmFP8GroupedGemm()
|
||||
if isinstance(compute, MXFP8MoEComputeConfig):
|
||||
import prime_kernels
|
||||
|
||||
kernel = prime_kernels.load("mxfp8_moe")
|
||||
return MXFP8GroupedGemm(
|
||||
kernel=kernel,
|
||||
high_precision_wgrad=compute.recipe == "mxfp8_rceil_wgrad_with_hp",
|
||||
token_group_alignment=kernel.TOKEN_GROUP_ALIGNMENT,
|
||||
)
|
||||
raise TypeError(f"Unsupported MoE compute config: {type(compute).__name__}")
|
||||
|
||||
|
||||
def configure_moe_runtime(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) -> None:
|
||||
moe_layers = [module for module in model.modules() if isinstance(module, MoE)]
|
||||
if not moe_layers:
|
||||
if config.moe != MoERuntimeConfig():
|
||||
raise ValueError("A non-default model.moe runtime was configured, but the model has no custom MoE layers.")
|
||||
return
|
||||
|
||||
grouped_gemm = _resolve_grouped_gemm(config)
|
||||
ep_mesh = parallel_dims.get_mesh("ep") if parallel_dims.ep_enabled else None
|
||||
dispatch = config.moe.dispatch
|
||||
|
||||
for moe in moe_layers:
|
||||
if ep_mesh is not None and moe.experts.num_experts % parallel_dims.ep:
|
||||
raise ValueError(
|
||||
f"MoE expert count {moe.experts.num_experts} must be divisible by model.ep={parallel_dims.ep}."
|
||||
)
|
||||
moe.experts.set_grouped_gemm(grouped_gemm)
|
||||
if ep_mesh is None:
|
||||
token_dispatcher = LocalTokenDispatcher(
|
||||
num_experts=moe.experts.num_experts,
|
||||
top_k=moe.router.top_k,
|
||||
token_group_alignment=grouped_gemm.token_group_alignment,
|
||||
)
|
||||
elif isinstance(dispatch, TorchMoEDispatchConfig):
|
||||
if dispatch.transport == "mxfp8":
|
||||
token_dispatcher = MXFP8TorchTokenDispatcher(
|
||||
num_experts=moe.experts.num_experts,
|
||||
top_k=moe.router.top_k,
|
||||
token_group_alignment=grouped_gemm.token_group_alignment,
|
||||
group=ep_mesh.get_group(),
|
||||
)
|
||||
else:
|
||||
token_dispatcher = TorchTokenDispatcher(
|
||||
num_experts=moe.experts.num_experts,
|
||||
top_k=moe.router.top_k,
|
||||
token_group_alignment=grouped_gemm.token_group_alignment,
|
||||
group=ep_mesh.get_group(),
|
||||
)
|
||||
elif isinstance(dispatch, DeepEPMoEDispatchConfig):
|
||||
from prime_rl.trainer.distributed.deepep import DeepEPTokenDispatcher
|
||||
|
||||
token_dispatcher = DeepEPTokenDispatcher(
|
||||
num_experts=moe.experts.num_experts,
|
||||
token_group_alignment=grouped_gemm.token_group_alignment,
|
||||
group=ep_mesh.get_group(),
|
||||
num_sms=dispatch.num_sms,
|
||||
token_chunk_size=dispatch.token_chunk_size,
|
||||
)
|
||||
else:
|
||||
raise TypeError(f"Unsupported MoE dispatch config: {type(dispatch).__name__}")
|
||||
moe.set_token_dispatcher(token_dispatcher)
|
||||
|
||||
if ep_mesh is not None:
|
||||
parallelize_module(moe.experts, device_mesh=ep_mesh, parallelize_plan=ExpertWeightParallel())
|
||||
|
||||
get_logger().info(
|
||||
f"Configured {len(moe_layers)} MoE layers with compute={config.moe.compute.type}, "
|
||||
f"dispatch={config.moe.dispatch.type}, ep={parallel_dims.ep}"
|
||||
)
|
||||
@@ -313,13 +313,6 @@ def resolve_ep(config: ModelConfig) -> None:
|
||||
config.ep = resolved_ep
|
||||
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
|
||||
|
||||
if config.ep_comm_backend != "torch" and config.ep <= 1:
|
||||
raise ValueError(
|
||||
f"model.ep_comm_backend='{config.ep_comm_backend}' requires ep > 1, "
|
||||
f"but auto-resolved ep=1 (world_size={world_size}). "
|
||||
"Set ep explicitly or use ep_comm_backend='torch'."
|
||||
)
|
||||
|
||||
|
||||
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
|
||||
assert isinstance(config.ep, int), (
|
||||
|
||||
@@ -43,11 +43,12 @@ class Batch(TypedDict):
|
||||
class StatefulIterableDataset(Stateful, IterableDataset):
|
||||
"""SFT dataset are iterable (infinite) and stateful (can be checkpointed)."""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, non_dp_size: int = 1):
|
||||
self.step, self.epoch = 0, 0
|
||||
self.num_samples = defaultdict(int)
|
||||
self.num_tokens = defaultdict(int)
|
||||
self.fast_forward = False
|
||||
self.non_dp_size = non_dp_size
|
||||
self._setup_world_info()
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
@@ -66,8 +67,10 @@ class StatefulIterableDataset(Stateful, IterableDataset):
|
||||
num_workers = worker_info.num_workers
|
||||
else:
|
||||
worker_id, num_workers = 0, 1
|
||||
self.data_rank = get_world().rank * num_workers + worker_id
|
||||
self.data_world_size = get_world().world_size * num_workers
|
||||
world = get_world()
|
||||
assert world.world_size % self.non_dp_size == 0, "world_size must be divisible by non_dp_size"
|
||||
self.data_rank = world.rank // self.non_dp_size * num_workers + worker_id
|
||||
self.data_world_size = world.world_size // self.non_dp_size * num_workers
|
||||
|
||||
|
||||
class FakeDataset(StatefulIterableDataset):
|
||||
@@ -80,8 +83,9 @@ class FakeDataset(StatefulIterableDataset):
|
||||
length: Literal["fixed", "variable"] = "fixed",
|
||||
input_ids: Literal["increasing", "random"] = "random",
|
||||
seed: int = 0,
|
||||
non_dp_size: int = 1,
|
||||
):
|
||||
super().__init__()
|
||||
super().__init__(non_dp_size)
|
||||
self.vocab_size = vocab_size
|
||||
self.seq_len = seq_len
|
||||
self.length = length
|
||||
@@ -103,6 +107,7 @@ class FakeDataset(StatefulIterableDataset):
|
||||
return seq_len, random_input_ids
|
||||
|
||||
def __iter__(self):
|
||||
self._setup_world_info()
|
||||
# use a rank seeded PRNG instead of torch global default PRNG because with num workers > 0
|
||||
# the data loader reseeds the global PRNG per worker process
|
||||
generator = torch.Generator().manual_seed(self.seed + self.data_rank)
|
||||
@@ -215,7 +220,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
max_epochs: int | None = None,
|
||||
multimodal: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
super().__init__(non_dp_size)
|
||||
self.logger = get_logger()
|
||||
self.dataset = dataset
|
||||
self.num_examples = len(self.dataset)
|
||||
@@ -233,16 +238,6 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.num_examples = min(self.num_examples, self.max_examples)
|
||||
self.dataset = self.dataset.take(self.max_examples)
|
||||
|
||||
# Get the data rank and world size
|
||||
worker_info = get_worker_info()
|
||||
worker_id, num_workers = 0, 1
|
||||
if worker_info is not None:
|
||||
worker_id = worker_info.id
|
||||
num_workers = worker_info.num_workers
|
||||
assert get_world().world_size % non_dp_size == 0, "world_size must be divisible by non_dp_size"
|
||||
self.data_rank = get_world().rank // non_dp_size * num_workers + worker_id
|
||||
self.data_world_size = get_world().world_size // non_dp_size * num_workers
|
||||
|
||||
def _process(self, example: dict) -> dict | None:
|
||||
def resolve_messages(example: dict) -> list[dict]:
|
||||
# `messages` takes precedence over explicit split fields and is interpreted
|
||||
@@ -393,6 +388,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
}
|
||||
|
||||
def __iter__(self):
|
||||
self._setup_world_info()
|
||||
dataset = self.dataset.shuffle(seed=self.epoch + self.seed) if self.shuffle else self.dataset
|
||||
while True:
|
||||
self.step += 1
|
||||
@@ -446,13 +442,22 @@ class CatDataset(StatefulIterableDataset):
|
||||
self.pending_sample: Sample | None = None
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
state = {"dataset": self.dataset.state_dict()}
|
||||
state = {
|
||||
"dataset": self.dataset.state_dict(),
|
||||
"progress": {
|
||||
"num_samples": dict(self.dataset.num_samples),
|
||||
"num_tokens": dict(self.dataset.num_tokens),
|
||||
},
|
||||
}
|
||||
if self.pending_sample is not None:
|
||||
state["pending_sample"] = self.pending_sample
|
||||
return state
|
||||
|
||||
def load_state_dict(self, state_dict: dict):
|
||||
self.dataset.load_state_dict(state_dict["dataset"])
|
||||
progress = state_dict.get("progress", {})
|
||||
self.dataset.num_samples.update(progress.get("num_samples", {}))
|
||||
self.dataset.num_tokens.update(progress.get("num_tokens", {}))
|
||||
self.pending_sample = state_dict.get("pending_sample")
|
||||
|
||||
def __iter__(self):
|
||||
@@ -655,6 +660,7 @@ def setup_dataset(
|
||||
length=config.length,
|
||||
input_ids=config.input_ids,
|
||||
seed=config.seed,
|
||||
non_dp_size=non_dp_size,
|
||||
)
|
||||
elif config.type == "sft":
|
||||
if renderer is None:
|
||||
@@ -697,3 +703,24 @@ def get_dataset_state(dataloader: StatefulDataLoader) -> dict:
|
||||
private worker-snapshot layout."""
|
||||
snapshots = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]
|
||||
return {wid: snap["dataset_state"]["dataset"] for wid, snap in sorted(snapshots.items())}
|
||||
|
||||
|
||||
def get_dataset_progress(dataloader: StatefulDataLoader) -> dict:
|
||||
"""Dataset position and aggregate counters from dataloader workers."""
|
||||
snapshot = dataloader.state_dict()["_snapshot"]
|
||||
worker_snapshots = snapshot["_worker_snapshots"]
|
||||
positions = [worker_snapshot["dataset_state"]["dataset"] for worker_snapshot in worker_snapshots.values()]
|
||||
furthest = max(positions, key=lambda position: position["step"])
|
||||
num_samples = defaultdict(int)
|
||||
num_tokens = defaultdict(int)
|
||||
for worker_snapshot in worker_snapshots.values():
|
||||
progress = worker_snapshot["dataset_state"].get("progress", {})
|
||||
for name, count in progress.get("num_samples", {}).items():
|
||||
num_samples[name] += count
|
||||
for name, count in progress.get("num_tokens", {}).items():
|
||||
num_tokens[name] += count
|
||||
return {
|
||||
**furthest,
|
||||
"num_samples": dict(num_samples),
|
||||
"num_tokens": dict(num_tokens),
|
||||
}
|
||||
|
||||
@@ -40,7 +40,13 @@ from prime_rl.trainer.model import (
|
||||
)
|
||||
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
|
||||
from prime_rl.trainer.perf import get_perf_counter
|
||||
from prime_rl.trainer.sft.data import get_dataset_state, load_sft_dataset, setup_dataloader, setup_dataset
|
||||
from prime_rl.trainer.sft.data import (
|
||||
get_dataset_progress,
|
||||
get_dataset_state,
|
||||
load_sft_dataset,
|
||||
setup_dataloader,
|
||||
setup_dataset,
|
||||
)
|
||||
from prime_rl.trainer.utils import (
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
@@ -590,7 +596,8 @@ def train(config: SFTConfig):
|
||||
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
|
||||
num_tokens = dp_size * num_local_tokens
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples = dataset.step
|
||||
dataset_progress = get_dataset_progress(dataloader)
|
||||
progress.total_samples = dataset_progress["step"]
|
||||
perf_counter = get_perf_counter(model, config.data.seq_len)
|
||||
perf_counter.count_tokens(num_tokens)
|
||||
throughput = perf_counter.get_tokens_per_second() or 0
|
||||
@@ -612,24 +619,26 @@ def train(config: SFTConfig):
|
||||
logger.success(step_message)
|
||||
|
||||
# Log progress metrics
|
||||
total_samples = sum(dataset.num_samples.values())
|
||||
total_tokens = sum(dataset.num_tokens.values())
|
||||
samples_by_source = dataset_progress["num_samples"]
|
||||
tokens_by_source = dataset_progress["num_tokens"]
|
||||
total_samples = sum(samples_by_source.values())
|
||||
total_tokens = sum(tokens_by_source.values())
|
||||
progress_metrics = {
|
||||
"progress/epoch": dataset.epoch,
|
||||
"progress/epoch": dataset_progress["epoch"],
|
||||
"progress/num_samples": progress.total_samples,
|
||||
"progress/num_tokens": progress.total_tokens,
|
||||
"step": progress.step,
|
||||
}
|
||||
# At least two subsets/splits
|
||||
if len(dataset.num_samples) > 1:
|
||||
if len(samples_by_source) > 1:
|
||||
progress_metrics.update(
|
||||
**{
|
||||
f"progress/{subset_or_split}/ratio_samples": num_samples / total_samples
|
||||
for subset_or_split, num_samples in dataset.num_samples.items()
|
||||
for subset_or_split, num_samples in samples_by_source.items()
|
||||
},
|
||||
**{
|
||||
f"progress/{subset_or_split}/ratio_tokens": num_tokens / total_tokens
|
||||
for subset_or_split, num_tokens in dataset.num_tokens.items()
|
||||
for subset_or_split, num_tokens in tokens_by_source.items()
|
||||
},
|
||||
)
|
||||
asyncio.run(monitors.log(progress_metrics, step=progress.step))
|
||||
|
||||
@@ -61,7 +61,7 @@ class NixlAgent:
|
||||
return self._agent.prep_xfer_dlist(
|
||||
agent_name=peer.remote_agent_name if peer is not None else "",
|
||||
xfer_list=list(descs),
|
||||
mem_type="cuda",
|
||||
mem_type="VRAM",
|
||||
backends=["UCX"],
|
||||
)
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@ from typing import Literal
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.nn as dist_nn
|
||||
import torch.nn as nn
|
||||
from ring_flash_attn import update_ring_flash_attn_params
|
||||
|
||||
from prime_rl.trainer.distributed.collectives import all_gather
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
CPStyle = Literal["ring", "ulysses"]
|
||||
@@ -126,9 +126,7 @@ def shard_position_ids_for_cp(position_ids: torch.Tensor, cp_rank: int, cp_world
|
||||
|
||||
|
||||
def gather_for_cp(t: torch.Tensor, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
gathered_t = dist_nn.all_gather(t, group=cp_group)
|
||||
|
||||
return torch.cat(gathered_t, dim=1)
|
||||
return all_gather(t, 1, cp_group)
|
||||
|
||||
|
||||
def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
|
||||
@@ -40,6 +40,8 @@ def rl_process(
|
||||
"--clean",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--trainer.model.conversion-dir",
|
||||
(output_dir / RUN_NAME / "model-conversion").as_posix(),
|
||||
"--monitors.wandb.project",
|
||||
wandb_project,
|
||||
"--monitors.wandb.name",
|
||||
|
||||
@@ -5,13 +5,12 @@ The full happy-path is owned upstream by vLLM's
|
||||
deltas here:
|
||||
* ``serialize_routed_experts`` round-trips a compact raw-byte payload.
|
||||
* The subclass attaches its overrides without monkey-patching the parent.
|
||||
* ``_client_set_max_tokens`` distinguishes raw-body shapes correctly.
|
||||
* ``post_process`` swaps in the compact routed_experts while preserving
|
||||
the rest of the upstream response (``usage`` included).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.entrypoints.openai.engine.protocol import UsageInfo
|
||||
@@ -19,12 +18,7 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateRespo
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
|
||||
from prime_rl.inference.vllm.serving_tokens import (
|
||||
PrimeRlGenerateResponse,
|
||||
PrimeRlGenerateResponseChoice,
|
||||
PrimeRlServingTokens,
|
||||
_build_usage,
|
||||
_client_set_max_tokens,
|
||||
_FinalOutputCapture,
|
||||
_GenerateRoutedExpertsCapture,
|
||||
)
|
||||
|
||||
@@ -36,17 +30,6 @@ def _decode_routed_experts(encoded: dict) -> np.ndarray:
|
||||
).reshape(encoded["shape"])
|
||||
|
||||
|
||||
class _FakeRawRequest:
|
||||
def __init__(self, body):
|
||||
self._body = body
|
||||
self._raise = isinstance(body, Exception)
|
||||
|
||||
async def json(self):
|
||||
if self._raise:
|
||||
raise self._body
|
||||
return self._body
|
||||
|
||||
|
||||
async def _empty_request_outputs():
|
||||
if False:
|
||||
yield
|
||||
@@ -81,8 +64,10 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
|
||||
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
|
||||
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
|
||||
capture.routed_experts[0] = compact_routed_experts
|
||||
usage = UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7)
|
||||
response = GenerateResponse(
|
||||
request_id="request-id",
|
||||
model="test-model",
|
||||
choices=[
|
||||
GenerateResponseChoice(
|
||||
index=0,
|
||||
@@ -90,180 +75,16 @@ def test_generate_response_post_process_replaces_upstream_routed_experts():
|
||||
routed_experts="upstream-npy-payload",
|
||||
)
|
||||
],
|
||||
usage=usage,
|
||||
)
|
||||
|
||||
processed = capture.post_process(response)
|
||||
|
||||
assert processed.choices[0].routed_experts == compact_routed_experts
|
||||
|
||||
|
||||
def test_client_set_max_tokens_recognizes_explicit_value():
|
||||
body = {"token_ids": [1, 2, 3], "sampling_params": {"max_tokens": 256}}
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body))) is True
|
||||
|
||||
|
||||
def test_client_set_max_tokens_detects_unset():
|
||||
body = {"token_ids": [1, 2, 3], "sampling_params": {}}
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body))) is False
|
||||
|
||||
body_without_sp = {"token_ids": [1, 2, 3]}
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
|
||||
|
||||
|
||||
class _FakeOutput:
|
||||
def __init__(self, token_ids):
|
||||
self.token_ids = token_ids
|
||||
|
||||
|
||||
class _FakeRequestOutput:
|
||||
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
|
||||
|
||||
``_build_usage`` only touches four attributes; constructing a real
|
||||
``RequestOutput`` would require a full ``CompletionOutput`` graph and
|
||||
isn't worth it for a serialization-shape test.
|
||||
"""
|
||||
|
||||
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
self.encoder_prompt_token_ids = encoder_prompt_token_ids
|
||||
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
|
||||
self.num_cached_tokens = num_cached_tokens
|
||||
|
||||
|
||||
def test_prime_rl_generate_response_serializes_usage_block():
|
||||
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
|
||||
# declare ``usage``, so the field must be declared on the subclass for
|
||||
# Pydantic to emit it in JSON. Without this the router can't extract
|
||||
# per-run token / cache counts for billing.
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id="req-1",
|
||||
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
|
||||
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
|
||||
)
|
||||
payload = response.model_dump(mode="json")
|
||||
assert payload["usage"] == {
|
||||
"prompt_tokens": 4,
|
||||
"completion_tokens": 3,
|
||||
"total_tokens": 7,
|
||||
"prompt_tokens_details": None,
|
||||
}
|
||||
|
||||
|
||||
def test_build_usage_sums_prompt_and_completion_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4, 5],
|
||||
output_token_ids_list=[[10, 11], [20, 21, 22]],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5
|
||||
assert usage.completion_tokens == 5 # 2 + 3
|
||||
assert usage.total_tokens == 10
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_build_usage_includes_encoder_prompt_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
output_token_ids_list=[[10]],
|
||||
encoder_prompt_token_ids=[100, 101],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5 # 3 + 2
|
||||
assert usage.total_tokens == 6
|
||||
|
||||
|
||||
def test_build_usage_reports_cached_tokens_unconditionally():
|
||||
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
|
||||
# surfaces cached tokens — the cache-discount billing pipeline needs them.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=3,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is not None
|
||||
assert usage.prompt_tokens_details.cached_tokens == 3
|
||||
|
||||
|
||||
def test_build_usage_skips_cached_tokens_when_zero():
|
||||
# Don't emit a details block with cached=0, which would be misleading
|
||||
# to the router's billing extractor.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=0,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_final_output_capture_records_last_item():
|
||||
async def _gen():
|
||||
for r in [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
|
||||
]:
|
||||
yield r
|
||||
|
||||
async def _drain(capture):
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
capture = _FinalOutputCapture(_gen())
|
||||
asyncio.run(_drain(capture))
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2, 3]
|
||||
|
||||
|
||||
def test_final_output_capture_works_over_async_def_aiter_source():
|
||||
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
|
||||
# via ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__``. The wrapper must drive it through ``async for`` rather
|
||||
# than poking ``__anext__`` directly, or routed-experts runs raise
|
||||
# AttributeError before the response is built.
|
||||
|
||||
class _AsyncGenAiterSource:
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
|
||||
async def __aiter__(self):
|
||||
for item in self._items:
|
||||
yield item
|
||||
|
||||
items = [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
]
|
||||
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2]
|
||||
|
||||
|
||||
def test_final_output_capture_handles_empty_stream():
|
||||
capture = _FinalOutputCapture(_empty_request_outputs())
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is None
|
||||
|
||||
|
||||
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
|
||||
# No raw_request → can't tell, don't override.
|
||||
assert asyncio.run(_client_set_max_tokens(None)) is True
|
||||
|
||||
# body read raises → can't tell, don't override.
|
||||
err = ValueError("bad json")
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(err))) is True
|
||||
|
||||
# non-dict body → can't tell, don't override.
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest([1, 2, 3]))) is True
|
||||
assert processed.model == "test-model"
|
||||
assert processed.usage == usage
|
||||
# The compact object form must survive JSON serialization (the parent
|
||||
# declares ``routed_experts`` as a base64 string).
|
||||
payload = processed.model_dump(mode="json")
|
||||
assert payload["choices"][0]["routed_experts"] == compact_routed_experts
|
||||
assert payload["usage"]["total_tokens"] == 7
|
||||
|
||||
@@ -163,6 +163,79 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_moe_runtime_defaults_are_independent_from_dense_quantization():
|
||||
config = TrainerModelConfig.model_validate({"quantization": {"type": "mxfp8"}})
|
||||
|
||||
assert config.quantization is not None and config.quantization.type == "mxfp8"
|
||||
assert config.moe.compute.type == "bf16"
|
||||
assert config.moe.dispatch.type == "torch"
|
||||
assert config.moe.dispatch.transport == "bf16"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model",
|
||||
[
|
||||
{"moe": {"compute": {"type": "deepgemm_fp8"}}},
|
||||
{"moe": {"compute": {"type": "mxfp8", "recipe": "mxfp8_rceil_wgrad_with_hp"}}},
|
||||
{"ep": 2, "moe": {"dispatch": {"type": "deepep", "num_sms": 16, "token_chunk_size": 1024}}},
|
||||
{
|
||||
"ep": 2,
|
||||
"moe": {
|
||||
"compute": {"type": "mxfp8"},
|
||||
"dispatch": {"type": "torch", "transport": "mxfp8"},
|
||||
},
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_supported_moe_runtime_configs(model):
|
||||
TrainerModelConfig.model_validate(model)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "message"),
|
||||
[
|
||||
(
|
||||
{
|
||||
"ep": 2,
|
||||
"moe": {
|
||||
"compute": {"type": "bf16"},
|
||||
"dispatch": {"type": "torch", "transport": "mxfp8"},
|
||||
},
|
||||
},
|
||||
"MXFP8 transport requires",
|
||||
),
|
||||
(
|
||||
{
|
||||
"ep": 2,
|
||||
"moe": {
|
||||
"compute": {"type": "mxfp8"},
|
||||
"dispatch": {"type": "deepep"},
|
||||
},
|
||||
},
|
||||
"does not support DeepEP",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_invalid_moe_runtime_configs_fail(model, message):
|
||||
with pytest.raises(ValidationError, match=message):
|
||||
TrainerModelConfig.model_validate(model)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"removed",
|
||||
[
|
||||
{"ep_comm_backend": "torch"},
|
||||
{"deepep_num_sms": 20},
|
||||
{"deepep_token_chunk_size": 1024},
|
||||
{"quantization": {"type": "fp8", "enable_grouped_gemm": True}},
|
||||
{"quantization": {"type": "mxfp8", "enable_a2a": True}},
|
||||
],
|
||||
)
|
||||
def test_removed_moe_runtime_fields_are_rejected(removed):
|
||||
with pytest.raises(ValidationError):
|
||||
TrainerModelConfig.model_validate(removed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
def test_optimizer_state_offload_keeps_legacy_default(config_cls):
|
||||
config = config_cls.model_validate({})
|
||||
@@ -378,11 +451,6 @@ def test_trainer_rejects_vlm_cp_with_ring():
|
||||
TrainerConfig.model_validate(config)
|
||||
|
||||
|
||||
def test_selective_activation_checkpointing_requires_custom_impl():
|
||||
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
|
||||
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
|
||||
|
||||
|
||||
def test_shared_model_name_propagates_to_subconfigs():
|
||||
model_name = "PrimeIntellect/test-model"
|
||||
config = RLConfig.model_validate(
|
||||
|
||||
@@ -1,76 +1,117 @@
|
||||
import torch.nn as nn
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.utils.checkpoint import CheckpointPolicy, SelectiveCheckpointContext
|
||||
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
from prime_rl.configs.trainer import ActivationCheckpointConfig
|
||||
from prime_rl.trainer.activation_checkpointing import (
|
||||
_mandatory_checkpoint_policy,
|
||||
_selective_checkpoint_policy,
|
||||
get_activation_checkpoint_wrapper,
|
||||
)
|
||||
|
||||
_PATCHED_METHODS_ATTR = "_prime_rl_selective_ac_patched_methods"
|
||||
from prime_rl.trainer.models.layers.moe import MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class DummySelfAttention(nn.Module):
|
||||
def attn_projections(self, hidden_states, position_embeddings=None):
|
||||
return hidden_states
|
||||
class IdentityExperts(nn.Module):
|
||||
num_experts = 2
|
||||
token_group_alignment = 1
|
||||
|
||||
def output_proj(self, attn_output):
|
||||
return attn_output
|
||||
|
||||
def forward(self, hidden_states):
|
||||
return hidden_states
|
||||
def forward(self, x: torch.Tensor, _token_counts: torch.Tensor) -> torch.Tensor:
|
||||
return x
|
||||
|
||||
|
||||
class DummySlidingAttentionLayer(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.self_attn = DummySelfAttention()
|
||||
self.attention_type = "sliding_attention"
|
||||
def test_selective_policy_saves_default_and_custom_targets():
|
||||
context = SelectiveCheckpointContext(is_recompute=False)
|
||||
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.aten._scaled_dot_product_flash_attention.default)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten.mm.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten.addmm.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten.bmm.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten._grouped_mm.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.prime_rl_collectives.all_to_all_single_equal.default)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.prime_rl_collectives.mxfp8_all_to_all.default)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert _selective_checkpoint_policy(context, torch.ops.aten.silu.default) is CheckpointPolicy.PREFER_RECOMPUTE
|
||||
|
||||
custom_targets = frozenset({"aten::silu", "prime_rl_collectives"})
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.aten.silu.default, targets=custom_targets)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert (
|
||||
_selective_checkpoint_policy(
|
||||
context,
|
||||
torch.ops.prime_rl_collectives.all_to_all_single_equal.default,
|
||||
targets=custom_targets,
|
||||
)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.aten.mm.default, targets=custom_targets)
|
||||
is CheckpointPolicy.PREFER_RECOMPUTE
|
||||
)
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
|
||||
|
||||
class DummyMamba(nn.Module):
|
||||
def forward(self, hidden_states):
|
||||
return hidden_states
|
||||
@pytest.mark.parametrize("mode", ["full", "selective"])
|
||||
def test_checkpoint_records_moe_routing_once(mode):
|
||||
moe = MoE(
|
||||
router=TokenChoiceTopKRouter(
|
||||
dim=4,
|
||||
num_experts=2,
|
||||
top_k=1,
|
||||
score_func="softmax",
|
||||
route_norm=False,
|
||||
route_scale=1.0,
|
||||
),
|
||||
experts=IdentityExperts(),
|
||||
shared_expert=None,
|
||||
score_before_experts=True,
|
||||
load_balance_coeff=0.1,
|
||||
)
|
||||
checkpointed = get_activation_checkpoint_wrapper(ActivationCheckpointConfig(mode=mode))(moe)
|
||||
hidden_states = torch.randn(1, 3, 4, requires_grad=True)
|
||||
|
||||
output = checkpointed(hidden_states)
|
||||
tokens_after_forward = moe.tokens_per_expert.clone()
|
||||
confidence_after_forward = moe.routing_confidence_sum.clone()
|
||||
output.sum().backward()
|
||||
|
||||
assert tokens_after_forward.sum() == 3
|
||||
torch.testing.assert_close(moe.tokens_per_expert, tokens_after_forward)
|
||||
torch.testing.assert_close(moe.routing_confidence_sum, confidence_after_forward)
|
||||
assert hidden_states.grad is not None
|
||||
|
||||
|
||||
class DummyMambaLayer(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.mamba = DummyMamba()
|
||||
def test_mandatory_policy_only_retains_non_replayable_ops():
|
||||
context = SelectiveCheckpointContext(is_recompute=False)
|
||||
|
||||
|
||||
class DummyMoEMlp(nn.Module):
|
||||
def forward(self, hidden_states):
|
||||
return hidden_states
|
||||
|
||||
def _run_routed_experts(self, hidden_states, *args):
|
||||
return hidden_states
|
||||
|
||||
def _run_local_routed_experts(self, hidden_states, num_tokens_per_expert):
|
||||
return hidden_states
|
||||
|
||||
|
||||
class DummyMoELayer(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.mlp = DummyMoEMlp()
|
||||
|
||||
|
||||
def test_get_supported_targets_treats_mamba_as_linear_attention():
|
||||
assert get_supported_targets(DummyMambaLayer()) == frozenset({"norm", "linear_attn"})
|
||||
|
||||
|
||||
def test_sliding_attention_linear_attn_subsumes_attn_proj_hooks():
|
||||
layer = DummySlidingAttentionLayer()
|
||||
|
||||
set_selective_activation_checkpointing(layer, ["attn_proj", "linear_attn"])
|
||||
|
||||
assert getattr(layer.self_attn, _PATCHED_METHODS_ATTR) == frozenset({"forward"})
|
||||
|
||||
|
||||
def test_routed_experts_checkpointing_patches_local_and_global_helpers():
|
||||
layer = DummyMoELayer()
|
||||
|
||||
assert "routed_experts" in get_supported_targets(layer)
|
||||
|
||||
set_selective_activation_checkpointing(layer, ["routed_experts"])
|
||||
|
||||
assert getattr(layer.mlp, _PATCHED_METHODS_ATTR) == frozenset({"_run_local_routed_experts", "_run_routed_experts"})
|
||||
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert (
|
||||
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert (
|
||||
_mandatory_checkpoint_policy(context, torch.ops.prime_rl_collectives.all_to_all_single_equal.default)
|
||||
is CheckpointPolicy.PREFER_RECOMPUTE
|
||||
)
|
||||
assert (
|
||||
_mandatory_checkpoint_policy(context, torch.ops.prime_rl_collectives.mxfp8_all_to_all.default)
|
||||
is CheckpointPolicy.PREFER_RECOMPUTE
|
||||
)
|
||||
assert (
|
||||
_mandatory_checkpoint_policy(context, torch.ops.aten._scaled_dot_product_flash_attention.default)
|
||||
is CheckpointPolicy.PREFER_RECOMPUTE
|
||||
)
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
"""Numerics of the fused MoE kernel against the grouped-mm expert path it replaces.
|
||||
|
||||
The kernel is forward only: `_FusedMoE` runs it in forward and computes gradients by hand
|
||||
(bf16) or by autograd through the reference (mxfp8), so both halves need checking against
|
||||
the path a run would take with `model.moe_fused_kernel=false`.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
_FusedMoE,
|
||||
_load_fused_moe_kernel,
|
||||
_quantize_mxfp8,
|
||||
_run_experts_fused_reference,
|
||||
)
|
||||
|
||||
|
||||
def _unavailable_reason() -> str | None:
|
||||
if not torch.cuda.is_available():
|
||||
return "no CUDA device"
|
||||
if importlib.util.find_spec("prime_kernels") is None:
|
||||
return "prime-kernels is not installed (`uv sync --extra kernels`)"
|
||||
import prime_kernels
|
||||
|
||||
return prime_kernels.unavailable_reason("flash_moe")
|
||||
|
||||
|
||||
_UNAVAILABLE = _unavailable_reason()
|
||||
|
||||
pytestmark = [
|
||||
pytest.mark.gpu,
|
||||
pytest.mark.skipif(_UNAVAILABLE is not None, reason=f"fused MoE kernel unavailable: {_UNAVAILABLE}"),
|
||||
]
|
||||
|
||||
NUM_EXPERTS, TOP_K, DIM, HIDDEN_DIM, NUM_TOKENS = 4, 2, 256, 128, 512
|
||||
|
||||
# Measured on a B200 at the shapes below: bf16 forward and gradients all land at 4e-3..5.5e-3
|
||||
# (two bf16 paths with different reduction orders), mxfp8 forward at 6.8e-2 — which is 1.14x
|
||||
# the 5.9e-2 that quantizing the inputs costs by itself, so almost all of it is e4m3, not the
|
||||
# kernel. These are backstops at ~3x and ~1.5x the measured values; the sharper checks are the
|
||||
# fp32 ratios in the forward test, which need no constant at all. `pytest -s` prints margins.
|
||||
BF16_TOL = 1.5e-2
|
||||
MXFP8_TOL = 1e-1
|
||||
# The mxfp8 backward re-runs the very reference this compares against, on unquantized
|
||||
# weights, so anything above float32 round-off means the glue around it is wrong. In
|
||||
# practice it is bitwise equal — the same kernels on the same inputs in the same order.
|
||||
GLUE_TOL = 1e-5
|
||||
# Quantizing to e4m3 costs accuracy no kernel can avoid, so the mxfp8 forward is judged
|
||||
# against that floor rather than a number picked by hand.
|
||||
MXFP8_FLOOR_RATIO = 1.5
|
||||
|
||||
GRAD_NAMES = ("x", "w1", "w2", "w3", "top_scores")
|
||||
|
||||
|
||||
def _rel_err(actual: torch.Tensor, expected: torch.Tensor) -> float:
|
||||
"""Relative Frobenius error, the scale-free way to compare two low-precision GEMM paths."""
|
||||
expected = expected.float()
|
||||
return ((actual.float() - expected).norm() / expected.norm().clamp_min(1e-12)).item()
|
||||
|
||||
|
||||
def _assert_close(actual: torch.Tensor, expected: torch.Tensor, tol: float, label: str) -> None:
|
||||
"""Compare, and report the measured error either way — `pytest -s` prints the margins."""
|
||||
norm = expected.float().norm().item()
|
||||
# A relative error of zero means "identical"; against an all-zero reference it would
|
||||
# instead mean "both sides computed nothing", which must not read as a pass.
|
||||
assert norm > 0, f"{label}: reference is all zeros, the comparison would be vacuous"
|
||||
err = _rel_err(actual, expected)
|
||||
print(f"{label}: rel_err={err:.3e} tol={tol:.1e} margin={tol / max(err, 1e-12):.1f}x |ref|={norm:.3e}")
|
||||
assert err < tol, f"{label}: relative error {err:.3e} exceeds {tol:.1e}"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def moe_inputs() -> tuple[torch.Tensor, ...]:
|
||||
"""Routed-expert inputs shaped like the fused path expects: hidden_dim % 128, dim % 256."""
|
||||
torch.manual_seed(0)
|
||||
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
|
||||
x = randn(NUM_TOKENS, DIM) * 0.2
|
||||
w1, w3 = randn(NUM_EXPERTS, HIDDEN_DIM, DIM) * 0.05, randn(NUM_EXPERTS, HIDDEN_DIM, DIM) * 0.05
|
||||
w2 = randn(NUM_EXPERTS, DIM, HIDDEN_DIM) * 0.05
|
||||
top_scores, selected_experts_indices = torch.softmax(
|
||||
torch.randn(NUM_TOKENS, NUM_EXPERTS, device="cuda", dtype=torch.float32), dim=-1
|
||||
).topk(TOP_K, dim=-1)
|
||||
return x, w1, w2, w3, selected_experts_indices, top_scores
|
||||
|
||||
|
||||
def _leaves(*tensors: torch.Tensor) -> list[torch.Tensor]:
|
||||
return [t.detach().clone().requires_grad_(True) for t in tensors]
|
||||
|
||||
|
||||
def _fp32_ground_truth(moe_inputs: tuple[torch.Tensor, ...]) -> torch.Tensor:
|
||||
"""Expert-by-expert MoE in fp32 — an independent yardstick both paths can be measured against."""
|
||||
x, w1, w2, w3, selected_experts_indices, top_scores = moe_inputs
|
||||
xf, w1f, w2f, w3f = x.float(), w1.float(), w2.float(), w3.float()
|
||||
out = torch.zeros_like(xf)
|
||||
for expert in range(NUM_EXPERTS):
|
||||
rows, slot = (selected_experts_indices == expert).nonzero(as_tuple=True)
|
||||
if rows.numel() == 0:
|
||||
continue
|
||||
tokens = xf[rows]
|
||||
hidden = torch.nn.functional.silu(tokens @ w1f[expert].T) * (tokens @ w3f[expert].T)
|
||||
out.index_add_(0, rows, (hidden @ w2f[expert].T) * top_scores[rows, slot].unsqueeze(-1).float())
|
||||
return out
|
||||
|
||||
|
||||
def _mxfp8_round_trip(tensor: torch.Tensor) -> torch.Tensor:
|
||||
"""Quantize to e4m3 and back, to price what mxfp8 costs before any kernel runs."""
|
||||
block = _load_fused_moe_kernel().MXFP8_SCALE_BLOCK
|
||||
data, scales = _quantize_mxfp8(tensor, block)
|
||||
return data.float().unflatten(-1, (-1, block)).mul(scales.float().unsqueeze(-1)).flatten(-2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mxfp8", [False, True])
|
||||
def test_fused_forward_matches_grouped_mm(moe_inputs, mxfp8: bool):
|
||||
"""Pairwise against grouped-mm, and — the tolerance-free part — against fp32.
|
||||
|
||||
A fixed tolerance only says "close enough"; the ratio against the grouped-mm path's own
|
||||
fp32 error says the kernel is no *less* accurate than what it replaces, which is the
|
||||
claim that actually matters and needs no magic number.
|
||||
"""
|
||||
x, w1, w2, w3, selected_experts_indices, top_scores = moe_inputs
|
||||
label = "mxfp8" if mxfp8 else "bf16"
|
||||
|
||||
out = _FusedMoE.apply(x, w1, w2, w3, selected_experts_indices, top_scores, NUM_EXPERTS, mxfp8)
|
||||
expected = _run_experts_fused_reference(x, w1, w2, w3, selected_experts_indices, top_scores, NUM_EXPERTS)
|
||||
|
||||
truth = _fp32_ground_truth(moe_inputs)
|
||||
grouped_mm_err, fused_err = _rel_err(expected, truth), _rel_err(out, truth)
|
||||
print(f"forward[{label}] vs fp32: grouped_mm={grouped_mm_err:.3e} fused={fused_err:.3e}")
|
||||
|
||||
assert out.shape == expected.shape and out.dtype == x.dtype
|
||||
_assert_close(out, expected, MXFP8_TOL if mxfp8 else BF16_TOL, f"forward[{label}]")
|
||||
|
||||
if not mxfp8:
|
||||
assert fused_err <= 1.5 * grouped_mm_err, (
|
||||
f"fused bf16 is less accurate than grouped-mm: {fused_err:.3e} vs {grouped_mm_err:.3e} against fp32"
|
||||
)
|
||||
return
|
||||
|
||||
# What e4m3 with one e8m0 scale per 32 elements costs on these inputs, kernel aside.
|
||||
floor_inputs = (_mxfp8_round_trip(x), *(_mxfp8_round_trip(w) for w in (w1, w2, w3)), *moe_inputs[4:])
|
||||
floor_err = _rel_err(_fp32_ground_truth(floor_inputs), truth)
|
||||
print(f"forward[mxfp8] vs fp32: quantization floor={floor_err:.3e} fused={fused_err:.3e}")
|
||||
assert fused_err <= MXFP8_FLOOR_RATIO * floor_err, (
|
||||
f"fused mxfp8 error {fused_err:.3e} exceeds {MXFP8_FLOOR_RATIO}x the {floor_err:.3e} "
|
||||
"that quantizing the inputs costs on its own — the kernel is losing accuracy beyond mxfp8"
|
||||
)
|
||||
|
||||
|
||||
def test_fused_bf16_backward_matches_grouped_mm(moe_inputs):
|
||||
"""`_run_experts_fused_backward_bf16` is closed form — check it against plain autograd."""
|
||||
x, w1, w2, w3, selected_experts_indices, top_scores = moe_inputs
|
||||
fused = _leaves(x, w1, w2, w3, top_scores)
|
||||
grouped_mm = _leaves(x, w1, w2, w3, top_scores)
|
||||
|
||||
out = _FusedMoE.apply(*fused[:4], selected_experts_indices, fused[4], NUM_EXPERTS, False)
|
||||
expected = _run_experts_fused_reference(*grouped_mm[:4], selected_experts_indices, grouped_mm[4], NUM_EXPERTS)
|
||||
|
||||
grad_out = torch.randn_like(out)
|
||||
out.backward(grad_out)
|
||||
expected.backward(grad_out)
|
||||
|
||||
for name, actual, reference in zip(GRAD_NAMES, fused, grouped_mm):
|
||||
_assert_close(actual.grad, reference.grad, BF16_TOL, f"grad_{name}[bf16]")
|
||||
|
||||
|
||||
def test_fused_mxfp8_backward_matches_its_reference(moe_inputs):
|
||||
"""The mxfp8 backward differentiates the reference, so this checks the glue around it.
|
||||
|
||||
Same math on both sides, so the gradients must agree to round-off. What it catches is
|
||||
everything between: the padded group layout, the `needs_input_grad` bookkeeping, and the
|
||||
order gradients are returned in — `w1` and `w3` share a shape, so a swapped slot is
|
||||
invisible to a shape check and obvious here.
|
||||
"""
|
||||
x, w1, w2, w3, selected_experts_indices, top_scores = moe_inputs
|
||||
fused = _leaves(x, w1, w2, w3, top_scores)
|
||||
reference = _leaves(x, w1, w2, w3, top_scores)
|
||||
|
||||
out = _FusedMoE.apply(*fused[:4], selected_experts_indices, fused[4], NUM_EXPERTS, True)
|
||||
expected = _run_experts_fused_reference(
|
||||
*reference[:4],
|
||||
selected_experts_indices,
|
||||
reference[4],
|
||||
NUM_EXPERTS,
|
||||
align_m=_load_fused_moe_kernel().MXFP8_SCALE_BLOCK,
|
||||
)
|
||||
|
||||
grad_out = torch.randn_like(out)
|
||||
out.backward(grad_out)
|
||||
expected.backward(grad_out)
|
||||
|
||||
for name, actual, ref in zip(GRAD_NAMES, fused, reference):
|
||||
assert actual.grad is not None and torch.isfinite(actual.grad).all(), f"grad_{name} is missing or non-finite"
|
||||
_assert_close(actual.grad, ref.grad, GLUE_TOL, f"grad_{name}[mxfp8]")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mxfp8", [False, True])
|
||||
def test_fused_backward_honours_needs_input_grad(moe_inputs, mxfp8: bool):
|
||||
"""Freezing some leaves must leave their slots None without shifting the others."""
|
||||
x, w1, w2, w3, selected_experts_indices, top_scores = moe_inputs
|
||||
wanted = (True, False, True, False, True) # x, w2 and top_scores only: w1/w3 frozen
|
||||
make = lambda: [t.detach().clone().requires_grad_(r) for t, r in zip((x, w1, w2, w3, top_scores), wanted)]
|
||||
fused, reference = make(), make()
|
||||
|
||||
out = _FusedMoE.apply(*fused[:4], selected_experts_indices, fused[4], NUM_EXPERTS, mxfp8)
|
||||
align_m = _load_fused_moe_kernel().MXFP8_SCALE_BLOCK if mxfp8 else None
|
||||
expected = _run_experts_fused_reference(
|
||||
*reference[:4], selected_experts_indices, reference[4], NUM_EXPERTS, align_m=align_m
|
||||
)
|
||||
|
||||
grad_out = torch.randn_like(out)
|
||||
out.backward(grad_out)
|
||||
expected.backward(grad_out)
|
||||
|
||||
tol = GLUE_TOL if mxfp8 else BF16_TOL
|
||||
for name, actual, ref, is_wanted in zip(GRAD_NAMES, fused, reference, wanted):
|
||||
if not is_wanted:
|
||||
assert actual.grad is None, f"grad_{name} was computed for a frozen leaf"
|
||||
continue
|
||||
_assert_close(actual.grad, ref.grad, tol, f"grad_{name}[{'mxfp8' if mxfp8 else 'bf16'}, partial]")
|
||||
@@ -12,7 +12,7 @@ pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
|
||||
hf_config = Glm4MoeConfig(
|
||||
config_kwargs = dict(
|
||||
hidden_size=1024,
|
||||
intermediate_size=2048,
|
||||
max_position_embeddings=4096,
|
||||
@@ -27,15 +27,17 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
|
||||
rope_theta=1000000.0,
|
||||
first_k_dense_replace=1,
|
||||
partial_rotary_factor=0.5,
|
||||
use_grouped_mm=False,
|
||||
)
|
||||
hf_config = Glm4MoeConfig(**config_kwargs, n_group=1, topk_group=1)
|
||||
prime_config = Glm4MoeConfig(**config_kwargs)
|
||||
# TODO: We should test this path because it's the most performant
|
||||
# But the grad seems to be off in attn because of precision
|
||||
# hf_config._attn_implementation = "flash_attention_2"
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
prime_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
hf_model = HFGlm4MoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLGlm4MoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLGlm4MoeForCausalLM._from_config(prime_config)
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
|
||||
@@ -20,13 +20,13 @@ def _build_prime_layer_state(layer_idx: int = 0) -> dict[str, torch.Tensor]:
|
||||
f"{prefix}.mlp.up_proj.weight": torch.randn(8, 6),
|
||||
f"{prefix}.mlp.down_proj.weight": torch.randn(6, 8),
|
||||
f"{prefix}.mlp.router.gate.weight": torch.randn(4, 6),
|
||||
f"{prefix}.mlp.expert_bias": torch.randn(4),
|
||||
f"{prefix}.mlp.experts.w1": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.w2": torch.randn(2, 6, 3),
|
||||
f"{prefix}.mlp.experts.w3": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.shared_expert.w1": torch.randn(1, 3, 6),
|
||||
f"{prefix}.mlp.shared_expert.w2": torch.randn(1, 6, 3),
|
||||
f"{prefix}.mlp.shared_expert.w3": torch.randn(1, 3, 6),
|
||||
f"{prefix}.mlp.router.selection_bias": torch.randn(4),
|
||||
f"{prefix}.mlp.experts.gate_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.up_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.down_proj": torch.randn(2, 6, 3),
|
||||
f"{prefix}.mlp.shared_expert.gate_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.up_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.down_proj.weight": torch.randn(6, 3),
|
||||
}
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user