Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5406f8d09 | ||
|
|
9b39a10949 | ||
|
|
f7e8ab6456 | ||
|
|
84e94bf05c | ||
|
|
37b48a996e | ||
|
|
88faa6dc22 | ||
|
|
083b8fe9ec | ||
|
|
853208336e | ||
|
|
31281d88f9 | ||
|
|
bc250759bf | ||
|
|
1983d8dfed | ||
|
|
26681fc6c7 | ||
|
|
6b0906c900 | ||
|
|
5e963f027a | ||
|
|
72834b3b52 | ||
|
|
0bcb868e91 | ||
|
|
746d8a96d0 | ||
|
|
765bbeba7b | ||
|
|
fec3acd8e7 | ||
|
|
adda4731fe | ||
|
|
a3f1f892c5 | ||
|
|
e6acff78aa | ||
|
|
3587b285f5 | ||
|
|
f3827c4ed2 | ||
|
|
93a0fe0d6b | ||
|
|
db2c00e9ed | ||
|
|
4250d895bc | ||
|
|
78bc69ccc4 | ||
|
|
81052082a9 | ||
|
|
b9c0bfe87b | ||
|
|
51879014fc | ||
|
|
52e985ae9d | ||
|
|
63b3e85864 | ||
|
|
7133f8f8f2 | ||
|
|
b029ef253e | ||
|
|
eae8bd9462 |
@@ -192,6 +192,12 @@ jobs:
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
with:
|
||||
# CVE-2026-93318: pin the BuildKit builder to the patched release so
|
||||
# the version is deterministic on the self-hosted runners (otherwise
|
||||
# the rolling moby/buildkit:buildx-stable-1 tag is used, and a
|
||||
# persistent runner may keep a stale local copy of it).
|
||||
driver-opts: image=moby/buildkit:v0.33.1@sha256:cec9f139f45e93c5c69c60f8b07cfad9f43f4ef6b6a6cd917527fea5ff2e3dea
|
||||
|
||||
- name: Set up uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
@@ -207,7 +213,12 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
key=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py fingerprint .)
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-${SUFFIX}"
|
||||
# deps-v2: remediation epoch for CVE-2026-93318 — the fingerprint
|
||||
# hashes only Dockerfile/lock inputs, not the workflow or BuildKit
|
||||
# version, so pre-fix deps-${key} images would otherwise be reused
|
||||
# as the runtime base instead of being rebuilt by the pinned v0.33.1
|
||||
# builder.
|
||||
image="${REGISTRY}/${IMAGE_NAME}:deps-${key}-v2-${SUFFIX}"
|
||||
digest=$(uv run --no-project --python 3.12 scripts/docker_dependencies.py resolve "$image")
|
||||
echo "image=${image}" >> "$GITHUB_OUTPUT"
|
||||
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
|
||||
@@ -222,8 +233,10 @@ jobs:
|
||||
file: ./Dockerfile.cuda
|
||||
target: dependencies
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
|
||||
# builders (cache writers since 2026-08-16) must not be re-imported.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:dependency-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: ${{ steps.dependency.outputs.image }}
|
||||
|
||||
@@ -240,8 +253,10 @@ jobs:
|
||||
RENDERERS_PRETEND_VERSION=${{ steps.dependency.outputs.renderers }}
|
||||
PYDANTIC_CONFIG_PRETEND_VERSION=${{ steps.dependency.outputs.pydantic_config }}
|
||||
outputs: type=image,push=true,compression=zstd,compression-level=3
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
# buildcache-v2: rotated 2026-10-05 for CVE-2026-93318 — the pre-v0.33.1
|
||||
# builders (cache writers since 2026-08-16) must not be re-imported.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }}
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:application-buildcache-v2-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
|
||||
platforms: ${{ matrix.platform }}
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
|
||||
|
||||
@@ -6,6 +6,10 @@ on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
@@ -15,15 +19,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run tests
|
||||
|
||||
@@ -5,20 +5,103 @@ on:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
name: Select tests
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
|
||||
integration: ${{ steps.matrix.outputs.tests }}
|
||||
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
|
||||
steps:
|
||||
- uses: dorny/paths-filter@v4
|
||||
id: filter
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
filters: |
|
||||
unit:
|
||||
- &runtime
|
||||
- '.github/workflows/gpu_tests.yaml'
|
||||
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
|
||||
- 'deps/**'
|
||||
- 'packages/**/pyproject.toml'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
|
||||
- 'src/prime_rl/*.py'
|
||||
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
|
||||
- 'tests/{__init__.py,conftest.py,utils.py}'
|
||||
- 'tests/integration/{__init__.py,conftest.py}'
|
||||
- 'tests/unit/{train,inference}/**'
|
||||
- 'src/prime_rl/inference/**'
|
||||
sft:
|
||||
- *runtime
|
||||
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
|
||||
- 'src/prime_rl/dashboard/**'
|
||||
- 'tests/integration/dashboard_smoke.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
|
||||
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
|
||||
- 'src/prime_rl/monitors/**'
|
||||
- 'src/prime_rl/eval/{online,runner}.py'
|
||||
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
|
||||
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
|
||||
rl:
|
||||
- *runtime
|
||||
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
|
||||
- 'src/prime_rl/dashboard/**'
|
||||
- 'tests/integration/dashboard_smoke.py'
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
|
||||
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
|
||||
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
|
||||
- 'src/prime_rl/eval/{online,runner}.py'
|
||||
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
|
||||
- 'tests/integration/test_alphabet_sort.py'
|
||||
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
|
||||
- 'configs/ci/integration/alphabet_sort.toml'
|
||||
eval:
|
||||
- *runtime
|
||||
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
|
||||
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
|
||||
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
|
||||
- 'tests/integration/test_gsm8k_eval.py'
|
||||
- 'configs/ci/integration/gsm8k-eval.toml'
|
||||
- name: Build integration matrix
|
||||
id: matrix
|
||||
env:
|
||||
# Main and manual runs retain the full suite.
|
||||
RUN_ALL: ${{ github.event_name != 'pull_request' }}
|
||||
SFT: ${{ steps.filter.outputs.sft || 'false' }}
|
||||
RL: ${{ steps.filter.outputs.rl || 'false' }}
|
||||
run: |
|
||||
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
|
||||
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
|
||||
if $all or $rl then
|
||||
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
|
||||
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
|
||||
else empty end
|
||||
]')
|
||||
echo "tests=$tests" >> "$GITHUB_OUTPUT"
|
||||
|
||||
unit-tests:
|
||||
name: Unit tests
|
||||
runs-on: vm
|
||||
needs: changes
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 45
|
||||
if: github.event_name == 'push' || github.event.pull_request.draft == false
|
||||
if: needs.changes.outputs.unit == 'true'
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -29,12 +112,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
@@ -50,46 +137,20 @@ jobs:
|
||||
|
||||
integration-tests:
|
||||
name: Integration tests (${{ matrix.test }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
needs: changes
|
||||
runs-on: prime-rl-2xh200
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
timeout-minutes: 60
|
||||
if: github.event_name == 'push' || github.event.pull_request.draft == false
|
||||
if: needs.changes.outputs.integration != '[]'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
|
||||
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
|
||||
max-parallel: 5
|
||||
matrix:
|
||||
include:
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
- test: reverse_text_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_lora.py"
|
||||
- test: reverse_text_moe
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_moe.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
test: ${{ fromJSON(needs.changes.outputs.integration) }}
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -100,12 +161,16 @@ jobs:
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
@@ -120,7 +185,7 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -129,3 +194,47 @@ jobs:
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
eval-tests:
|
||||
name: Integration tests (gsm8k_eval)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.eval == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: false
|
||||
- parallel:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v10.0.1
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run eval tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: gsm8k_eval-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
@@ -9,6 +9,10 @@ on:
|
||||
# This will trigger the workflow for pull requests to any branch
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
ruff:
|
||||
name: Ruff
|
||||
|
||||
+5
-2
@@ -94,7 +94,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# The runtime dependency image contains no first-party source or editable installs.
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels --locked --no-dev \
|
||||
--no-install-local
|
||||
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
@@ -243,7 +243,10 @@ COPY --from=builder --chown=appuser:appuser \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn \
|
||||
--exclude=lib/python3.12/site-packages/flash_attn_2_cuda*.so \
|
||||
/app/.venv /app/.venv
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
RUN /app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]' \
|
||||
&& if [ "$(uname -m)" = "x86_64" ]; then \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; version("flash-mla")'; \
|
||||
fi
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: d4fb80a56f...89dcc7ffcb
Vendored
+1
-1
Submodule deps/renderers updated: d43c43015a...41f9290949
Vendored
+1
-1
Submodule deps/verifiers updated: 4fd5921071...2cb0a6d33a
+1
-1
@@ -187,7 +187,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
|
||||
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`). With LoRA on, the inference server registers the adapter under the model name and serves the base model as `<model>-base`.
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
+1
-1
@@ -139,7 +139,7 @@ algo.type = "echo"
|
||||
|
||||
### The Algorithm Classes
|
||||
|
||||
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
|
||||
|
||||
| `algo.type` | Class | hook(s) — stage |
|
||||
|---|---|---|
|
||||
|
||||
@@ -173,6 +173,10 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — holds defaults for its sources. Every field that a group and its sources both have is a default: `env`, `sampling`, `select` and `group_size`, plus `algo` on the train group and `interval` on the eval groups of a training run. Each source inherits the fields that its group sets. One rule applies to all of them: nested blocks merge key by key, a source's own values win, and a block whose `type` (e.g. of `algo`) differs from the group's is the source's alone.
|
||||
|
||||
Sampling parameters use Verifiers' shared normalization: `max_tokens` and `max_completion_tokens` name the same limit, and `extra_body` parameters merge like top-level parameters. Agent overrides apply after source defaults; an explicit null clears an inherited parameter. Resolved sampling is recorded on each trace.
|
||||
|
||||
For live-policy training, set distribution parameters (`temperature`, `top_p`, `top_k`) on the source's `sampling` block. Every agent in that source, including non-trainable roles, may override only `max_tokens`, `reasoning_effort`, and `chat_template_kwargs`. These rules are checked when loading the config; evaluation and frozen-model sources allow general agent sampling overrides.
|
||||
|
||||
```toml
|
||||
[orchestrator.train]
|
||||
group_size = 16
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
|
||||
| Workflow | Trigger | What runs | Where |
|
||||
|---|---|---|---|
|
||||
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
|
||||
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
|
||||
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
|
||||
|
||||
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
|
||||
|
||||
+4
-2
@@ -25,6 +25,8 @@ uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Infe
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
The default endpoint comes from `PRIME_INFERENCE_URL`, then the Prime CLI's `inference_url`, then the standard Prime Inference URL. An explicit `client.base_url` wins. API keys and environment-backed headers are resolved when clients are built; Prime CLI credential and team fallbacks apply only to Prime Inference hosts, including for a separate admin URL.
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
@@ -80,7 +82,7 @@ Every source's env server is spawned by the eval process unless the source sets
|
||||
|
||||
## Resume
|
||||
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: saved episodes with `episode.ok` rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch), and only the rollouts still owed run. Failed episodes and the ones the interruption cut off run again. Saved records that fail schema validation stop the resume before the current stream is archived.
|
||||
|
||||
```bash
|
||||
uv run eval @ eval.toml --run.name my-eval
|
||||
@@ -90,7 +92,7 @@ uv run eval @ eval.toml --run.name my-eval --resume
|
||||
|
||||
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
|
||||
|
||||
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
A landed episode counts toward a selected task in the same source when their content hashes (`task.hash`) match. A task whose content changes runs again even if its public `task.key` stays the same. `select` and `group_size` may change between launches: each selected occurrence keeps up to `group_size` matching episodes, and only its missing rollouts run. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. Each selected occurrence owns a separate group containing its restored and new rollouts, even when the same task is selected more than once, so pass@k and the dashboard see one group per selected occurrence. Use `--clean` to start over instead.
|
||||
|
||||
## Monitors
|
||||
|
||||
|
||||
+2
-2
@@ -287,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. Capture runs on vLLM's V2 model runner (forced automatically). Router replay is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
@@ -313,6 +313,6 @@ top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling
|
||||
|
||||
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`. Frozen-source envs are exempt.
|
||||
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run together with router replay. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
|
||||
|
||||
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
|
||||
|
||||
@@ -62,6 +62,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
| `orchestrator.train.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.train.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `trainer.model.freeze_moe_router` | Freeze MoE router gates (default `true` for RL, `false` for SFT). Router updates in RL shift the trainer's expert choices away from the ones inference sampled, amplifying the train-inference mismatch, so RL keeps the pretrained router. Set `false` to train it. |
|
||||
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
|
||||
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
|
||||
@@ -158,6 +159,10 @@ messages = "conversation"
|
||||
tools = "schemas"
|
||||
```
|
||||
|
||||
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
|
||||
|
||||
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
|
||||
|
||||
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
|
||||
|
||||
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
|
||||
|
||||
@@ -5,10 +5,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
|
||||
@@ -23,11 +23,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
partition = "all"
|
||||
|
||||
|
||||
@@ -19,11 +19,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
partition = "all"
|
||||
|
||||
@@ -6,10 +6,6 @@
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
|
||||
@@ -2,7 +2,6 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
|
||||
@@ -89,6 +89,7 @@ attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
cp = 4 # context parallel for the 131K seq len
|
||||
ep = 8
|
||||
dsa_backend = "cudnn_flashmla"
|
||||
|
||||
[trainer.model.quantization]
|
||||
type = "fp8"
|
||||
|
||||
@@ -2,7 +2,6 @@ clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
|
||||
|
||||
@@ -40,11 +40,11 @@ import verifiers.v1 as vf
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.configs.shared import VLLMClientConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class FrozenModelConfig(ClientConfig):
|
||||
class FrozenModelConfig(VLLMClientConfig):
|
||||
"""An externally hosted model behind an OpenAI-compatible endpoint: the
|
||||
client config plus the served model's ``name``.
|
||||
|
||||
@@ -57,14 +57,7 @@ class FrozenModelConfig(ClientConfig):
|
||||
name: str
|
||||
"""Served model name, sent as the ``model`` field of every request."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_explicit_endpoint(self):
|
||||
if "base_url" not in self.model_fields_set:
|
||||
raise ValueError(
|
||||
"a frozen model reference needs base_url — frozen models are externally "
|
||||
"hosted; prime-rl only ever hosts the trainable policy."
|
||||
)
|
||||
return self
|
||||
base_url: str
|
||||
|
||||
|
||||
ModelReference: TypeAlias = Literal["policy"] | FrozenModelConfig
|
||||
|
||||
@@ -6,7 +6,14 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig, WeightBroadcastConfig
|
||||
from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
RunConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
@@ -14,7 +21,7 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
@@ -43,9 +50,6 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
@@ -55,7 +59,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
client: ClientConfig = Field(default_factory=ClientConfig)
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
|
||||
@@ -509,16 +509,12 @@ class InferenceConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
|
||||
if (
|
||||
self.deployment.type == "disaggregated"
|
||||
and self.enable_return_sampling_mask
|
||||
and self.vllm.enable_return_routed_experts
|
||||
):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""vLLM rejects routed-expert capture with NIXL KV transfer."""
|
||||
if self.deployment.type == "disaggregated" and self.vllm.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Routed-expert return (enable_return_routed_experts) is not supported with disaggregated P/D: "
|
||||
"vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -662,6 +658,11 @@ class InferenceConfig(BaseConfig):
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
# The LoRA adapter is registered under the model name clients send, and vLLM rejects
|
||||
# an adapter named like a served base model, so serve the base under another name.
|
||||
if self.vllm.enable_lora and "served_model_name" not in extra_fields:
|
||||
namespace.served_model_name = [f"{self.vllm.model}-base"]
|
||||
|
||||
kv_transfer_config = self.build_kv_transfer_config()
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
@@ -6,6 +6,7 @@ import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, BaseModel, Field, SerializeAsAny, TypeAdapter, ValidationError, model_validator
|
||||
from pydantic.fields import FieldInfo
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
from verifiers.v1.configs.agent import agent_config_fields
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
@@ -14,13 +15,13 @@ from prime_rl.configs.algorithm import (
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileSystemWeightBroadcastConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
ResumeConfig,
|
||||
TransportConfig,
|
||||
VLLMClientConfig,
|
||||
WeightBroadcastConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
@@ -40,7 +41,7 @@ class ModelConfig(BaseModelConfig):
|
||||
lora: LoRAConfig | None = None
|
||||
"""Per-run LoRA configuration. If None, LoRA is disabled."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
client: VLLMClientConfig = Field(default_factory=VLLMClientConfig)
|
||||
"""Client of the live deployment (``[orchestrator.model.client]``)."""
|
||||
|
||||
|
||||
@@ -90,70 +91,6 @@ class TrainSamplingConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict, omitting None values."""
|
||||
args: dict[str, Any] = {
|
||||
"temperature": self.temperature,
|
||||
"top_p": self.top_p,
|
||||
"logprobs": True,
|
||||
}
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
|
||||
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
"""Nucleus sampling threshold. None defers to the inference server default."""
|
||||
|
||||
top_k: int | None = None
|
||||
"""Top-k sampling. None defers to the inference server default."""
|
||||
|
||||
min_p: float | None = Field(None, ge=0)
|
||||
"""Min-p sampling threshold. None defers to the inference server default."""
|
||||
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. None defers to the inference server default."""
|
||||
|
||||
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
|
||||
"""Reasoning effort constraint for reasoning models."""
|
||||
|
||||
extra_body: dict[str, Any] = {}
|
||||
"""Extra body parameters forwarded to the inference server."""
|
||||
|
||||
def to_sampling_args(self) -> dict[str, Any]:
|
||||
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
|
||||
args: dict[str, Any] = {}
|
||||
if self.temperature is not None:
|
||||
args["temperature"] = self.temperature
|
||||
if self.top_p is not None:
|
||||
args["top_p"] = self.top_p
|
||||
if self.max_completion_tokens is not None:
|
||||
args["max_completion_tokens"] = self.max_completion_tokens
|
||||
if self.reasoning_effort is not None:
|
||||
args["reasoning_effort"] = self.reasoning_effort
|
||||
|
||||
extra_body = dict(self.extra_body)
|
||||
if self.top_k is not None:
|
||||
extra_body["top_k"] = self.top_k
|
||||
if self.min_p is not None:
|
||||
extra_body["min_p"] = self.min_p
|
||||
if extra_body:
|
||||
args["extra_body"] = extra_body
|
||||
|
||||
return args
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
|
||||
@@ -316,9 +253,37 @@ class TrainSourceConfig(EnvConfig):
|
||||
"""User-authored task sampler and admission gates. The default cycles
|
||||
through the taskset and admits every finalized group."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_policy_sampling(self):
|
||||
if self.algo.sampling.source != "policy":
|
||||
return self
|
||||
# The source owns the distribution replayed by the trainer; agents may
|
||||
# change generation limits and rendering without changing that distribution.
|
||||
agent_options = {"max_tokens", "reasoning_effort", "chat_template_kwargs"}
|
||||
supported = (
|
||||
agent_options
|
||||
| TrainSamplingConfig.model_fields.keys()
|
||||
| {"min_p", "logprobs", "return_token_ids", "cache_salt"}
|
||||
)
|
||||
sampling = vf.SamplingConfig(**self.sampling.model_dump(exclude_none=True))
|
||||
if unsupported := sampling.model_dump(exclude_none=True).keys() - supported:
|
||||
raise ValueError(
|
||||
f"Policy source '{self.resolved_name}' has unsupported sampling parameters: {sorted(unsupported)}"
|
||||
)
|
||||
for name, agent in agent_config_fields(self.env).items():
|
||||
if agent.sampling is None:
|
||||
continue
|
||||
if unsupported := agent.sampling.model_dump(exclude_unset=True).keys() - agent_options:
|
||||
raise ValueError(
|
||||
f"Agent '{name}' in policy source '{self.resolved_name}' sets sampling {sorted(unsupported)}. "
|
||||
"Set distribution parameters on the source's sampling config; agent sampling only supports "
|
||||
f"{sorted(agent_options)}."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
sampling: vf.SamplingConfig = vf.SamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
@@ -409,7 +374,7 @@ class EvalSourcesConfig(SourceGroupConfig):
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
sampling: vf.SamplingConfig = Field(default_factory=vf.SamplingConfig)
|
||||
"""Sampling that every eval source inherits; can differ from training sampling."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
|
||||
@@ -433,17 +433,8 @@ class RLConfig(BaseConfig):
|
||||
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
|
||||
"have no disk artifact to load from."
|
||||
)
|
||||
if "inference_world_size" in self.weight_broadcast.model_fields_set:
|
||||
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
|
||||
update = {}
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
update["inference_world_size"] = (
|
||||
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
|
||||
if self.inference
|
||||
else 1
|
||||
)
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
|
||||
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
|
||||
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
return self
|
||||
@@ -595,17 +586,17 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_disaggregated_combined_replay(self):
|
||||
def validate_disaggregated_no_routed_experts(self):
|
||||
"""Runs after ``auto_setup_router_replay``, which sets the inference flag after InferenceConfig's validators."""
|
||||
inference = self.inference
|
||||
if (
|
||||
inference is not None
|
||||
and inference.deployment.type == "disaggregated"
|
||||
and inference.enable_return_sampling_mask
|
||||
and inference.vllm.enable_return_routed_experts
|
||||
):
|
||||
raise ValueError(
|
||||
"Combined router and sampling replay is not supported with disaggregated P/D: "
|
||||
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
|
||||
"Router replay (inference.vllm.enable_return_routed_experts / trainer.enable_router_replay) "
|
||||
"is not supported with disaggregated P/D: vLLM does not capture routed experts across NIXL KV transfer."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -659,6 +650,11 @@ class RLConfig(BaseConfig):
|
||||
dp = self.inference.vllm.data_parallel_size
|
||||
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
|
||||
self.inference.vllm.api_server_count = dp
|
||||
if self.weight_broadcast.type != "filesystem":
|
||||
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
|
||||
world_size = dp * self.inference.vllm.tensor_parallel_size
|
||||
self.trainer.weight_broadcast.inference_world_size = world_size
|
||||
self.orchestrator.weight_broadcast.inference_world_size = world_size
|
||||
|
||||
elif self.deployment.type == "multi_node": # multi-node
|
||||
self.orchestrator.num_train_workers = (
|
||||
|
||||
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
|
||||
tools: str = "tools"
|
||||
"""Column with the tool schemas in OpenAI function-calling format."""
|
||||
|
||||
message_loss_mask: str = "message_loss_mask"
|
||||
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
|
||||
|
||||
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
|
||||
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
|
||||
|
||||
@@ -283,6 +286,13 @@ class SFTConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.01
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: SFT trains the router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = False
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import AfterValidator, Field, model_validator
|
||||
from verifiers.v1.configs.client import BaseClientConfig
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -212,22 +213,10 @@ class DynamoConfig(BaseConfig):
|
||||
"""Dynamo frontend URL used to discover inference workers for RL control."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
class ClientConfig(BaseClientConfig):
|
||||
wait_for_ready_timeout: int = 3600
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
"""Base URL for the OpenAI API. For multi-replica deployments, point this at a router in front of the replicas."""
|
||||
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
"""Static headers sent with every request."""
|
||||
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
@@ -238,6 +227,13 @@ class ClientConfig(BaseConfig):
|
||||
"""Dynamo RL worker-discovery configuration."""
|
||||
|
||||
|
||||
class VLLMClientConfig(ClientConfig):
|
||||
"""Client defaults for the live inference deployment managed by training."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
@@ -332,8 +332,8 @@ class ModelConfig(BaseModelConfig):
|
||||
index_cache: IndexCacheConfig | None = None
|
||||
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
|
||||
|
||||
freeze_moe_router: bool = False
|
||||
"""Freeze MoE router parameters during training."""
|
||||
freeze_moe_router: bool | Literal["auto"] = "auto"
|
||||
"""Freeze MoE router gate parameters. ``auto`` (default): ``True`` for RL, ``False`` for SFT; a no-op on non-MoE models. Frozen routers get no optimizer state, so resuming a checkpoint saved with a frozen router with ``freeze_moe_router=false`` fails on missing DCP keys."""
|
||||
|
||||
lora: LoRAConfig | None = None
|
||||
"""LoRA configuration. If None, LoRA is disabled."""
|
||||
@@ -612,6 +612,9 @@ class DataLoaderConfig(BaseConfig):
|
||||
fake: FakeDataLoaderConfig | None = None
|
||||
"""Use a fake data loader sampling random micro-batches (for debugging)."""
|
||||
|
||||
num_workers: int = Field(0, ge=0)
|
||||
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
@@ -688,6 +691,13 @@ class TrainerConfig(BaseConfig):
|
||||
self.optim.weight_decay = 0.0
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_freeze_moe_router_auto(self):
|
||||
"""Resolve ``model.freeze_moe_router='auto'``: RL keeps the pretrained router."""
|
||||
if self.model.freeze_moe_router == "auto":
|
||||
self.model.freeze_moe_router = True
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
|
||||
|
||||
+9
-7
@@ -16,7 +16,7 @@ dependencies = [
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.8.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"prime-runs[train]>=0.1.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -53,7 +53,7 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.30.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.31.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
@@ -147,7 +147,7 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# vLLM 0.31.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
@@ -225,10 +225,12 @@ requires-dist = [
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# verifiers pins harbor==0.24.0, published inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
harbor = "2026-10-08T00:00:00Z"
|
||||
tokenspeed-mla = false
|
||||
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
|
||||
flashinfer-python = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published packages in this project's dependency closure —
|
||||
@@ -278,8 +280,8 @@ vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.2/vllm_router-0.2.2-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.31.0/vllm-0.31.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
|
||||
@@ -113,7 +113,7 @@ HEAVY_PINS_PY
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels )
|
||||
--extra flash-attn-cute --extra flash-mla --extra disagg --extra quack --extra kernels )
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
|
||||
@@ -7314,6 +7314,8 @@ $("#tm-messages").addEventListener(
|
||||
"scroll",
|
||||
(e) => {
|
||||
if (!e.target.matches?.("#replay-output") || !replay) return;
|
||||
// top and bottom coincide when the output fits; keep the mode Home/End chose
|
||||
if (e.target.scrollHeight - e.target.clientHeight < 24) return;
|
||||
const atBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 24;
|
||||
replay.followOutput = atBottom;
|
||||
$("#replay-top")?.classList.toggle("active", !atBottom);
|
||||
|
||||
@@ -8,6 +8,8 @@ rollouts still owed run (``prime_rl.eval.resume``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.eval import resume
|
||||
@@ -24,7 +26,7 @@ class Eval:
|
||||
|
||||
async def run(self) -> None:
|
||||
config = self.config
|
||||
landed: list[dict] = []
|
||||
landed: list[vf.WireEpisode] = []
|
||||
if config.resume:
|
||||
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
|
||||
landed = resume.take_landed(config.run_dir)
|
||||
@@ -41,17 +43,14 @@ class Eval:
|
||||
)
|
||||
resume.stamp_config(config.run_dir, dump_resolved_config(config))
|
||||
await self.runner.setup()
|
||||
restored: list = []
|
||||
fired, restored = self.runner.eval_source.trigger(0, completed=landed)
|
||||
if config.resume:
|
||||
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
|
||||
self.runner.eval_source.restore(owed, groups)
|
||||
get_logger().info(
|
||||
f"Resuming from the trace stream: {len(restored)} episodes restored, "
|
||||
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
|
||||
f"{sum(request.rollouts or 0 for request in self.runner.eval_source.queue)} rollouts owed"
|
||||
)
|
||||
|
||||
await self.runner.start()
|
||||
fired = self.runner.eval_source.trigger(0)
|
||||
await self.runner.run_epoch(fired, 0, restored=restored)
|
||||
await self.runner.drain()
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ class OnlineEval:
|
||||
|
||||
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
|
||||
# so nothing dispatches until ``run_epoch`` switches modes below.
|
||||
fired = runner.eval_source.trigger(step, force=force)
|
||||
fired, _ = runner.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
|
||||
if reload_weights:
|
||||
|
||||
+14
-50
@@ -1,20 +1,18 @@
|
||||
"""Resume an interrupted eval from its trace stream.
|
||||
|
||||
The stream records what landed, so it is what a resume continues from. The run's ok
|
||||
episodes are read back and rejoin the epoch as if they had just arrived - through the
|
||||
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
|
||||
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
|
||||
The stream records what landed, so it is what a resume continues from. Successful
|
||||
episodes rejoin the epoch through the monitors as if they had just arrived,
|
||||
so the rebuilt stream, the epoch's metrics and the platform upload cover the
|
||||
whole epoch - and only the rollouts still owed run. Failed episodes and the in-flight
|
||||
ones the interruption cut off are owed again.
|
||||
|
||||
A landed episode counts toward the task with its ``task.key``, so a resumed run may
|
||||
select more or fewer examples or rollouts per example than the interrupted one: the
|
||||
kept episodes are matched to the new selection and the rest is owed. The resumed
|
||||
config is not checked against the interrupted one: any of it may be overridden.
|
||||
The shared Verifiers rollout planner matches these episodes to the current tasks
|
||||
by content hash. The resumed config is not checked against the interrupted one:
|
||||
any of it may be overridden.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
@@ -23,7 +21,6 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.monitors.file.traces import get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
CONFIG_NAME = "eval.json"
|
||||
@@ -57,52 +54,19 @@ def archives(run_dir: Path) -> list[Path]:
|
||||
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
|
||||
|
||||
|
||||
def take_landed(run_dir: Path) -> list[dict]:
|
||||
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
|
||||
def take_landed(run_dir: Path) -> list[vf.WireEpisode]:
|
||||
"""Successful episodes from every attempt; the planner deduplicates them.
|
||||
The current file monitor directory joins the archives so the resumed attempt writes a
|
||||
fresh stream, plan and metrics; nothing is deleted."""
|
||||
current = get_file_monitor_dir(run_dir)
|
||||
stream = get_trace_stream(run_dir).relative_to(current)
|
||||
landed: dict[str, dict] = {}
|
||||
landed: list[vf.WireEpisode] = []
|
||||
for directory in [*archives(run_dir), current]:
|
||||
if (directory / stream).is_dir():
|
||||
for record in read_records(directory / stream):
|
||||
if record.get("ok"):
|
||||
landed.setdefault(record["id"], record)
|
||||
episode = vf.WireEpisode.model_validate(record)
|
||||
if episode.ok and "traces" in record:
|
||||
landed.append(episode)
|
||||
if current.is_dir():
|
||||
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
|
||||
return list(landed.values())
|
||||
|
||||
|
||||
def plan(
|
||||
landed: list[dict], eval_envs: EvalEnvs
|
||||
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
|
||||
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
|
||||
order, the rollouts still owed per env and task key, and the group id a task's kept
|
||||
episodes carry, so the owed ones complete that group rather than open another."""
|
||||
targets: dict[str, Counter[str]] = {}
|
||||
for env in eval_envs:
|
||||
targets[env.name] = Counter(task.key for task in env.examples)
|
||||
for key in targets[env.name]:
|
||||
targets[env.name][key] *= env.config.group_size
|
||||
kept: list[vf.WireEpisode] = []
|
||||
counts: dict[str, Counter[str]] = defaultdict(Counter)
|
||||
groups: dict[str, dict[str, str]] = defaultdict(dict)
|
||||
for record in landed:
|
||||
env_name = record["env"].get("name") or record["env"]["id"]
|
||||
key = record["task"]["key"]
|
||||
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
|
||||
continue
|
||||
kept.append(vf.WireEpisode.model_validate(record))
|
||||
counts[env_name][key] += 1
|
||||
if (group := record.get("group") or {}).get("id"):
|
||||
groups[env_name].setdefault(key, group["id"])
|
||||
owed = {
|
||||
env_name: {
|
||||
key: target - counts[env_name][key]
|
||||
for key, target in target_counts.items()
|
||||
if target > counts[env_name][key]
|
||||
}
|
||||
for env_name, target_counts in targets.items()
|
||||
}
|
||||
return kept, owed, dict(groups)
|
||||
return landed
|
||||
|
||||
@@ -105,7 +105,7 @@ class EvalRunner:
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
# only used when the engine doesn't report its max context length.
|
||||
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
|
||||
fallback_cost = max((source.sampling.max_tokens or 0) for source in config.source) or 8192
|
||||
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=None,
|
||||
@@ -114,6 +114,7 @@ class EvalRunner:
|
||||
eval_source=self.eval_source,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
|
||||
@@ -18,11 +18,9 @@ def apply_shared_vllm_patches():
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
monkey_patch_tokenize_params_validation()
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -49,64 +47,6 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
@@ -243,51 +183,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm.config.vllm import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
original_post_init = VllmConfig.__post_init__
|
||||
|
||||
if getattr(original_post_init, "_prime_rl_allows_nixl_routed_experts", False):
|
||||
return
|
||||
|
||||
def _is_nixl_routed_experts_pd_config(config: VllmConfig) -> bool:
|
||||
kv_transfer_config = config.kv_transfer_config
|
||||
return (
|
||||
config.model_config is not None
|
||||
and config.model_config.enable_return_routed_experts
|
||||
and kv_transfer_config is not None
|
||||
and kv_transfer_config.kv_connector == "NixlConnector"
|
||||
and kv_transfer_config.is_kv_transfer_instance
|
||||
)
|
||||
|
||||
def _post_init(config: VllmConfig):
|
||||
if not _is_nixl_routed_experts_pd_config(config):
|
||||
return original_post_init(config)
|
||||
|
||||
if config.parallel_config.pipeline_parallel_size > 1:
|
||||
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
|
||||
if config.use_v2_model_runner:
|
||||
raise ValueError(
|
||||
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
|
||||
)
|
||||
|
||||
# vLLM rejects every KV connector, but our P/D path uses NIXL and
|
||||
# stitches prefill/decode routed experts in the router. CPU KV offload
|
||||
# remains rejected by prime-rl config validation.
|
||||
config.model_config.enable_return_routed_experts = False
|
||||
try:
|
||||
return original_post_init(config)
|
||||
finally:
|
||||
config.model_config.enable_return_routed_experts = True
|
||||
|
||||
_post_init._prime_rl_allows_nixl_routed_experts = True
|
||||
VllmConfig.__post_init__ = _post_init
|
||||
logger.warning("Enabled vLLM routed-experts capture with NIXL connector patch.")
|
||||
|
||||
|
||||
def monkey_patch_strip_routed_experts_from_chat():
|
||||
"""Drop routed_experts from chat-completions responses.
|
||||
|
||||
@@ -431,6 +326,7 @@ def _patch_lora_key_prefix():
|
||||
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
base_name = module_name.rsplit(".", 1)[-1]
|
||||
# Case for expert lora weights.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
@@ -440,7 +336,7 @@ def _patch_lora_key_prefix():
|
||||
unexpected_modules.append(module_name)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
elif base_name not in expected_lora_modules and base_name not in (peft_helper.modules_to_save or ()):
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
if unexpected_modules:
|
||||
|
||||
@@ -10,15 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
|
||||
# for sampling-mask capture, but router replay remains on V1 because vLLM
|
||||
# rejects routed-expert capture with KV connectors and prime-rl's stitching
|
||||
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask:
|
||||
# vLLM captures sampling masks and routed experts only on the V2 model runner.
|
||||
# setdefault keeps an explicit env-var choice authoritative.
|
||||
if config.enable_return_sampling_mask or config.vllm.enable_return_routed_experts:
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
elif config.vllm.enable_return_routed_experts:
|
||||
use_v2_runner = config.deployment.type != "disaggregated"
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
|
||||
@@ -62,14 +62,12 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant — the base model name, which
|
||||
the adapter shadows: ``_maybe_get_adapters`` resolves ``lora_requests`` before
|
||||
the base-model match, so requests keep addressing one stable name. If a future
|
||||
vLLM rejects registering an adapter under a served model name, fall back to a
|
||||
distinct constant adapter name set once at startup.) vLLM's native loader
|
||||
rejects a same-name reload unless ``load_inplace=True``, so we force it here —
|
||||
that makes the worker re-read the new weights during ``add_lora``, reusing the
|
||||
existing ``lora_int_id``.
|
||||
changes per policy version; the name is constant — the model name every client
|
||||
sends. vLLM rejects an adapter named like a served base model, so with LoRA on
|
||||
the base model is served as ``<model>-base``; see ``InferenceConfig.to_namespace``.)
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``, so
|
||||
we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
|
||||
@@ -66,7 +66,7 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
if self.engine_client.vllm_config.aux_output_config.enable_return_routed_experts:
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import fcntl
|
||||
import os
|
||||
import time
|
||||
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
|
||||
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
|
||||
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
|
||||
(``log_eval_epoch``), so the platform page follows the run from its first episode.
|
||||
Metrics are not forwarded; the evaluation is the epoch."""
|
||||
|
||||
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
|
||||
the parent training run, which is what the run dashboard groups into its `eval`
|
||||
section. The orchestrator's in-process evals reach it through the train monitor, but
|
||||
an eval process of its own (SFT online evals) has no other way there, so without
|
||||
this the run shows every metric group except the one its evals produced."""
|
||||
|
||||
config: PrimeEvalMonitorConfig
|
||||
|
||||
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
|
||||
# episodes do not retry the platform on every arrival
|
||||
self.runs: dict[tuple[str, int], pr.Run | None] = {}
|
||||
self.parent: pr.Run | None = None
|
||||
self._lock = asyncio.Lock()
|
||||
self.evaluation_id = os.getenv(EVAL_ID_VAR)
|
||||
if self.evaluation_id and len(self.sources) != 1:
|
||||
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
)
|
||||
if self.mode == "online":
|
||||
self.logger.info("Streaming eval epochs to the Prime platform")
|
||||
self.parent = await asyncio.to_thread(self._attach_parent)
|
||||
if output_dir is not None:
|
||||
# Merge, not overwrite: when the eval process shares the
|
||||
# trainer's run dir (SFT online evals), the train record's
|
||||
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
|
||||
else:
|
||||
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
def _attach_parent(self) -> pr.Run | None:
|
||||
"""The parent training run this eval process belongs to, for metrics only.
|
||||
Blocking: runs in a worker thread.
|
||||
|
||||
Attaching is a local handle, not a request, so a run that turns out to be
|
||||
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
|
||||
drop the SDK's atexit crash hook, because an eval process that exits while the
|
||||
trainer is still going would otherwise report the WHOLE run failed."""
|
||||
run_id = os.getenv("RUN_ID")
|
||||
if not run_id:
|
||||
return None
|
||||
run = pr.init(
|
||||
kind="train",
|
||||
mode=self.mode,
|
||||
base_url=_base_url(),
|
||||
id=run_id,
|
||||
finish_timeout=FINISH_TIMEOUT,
|
||||
)
|
||||
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
|
||||
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
|
||||
return run
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
pass
|
||||
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
|
||||
Only there: a standalone eval has no parent, and the per-epoch evaluation
|
||||
carries its own aggregates through ``log_eval_epoch``."""
|
||||
if self.parent is None:
|
||||
return
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# A queue put that can block briefly under backpressure - off the loop.
|
||||
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
|
||||
|
||||
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
|
||||
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
|
||||
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
|
||||
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
|
||||
if self.parent is not None:
|
||||
# Drain only. The parent run belongs to the trainer and the platform: an
|
||||
# eval process must never report its status, not even a clean completion.
|
||||
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
|
||||
is — a bundle of sampling and the per-token training signal. This package
|
||||
turns the signal half into runtime objects (the sampling half is the env's
|
||||
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
|
||||
turns the signal half into runtime objects (the sampling half is interpreted by
|
||||
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
|
||||
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
|
||||
@@ -22,7 +22,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
|
||||
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
|
||||
# (its TrainEnv interprets the sampling half). Every algorithm is
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
@@ -75,7 +75,6 @@ __all__ = [
|
||||
"RAEAlgorithm",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
"connect_frozen_client",
|
||||
"assign_advantages",
|
||||
"stamp_loss_routing",
|
||||
]
|
||||
|
||||
@@ -2,41 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
|
||||
|
||||
|
||||
def iter_trainable_traces(episodes: list[vf.Episode]):
|
||||
"""Yield clean trainable traces that contain sampled tokens."""
|
||||
for episode in episodes:
|
||||
for trace in episode.traces:
|
||||
if trace.has_error or not trace.agent.trainable:
|
||||
if not episode.ok or trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
|
||||
continue
|
||||
if any(any(node.mask) for node in trace.nodes):
|
||||
yield episode, trace
|
||||
|
||||
@@ -696,11 +696,10 @@ def _distribute_group(
|
||||
|
||||
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
|
||||
"""
|
||||
Pad a micro batch with the given padding size sample
|
||||
Return the padded micro batch.
|
||||
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
|
||||
Args:
|
||||
micro_batch: The micro batch to pad.
|
||||
padding_size: The number of padding tokens to add.
|
||||
pad_to_multiple_of: The multiple to pad the sequence length up to.
|
||||
Returns:
|
||||
The padded micro batch.
|
||||
"""
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
@@ -12,40 +11,20 @@ from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI
|
||||
from renderers import RendererConfig
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from verifiers.v1.configs.client import EvalClientConfig, TrainClientConfig
|
||||
from verifiers.v1.clients.base import build_async_openai
|
||||
from verifiers.v1.configs.client import (
|
||||
BaseClientConfig,
|
||||
EvalClientConfig,
|
||||
TrainClientConfig,
|
||||
resolve_api_key,
|
||||
resolve_headers,
|
||||
)
|
||||
|
||||
from prime_rl.configs.eval import PRIME_INFERENCE_URL
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def resolve_api_key(api_key_var: str) -> str:
|
||||
"""The API key named by ``api_key_var``; ``PRIME_API_KEY`` also falls back to the prime
|
||||
CLI config (``prime login``), like the verifiers client does. ``"EMPTY"`` when unset."""
|
||||
api_key = os.environ.get(api_key_var)
|
||||
if not api_key and api_key_var == "PRIME_API_KEY":
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
api_key = PrimeConfig().api_key
|
||||
return api_key or "EMPTY"
|
||||
|
||||
|
||||
def resolve_headers(client_config: ClientConfig) -> dict[str, str]:
|
||||
"""The static headers plus those read from the environment. A Prime Inference client
|
||||
without a team header gets the team from ``$PRIME_TEAM_ID`` or the prime CLI config,
|
||||
like the verifiers client: a team's internal models are served only under it."""
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.base_url.startswith(PRIME_INFERENCE_URL) and "X-Prime-Team-ID" not in headers:
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
if team_id := os.environ.get("PRIME_TEAM_ID") or PrimeConfig().team_id:
|
||||
headers["X-Prime-Team-ID"] = team_id
|
||||
return headers
|
||||
|
||||
|
||||
class PrefillScorer:
|
||||
"""Prefill-scores token ids against a pool's endpoint, lazily resolving
|
||||
a single OpenAI client from the pool's train client config."""
|
||||
@@ -55,14 +34,8 @@ class PrefillScorer:
|
||||
|
||||
async def score(self, config: vf.ClientConfig, model: str, token_ids: list[int]) -> list[float]:
|
||||
if self._client is None:
|
||||
# Build the OpenAI client straight from the config fields — works for any
|
||||
# ClientConfig type; resolve_client would hand back an EvalClient (no `.openai`)
|
||||
# for these chat-completions teacher configs.
|
||||
self._client = AsyncOpenAI(
|
||||
base_url=config.base_url,
|
||||
api_key=resolve_api_key(config.api_key_var),
|
||||
default_headers=config.headers or None,
|
||||
)
|
||||
# Prefill scoring uses the SDK even when generation uses the eval relay.
|
||||
self._client = build_async_openai(config)
|
||||
return await prefill_logprobs(self._client, model, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
@@ -256,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
|
||||
await admin.aclose()
|
||||
|
||||
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
|
||||
|
||||
def setup_client(
|
||||
client_config: ClientConfig,
|
||||
client_type: str = "openai_chat_completions",
|
||||
@@ -274,10 +262,7 @@ def setup_client(
|
||||
"renderer": renderer_config,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
}
|
||||
headers = resolve_headers(client_config)
|
||||
return config_cls(
|
||||
base_url=client_config.base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra
|
||||
)
|
||||
return config_cls(**client_config.model_dump(include=set(BaseClientConfig.model_fields)), **renderer_extra)
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -290,8 +275,9 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
urls = client_config.admin_base_url if client_config.admin_base_url else [client_config.base_url]
|
||||
|
||||
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
|
||||
headers = resolve_headers(client_config)
|
||||
api_key = resolve_api_key(client_config.api_key_var)
|
||||
config = client_config.model_copy(update={"base_url": base_url})
|
||||
headers = resolve_headers(config)
|
||||
api_key = resolve_api_key(config)
|
||||
if api_key != "EMPTY":
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
@@ -324,7 +310,9 @@ async def maybe_check_has_model(
|
||||
f"{result.text[:300]}"
|
||||
)
|
||||
models = body["data"]
|
||||
if not any(model["id"] == model_name for model in models):
|
||||
# A LoRA server lists the model name only once the adapter is loaded; until then
|
||||
# the base model (served as ``<model>-base``) carries it as its ``root``.
|
||||
if not any(model_name in (model["id"], model.get("root")) for model in models):
|
||||
raise ValueError(f"Model {model_name} was not found in the inference pool on {admin_client.base_url}")
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.algo.base import iter_trainable_traces
|
||||
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
|
||||
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
|
||||
|
||||
@@ -48,7 +49,7 @@ class Curriculum:
|
||||
self.gates[name] = gate
|
||||
|
||||
def on_result(self, group: list[vf.Episode]) -> bool:
|
||||
"""Observe every result, evaluate every gate, and combine with AND."""
|
||||
"""Observe every result and admit trainable groups that pass every gate."""
|
||||
if not group:
|
||||
raise ValueError("Cannot report an empty rollout group")
|
||||
task_keys = {episode.task.key for episode in group}
|
||||
@@ -63,7 +64,7 @@ class Curriculum:
|
||||
if not isinstance(decision, bool):
|
||||
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
|
||||
decisions.append(decision)
|
||||
return all(decisions)
|
||||
return all(decisions) and any(iter_trainable_traces(group))
|
||||
|
||||
def state_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
|
||||
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
|
||||
advantage
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
if episode.ok and not trace.has_error and trace.agent.trainable
|
||||
for node in trace.nodes
|
||||
for advantage in node.advantages or []
|
||||
]
|
||||
|
||||
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
|
||||
trace.reward
|
||||
for episode in group
|
||||
for trace in episode.traces
|
||||
if not trace.has_error and trace.agent.trainable
|
||||
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
|
||||
]
|
||||
if not rewards:
|
||||
return
|
||||
|
||||
@@ -143,9 +143,11 @@ class Dispatcher:
|
||||
max_off_policy_steps: int,
|
||||
run_id: str,
|
||||
run_name: str | None,
|
||||
policy_weights_change: bool = True,
|
||||
on_episode_complete: Callable[[int], None] | None = None,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.policy_weights_change = policy_weights_change
|
||||
self.progress = progress
|
||||
self.train_envs = train_envs
|
||||
self.eval_envs = eval_envs
|
||||
@@ -214,10 +216,10 @@ class Dispatcher:
|
||||
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.clients, self.policy.model_name, True
|
||||
return source.clients, source.clients.model_name, False
|
||||
env = self.train_envs.get(env_name)
|
||||
if env.uses_live_policy:
|
||||
return env.clients, self.policy.model_name, True
|
||||
return env.clients, env.clients.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -316,7 +318,7 @@ class Dispatcher:
|
||||
return [
|
||||
(self.progress.step - 1) - meta.policy_version
|
||||
for meta in self.inflight.values()
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
|
||||
]
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
@@ -423,7 +425,7 @@ class Dispatcher:
|
||||
gid
|
||||
for gid, group in self.groups.items()
|
||||
if group.kind == "train"
|
||||
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
|
||||
and self.train_envs.get(group.env_name).uses_live_policy
|
||||
and group.policy_version_at_start < min_version
|
||||
]
|
||||
cancelled = 0
|
||||
@@ -556,10 +558,8 @@ class Dispatcher:
|
||||
if env_collection is None:
|
||||
return False
|
||||
env = env_collection.get(group.env_name)
|
||||
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
|
||||
# version would invalidate its prefix cache every weight update for
|
||||
# no reason.
|
||||
if live_sourced:
|
||||
# Only endpoints receiving policy weight updates need a cache salt.
|
||||
if live_sourced and self.policy_weights_change:
|
||||
cache_salt = str(group.policy_version_at_start)
|
||||
else:
|
||||
cache_salt = None
|
||||
@@ -665,10 +665,6 @@ class Dispatcher:
|
||||
)
|
||||
return
|
||||
|
||||
if not episode.traces and episode.ok:
|
||||
episode.ok = False
|
||||
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
|
||||
|
||||
for trace in episode.traces:
|
||||
if trace.is_timeout and not trace.has_error and meta.kind == "train":
|
||||
# Training keeps a timed-out rollout out of the batch: an error,
|
||||
@@ -676,14 +672,6 @@ class Dispatcher:
|
||||
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure (``has_error`` reads ``ok``).
|
||||
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
|
||||
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
|
||||
trace.ok = False
|
||||
episode.ok = False
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if trace.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if trace.last_error is not None:
|
||||
@@ -691,8 +679,14 @@ class Dispatcher:
|
||||
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{trace.last_error.type}: {trace.last_error.message}"
|
||||
)
|
||||
if not episode.ok and not episode.traces:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not episode.ok:
|
||||
if not any(trace.has_error for trace in episode.traces):
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
error = episode.last_error
|
||||
get_logger().warning(
|
||||
f"Episode failed in group {meta.group_id} ({meta.env_name})"
|
||||
+ (f" — {error.type}: {error.message}" if error is not None else "")
|
||||
)
|
||||
if self.on_episode_complete is not None and meta.started_at > 0:
|
||||
self.on_episode_complete(episode.num_total_tokens)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
@@ -722,7 +716,7 @@ class Dispatcher:
|
||||
live_policy = meta.kind == "eval"
|
||||
if meta.kind == "train":
|
||||
assert self.train_envs is not None
|
||||
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
|
||||
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
|
||||
work: vf.WorkInfo = (
|
||||
vf.EvalWorkInfo(step=meta.step, policy=policy)
|
||||
|
||||
@@ -26,11 +26,13 @@ from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from renderers import RendererConfig
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import env_address_file
|
||||
|
||||
@@ -65,7 +67,7 @@ class Env:
|
||||
self.address_file = address_file
|
||||
"""Where a launcher-managed server publishes its address; read when ``address``
|
||||
is None."""
|
||||
self.sampling_args: dict = {}
|
||||
self.sampling = vf.SamplingConfig()
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count; ``None`` means the selected tasks never end."""
|
||||
self.tasks: Iterator[vf.Task] | None = None
|
||||
@@ -108,10 +110,10 @@ class Env:
|
||||
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
sampling = self.sampling
|
||||
if cache_salt is not None:
|
||||
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
return vf.SamplingConfig(**sampling)
|
||||
sampling = sampling.model_copy(update={"cache_salt": cache_salt})
|
||||
return sampling
|
||||
|
||||
async def run(
|
||||
self,
|
||||
@@ -121,25 +123,16 @@ class Env:
|
||||
task_data: dict,
|
||||
on_delta: Callable[[dict], None] | None = None,
|
||||
) -> vf.WireEpisode:
|
||||
"""Run and return one typed episode. A failed multi-trace episode marks
|
||||
its otherwise-clean traces failed so partial episodes never train.
|
||||
"""Run and return the native typed episode.
|
||||
``on_delta`` sees each delta of the env server's stream — a turn or a phase
|
||||
change of one of the episode's traces — as it lands."""
|
||||
episode = await self.env_client.run(
|
||||
return await self.env_client.run(
|
||||
task_data=task_data,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling=self._sampling(cache_salt),
|
||||
on_delta=on_delta,
|
||||
)
|
||||
for trace in episode.traces:
|
||||
if not episode.ok and trace.ok:
|
||||
error = episode.last_error or vf.Error(
|
||||
type="EpisodeFailed", message="A sibling trace in this episode failed"
|
||||
)
|
||||
trace.errors = [*trace.errors, error]
|
||||
trace.ok = False
|
||||
return episode
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
@@ -150,17 +143,39 @@ class TrainEnv(Env):
|
||||
config: TrainSourceConfig,
|
||||
address: str | None,
|
||||
address_file: Path,
|
||||
generation_source: GenerationSource,
|
||||
clients: InferenceClient,
|
||||
renderer_config: RendererConfig | None,
|
||||
algorithm: Algorithm,
|
||||
):
|
||||
super().__init__(config, address, address_file)
|
||||
self.generation_source = generation_source
|
||||
# Train rollouts are generated from `clients`: the policy, or the frozen
|
||||
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
|
||||
self.clients = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected: InferenceClient | None = None
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = (
|
||||
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
|
||||
self.uses_live_policy = config.algo.sampling.source == "policy"
|
||||
self.sampling = vf.SamplingConfig(
|
||||
**config.sampling.model_dump(exclude_none=True),
|
||||
# Only policy rollouts need sampling logprobs for importance ratios.
|
||||
logprobs=True if self.uses_live_policy else None,
|
||||
)
|
||||
# Truncated policy sampling must ship the sampling masks the trainer replays.
|
||||
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
|
||||
|
||||
async def setup(self) -> None:
|
||||
async def connect_source() -> None:
|
||||
source = self.config.algo.sampling.source
|
||||
if isinstance(source, FrozenModelConfig):
|
||||
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
|
||||
self.clients = self.connected
|
||||
|
||||
await asyncio.gather(connect_source(), self.algorithm.setup())
|
||||
|
||||
async def aclose(self) -> None:
|
||||
for clients in (self.connected, self.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
@@ -168,7 +183,7 @@ class EvalEnv(Env):
|
||||
|
||||
def __init__(self, config: EvalSourceConfig, address: str | None, address_file: Path):
|
||||
super().__init__(config, address, address_file)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.sampling = config.sampling
|
||||
self.examples: list[vf.Task] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
@@ -218,9 +233,8 @@ class Envs(Generic[EnvT]):
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments, each paired with its
|
||||
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
"""Collection of training environments, each with its runtime
|
||||
:class:`Algorithm`, built from the env's resolved algorithm config."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -238,7 +252,8 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
env_address_file(config_dir, "train", config.resolved_name),
|
||||
GenerationSource(config.algo.sampling, clients, renderer_config),
|
||||
clients,
|
||||
renderer_config,
|
||||
build_algorithm(config.algo, clients),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -6,15 +6,18 @@ including startup. The dispatcher pulls via ``next_task()`` until
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
import uuid
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import Iterable
|
||||
from itertools import zip_longest
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.utils.eval import plan_rollouts
|
||||
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
|
||||
|
||||
@@ -42,54 +45,50 @@ class EvalSource:
|
||||
self.intervals[env.name] = intervals[env.name] if intervals is not None else 1
|
||||
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
self.owed: dict[str, dict[str, int]] | None = None
|
||||
self.groups: dict[str, dict[str, str]] = {}
|
||||
|
||||
# A fresh run evaluates the base policy. Resumed runs apply interval
|
||||
# rules to the loaded checkpoint and later policies.
|
||||
self.first_trigger = not is_resumed
|
||||
|
||||
def restore(self, owed: dict[str, dict[str, int]], groups: dict[str, dict[str, str]]) -> None:
|
||||
"""Rollouts the next trigger still owes per env and task key, the rest having
|
||||
landed before a resume; a task without an entry is complete. ``groups`` is the
|
||||
group id the landed rollouts of a task carry, which the owed ones join."""
|
||||
self.owed = owed
|
||||
self.groups = groups
|
||||
|
||||
def trigger(self, step: int, *, force: bool = False) -> list[str]:
|
||||
"""Fire eligible envs for ``step`` and return their names. On resume
|
||||
def trigger(
|
||||
self, step: int, *, force: bool = False, completed: Iterable[vf.WireEpisode] = ()
|
||||
) -> tuple[list[str], list[vf.WireEpisode]]:
|
||||
"""Fire eligible envs and return their names and matched saved episodes. On resume
|
||||
``first_trigger`` is False, so the startup/base eval doesn't re-run.
|
||||
``force`` fires every env regardless of interval (e.g. the evals process's
|
||||
final-checkpoint eval)."""
|
||||
is_first, self.first_trigger = self.first_trigger, False
|
||||
if is_first and self.skip_first_step:
|
||||
return []
|
||||
return [], []
|
||||
fired = [
|
||||
name
|
||||
for name, interval in self.intervals.items()
|
||||
if (is_first or force or step % interval == 0) and self.tasks_by_env[name]
|
||||
]
|
||||
owed, self.owed = self.owed, None
|
||||
saved: dict[str, list[vf.WireEpisode]] = defaultdict(list)
|
||||
for episode in completed:
|
||||
saved[episode.env.name or episode.env.id].append(episode)
|
||||
restored: list[vf.WireEpisode] = []
|
||||
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
# rollouts back-to-back, so per-example prefix-cache locality holds
|
||||
iters = [iter(self.tasks_by_env[name]) for name in fired]
|
||||
iters = [iter(plan_rollouts(self.tasks_by_env[name], self.group_sizes[name], saved[name])) for name in fired]
|
||||
for round_tasks in zip_longest(*iters):
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
for env_name, planned in zip(fired, round_tasks, strict=True):
|
||||
if planned is None:
|
||||
continue
|
||||
rollouts = self.group_sizes[env_name]
|
||||
if owed is not None:
|
||||
# duplicate tasks share a key: each takes up to a group of what the key owes
|
||||
rollouts = min(rollouts, owed[env_name].get(task.key, 0))
|
||||
owed[env_name][task.key] = owed[env_name].get(task.key, 0) - rollouts
|
||||
task, kept, rollouts = planned
|
||||
# Each selected occurrence owns one group, including its restored episodes.
|
||||
group = vf.GroupInfo(id=str(uuid.uuid4()))
|
||||
for episode in kept:
|
||||
episode.group = group
|
||||
restored.extend(kept)
|
||||
if rollouts > 0:
|
||||
group_id = self.groups.get(env_name, {}).get(task.key)
|
||||
self.queue.append(
|
||||
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group_id)
|
||||
TaskRequest(env_name=env_name, task=task, step=step, rollouts=rollouts, group_id=group.id)
|
||||
)
|
||||
return fired
|
||||
return fired, restored
|
||||
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
"""Resolve the model source used to generate an env's train episodes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
|
||||
from prime_rl.orchestrator.algo import connect_frozen_client
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference clients.
|
||||
|
||||
``clients`` is what train rollouts are generated from: the policy clients,
|
||||
swapped for a connected frozen endpoint in :meth:`setup` when the source is
|
||||
an inline frozen model. A frozen source *generates* rollouts, so it uses
|
||||
the renderer (token-in/out) client (built from ``renderer_config``) — the
|
||||
rollout must carry tokens for training."""
|
||||
|
||||
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
|
||||
assert config.source is not None, "sampling.source must be resolved by config validation"
|
||||
self.config = config
|
||||
self.clients: InferenceClient = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect clients to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected = self.clients
|
||||
|
||||
@property
|
||||
def uses_live_policy(self) -> bool:
|
||||
return self.config.source == "policy"
|
||||
|
||||
def sampling_args(self, args: dict) -> dict:
|
||||
"""Source-specific sampling-arg overrides. Sampling logprobs are only
|
||||
needed for importance ratios on policy-sampled tokens — frozen
|
||||
endpoints may reject the knob."""
|
||||
if not self.uses_live_policy:
|
||||
args.pop("logprobs", None)
|
||||
return args
|
||||
@@ -282,16 +282,12 @@ class Orchestrator:
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
*(env.generation_source.setup() for env in self.train_envs),
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
await asyncio.gather(*(env.setup() for env in self.train_envs))
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
# A LoRA run's adapter is registered under the base model name: the
|
||||
# single adapter shadows it (vLLM resolves lora_requests before the
|
||||
# base-model match), so requests keep addressing one stable name.
|
||||
# A LoRA run's adapter is registered under the model name clients send;
|
||||
# the inference server serves the base model as ``<model>-base``.
|
||||
self.receiver = setup_weight_receiver(
|
||||
get_broadcast_dir(config.output_dir),
|
||||
config.weight_broadcast,
|
||||
@@ -770,7 +766,7 @@ class Orchestrator:
|
||||
if self.resume_step == step and self.config.eval is not None and not self.config.eval.retrigger_on_resume:
|
||||
return
|
||||
is_final = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
fired = self.eval_source.trigger(step, force=is_final)
|
||||
fired, _ = self.eval_source.trigger(step, force=is_final)
|
||||
if not fired:
|
||||
return
|
||||
self.eval_triggered_steps.add(step)
|
||||
@@ -1025,11 +1021,9 @@ class Orchestrator:
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
if self.train_envs is not None:
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
get_logger().debug("Stopping train env clients")
|
||||
for env in self.train_envs:
|
||||
for clients in (env.generation_source.connected, env.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
await env.aclose()
|
||||
|
||||
get_logger().info("Stopping orchestrator components")
|
||||
t0 = time.perf_counter()
|
||||
|
||||
@@ -255,7 +255,7 @@ class TrainSink:
|
||||
return
|
||||
|
||||
samples_by_trace: dict[str, list[TrainingSample]] = {}
|
||||
temperature = env.sampling_args["temperature"]
|
||||
temperature = env.config.sampling.temperature
|
||||
for trace in survivors:
|
||||
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
|
||||
for sample in samples:
|
||||
|
||||
@@ -24,7 +24,7 @@ class WeightWatcher:
|
||||
policy: Policy,
|
||||
observers: list[VersionObserver],
|
||||
ckpt_step: int = 0,
|
||||
poll_interval: float = 1.0,
|
||||
poll_interval: float = 0.1,
|
||||
) -> None:
|
||||
self.receiver = receiver
|
||||
self.policy = policy
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -16,6 +16,7 @@ import torch.nn as nn
|
||||
from huggingface_hub import snapshot_download
|
||||
from jaxtyping import Int
|
||||
from torch import Tensor
|
||||
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import CheckpointWrapper
|
||||
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
|
||||
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
@@ -125,23 +126,26 @@ def freeze_vision_encoder(model: nn.Module, override_attr: str | None = None) ->
|
||||
logger.info(f"Froze {num_frozen} parameters in vision encoder")
|
||||
|
||||
|
||||
def iter_moe_blocks(model: nn.Module) -> Iterator[MoE]:
|
||||
"""Yield the MoE MLP of each decoder layer, skipping dense layers."""
|
||||
for layer in get_language_model(model).layers:
|
||||
mlp = getattr(layer, "mlp", None)
|
||||
if isinstance(mlp, MoE):
|
||||
yield mlp
|
||||
|
||||
|
||||
def freeze_moe_router(model: nn.Module) -> None:
|
||||
"""Freeze MoE router parameters to maintain stable routing during training."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_frozen = 0
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen == 0:
|
||||
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
|
||||
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
# No-op for non-MoE models: freeze_moe_router=True is the RL default.
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
@@ -150,16 +154,12 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
|
||||
The FSDP bf16 cast exemption is applied separately in `setup_fsdp`.
|
||||
"""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.to(torch.float32)
|
||||
if isinstance(mlp.router, TokenChoiceTopKRouter):
|
||||
mlp.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.to(torch.float32)
|
||||
if isinstance(moe.router, TokenChoiceTopKRouter):
|
||||
moe.router.fp32_gate = True
|
||||
num_routers += 1
|
||||
|
||||
# No-op for non-MoE models: moe_router_dtype='float32' is the default,
|
||||
# so absence of MoE routers is the common case, not an error.
|
||||
@@ -177,13 +177,10 @@ def get_full_offload_dtype_policy(
|
||||
if config.moe_router_dtype != "float32":
|
||||
return policy
|
||||
|
||||
language_model = get_language_model(model)
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
for moe in iter_moe_blocks(model):
|
||||
for param in moe.router.parameters():
|
||||
if param.is_floating_point():
|
||||
policy[id(param)] = (torch.float32, torch.float32)
|
||||
return policy
|
||||
|
||||
|
||||
@@ -215,14 +212,10 @@ def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, MoE):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
for moe in iter_moe_blocks(model):
|
||||
moe.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
if num_routers == 0:
|
||||
raise ValueError("No MoE routers found to force-balance. Is this a MoE model?")
|
||||
@@ -248,13 +241,7 @@ def get_load_balance_stats(
|
||||
"""
|
||||
per_layer_max_vio = []
|
||||
per_layer_routing_confidence = []
|
||||
language_model = get_language_model(model)
|
||||
block_mlps = []
|
||||
for transformer_block in language_model.layers:
|
||||
# This is necessary for models that have mixed dense layers
|
||||
block_mlp = getattr(transformer_block, "mlp", None)
|
||||
if block_mlp is not None and hasattr(block_mlp, "tokens_per_expert"):
|
||||
block_mlps.append(block_mlp)
|
||||
block_mlps = list(iter_moe_blocks(model))
|
||||
if not block_mlps:
|
||||
return {"max_vio": None, "routing_confidence": None, "tokens_per_expert": torch.empty(0, 0)}
|
||||
|
||||
@@ -333,7 +320,7 @@ def compute_expert_load_stats(tokens_per_expert: Tensor) -> dict[str, Tensor]:
|
||||
|
||||
def get_expert_load_stats(tokens_per_expert: Tensor, group: dist.ProcessGroup) -> dict[str, float]:
|
||||
"""Sum a step's per-layer expert counts across the group (every rank routes distinct tokens) and compute load stats."""
|
||||
if tokens_per_expert.numel() == 0: # MoE model without prime-rl MoE layers (HF impl)
|
||||
if tokens_per_expert.numel() == 0:
|
||||
return {}
|
||||
dist.all_reduce(tokens_per_expert, op=dist.ReduceOp.SUM, group=group)
|
||||
return {name: value.item() for name, value in compute_expert_load_stats(tokens_per_expert).items()}
|
||||
@@ -829,12 +816,41 @@ def apply_ac(model: nn.Module, ac_config: ActivationCheckpointConfig):
|
||||
)
|
||||
|
||||
|
||||
# Int args whose value changes between calls. torch.compile treats an int arg as a constant and recompiles
|
||||
# whenever it changes, and every other rank waits in collectives until that rank finishes recompiling. Listed
|
||||
# here, an arg is symbolic from the first compile instead.
|
||||
DYNAMIC_INT_ARGS = (
|
||||
# Longest document in the packed row. FlashAttention uses it to size the attention launch grid.
|
||||
"max_seqlen",
|
||||
)
|
||||
|
||||
|
||||
def mark_dynamic_int_args() -> None:
|
||||
"""Add DYNAMIC_INT_ARGS to torch.compiler.config.dynamic_sources, keeping entries already set."""
|
||||
sources = [source for source in torch.compiler.config.dynamic_sources.split(",") if source]
|
||||
for arg in DYNAMIC_INT_ARGS:
|
||||
# Matches the arg passed directly (L['max_seqlen']) or through a wrapper's kwargs (L['kwargs']['max_seqlen']).
|
||||
pattern = rf".*\['{arg}'\]"
|
||||
if pattern not in sources:
|
||||
sources.append(pattern)
|
||||
torch.compiler.config.dynamic_sources = ",".join(sources)
|
||||
|
||||
|
||||
def apply_compile(model: nn.Module, compile_config: CompileConfig):
|
||||
torch._dynamo.config.capture_scalar_outputs = True
|
||||
mark_dynamic_int_args()
|
||||
language_model = get_language_model(model)
|
||||
for layer_id in range(len(language_model.layers)):
|
||||
layer = language_model.layers[layer_id]
|
||||
if isinstance(layer, CheckpointWrapper) and any(
|
||||
isinstance(module, FSDPModule) for module in layer._checkpoint_wrapped_module.modules()
|
||||
):
|
||||
# A nested FSDP unit's hooks always break the graph, and a break inside a compiled checkpoint
|
||||
# sends the block to eager, so keep AC eager around the compiled block. pytorch/pytorch#196626
|
||||
# removes the fp32 router's nested unit by letting it join the block's FSDP unit.
|
||||
layer = layer._checkpoint_wrapped_module
|
||||
# Doing it in-place avoids mangled fqn which can break checkpoint loading
|
||||
language_model.layers[layer_id].compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
layer.compile(fullgraph=compile_config.fullgraph, mode=compile_config.mode)
|
||||
get_logger().info(
|
||||
f"Compiled {len(language_model.layers)} layers (fullgraph={compile_config.fullgraph}, mode={compile_config.mode})"
|
||||
)
|
||||
@@ -995,14 +1011,15 @@ def setup_model(
|
||||
override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None,
|
||||
)
|
||||
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
# the right order is AC -> FSDP -> Compile: compile needs to see which blocks hold nested FSDP units
|
||||
if config.ac is not None:
|
||||
apply_ac(model, config.ac)
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
setup_fsdp(model, config, parallel_dims)
|
||||
|
||||
if config.compile is not None:
|
||||
apply_compile(model, config.compile)
|
||||
|
||||
if loading_from_checkpoint_later:
|
||||
logger.warning(
|
||||
"Skipping loading weights. Initializing an empty model on device, loading from checkpoint later."
|
||||
|
||||
@@ -15,9 +15,9 @@ from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
@@ -87,30 +87,25 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
|
||||
"""AFMoE attention using Flash Attention varlen functions."""
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
4: flash_attn_4_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: AfmoeAttentionConfig, flash_attn_version: int = 4):
|
||||
super().__init__(config)
|
||||
self._flash_attn_version = flash_attn_version
|
||||
self.func = self._funcs[flash_attn_version]
|
||||
self._flash_attn_call = self.func
|
||||
if self._flash_attn_version == 4:
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
kwargs: dict = {"causal": True}
|
||||
if self.sliding_window is not None:
|
||||
kwargs["window_size"] = (self.sliding_window - 1, 0)
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
if self._flash_attn_version == 4:
|
||||
out, _ = self.func(q, k, v, cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens, **kwargs)
|
||||
else:
|
||||
out = self.func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
|
||||
return out
|
||||
|
||||
def forward(
|
||||
@@ -372,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
|
||||
@@ -61,8 +61,8 @@ class DeepseekV4Config(PretrainedConfig):
|
||||
num_experts_per_tok: Number of routed experts activated per token.
|
||||
n_routed_experts: Total number of routed experts.
|
||||
n_shared_experts: Number of always-on shared experts.
|
||||
scoring_func: Router activation. Only `sqrtsoftplus` is implemented; any other
|
||||
value is rejected when the MoE layer is built.
|
||||
scoring_func: Router score function, passed to the shared router: `sqrtsoftplus`
|
||||
(V4's checkpoints), `sigmoid`, `softmax` or `topk_softmax`.
|
||||
topk_method: Router top-k selection. Only `noaux_tc` (aux-loss-free bias correction) is
|
||||
implemented; the field is carried because vLLM gates `e_score_correction_bias` on it.
|
||||
norm_topk_prob: Whether to renormalize the top-k routing probabilities.
|
||||
|
||||
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
|
||||
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
mhc_states = decoder_layer(
|
||||
mhc_states,
|
||||
input_ids=input_ids,
|
||||
|
||||
@@ -6,96 +6,15 @@ selection with a frozen token-id lookup but keeps the learned gating weights.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.layers.activations import ClampedSilu
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class ClampedSwiglu:
|
||||
"""SwiGLU with both branches clamped, as in HF's `DeepseekV4Experts`.
|
||||
|
||||
Structurally an `Activation`, but with `limit` as instance state: V4 reads its clamp
|
||||
off `config.swiglu_limit`, while the shared `ActivationDispatch` holds stateless
|
||||
classes keyed by name and so has nowhere to put a per-model number.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None, "V4's routed experts are gated"
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class DeepseekV4Router(TokenChoiceTopKRouter):
|
||||
"""Token-choice router scored with `sqrt(softplus(.))`, V4's only scoring function.
|
||||
|
||||
`TokenChoiceTopKRouter.forward` picks its scoring function from an inline
|
||||
`if/elif/else: raise` chain with no hook to extend, and `"sqrtsoftplus"` is outside
|
||||
the `ScoreFuncType` it accepts, so the whole method is restated below. Only the
|
||||
scoring line is new: the `routed_experts` bypass, the selection bias, the
|
||||
normalization, the scaling and the per-expert token count are the base class's,
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, routed_experts: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
if self.fp32_gate:
|
||||
gate_bias = self.gate.bias.float() if self.gate.bias is not None else None
|
||||
logits = F.linear(x.float(), self.gate.weight.float(), gate_bias)
|
||||
else:
|
||||
logits = self.gate(x)
|
||||
|
||||
# Scoring runs in float32 to avoid loss explosion, as in the base class. HF scores
|
||||
# in the input dtype instead, so bf16 activations drift from HF by ~1e-3 here.
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
|
||||
# NOTE: the selection bias only steers selection. The gating value top_scores is
|
||||
# still derived from the original scores.
|
||||
if routed_experts is not None:
|
||||
top_scores = scores.gather(dim=1, index=routed_experts)
|
||||
selected_experts_indices = routed_experts
|
||||
elif self.force_balanced:
|
||||
num_tokens = scores.shape[0]
|
||||
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
|
||||
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
else:
|
||||
selection_scores = scores
|
||||
if self.selection_bias is not None:
|
||||
selection_scores = selection_scores + self.selection_bias
|
||||
_, selected_experts_indices = torch.topk(selection_scores, k=self.top_k, dim=1, sorted=self.topk_sorted)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
|
||||
with torch.no_grad():
|
||||
selected_probability_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
|
||||
routing_confidence_sum = selected_probability_mass.sum()
|
||||
|
||||
if self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
top_scores = top_scores * self.route_scale
|
||||
|
||||
num_tokens_per_expert = torch.histc(
|
||||
selected_experts_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
).to(torch.int64)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
|
||||
class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
class DeepseekV4HashRouter(TokenChoiceTopKRouter):
|
||||
"""A bootstrap layer's router: selection is a frozen token-id lookup, gating still learned.
|
||||
|
||||
`tid2eid` replaces the top-k of the scores with `tid2eid[token_id]`, read from the checkpoint
|
||||
@@ -105,73 +24,9 @@ class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
unbuilt, keeping the state dict aligned with HF's.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: str,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
vocab_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
dim=dim,
|
||||
num_experts=num_experts,
|
||||
top_k=top_k,
|
||||
score_func=score_func,
|
||||
route_norm=route_norm,
|
||||
route_scale=route_scale,
|
||||
selection_bias=False,
|
||||
)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4Experts(GroupedExperts):
|
||||
"""Routed experts with V4's clamped SwiGLU.
|
||||
|
||||
The shared `GroupedExperts` already stores the stacked `gate_proj`/`up_proj`/`down_proj`
|
||||
that the on-disk per-expert `w1`/`w2`/`w3` convert into, and its `forward` reaches the
|
||||
activation through `self.activation`, so only that attribute and the initialization
|
||||
spread differ from the base class.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, hidden_dim: int, num_experts: int, swiglu_limit: float) -> None:
|
||||
super().__init__(dim, hidden_dim, num_experts, expert_type="gated")
|
||||
self.activation = ClampedSwiglu(swiglu_limit)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# Both halves of HF's fused gate_up_proj are drawn from the same std=0.02
|
||||
# distribution, so gate and up match that here despite being separate tensors.
|
||||
# The base class scales up_proj by init_std instead.
|
||||
nn.init.trunc_normal_(self.gate_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.up_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class DeepseekV4MLP(FeedForward):
|
||||
"""Dense SwiGLU MLP with V4's clamp, used as the MoE layer's shared expert.
|
||||
|
||||
The shared `FeedForward` already names its projections the way HF's `LlamaMLP` (which
|
||||
HF's `DeepseekV4MLP` subclasses) does, and initializes them the same way, so only the
|
||||
activation changes: gate and up are clamped before the SwiGLU. Unlike the routed
|
||||
experts they are separate tensors here, so there is nothing to chunk.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
# `FeedForward` builds its projections without a bias whatever `bias` says.
|
||||
assert not config.mlp_bias, "mlp_bias is not supported by the shared `FeedForward`"
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.limit = config.swiglu_limit
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x).clamp(max=self.limit)
|
||||
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
|
||||
return self.down_proj(F.silu(gate) * up)
|
||||
def __init__(self, *, vocab_size: int, **router_kwargs) -> None:
|
||||
super().__init__(**router_kwargs, selection_bias=False)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, self.top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4MoE(MoE):
|
||||
@@ -190,13 +45,9 @@ class DeepseekV4MoE(MoE):
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
assert config.hidden_act == "silu", (
|
||||
f"the routed experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
f"the experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
)
|
||||
if config.scoring_func != "sqrtsoftplus":
|
||||
raise ValueError(
|
||||
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
|
||||
)
|
||||
|
||||
assert not config.mlp_bias, "mlp_bias is not supported"
|
||||
is_hash = layer_idx < config.num_hash_layers
|
||||
|
||||
router_kwargs = dict(
|
||||
@@ -212,17 +63,22 @@ class DeepseekV4MoE(MoE):
|
||||
router = (
|
||||
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
|
||||
if is_hash
|
||||
else DeepseekV4Router(**router_kwargs, selection_bias=True)
|
||||
else TokenChoiceTopKRouter(**router_kwargs, selection_bias=True)
|
||||
)
|
||||
experts = DeepseekV4Experts(
|
||||
activation = ClampedSilu(config.swiglu_limit)
|
||||
experts = GroupedExperts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
swiglu_limit=config.swiglu_limit,
|
||||
activation=activation,
|
||||
)
|
||||
# HF sizes its shared expert at `moe_intermediate_size` regardless of
|
||||
# `n_shared_experts`, which therefore only decides whether one exists at all.
|
||||
shared_expert = DeepseekV4MLP(config) if config.n_shared_experts > 0 else None
|
||||
shared_expert = (
|
||||
FeedForward(dim=config.hidden_size, hidden_dim=config.moe_intermediate_size, activation=activation)
|
||||
if config.n_shared_experts > 0
|
||||
else None
|
||||
)
|
||||
|
||||
super().__init__(
|
||||
router=router,
|
||||
@@ -235,6 +91,11 @@ class DeepseekV4MoE(MoE):
|
||||
self.layer_idx = layer_idx
|
||||
self.is_hash = is_hash
|
||||
|
||||
def init_weights(self, init_std: float, buffer_device: torch.device) -> None:
|
||||
super().init_weights(init_std, buffer_device)
|
||||
# HF draws both halves of its fused gate_up_proj from std=0.02; the shared init uses init_std for up.
|
||||
nn.init.trunc_normal_(self.experts.up_proj, mean=0.0, std=0.02)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
|
||||
if weight.ndim != 2:
|
||||
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
|
||||
|
||||
rows, cols = weight.shape
|
||||
pad_rows = (block_size - rows % block_size) % block_size
|
||||
pad_cols = (block_size - cols % block_size) % block_size
|
||||
|
||||
if pad_rows or pad_cols:
|
||||
padded = torch.zeros(
|
||||
rows + pad_rows,
|
||||
cols + pad_cols,
|
||||
dtype=weight.dtype,
|
||||
device=weight.device,
|
||||
)
|
||||
padded[:rows, :cols] = weight
|
||||
else:
|
||||
padded = weight.contiguous()
|
||||
|
||||
padded_rows, padded_cols = padded.shape
|
||||
blocks = padded.view(
|
||||
padded_rows // block_size,
|
||||
block_size,
|
||||
padded_cols // block_size,
|
||||
block_size,
|
||||
).permute(0, 2, 1, 3)
|
||||
|
||||
fp8_max = torch.finfo(torch.float8_e4m3fn).max
|
||||
max_abs = blocks.float().abs().amax(dim=(2, 3))
|
||||
scales = (max_abs / fp8_max).clamp(min=1e-12)
|
||||
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
|
||||
|
||||
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
|
||||
return quantized, scales.float().contiguous()
|
||||
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
cached_indices = None
|
||||
use_index_cache = getattr(self.config, "use_index_cache", False)
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states, next_cached_indices = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings,
|
||||
|
||||
@@ -12,6 +12,7 @@ import triton.language as tl
|
||||
FP8_MAX = 448.0
|
||||
FP8_MIN = -448.0
|
||||
FP8_EPS = 1e-10
|
||||
KEY_ALIGNMENT = 16
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
|
||||
return x_q, x_s
|
||||
|
||||
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
|
||||
],
|
||||
key=["S_Q", "S_K_BUCKET", "H", "D"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_fp8_indexer_kernel(
|
||||
Q_fp8,
|
||||
@@ -116,7 +106,6 @@ def _triton_fp8_indexer_kernel(
|
||||
stride_ws,
|
||||
H: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
S_K_BUCKET: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
@@ -201,6 +190,8 @@ def fp8_indexer(
|
||||
|
||||
q_flat = q.reshape(S_q * H, D).contiguous()
|
||||
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
|
||||
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
|
||||
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
|
||||
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
|
||||
|
||||
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
|
||||
@@ -209,12 +200,10 @@ def fp8_indexer(
|
||||
q_scales = q_scales.view(S_q, H)
|
||||
w = w * q_scales
|
||||
|
||||
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
|
||||
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
|
||||
|
||||
grid = lambda meta: (
|
||||
triton.cdiv(S_q, meta["BLOCK_M"]),
|
||||
triton.cdiv(S_k, meta["BLOCK_N"]),
|
||||
)
|
||||
BLOCK_M, BLOCK_N = 64, 128
|
||||
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
|
||||
_triton_fp8_indexer_kernel[grid](
|
||||
q_fp8,
|
||||
k_fp8,
|
||||
@@ -224,16 +213,17 @@ def fp8_indexer(
|
||||
ks,
|
||||
ke,
|
||||
S_q,
|
||||
S_k,
|
||||
S_k_aligned,
|
||||
q_fp8.stride(0),
|
||||
q_fp8.stride(1),
|
||||
k_fp8.stride(0),
|
||||
w.stride(0),
|
||||
H=H,
|
||||
D=D,
|
||||
# Packed document tails change S_k between batches. Reuse tuning within
|
||||
# a size bucket; exact S_k still controls strides and all bounds masks.
|
||||
S_K_BUCKET=triton.next_power_of_2(S_k),
|
||||
BLOCK_M=BLOCK_M,
|
||||
BLOCK_N=BLOCK_N,
|
||||
num_warps=4,
|
||||
num_stages=2,
|
||||
)
|
||||
|
||||
actual_topk = min(topk, S_k)
|
||||
|
||||
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
|
||||
}
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
|
||||
|
||||
@@ -18,6 +18,19 @@ class ClampedSwiglu(Activation):
|
||||
return (up + 1) * gate * torch.sigmoid(gate * 1.702)
|
||||
|
||||
|
||||
class ClampedSilu(Activation):
|
||||
"""SwiGLU with the gate clamped to `max=limit` and up to `[-limit, limit]` (DeepSeek V4)."""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class Relu2(Activation):
|
||||
@staticmethod
|
||||
def apply(gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -13,14 +13,19 @@ from .rotary_emb import apply_rotary_pos_emb
|
||||
# flash-attention-2
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
from flash_attn.flash_attn_interface import _flash_attn_varlen_backward, _flash_attn_varlen_forward
|
||||
except ImportError:
|
||||
flash_attn_varlen_func = None # type: ignore
|
||||
_flash_attn_varlen_backward = _flash_attn_varlen_forward = None # type: ignore
|
||||
|
||||
# flash-attention-3
|
||||
try:
|
||||
from flash_attn_interface import _flash_attn_backward as _flash_attn_3_bwd
|
||||
from flash_attn_interface import _flash_attn_forward as _flash_attn_3_fwd
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
|
||||
except ImportError:
|
||||
flash_attn_3_varlen_func = None # type: ignore
|
||||
_flash_attn_3_bwd = _flash_attn_3_fwd = None # type: ignore
|
||||
|
||||
try:
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
|
||||
@@ -30,9 +35,11 @@ except ImportError:
|
||||
_flash_attn_bwd = _flash_attn_fwd = None # type: ignore
|
||||
|
||||
|
||||
# FA4's flash_attn_varlen_func is a Python autograd.Function that Dynamo cannot trace. Inside a
|
||||
# checkpointed block that graph break drops the whole block to eager, so FA4 is exposed as an
|
||||
# opaque custom op instead, which also lets selective activation checkpointing save its output.
|
||||
# Each FlashAttention version's flash_attn_varlen_func is a Python autograd.Function that Dynamo
|
||||
# cannot trace (FA2 and FA3 also reject the same cu_seqlens tensor passed as both cu_seqlens_q and
|
||||
# cu_seqlens_k). Inside a checkpointed block that graph break drops the whole block to eager, so
|
||||
# each version is exposed as an opaque custom op instead, which also lets selective activation
|
||||
# checkpointing save its output.
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_4_varlen", mutates_args=())
|
||||
def _flash_attn_4_varlen(
|
||||
q: torch.Tensor,
|
||||
@@ -40,6 +47,8 @@ def _flash_attn_4_varlen(
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -50,6 +59,8 @@ def _flash_attn_4_varlen(
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
@@ -59,7 +70,7 @@ def _flash_attn_4_varlen(
|
||||
|
||||
|
||||
@_flash_attn_4_varlen.register_fake
|
||||
def _(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
@@ -75,6 +86,8 @@ def _flash_attn_4_varlen_backward(
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None,
|
||||
max_seqlen_k: int | None,
|
||||
causal: bool,
|
||||
window_size_left: int | None,
|
||||
window_size_right: int | None,
|
||||
@@ -91,19 +104,24 @@ def _flash_attn_4_varlen_backward(
|
||||
window_size_right=window_size_right,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_4_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right):
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size_left, window_size_right = inputs
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size_left, window_size_right = (
|
||||
inputs
|
||||
)
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.max_seqlen = (max_seqlen_q, max_seqlen_k)
|
||||
ctx.causal = causal
|
||||
ctx.window_size = (window_size_left, window_size_right)
|
||||
|
||||
@@ -111,9 +129,9 @@ def _flash_attn_4_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
def _flash_attn_4_varlen_autograd(ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
|
||||
dq, dk, dv = _flash_attn_4_varlen_backward(
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, ctx.causal, *ctx.window_size
|
||||
dout.contiguous(), q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k, *ctx.max_seqlen, ctx.causal, *ctx.window_size
|
||||
)
|
||||
return dq, dk, dv, None, None, None, None, None
|
||||
return dq, dk, dv, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_4_varlen.register_autograd(_flash_attn_4_varlen_autograd, setup_context=_flash_attn_4_varlen_setup_context)
|
||||
@@ -126,11 +144,264 @@ def flash_attn_4_varlen_op(
|
||||
*,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int | None = None,
|
||||
max_seqlen_k: int | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int | None, int | None] = (None, None),
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Drop-in for FA4's ``flash_attn_varlen_func`` as called by ``FlashAttention``, routed through the custom op."""
|
||||
return _flash_attn_4_varlen(q, k, v, cu_seqlens_q, cu_seqlens_k, causal, window_size[0], window_size[1])
|
||||
return _flash_attn_4_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, causal, window_size[0], window_size[1]
|
||||
)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen", mutates_args=())
|
||||
def _flash_attn_3_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
out, lse, _, _ = _flash_attn_3_fwd(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out, lse
|
||||
|
||||
|
||||
@_flash_attn_3_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
out = q.new_empty((*q.shape[:-1], v.shape[-1]))
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_3_varlen_backward", mutates_args=())
|
||||
def _flash_attn_3_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_3_bwd(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
cu_seqlens_q=cu_seqlens_q,
|
||||
cu_seqlens_k=cu_seqlens_k,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
max_seqlen_k=max_seqlen_k,
|
||||
dq=dq,
|
||||
dk=dk,
|
||||
dv=dv,
|
||||
softmax_scale=softmax_scale,
|
||||
is_causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return dq, dk, dv
|
||||
|
||||
|
||||
@_flash_attn_3_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
return torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
|
||||
|
||||
# FA2's public flash_attn_varlen_func pads the head dim to a multiple of 8 around its kernels; these ops call
|
||||
# the kernels directly, so they pad the same way.
|
||||
def pad_head_dim_to_multiple_of_8_for_fa2(t: torch.Tensor) -> torch.Tensor:
|
||||
head_dim = t.shape[-1]
|
||||
if head_dim % 8 == 0:
|
||||
return t
|
||||
return torch.nn.functional.pad(t, [0, 8 - head_dim % 8])
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen", mutates_args=())
|
||||
def _flash_attn_2_varlen(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
q, k, v = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (q, k, v))
|
||||
out_padded, lse, _, _ = _flash_attn_varlen_forward(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal=causal,
|
||||
window_size_left=window_size_left,
|
||||
window_size_right=window_size_right,
|
||||
)
|
||||
return out_padded[..., :head_dim], lse
|
||||
|
||||
|
||||
# FA2's kernel allocates its outputs with empty_like on the padded inputs, so the fakes keep their strides and padding.
|
||||
@_flash_attn_2_varlen.register_fake
|
||||
def _(q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
out = torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(q))[..., :head_dim]
|
||||
lse = q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
|
||||
return out, lse
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl_attn::flash_attn_2_varlen_backward", mutates_args=())
|
||||
def _flash_attn_2_varlen_backward(
|
||||
dout: torch.Tensor,
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float,
|
||||
causal: bool,
|
||||
window_size_left: int,
|
||||
window_size_right: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
head_dim = q.shape[-1]
|
||||
dout, q, k, v, out = (pad_head_dim_to_multiple_of_8_for_fa2(t) for t in (dout, q, k, v, out))
|
||||
dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
|
||||
_flash_attn_varlen_backward(
|
||||
dout,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
out,
|
||||
lse,
|
||||
dq,
|
||||
dk,
|
||||
dv,
|
||||
cu_seqlens_q,
|
||||
cu_seqlens_k,
|
||||
max_seqlen_q,
|
||||
max_seqlen_k,
|
||||
0.0,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size_left,
|
||||
window_size_right,
|
||||
0.0,
|
||||
None,
|
||||
False,
|
||||
)
|
||||
return dq[..., :head_dim], dk[..., :head_dim], dv[..., :head_dim]
|
||||
|
||||
|
||||
@_flash_attn_2_varlen_backward.register_fake
|
||||
def _(dout, q, k, v, *args):
|
||||
head_dim = q.shape[-1]
|
||||
return tuple(torch.empty_like(pad_head_dim_to_multiple_of_8_for_fa2(t))[..., :head_dim] for t in (q, k, v))
|
||||
|
||||
|
||||
def _flash_attn_varlen_setup_context(ctx, inputs, output) -> None:
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, *scalar_args = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
|
||||
ctx.scalar_args = scalar_args
|
||||
|
||||
|
||||
def _flash_attn_varlen_autograd(backward_op, ctx, dout: torch.Tensor, _dlse: torch.Tensor | None):
|
||||
dq, dk, dv = backward_op(dout.contiguous(), *ctx.saved_tensors, *ctx.scalar_args)
|
||||
return dq, dk, dv, None, None, None, None, None, None, None, None
|
||||
|
||||
|
||||
_flash_attn_2_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_2_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
_flash_attn_3_varlen.register_autograd(
|
||||
functools.partial(_flash_attn_varlen_autograd, _flash_attn_3_varlen_backward),
|
||||
setup_context=_flash_attn_varlen_setup_context,
|
||||
)
|
||||
|
||||
|
||||
def flash_attn_2_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA2's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_2_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def flash_attn_3_varlen_op(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
cu_seqlens_k: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
max_seqlen_k: int,
|
||||
softmax_scale: float | None = None,
|
||||
causal: bool = False,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
) -> torch.Tensor:
|
||||
"""Drop-in for FA3's ``flash_attn_varlen_func``, routed through the custom op."""
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** -0.5
|
||||
out, _ = _flash_attn_3_varlen(
|
||||
q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, softmax_scale, causal, *window_size
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -158,8 +429,8 @@ class FlashAttention(nn.Module):
|
||||
supported_fusions = {"qkv": fuse_qkv_projections}
|
||||
|
||||
_funcs = {
|
||||
2: flash_attn_varlen_func,
|
||||
3: flash_attn_3_varlen_func,
|
||||
2: flash_attn_2_varlen_op,
|
||||
3: flash_attn_3_varlen_op,
|
||||
4: flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from typing import Literal
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
|
||||
ExpertType = Literal["gated", "non_gated"]
|
||||
|
||||
@@ -17,14 +17,14 @@ class FeedForward(nn.Module):
|
||||
hidden_dim: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.gate_proj = nn.Linear(dim, hidden_dim, bias=bias) if expert_type == "gated" else None
|
||||
self.up_proj = nn.Linear(dim, hidden_dim, bias=bias)
|
||||
self.down_proj = nn.Linear(hidden_dim, dim, bias=bias)
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x) if self.gate_proj is not None else None
|
||||
|
||||
@@ -13,11 +13,11 @@ from torch import nn
|
||||
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.activations import Activation, ActivationDispatch, ActivationType
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, ExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
|
||||
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax"]
|
||||
ScoreFuncType = Literal["softmax", "sigmoid", "topk_softmax", "sqrtsoftplus"]
|
||||
|
||||
|
||||
@torch.library.custom_op(
|
||||
@@ -76,7 +76,7 @@ class GroupedExperts(nn.Module):
|
||||
num_experts: int,
|
||||
*,
|
||||
expert_type: ExpertType = "gated",
|
||||
activation: ActivationType = "silu",
|
||||
activation: ActivationType | Activation = "silu",
|
||||
bias: bool = False,
|
||||
compute: ExpertCompute | None = None,
|
||||
):
|
||||
@@ -93,7 +93,7 @@ class GroupedExperts(nn.Module):
|
||||
self.up_proj_bias = nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias else None
|
||||
self.down_proj_bias = nn.Parameter(torch.empty(num_experts, dim)) if bias else None
|
||||
|
||||
self.activation = ActivationDispatch[activation]
|
||||
self.activation = ActivationDispatch[activation] if isinstance(activation, str) else activation
|
||||
if expert_type == "non_gated":
|
||||
self.supported_fusions = {}
|
||||
self.set_compute(compute or BF16ExpertCompute())
|
||||
@@ -136,8 +136,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim (int): Dimension of input tokens.
|
||||
num_experts (int): Number of experts in each moe layer.
|
||||
top_k (int): Number of experts each token will be routed to in token-choice routing.
|
||||
score_func (Literal["softmax", "sigmoid", "topk_softmax"]): Score transform. ``topk_softmax``
|
||||
selects experts from the logits and normalizes only the selected logits.
|
||||
score_func (ScoreFuncType): Score transform. ``topk_softmax`` selects experts from the logits
|
||||
and normalizes only the selected logits. ``sqrtsoftplus`` is DeepSeek V4's ``sqrt(softplus(.))``.
|
||||
route_norm (bool): Whether to normalize the routing scores when using sigmoid.
|
||||
route_scale (float): Scaling factor applied to the routing scores.
|
||||
gate_bias (bool): Whether the gate has a trainable logit bias.
|
||||
@@ -151,7 +151,7 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: Literal["softmax", "sigmoid", "topk_softmax"],
|
||||
score_func: ScoreFuncType,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
*,
|
||||
@@ -214,6 +214,8 @@ class TokenChoiceTopKRouter(nn.Module):
|
||||
scores = F.softmax(logits.float(), dim=1)
|
||||
elif self.score_func == "topk_softmax":
|
||||
scores = logits
|
||||
elif self.score_func == "sqrtsoftplus":
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown score function {self.score_func}")
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
|
||||
__all__ = ["RMSNorm", "RMSNormConfig"]
|
||||
@@ -176,15 +176,15 @@ def substitute_ulysses_attn(
|
||||
|
||||
# Resolve flash kernel + version from attn_impl.
|
||||
if attn_impl == "flash_attention_4":
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_4_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
elif attn_impl == "flash_attention_3":
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_3_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 3
|
||||
else:
|
||||
from flash_attn import flash_attn_varlen_func as flash_fn
|
||||
from prime_rl.trainer.models.layers.attn import flash_attn_2_varlen_op as flash_fn
|
||||
|
||||
flash_attn_version = 2
|
||||
|
||||
|
||||
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
|
||||
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
cu_seqlens,
|
||||
|
||||
@@ -6,9 +6,9 @@ from torch import nn
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPooling
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
flash_attn_varlen_func,
|
||||
flash_attn_2_varlen_op,
|
||||
flash_attn_3_varlen_op,
|
||||
flash_attn_4_varlen_op,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.trainer.models.qwen3_5.configuration_qwen3_5 import Qwen3_5VisionConfig
|
||||
@@ -69,9 +69,9 @@ class Qwen3_5VisionMLP(nn.Module):
|
||||
|
||||
class Qwen3_5VisionAttention(nn.Module):
|
||||
FLASH_ATTENTION_FUNCTIONS = {
|
||||
"flash_attention_2": flash_attn_varlen_func,
|
||||
"flash_attention_3": flash_attn_3_varlen_func,
|
||||
"flash_attention_4": flash_attn_4_varlen_func,
|
||||
"flash_attention_2": flash_attn_2_varlen_op,
|
||||
"flash_attention_3": flash_attn_3_varlen_op,
|
||||
"flash_attention_4": flash_attn_4_varlen_op,
|
||||
}
|
||||
|
||||
def __init__(self, config: Qwen3_5VisionConfig) -> None:
|
||||
|
||||
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -112,7 +112,7 @@ class ParallelDims:
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
# Mesh for data loading and per-step token counts
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
@@ -172,7 +172,7 @@ class ParallelDims:
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
# Mesh for data loading (no communication on this mesh)
|
||||
# Mesh for data loading and per-step token counts
|
||||
dp_mesh_dim_names = []
|
||||
# Mesh for param sharding
|
||||
dp_shard_cp_mesh_dim_names = []
|
||||
@@ -263,13 +263,6 @@ class ParallelDims:
|
||||
def non_data_parallel_size(self):
|
||||
return self.cp * self.pp
|
||||
|
||||
@cached_property
|
||||
def seq_len_divisor(self):
|
||||
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
|
||||
# when load balancing is enabled (by default).
|
||||
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
|
||||
return self.cp * 2
|
||||
|
||||
@cached_property
|
||||
def logger(self):
|
||||
return get_logger()
|
||||
@@ -309,7 +302,7 @@ def resolve_ep(config: ModelConfig) -> None:
|
||||
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
|
||||
|
||||
|
||||
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
|
||||
def get_parallel_dims(config: ModelConfig) -> ParallelDims:
|
||||
assert isinstance(config.ep, int), (
|
||||
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
|
||||
"Call resolve_ep(config) first."
|
||||
@@ -325,12 +318,4 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
|
||||
world_size=dist.get_world_size(),
|
||||
)
|
||||
|
||||
# Validate sequence length against parallel dimensions requirements
|
||||
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
|
||||
raise ValueError(
|
||||
f"Sequence length ({seq_len}) must be divisible by "
|
||||
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
|
||||
f"This requirement comes from context parallel (CP={config.cp})."
|
||||
)
|
||||
|
||||
return parallel_dims
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -7,6 +7,8 @@ from jaxtyping import Bool, Float, Int
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.multimodal import ForwardPolicy, MultimodalAdapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transports.batch import (
|
||||
BatchReceiver,
|
||||
@@ -47,8 +49,11 @@ class TensorMicroBatch(TypedDict):
|
||||
# maximum mask size. A row containing only -1 has no mask.
|
||||
sampling_mask: Int[Tensor, "batch seq mask"] | None
|
||||
|
||||
# Materialized immediately before this microbatch's forward pass.
|
||||
# Multimodal inputs. The data loader sets mm_refs (undecoded image references), and prepare_micro_batch
|
||||
# replaces them with mm_kwargs (CPU tensors for the vision encoder) and mm_forward_policy.
|
||||
mm_refs: MMRefs | None
|
||||
mm_kwargs: NotRequired[dict[str, Tensor] | None]
|
||||
mm_forward_policy: NotRequired[ForwardPolicy | None]
|
||||
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None
|
||||
|
||||
@@ -172,6 +177,23 @@ class FakeDataLoader:
|
||||
}
|
||||
|
||||
|
||||
def prepare_micro_batch(
|
||||
micro_batch: TensorMicroBatch, processor: Any | None, mm_adapter: MultimodalAdapter | None
|
||||
) -> TensorMicroBatch:
|
||||
"""Prepare a micro batch for the training loop. Currently only multimodal samples need preparation."""
|
||||
micro_batch["mm_kwargs"] = None
|
||||
micro_batch["mm_forward_policy"] = None
|
||||
mm_refs = micro_batch.get("mm_refs")
|
||||
if mm_refs is not None:
|
||||
if processor is None or mm_adapter is None:
|
||||
raise ValueError("Received multimodal samples but [model.vlm] is not set")
|
||||
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
|
||||
micro_batch["mm_kwargs"] = materialized.kwargs
|
||||
micro_batch["mm_forward_policy"] = materialized.forward_policy
|
||||
micro_batch["mm_refs"] = None
|
||||
return micro_batch
|
||||
|
||||
|
||||
class DataLoader:
|
||||
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
|
||||
|
||||
from contextlib import nullcontext
|
||||
from functools import partial
|
||||
import time
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
@@ -17,7 +18,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer
|
||||
from prime_rl.trainer.scheduler import setup_scheduler
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader, prepare_micro_batch
|
||||
from prime_rl.utils.cp import (
|
||||
gather_for_cp,
|
||||
gather_for_cp_wo_grad,
|
||||
@@ -37,7 +38,6 @@ from prime_rl.trainer.rl.loss import (
|
||||
shift_tensor_right,
|
||||
)
|
||||
from prime_rl.multimodal import get_multimodal_adapter
|
||||
from prime_rl.trainer.multimodal import materialize_mm_refs
|
||||
from prime_rl.trainer.rl.annotations import AnnotationWriter
|
||||
from prime_rl.trainer.model import (
|
||||
forward,
|
||||
@@ -71,6 +71,7 @@ from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl import monitors
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.worker_pool import WorkerPool
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@@ -147,6 +148,8 @@ def train(config: TrainerConfig):
|
||||
if processor is None:
|
||||
raise ValueError("Multimodal training requires a model image processor")
|
||||
mm_adapter = get_multimodal_adapter(model.config.model_type)
|
||||
prepare = partial(prepare_micro_batch, processor=processor, mm_adapter=mm_adapter)
|
||||
micro_batch_workers = WorkerPool(config.data.num_workers)
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
@@ -336,7 +339,9 @@ def train(config: TrainerConfig):
|
||||
cp_size = parallel_dims.cp
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
step_local_num_tokens = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
|
||||
step_local_num_tokens += micro_batch["input_ids"].shape[1]
|
||||
input_ids = micro_batch["input_ids"].to("cuda")
|
||||
position_ids = micro_batch["position_ids"].to("cuda")
|
||||
advantages = micro_batch["advantages"].to("cuda")
|
||||
@@ -365,17 +370,10 @@ def train(config: TrainerConfig):
|
||||
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
|
||||
)
|
||||
|
||||
mm_kwargs = None
|
||||
mm_forward_policy = None
|
||||
mm_refs = micro_batch.get("mm_refs")
|
||||
if mm_refs is not None:
|
||||
if processor is None or mm_adapter is None:
|
||||
raise ValueError("Received multimodal samples but [model.vlm] is not set")
|
||||
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
|
||||
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
|
||||
mm_forward_policy = materialized.forward_policy
|
||||
micro_batch["mm_refs"] = None
|
||||
del materialized, mm_refs
|
||||
mm_kwargs = micro_batch.pop("mm_kwargs")
|
||||
if mm_kwargs is not None:
|
||||
mm_kwargs = {key: value.to("cuda") for key, value in mm_kwargs.items()}
|
||||
mm_forward_policy = micro_batch.pop("mm_forward_policy")
|
||||
mm_token_type_ids = (
|
||||
micro_batch["mm_token_type_ids"].to("cuda")
|
||||
if micro_batch.get("mm_token_type_ids") is not None
|
||||
@@ -631,9 +629,10 @@ def train(config: TrainerConfig):
|
||||
if is_moe_model:
|
||||
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
|
||||
|
||||
# Compute step metrics
|
||||
num_local_tokens = seq_len * batch_size
|
||||
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
|
||||
# The dp mesh excludes cp, whose ranks hold the same rows.
|
||||
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
|
||||
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
|
||||
num_tokens = global_num_tokens.item()
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += batch_size
|
||||
perf_counter = get_perf_counter(model, seq_len)
|
||||
@@ -732,6 +731,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
if gradient_manager is not None:
|
||||
gradient_manager.close()
|
||||
micro_batch_workers.close()
|
||||
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("RL trainer finished")
|
||||
|
||||
@@ -249,6 +249,13 @@ class RendererResolver:
|
||||
renderer = create_renderer(self.tokenizer, config)
|
||||
if self.processor is not None and hasattr(renderer, "_processor"):
|
||||
renderer._processor = self.processor
|
||||
if not getattr(renderer, "is_prefix_stable", False):
|
||||
get_logger().warning(
|
||||
f"SFT renderer {type(renderer).__name__} does not guarantee prefix stability. "
|
||||
"SFT renders each conversation once to produce one training sample; "
|
||||
"it does not expand N assistant turns into N samples. Depending on the template, "
|
||||
"reasoning from earlier turns may be omitted from the training sample."
|
||||
)
|
||||
self.renderers[config] = renderer
|
||||
return renderer
|
||||
|
||||
@@ -279,7 +286,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
# Default names are optional: a dataset carries either messages or
|
||||
# prompt/completion, and tools only for tool use. A name set in the
|
||||
# config must exist.
|
||||
for field in ("messages", "prompt", "completion", "tools"):
|
||||
for field in ("messages", "prompt", "completion", "tools", "message_loss_mask"):
|
||||
column = getattr(columns, field)
|
||||
if column != field and column not in dataset.column_names:
|
||||
raise ValueError(f"data.columns.{field} is {column!r}, but the dataset has only {dataset.column_names}")
|
||||
@@ -342,9 +349,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
# Defer to the renderer's sampled_mask by default: a role filter would
|
||||
# drop sampled stop markers attributed to the next message (e.g. GLM's
|
||||
# turn-closing <|user|> / <|observation|>).
|
||||
# Let the renderer identify sampled targets when assistant loss is enabled.
|
||||
role_to_mask = None if self.loss_mask_config.assistant else should_mask
|
||||
|
||||
# Non-assistant roles are opted into the loss via the renderer's
|
||||
@@ -359,6 +364,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
tools=tools,
|
||||
content_sft_roles=content_sft_roles or None,
|
||||
ensure_final_stop=True,
|
||||
message_loss_mask=example.get(self.columns.message_loss_mask),
|
||||
)
|
||||
input_ids = list(sample.token_ids)
|
||||
loss_mask = list(sample.loss_mask)
|
||||
@@ -474,12 +480,13 @@ class SFTDataset(StatefulIterableDataset):
|
||||
|
||||
|
||||
class CatDataset(StatefulIterableDataset):
|
||||
"""Concatenate text and multimodal samples into one fixed-length row."""
|
||||
"""Pack samples into rows of at most `seq_len` tokens, padded to a multiple of `pad_to_multiple_of`."""
|
||||
|
||||
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
|
||||
def __init__(self, dataset: StatefulIterableDataset, seq_len: int, pad_to_multiple_of: int):
|
||||
self.logger = get_logger()
|
||||
self.dataset = dataset
|
||||
self.seq_len = seq_len
|
||||
self.pad_to_multiple_of = pad_to_multiple_of
|
||||
self.pending_sample: Sample | None = None
|
||||
|
||||
def state_dict(self) -> dict:
|
||||
@@ -583,7 +590,7 @@ class CatDataset(StatefulIterableDataset):
|
||||
if kept > 0:
|
||||
result["seq_lens"].append(kept)
|
||||
remaining -= kept
|
||||
pad_len = seq_len - len(result["input_ids"])
|
||||
pad_len = -len(result["input_ids"]) % self.pad_to_multiple_of
|
||||
if pad_len > 0:
|
||||
result["input_ids"].extend([0] * pad_len)
|
||||
result["position_ids"].extend(range(pad_len))
|
||||
@@ -753,8 +760,8 @@ def setup_dataset(
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
|
||||
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size)
|
||||
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig, cp: int) -> StatefulDataLoader:
|
||||
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size, pad_to_multiple_of=cp)
|
||||
return StatefulDataLoader(
|
||||
packing_dataset,
|
||||
batch_size=1,
|
||||
|
||||
@@ -113,7 +113,7 @@ def train(config: SFTConfig):
|
||||
resolve_ep(config.model)
|
||||
|
||||
# Initialize parallel dimensions
|
||||
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
|
||||
parallel_dims = get_parallel_dims(config.model)
|
||||
|
||||
total_micro_batches = config.data.batch_size * config.model.cp
|
||||
micro_batches_per_step = world.world_size * config.data.micro_batch_size
|
||||
@@ -192,7 +192,7 @@ def train(config: SFTConfig):
|
||||
processor=processor,
|
||||
multimodal=multimodal,
|
||||
)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataloader = setup_dataloader(dataset, config.data, config.model.cp)
|
||||
|
||||
val_raw_dataset = None
|
||||
if config.val is not None:
|
||||
@@ -257,7 +257,7 @@ def train(config: SFTConfig):
|
||||
|
||||
if cp_enabled:
|
||||
# CP requires the sequence length to be divisible by cp_size. CatDataset
|
||||
# pads every pack to seq_len; shard_for_cp raises on violations.
|
||||
# pads every pack to a multiple of it; shard_for_cp raises on violations.
|
||||
defer_vlm_cp_to_model = (
|
||||
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
|
||||
)
|
||||
@@ -345,7 +345,7 @@ def train(config: SFTConfig):
|
||||
processor=processor,
|
||||
multimodal=multimodal,
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data, config.model.cp)
|
||||
|
||||
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
|
||||
mean_loss, nan_count = run_eval_loop(val_dataloader)
|
||||
@@ -451,7 +451,9 @@ def train(config: SFTConfig):
|
||||
)
|
||||
|
||||
step_tokens_per_expert = 0
|
||||
step_local_num_tokens = 0
|
||||
for micro_step, micro_batch in enumerate(micro_batches):
|
||||
step_local_num_tokens += micro_batch["input_ids"].shape[1]
|
||||
if config.log.log_data:
|
||||
print_sample(
|
||||
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
|
||||
@@ -549,14 +551,10 @@ def train(config: SFTConfig):
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
|
||||
# Compute step metrics. CP shards the same sequences across cp ranks
|
||||
# (sequence-sharded data parallelism on the seq dim), so the unique
|
||||
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
|
||||
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
|
||||
# the RL trainer's accounting (rl/train.py).
|
||||
dp_size = parallel_dims.get_mesh("dp").size()
|
||||
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
|
||||
num_tokens = dp_size * num_local_tokens
|
||||
# The dp mesh excludes cp, whose ranks hold the same rows.
|
||||
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
|
||||
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
|
||||
num_tokens = global_num_tokens.item()
|
||||
progress.total_tokens += num_tokens
|
||||
dataset_progress = get_dataset_progress(dataloader)
|
||||
progress.total_samples = dataset_progress["step"]
|
||||
|
||||
@@ -153,7 +153,7 @@ class WeightReceiver(ABC):
|
||||
while not sender_ready.exists():
|
||||
if cancelled is not None and cancelled():
|
||||
raise asyncio.CancelledError
|
||||
await asyncio.sleep(0.2)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
def _ack(self, step: int) -> None:
|
||||
"""Acknowledge the offered version — unblocks the waiting trainer."""
|
||||
|
||||
@@ -143,11 +143,12 @@ def setup_logger(
|
||||
if json_logging and tag:
|
||||
logger = logger.bind(tag=tag)
|
||||
|
||||
# diagnose=False: repr()-ing frame locals that hold multi-GB tensors makes a crash look like a hang.
|
||||
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
|
||||
if json_logging:
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True)
|
||||
logger.add(json_sink, level=(console_level or log_level).upper(), enqueue=True, diagnose=False)
|
||||
else:
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True)
|
||||
logger.add(sys.stdout, format=format, level=(console_level or log_level).upper(), colorize=True, diagnose=False)
|
||||
if log_file is not None:
|
||||
# The console format carries raw ANSI codes; the file gets a plain layout.
|
||||
logger.add(
|
||||
@@ -155,6 +156,7 @@ def setup_logger(
|
||||
format="{time:HH:mm:ss} {level: >7} " + f"{tag_prefix}{{message}}",
|
||||
level=log_level.upper(),
|
||||
colorize=False,
|
||||
diagnose=False,
|
||||
)
|
||||
|
||||
# Disable critical logging
|
||||
|
||||
@@ -22,6 +22,8 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
|
||||
"PYTHONUNBUFFERED": "1",
|
||||
"OMP_NUM_THREADS": "1",
|
||||
"GIT_LFS_SKIP_SMUDGE": "1",
|
||||
# Processes sharing ~/.triton on a shared FS hang or crash. Per-user because /tmp is shared by all users.
|
||||
"TRITON_CACHE_DIR": f"/tmp/triton-{os.getuid()}",
|
||||
}
|
||||
|
||||
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import TypeVar
|
||||
|
||||
T = TypeVar("T")
|
||||
R = TypeVar("R")
|
||||
|
||||
|
||||
class WorkerPool:
|
||||
"""Persistent background threads that map a function over an iterator in order, or the calling thread when ``num_workers`` is 0.
|
||||
|
||||
``map_fn`` runs concurrently on up to ``num_workers`` threads, so it must be thread-safe.
|
||||
"""
|
||||
|
||||
def __init__(self, num_workers: int):
|
||||
self.num_workers = num_workers
|
||||
self.executor: ThreadPoolExecutor | None = None
|
||||
if num_workers > 0:
|
||||
# Threads share the trainer's memory, so items and results pass by reference: no pickling,
|
||||
# no /dev/shm copies, and no forked copy-on-write memory, unlike worker processes.
|
||||
self.executor = ThreadPoolExecutor(max_workers=num_workers, thread_name_prefix="worker-pool")
|
||||
|
||||
def __call__(self, map_fn: Callable[[T], R], items: Iterable[T]) -> Iterator[R]:
|
||||
"""Yield ``map_fn(item)`` in input order, with at most ``2 * num_workers`` items submitted but not yet yielded.
|
||||
|
||||
The factor 2 plays the role of torch DataLoader's ``prefetch_factor`` (batches loaded ahead per worker),
|
||||
hard-coded to its torch default for simplicity. Any bound above ``num_workers`` keeps every worker busy while
|
||||
the caller holds a result; the extra slack absorbs items that take unusually long.
|
||||
"""
|
||||
if self.executor is None:
|
||||
yield from map(map_fn, items)
|
||||
return
|
||||
max_in_flight = 2 * self.num_workers
|
||||
pending: deque[Future[R]] = deque()
|
||||
try:
|
||||
for item in items:
|
||||
pending.append(self.executor.submit(map_fn, item))
|
||||
if len(pending) >= max_in_flight:
|
||||
yield pending.popleft().result()
|
||||
while pending:
|
||||
yield pending.popleft().result()
|
||||
finally:
|
||||
for future in pending:
|
||||
future.cancel()
|
||||
|
||||
def close(self) -> None:
|
||||
if self.executor is not None:
|
||||
self.executor.shutdown(cancel_futures=True)
|
||||
|
||||
def __enter__(self) -> "WorkerPool":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc_info: object) -> None:
|
||||
self.close()
|
||||
@@ -1,6 +1,5 @@
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Callable, Generator
|
||||
@@ -46,14 +45,6 @@ def cleanup_zombies():
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def free_port() -> int:
|
||||
"""Fixture to get a free port per tests"""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def user() -> str:
|
||||
"""Fixture for current user from environment for test session."""
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
import orjson
|
||||
import pytest
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ValidationError
|
||||
from verifiers.v1.utils.eval import plan_rollouts
|
||||
|
||||
from prime_rl.eval import resume
|
||||
from prime_rl.monitors.file.traces import get_trace_stream
|
||||
@@ -21,6 +26,7 @@ def _env(name: str, task_keys: list[str], *, group_size: int = 1) -> SimpleNames
|
||||
|
||||
def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) -> dict:
|
||||
return {
|
||||
"id": uuid.uuid4().hex,
|
||||
"env": {"id": env, "name": env},
|
||||
"task": {"type": "Task", "data": {"idx": 0}, "key": key, "hash": key},
|
||||
"group": {"id": group or f"group-{key}"},
|
||||
@@ -29,38 +35,64 @@ def _record(env: str, key: str, *, ok: bool = True, group: str | None = None) ->
|
||||
}
|
||||
|
||||
|
||||
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest() -> None:
|
||||
envs = [_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])]
|
||||
landed = [
|
||||
_record("math", "m0"),
|
||||
_record("math", "m0"),
|
||||
_record("math", "m0"), # a third rollout of m0 exceeds group_size 2
|
||||
_record("math", "m1"),
|
||||
_record("math", "m9"), # no longer selected (select.limit shrank)
|
||||
_record("code", "c0", ok=False), # errored: owed again
|
||||
]
|
||||
@pytest.mark.parametrize(
|
||||
"hashes,rollouts,landed,expected_kept,expected_missing",
|
||||
[
|
||||
(["a", "b"], 2, [], [[], []], [2, 2]),
|
||||
(["a"], 1, [("e1", "a")], [["e1"]], [0]),
|
||||
(["changed"], 1, [("e1", "a")], [[]], [1]),
|
||||
(["a"], 3, [("e1", "a"), ("e2", "a")], [["e1", "e2"]], [1]),
|
||||
(["a"], 1, [("e1", "a"), ("e2", "a")], [["e1"]], [0]),
|
||||
(["a", "a"], 2, [("e1", "a")], [["e1"], []], [1, 2]),
|
||||
(["a", "changed"], 1, [("e1", "a"), ("e2", "a")], [["e1"], []], [0, 1]),
|
||||
(["a"], 2, [("e1", "a"), ("e1", "a")], [["e1"]], [1]),
|
||||
(["a"], 1, [("e1", "removed")], [[]], [1]),
|
||||
([], 1, [("e1", "a")], [], []),
|
||||
],
|
||||
)
|
||||
def test_plan_keeps_landed_rollouts_up_to_the_target_and_owes_the_rest(
|
||||
hashes, rollouts, landed, expected_kept, expected_missing
|
||||
) -> None:
|
||||
tasks = [SimpleNamespace(key="stable-key", hash=content_hash) for content_hash in hashes]
|
||||
episodes = []
|
||||
for episode_id, content_hash in landed:
|
||||
row = _record("math", "stable-key")
|
||||
row["id"] = episode_id
|
||||
row["task"]["hash"] = content_hash
|
||||
episodes.append(vf.WireEpisode.model_validate(row))
|
||||
|
||||
kept, owed, groups = resume.plan([record for record in landed if record["ok"]], envs)
|
||||
plan = plan_rollouts(tasks, rollouts, episodes)
|
||||
|
||||
assert [(episode.env.name, episode.task.key) for episode in kept] == [
|
||||
("math", "m0"),
|
||||
("math", "m0"),
|
||||
("math", "m1"),
|
||||
]
|
||||
assert owed == {"math": {"m1": 1, "m2": 2}, "code": {"c0": 1}}
|
||||
# the owed rollout of m1 completes the group its landed rollout opened
|
||||
assert groups == {"math": {"m0": "group-m0", "m1": "group-m1"}}
|
||||
assert [task for task, _, _ in plan] == tasks
|
||||
assert [[episode.id for episode in kept] for _, kept, _ in plan] == expected_kept
|
||||
assert [missing for _, _, missing in plan] == expected_missing
|
||||
assert all(len(kept) + missing == rollouts for _, kept, missing in plan)
|
||||
|
||||
|
||||
def test_trigger_queues_only_owed_rollouts() -> None:
|
||||
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2), _env("code", ["c0"])])
|
||||
source.restore({"math": {"m1": 1, "m2": 2}, "code": {}}, {"math": {"m1": "group-m1"}})
|
||||
source = EvalSource([_env("math", ["m0", "m1", "m1"], group_size=2), _env("code", ["m1"])])
|
||||
episodes = [vf.WireEpisode.model_validate(_record("math", key)) for key in ["m0", "m0", "m1"]]
|
||||
|
||||
assert source.trigger(0) == ["math", "code"]
|
||||
assert [(request.env_name, request.task.key, request.rollouts, request.group_id) for request in source.queue] == [
|
||||
("math", "m1", 1, "group-m1"),
|
||||
("math", "m2", 2, None),
|
||||
fired, restored = source.trigger(0, completed=episodes)
|
||||
|
||||
assert fired == ["math", "code"]
|
||||
requests = list(source.queue)
|
||||
assert [(request.env_name, request.task.key, request.rollouts) for request in requests] == [
|
||||
("code", "m1", 1),
|
||||
("math", "m1", 1),
|
||||
("math", "m1", 2),
|
||||
]
|
||||
assert restored == episodes
|
||||
assert len({request.group_id for request in requests}) == 3
|
||||
assert restored[-1].group.id == requests[1].group_id
|
||||
assert restored[0].group == restored[1].group
|
||||
assert restored[0].group != restored[-1].group
|
||||
assert all(str(uuid.UUID(request.group_id)) == request.group_id for request in requests)
|
||||
|
||||
# Saved episodes affect only this epoch; later triggers plan every rollout again.
|
||||
source.queue.clear()
|
||||
assert source.trigger(1) == (["math", "code"], [])
|
||||
assert [request.rollouts for request in source.queue] == [2, 1, 2, 2]
|
||||
|
||||
|
||||
def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
|
||||
@@ -71,11 +103,39 @@ def test_take_landed_reads_every_attempt_once(tmp_path) -> None:
|
||||
stream.close()
|
||||
|
||||
land("m0", "m1")
|
||||
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1"]
|
||||
assert [episode.id for episode in resume.take_landed(tmp_path)] == ["m0", "m1"]
|
||||
assert not get_file_monitor_dir(tmp_path).exists()
|
||||
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1"]
|
||||
|
||||
# the resumed attempt re-logged one episode and landed a new one before it died
|
||||
land("m0", "m2")
|
||||
assert [record["id"] for record in resume.take_landed(tmp_path)] == ["m0", "m1", "m2"]
|
||||
landed = resume.take_landed(tmp_path)
|
||||
source = EvalSource([_env("math", ["m0", "m1", "m2"], group_size=2)])
|
||||
_, kept = source.trigger(0, completed=landed)
|
||||
assert [episode.id for episode in kept] == ["m0", "m1", "m2"]
|
||||
assert [request.rollouts for request in source.queue] == [1, 1, 1]
|
||||
assert [path.name for path in resume.archives(tmp_path)] == ["file.attempt_1", "file.attempt_2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ok", [True, False])
|
||||
@pytest.mark.parametrize("traces,valid", [([], True), (None, False), ([{}], False)])
|
||||
def test_resume_validates_saved_episodes(tmp_path, ok, traces, valid) -> None:
|
||||
record = {**_record("math", "m0", ok=ok), "id": "saved", "traces": traces}
|
||||
stream = ChunkedJsonl(get_trace_stream(tmp_path), max_bytes=1 << 20, compress=False)
|
||||
for row in [{key: value for key, value in record.items() if key != "traces"}, record]:
|
||||
stream.append(orjson.dumps(row, option=orjson.OPT_APPEND_NEWLINE))
|
||||
stream.close()
|
||||
|
||||
if not valid:
|
||||
with pytest.raises(ValidationError):
|
||||
resume.take_landed(tmp_path)
|
||||
assert get_file_monitor_dir(tmp_path).is_dir()
|
||||
assert resume.archives(tmp_path) == []
|
||||
return
|
||||
|
||||
landed = resume.take_landed(tmp_path)
|
||||
source = EvalSource([_env("math", ["m0"], group_size=2)])
|
||||
_, restored = source.trigger(0, completed=landed)
|
||||
|
||||
assert [episode.id for episode in restored] == (["saved"] if ok else [])
|
||||
assert [request.rollouts for request in source.queue] == [1 if ok else 2]
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers.deepseek_v4_encoding import encode_messages
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_request_tools_placement
|
||||
|
||||
|
||||
class _StubTokenizer:
|
||||
def get_added_vocab(self):
|
||||
return {}
|
||||
|
||||
def encode(self, text, **_kwargs):
|
||||
return text
|
||||
|
||||
|
||||
def _request_tools():
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get weather for a city",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def _tokenizer():
|
||||
from vllm.tokenizers import deepseek_v4
|
||||
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
return deepseek_v4.get_deepseek_v4_tokenizer(_StubTokenizer())
|
||||
|
||||
|
||||
def _render(messages, tools):
|
||||
return _tokenizer().apply_chat_template(
|
||||
messages,
|
||||
tools=tools,
|
||||
tokenize=False,
|
||||
thinking=True,
|
||||
reasoning_effort="low",
|
||||
)
|
||||
|
||||
|
||||
def _reference(messages):
|
||||
return encode_messages(messages, thinking_mode="thinking", reasoning_effort="low")
|
||||
|
||||
|
||||
def test_request_tools_attach_to_first_existing_system_without_mutation():
|
||||
messages = [
|
||||
{"role": "user", "content": "This may precede the system message."},
|
||||
{"role": "system", "content": "You are helpful.", "tools": []},
|
||||
{"role": "system", "content": "A later system message."},
|
||||
{"role": "user", "content": "Weather in Paris?"},
|
||||
]
|
||||
snapshot = copy.deepcopy(messages)
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
expected_messages = messages.copy()
|
||||
expected_messages[1] = {**messages[1], "tools": tools}
|
||||
assert prompt == _reference(expected_messages)
|
||||
assert prompt.count("## Tools") == 1
|
||||
assert messages == snapshot
|
||||
|
||||
|
||||
def test_request_tools_synthesize_system_only_when_none_exists():
|
||||
messages = [{"role": "user", "content": "Weather in Paris?"}]
|
||||
tools = _request_tools()
|
||||
|
||||
prompt = _render(messages, tools)
|
||||
|
||||
assert prompt == _reference([{"role": "system", "tools": tools}, *messages])
|
||||
@@ -110,6 +110,7 @@ def _build_episode(
|
||||
task=trace.task,
|
||||
group=vf.GroupInfo(id="group"),
|
||||
traces=[trace],
|
||||
ok=True,
|
||||
)
|
||||
return episode
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
|
||||
|
||||
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
|
||||
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
|
||||
from prime_rl.orchestrator.algo.base import iter_trainable_traces
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.transports.batch.types import TrainingSample
|
||||
|
||||
@@ -201,10 +202,33 @@ def _make_episode() -> vf.Episode:
|
||||
task=trace.task,
|
||||
group=vf.GroupInfo(id="group"),
|
||||
traces=[trace],
|
||||
ok=True,
|
||||
)
|
||||
return episode
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", ["participant", "untrainable_participant", "environment"])
|
||||
def test_trainable_traces_exclude_failed_episodes_without_changing_verdicts(failure):
|
||||
good = _make_episode()
|
||||
good.errors = [vf.Error(type="RecoveredError", message="Previous attempt failed")]
|
||||
good.traces[0].errors = list(good.errors)
|
||||
failed = _make_episode()
|
||||
failed.ok = False
|
||||
if failure == "environment":
|
||||
failed.errors = [vf.Error(type="EnvError", message="Finalization failed")]
|
||||
else:
|
||||
sibling = failed.traces[0].model_copy(deep=True)
|
||||
sibling.id = "failed-sibling"
|
||||
sibling.ok = False
|
||||
sibling.errors = [vf.Error(type="AgentError", message="Participant failed")]
|
||||
sibling.agent.trainable = failure == "participant"
|
||||
failed.traces.append(sibling)
|
||||
before = failed.model_dump()
|
||||
|
||||
assert list(iter_trainable_traces([failed, good])) == [(good, good.traces[0])]
|
||||
assert failed.model_dump() == before
|
||||
|
||||
|
||||
def test_assign_advantages_full_length_stream():
|
||||
# The advantage stream is full-length-N: 0.0 on prompt + non-trainable
|
||||
# positions, the rl credit on trainable (mask True) tokens.
|
||||
|
||||
@@ -93,6 +93,8 @@ def test_setup_client_creates_renderer_client():
|
||||
base_url="http://worker-a:8000/v1",
|
||||
api_key_var="PRIME_API_KEY",
|
||||
headers={"X-Test": "test"},
|
||||
headers_from_env={"X-Token": "PROVIDER_TOKEN"},
|
||||
timeout={"read": 12},
|
||||
)
|
||||
|
||||
renderer_settings = Qwen3VLRendererConfig()
|
||||
@@ -108,6 +110,8 @@ def test_setup_client_creates_renderer_client():
|
||||
assert client.base_url == "http://worker-a:8000/v1"
|
||||
assert "X-data-parallel-rank" not in client.headers
|
||||
assert client.headers["X-Test"] == "test"
|
||||
assert client.headers_from_env == {"X-Token": "PROVIDER_TOKEN"}
|
||||
assert client.timeout.read == 12
|
||||
|
||||
|
||||
def test_check_health_retries_non_success_status():
|
||||
|
||||
@@ -42,7 +42,7 @@ def make_rollout(
|
||||
)
|
||||
]
|
||||
if advantages is not None
|
||||
else []
|
||||
else [vf.MessageNode(message=vf.AssistantMessage(content="answer"), sampled=True)]
|
||||
)
|
||||
trace = vf.Trace(
|
||||
task=vf.TraceTask(
|
||||
@@ -61,6 +61,7 @@ def make_rollout(
|
||||
task=trace.task,
|
||||
group=vf.GroupInfo(id=str(uuid.uuid4())),
|
||||
traces=[trace],
|
||||
ok=True,
|
||||
)
|
||||
return [episode]
|
||||
|
||||
@@ -111,7 +112,12 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
|
||||
source = TrainSource([env])
|
||||
|
||||
sampled = source.next_task(step=1).task
|
||||
assert source.on_result(make_rollout(sampled, reward=0.25, advantages=[0.0])) is False
|
||||
empty = make_rollout(sampled, reward=1.0)
|
||||
empty[0].traces[0].nodes[0].sampled = False
|
||||
group = make_rollout(sampled, reward=0.25, advantages=[0.0])
|
||||
failed = make_rollout(sampled, reward=1.0, advantages=[1.0])
|
||||
failed[0].ok = False
|
||||
assert source.on_result(group + failed + empty) is False
|
||||
assert source.metrics() == {
|
||||
"curriculum/test/admission_rate": 0.0,
|
||||
"curriculum/test/sampler/pool/unseen": 2.0,
|
||||
@@ -127,6 +133,19 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
|
||||
"admit": {},
|
||||
}
|
||||
|
||||
assert source.on_result(empty) is False
|
||||
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
|
||||
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.25}
|
||||
|
||||
# A scored rollout without token metadata still informs task difficulty.
|
||||
assert source.on_result(make_rollout(sampled, reward=0.5)) is False
|
||||
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
|
||||
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.5}
|
||||
|
||||
assert source.on_result(make_rollout(sampled, reward=0.75, advantages=[1.0])) is True
|
||||
assert source.metrics()["curriculum/test/admission_rate"] == 1.0
|
||||
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.75}
|
||||
|
||||
|
||||
def test_difficulty_pools_stack_with_advantage_gate_and_resume_sampling() -> None:
|
||||
tasks = [make_task(i) for i in range(3)]
|
||||
|
||||
+132
-4
@@ -4,6 +4,7 @@ from typing import Annotated, Literal, get_args
|
||||
|
||||
import pytest
|
||||
import tomli_w
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import BaseModel, Field, ValidationError
|
||||
from pydantic_config import ConfigFileError
|
||||
from renderers import custom_renderer_config
|
||||
@@ -17,6 +18,10 @@ from prime_rl.configs.orchestrator import (
|
||||
RLOnlineEvalConfig,
|
||||
ScheduledEvalConfig,
|
||||
TrainConfig,
|
||||
TrainSourceConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
ModelConfig as OrchestratorModelConfig,
|
||||
)
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
@@ -340,6 +345,16 @@ def test_moe_router_dtype_auto_resolves_per_trainer():
|
||||
assert config_cls.model_validate({"model": {"moe_router_dtype": dtype}}).model.moe_router_dtype == dtype
|
||||
|
||||
|
||||
def test_freeze_moe_router_auto_resolves_per_trainer():
|
||||
"""``freeze_moe_router='auto'`` (the default) freezes the router for RL, not SFT; explicit values are kept."""
|
||||
assert TrainerConfig.model_validate({}).model.freeze_moe_router is True
|
||||
assert SFTConfig.model_validate({}).model.freeze_moe_router is False
|
||||
|
||||
for config_cls in (TrainerConfig, SFTConfig):
|
||||
for freeze in (True, False):
|
||||
assert config_cls.model_validate({"model": {"freeze_moe_router": freeze}}).model.freeze_moe_router is freeze
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
|
||||
def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
|
||||
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
|
||||
@@ -393,6 +408,36 @@ def test_resolved_json_roundtrips_explicit_none(tmp_path):
|
||||
assert reloaded == config
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_class,source_args,expected_url,expected_key",
|
||||
[
|
||||
(
|
||||
EvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"https://configured.pinference.ai/api/v1",
|
||||
"PRIME_API_KEY",
|
||||
),
|
||||
(
|
||||
SFTOnlineEvalConfig,
|
||||
["--source", '[{"env":{"id":"single_agent"}}]'],
|
||||
"http://localhost:8000/v1",
|
||||
"VLLM_API_KEY",
|
||||
),
|
||||
(OrchestratorModelConfig, [], "http://localhost:8000/v1", "VLLM_API_KEY"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("overrides", [[], ["--client.skip-model-check"], ["--client.wait-for-ready-timeout", "10"]])
|
||||
def test_client_defaults_survive_partial_overrides(
|
||||
monkeypatch, config_class, source_args, expected_url, expected_key, overrides
|
||||
):
|
||||
monkeypatch.setenv("PRIME_INFERENCE_URL", "https://configured.pinference.ai/api/v1")
|
||||
config = cli(config_class, args=source_args + overrides)
|
||||
assert config.client.base_url == expected_url
|
||||
assert config.client.api_key_var == expected_key
|
||||
reloaded = config_class.model_validate_json(config.model_dump_json())
|
||||
assert reloaded.client == config.client
|
||||
|
||||
|
||||
def test_env_algo_inherits_the_group_algo():
|
||||
config = OrchestratorConfig.model_validate(
|
||||
{
|
||||
@@ -419,11 +464,25 @@ def test_env_algo_inherits_the_group_algo():
|
||||
assert [env.algo.type for env in reloaded.train.source] == ["grpo", "echo", "echo"]
|
||||
|
||||
|
||||
def test_sources_inherit_the_group_fields_they_leave_unset():
|
||||
@pytest.mark.parametrize("group_token_key", ["max_tokens", "max_completion_tokens"])
|
||||
@pytest.mark.parametrize("source_token_key", ["max_tokens", "max_completion_tokens"])
|
||||
@pytest.mark.parametrize("source_token_limit", [200, None])
|
||||
@pytest.mark.parametrize("nested_sampling", [False, True])
|
||||
def test_sources_inherit_the_group_fields_they_leave_unset(
|
||||
group_token_key, source_token_key, source_token_limit, nested_sampling
|
||||
):
|
||||
overrides = {source_token_key: source_token_limit, "top_k": 20}
|
||||
config = EvalConfig.model_validate(
|
||||
{
|
||||
"r": 4,
|
||||
"sampling": {"temperature": 0.5, "extra_body": {"a": 1}},
|
||||
"sampling": {
|
||||
group_token_key: 100,
|
||||
"temperature": 3.0,
|
||||
"reasoning_effort": "xhigh",
|
||||
"top_k": 40,
|
||||
"frequency_penalty": 0.5,
|
||||
"extra_body": {"a": 1},
|
||||
},
|
||||
"select": {"limit": 8, "include": {"idx": [":100"]}},
|
||||
"env": {"retries": {"max_retries": 3}},
|
||||
"source": [
|
||||
@@ -432,7 +491,11 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
|
||||
"name": "b",
|
||||
"env": {"taskset": {"id": "gsm8k"}},
|
||||
"group_size": 2,
|
||||
"sampling": {"extra_body": {"b": 2}},
|
||||
"sampling": {
|
||||
**({} if nested_sampling else overrides),
|
||||
"reasoning_effort": "max",
|
||||
"extra_body": {"b": 2, **(overrides if nested_sampling else {})},
|
||||
},
|
||||
"select": {"include": {"names": ["x"]}},
|
||||
},
|
||||
],
|
||||
@@ -440,7 +503,18 @@ def test_sources_inherit_the_group_fields_they_leave_unset():
|
||||
)
|
||||
a, b = config.source
|
||||
assert (a.group_size, b.group_size) == (4, 2)
|
||||
assert b.sampling.temperature == 0.5 and b.sampling.extra_body == {"a": 1, "b": 2}
|
||||
assert isinstance(a.sampling, vf.SamplingConfig) and isinstance(b.sampling, vf.SamplingConfig)
|
||||
assert a.sampling.max_tokens == 100 and b.sampling.max_tokens == source_token_limit
|
||||
assert a.sampling.reasoning_effort == "xhigh" and a.sampling.top_k == 40
|
||||
assert b.sampling.model_dump(exclude_none=True) == {
|
||||
**({"max_tokens": source_token_limit} if source_token_limit is not None else {}),
|
||||
"temperature": 3.0,
|
||||
"reasoning_effort": "max",
|
||||
"top_k": 20,
|
||||
"frequency_penalty": 0.5,
|
||||
"a": 1,
|
||||
"b": 2,
|
||||
}
|
||||
assert b.select.limit == 8 and b.select.include.idx == [":100"] and b.select.include.names == ["x"]
|
||||
assert a.env.retries.max_retries == 3 and b.env.retries.max_retries == 3
|
||||
reloaded = EvalConfig.model_validate(config.model_dump(mode="json"))
|
||||
@@ -521,6 +595,39 @@ def test_policy_sources_accept_different_top_p_values():
|
||||
assert [source.sampling.top_k for source in config.train.source] == [512, 512]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("frozen", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"sampling,agent_sampling,rejected",
|
||||
[
|
||||
({}, {}, False),
|
||||
({"top_p": 0.9}, {"max_completion_tokens": 200, "reasoning_effort": "high"}, False),
|
||||
({}, {"extra_body": {"chat_template_kwargs": {"enable_thinking": True}}}, False),
|
||||
({}, {"temperature": 1.0}, True),
|
||||
({}, {"temperature": None}, True),
|
||||
({}, {"extra_body": {"top_k": 20}}, True),
|
||||
({}, {"frequency_penalty": 0.5}, True),
|
||||
({}, {"extra_body": {"frequency_penalty": 0.5}}, True),
|
||||
({"extra_body": {"frequency_penalty": 0.5}}, {}, True),
|
||||
],
|
||||
)
|
||||
def test_policy_sampling_is_validated_before_rollouts(sampling, agent_sampling, rejected, frozen):
|
||||
source = {
|
||||
"env": {"taskset": {"id": "reverse-text"}, "agent": {"sampling": agent_sampling}},
|
||||
"sampling": sampling,
|
||||
}
|
||||
if frozen:
|
||||
source["algo"] = {
|
||||
"type": "sft",
|
||||
"sampling": {"source": {"name": "teacher", "base_url": "http://localhost:8000/v1"}},
|
||||
}
|
||||
if rejected and not frozen:
|
||||
with pytest.raises(ValidationError, match="sampling"):
|
||||
TrainSourceConfig.model_validate(source)
|
||||
else:
|
||||
config = TrainSourceConfig.model_validate(source)
|
||||
assert TrainSourceConfig.model_validate_json(config.model_dump_json()) == config
|
||||
|
||||
|
||||
def test_policy_sources_reject_mixed_top_k_capture():
|
||||
with pytest.warns(UserWarning, match="defaulting top_k"):
|
||||
with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"):
|
||||
@@ -561,10 +668,31 @@ def test_single_node_auto_inference_ports_follow_server_port():
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.vllm.data_parallel_size == 2
|
||||
assert config.trainer.weight_broadcast.inference_world_size == 2
|
||||
assert config.orchestrator.weight_broadcast.inference_world_size == 2
|
||||
assert config.inference.backend_port == 8101
|
||||
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
|
||||
|
||||
|
||||
def test_single_node_nccl_resolved_json_roundtrips(tmp_path):
|
||||
"""The resolved rl.json re-parses (as a SLURM launch does) to the same config."""
|
||||
import json
|
||||
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"vllm": {"tensor_parallel_size": 1}},
|
||||
"deployment": {"type": "single_node", "gpus_per_node": 4, "num_train_gpus": 2, "num_infer_gpus": 2},
|
||||
}
|
||||
)
|
||||
path = tmp_path / "rl.json"
|
||||
path.write_text(json.dumps(dump_resolved_config(config, exclude={"slurm", "dry_run", "clean"})))
|
||||
reloaded = cli(RLConfig, args=["@", str(path)])
|
||||
assert reloaded.trainer.weight_broadcast.inference_world_size == 2
|
||||
assert reloaded == config
|
||||
|
||||
|
||||
def test_multi_node_auto_inference_parallelism():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
|
||||
from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class AfmoeConfig(PretrainedConfig):
|
||||
"""
|
||||
n_group (`int`, *optional*, defaults to 1):
|
||||
Number of groups for routed experts.
|
||||
topk_group (`int`, *optional*, defaults to 1):
|
||||
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
||||
"""
|
||||
|
||||
model_type = "afmoe"
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_hidden_layers: int = 32,
|
||||
vocab_size: int = 200192,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 6144,
|
||||
moe_intermediate_size=1408,
|
||||
num_dense_layers=1,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=None,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=16384,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-5,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=10000.0,
|
||||
rope_scaling=None,
|
||||
num_experts=64,
|
||||
num_experts_per_tok=6,
|
||||
num_shared_experts=2,
|
||||
num_expert_groups=1,
|
||||
num_limited_groups=1,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
load_balance_coeff: float | None = None,
|
||||
use_grouped_mm: bool = True,
|
||||
global_attn_every_n_layers=4,
|
||||
sliding_window=1024,
|
||||
mup_enabled=False,
|
||||
layer_types=None,
|
||||
attention_dropout: float = 0.0,
|
||||
n_group: int = 1,
|
||||
topk_group: int = 1,
|
||||
pad_token_id: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_dense_layers = num_dense_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
|
||||
# MoE specific
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_group = n_group
|
||||
self.topk_group = topk_group
|
||||
self.num_experts = num_experts
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.num_expert_groups = num_expert_groups
|
||||
self.num_limited_groups = num_limited_groups
|
||||
self.score_func = score_func
|
||||
self.route_norm = route_norm
|
||||
self.route_scale = route_scale
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
# Attention specific
|
||||
self.attention_dropout = attention_dropout
|
||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||
self.sliding_window = sliding_window
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
self.layer_types = [
|
||||
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
|
||||
for i in range(self.num_hidden_layers)
|
||||
]
|
||||
layer_type_validation(self.layer_types)
|
||||
|
||||
# muP specific
|
||||
self.mup_enabled = mup_enabled
|
||||
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.pad_token_id = pad_token_id
|
||||
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["AfmoeConfig"]
|
||||
@@ -1,645 +0,0 @@
|
||||
from typing import Callable, Optional, Tuple, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from transformers.activations import ACT2FN
|
||||
from transformers.cache_utils import Cache, DynamicCache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.integrations import use_kernel_forward_from_hub
|
||||
from transformers.masking_utils import (
|
||||
create_causal_mask,
|
||||
create_sliding_window_causal_mask,
|
||||
)
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import (
|
||||
MoeCausalLMOutputWithPast,
|
||||
MoeModelOutputWithPast,
|
||||
)
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
try:
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
except:
|
||||
from configuration_afmoe import AfmoeConfig
|
||||
|
||||
|
||||
class AfmoeRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: AfmoeConfig, device=None):
|
||||
super().__init__()
|
||||
# BC: "rope_type" was originally "type"
|
||||
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
|
||||
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
self.rope_type = "default"
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
|
||||
self.config = config
|
||||
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
||||
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.original_inv_freq = self.inv_freq
|
||||
|
||||
def compute_default_rope_parameters(self, config=None, device=None, seq_len=None, layer_type=None):
|
||||
"""Required by transformers 5.0.0 for weight initialization when rope_type is 'default'."""
|
||||
cfg = config or self.config
|
||||
cfg.standardize_rope_params()
|
||||
rope_params = cfg.rope_parameters[layer_type] if layer_type is not None else cfg.rope_parameters
|
||||
base = rope_params["rope_theta"]
|
||||
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(cfg, "head_dim", None) or cfg.hidden_size // cfg.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
inv_freq = 1.0 / (
|
||||
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
||||
)
|
||||
return inv_freq, 1.0
|
||||
|
||||
def _dynamic_frequency_update(self, position_ids, device):
|
||||
"""
|
||||
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
||||
1 - growing beyond the cached sequence length (allow scaling)
|
||||
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
||||
"""
|
||||
seq_len = torch.max(position_ids) + 1
|
||||
if seq_len > self.max_seq_len_cached: # growth
|
||||
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = seq_len
|
||||
|
||||
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
||||
# This .to() is needed if the model has been moved to a device after being initialized (because
|
||||
# the buffer is automatically moved, but not the original copy)
|
||||
self.original_inv_freq = self.original_inv_freq.to(device)
|
||||
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
||||
self.max_seq_len_cached = self.original_max_seq_len
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, x, position_ids):
|
||||
if "dynamic" in self.rope_type:
|
||||
self._dynamic_frequency_update(position_ids, device=x.device)
|
||||
|
||||
# Core RoPE block
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
||||
device_type = x.device.type
|
||||
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False):
|
||||
freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
|
||||
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
||||
cos = cos * self.attention_scaling
|
||||
sin = sin * self.attention_scaling
|
||||
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def rotate_half(x):
|
||||
"""Rotates half the hidden dims of the input."""
|
||||
x1 = x[..., : x.shape[-1] // 2]
|
||||
x2 = x[..., x.shape[-1] // 2 :]
|
||||
return torch.cat((-x2, x1), dim=-1)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
||||
"""Applies Rotary Position Embedding to the query and key tensors.
|
||||
Args:
|
||||
q (`torch.Tensor`): The query tensor.
|
||||
k (`torch.Tensor`): The key tensor.
|
||||
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
||||
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
||||
position_ids (`torch.Tensor`, *optional*):
|
||||
Deprecated and unused.
|
||||
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
||||
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
||||
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
||||
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
||||
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
||||
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
||||
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
||||
Returns:
|
||||
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
||||
"""
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
q_embed = (q * cos) + (rotate_half(q) * sin)
|
||||
k_embed = (k * cos) + (rotate_half(k) * sin)
|
||||
return q_embed, k_embed
|
||||
|
||||
|
||||
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
||||
"""
|
||||
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
||||
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
||||
"""
|
||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||
|
||||
|
||||
@use_kernel_forward_from_hub("RMSNorm")
|
||||
class AfmoeRMSNorm(nn.Module):
|
||||
def __init__(self, hidden_size: int, eps: float):
|
||||
"""
|
||||
AfmoeRMSNorm is equivalent to T5LayerNorm
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
self.variance_epsilon = eps
|
||||
|
||||
def forward(self, hidden_states):
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
||||
return self.weight * hidden_states.to(input_dtype)
|
||||
|
||||
def extra_repr(self):
|
||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
**kwargs,
|
||||
):
|
||||
key_states = repeat_kv(key, module.num_key_value_groups)
|
||||
value_states = repeat_kv(value, module.num_key_value_groups)
|
||||
|
||||
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
||||
if attention_mask is not None:
|
||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||
attn_weights = attn_weights + causal_mask
|
||||
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||
attn_output = torch.matmul(attn_weights, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
return attn_output, attn_weights
|
||||
|
||||
|
||||
class AfmoeMLP(nn.Module):
|
||||
def __init__(self, config, intermediate_size=None):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.hidden_size = config.hidden_size
|
||||
self.intermediate_size = intermediate_size or config.intermediate_size
|
||||
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
||||
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
||||
self.act_fn = ACT2FN[config.hidden_act]
|
||||
|
||||
def forward(self, x):
|
||||
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
||||
|
||||
|
||||
class AfmoeTokenChoiceRouter(nn.Module):
|
||||
"""Token-choice top-K router for MoE routing."""
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.num_experts = config.num_experts
|
||||
self.score_func = config.score_func
|
||||
self.route_norm = config.route_norm
|
||||
self.route_scale = config.route_scale
|
||||
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
||||
|
||||
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
|
||||
_, _, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
scores = self.gate(hidden_states)
|
||||
|
||||
# Apply scoring function in float32 for stability
|
||||
if self.score_func == "sigmoid":
|
||||
scores = torch.sigmoid(scores.to(torch.float32))
|
||||
else:
|
||||
scores = F.softmax(scores.to(torch.float32), dim=-1)
|
||||
|
||||
if expert_bias is not None:
|
||||
_, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts)
|
||||
else:
|
||||
top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
|
||||
|
||||
# Normalize weights if using sigmoid
|
||||
if self.score_func == "sigmoid" and self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
|
||||
top_scores = top_scores * self.route_scale
|
||||
return top_scores, selected_experts
|
||||
|
||||
|
||||
class AfmoeMoE(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.router = AfmoeTokenChoiceRouter(config)
|
||||
|
||||
self.shared_experts = None
|
||||
if config.num_shared_experts > 0:
|
||||
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
|
||||
self.experts = nn.ModuleList(
|
||||
[AfmoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
|
||||
)
|
||||
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
|
||||
|
||||
def forward(self, hidden_states):
|
||||
batch_size, seq_len, hidden_dim = hidden_states.shape
|
||||
hidden_states_flat = hidden_states.view(-1, hidden_dim)
|
||||
|
||||
# Get routing decisions
|
||||
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
|
||||
|
||||
# Process through shared experts
|
||||
if self.shared_experts is not None:
|
||||
shared_output = self.shared_experts(hidden_states_flat)
|
||||
else:
|
||||
shared_output = torch.zeros_like(hidden_states_flat)
|
||||
|
||||
# Reorder tokens by expert for efficient processing
|
||||
token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
|
||||
top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
|
||||
token_to_expert = selected_experts.view(-1)[token_indices_sorted]
|
||||
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
||||
|
||||
# Gather input tokens
|
||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
|
||||
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
|
||||
|
||||
routed_output = torch.zeros_like(routed_input)
|
||||
for expert_id in range(self.config.num_experts):
|
||||
mask = token_to_expert == expert_id
|
||||
if mask.any():
|
||||
expert_input = routed_input[mask]
|
||||
expert_out = self.experts[expert_id](expert_input)
|
||||
routed_output[mask] = expert_out
|
||||
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
|
||||
|
||||
# Scatter back to original positions
|
||||
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
|
||||
|
||||
return output.view(batch_size, seq_len, hidden_dim)
|
||||
|
||||
|
||||
class AfmoeAttention(nn.Module):
|
||||
"""Multi-headed attention with local/global pattern and gating."""
|
||||
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.num_key_value_heads = config.num_key_value_heads
|
||||
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
||||
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
|
||||
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
|
||||
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
past_key_value: Optional[Cache] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.Tensor:
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
gate_states = self.gate_proj(hidden_states)
|
||||
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.transpose(1, 2)
|
||||
key_states = key_states.transpose(1, 2)
|
||||
value_states = value_states.transpose(1, 2)
|
||||
|
||||
if self.is_local_attention:
|
||||
cos, sin = position_embeddings
|
||||
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
||||
|
||||
if past_key_value is not None:
|
||||
cache_kwargs = {"cache_position": cache_position}
|
||||
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
||||
|
||||
attention_interface: Callable = eager_attention_forward
|
||||
if self.config._attn_implementation != "eager":
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||
|
||||
output, _ = attention_interface(
|
||||
self,
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attention_mask=attention_mask,
|
||||
dropout=0.0 if not self.training else self.attention_dropout,
|
||||
scaling=self.scaling,
|
||||
sliding_window=self.sliding_window,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
output = output.view(*input_shape, -1).contiguous()
|
||||
output = output * F.sigmoid(gate_states)
|
||||
return self.o_proj(output)
|
||||
|
||||
|
||||
class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: AfmoeConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_idx = layer_idx
|
||||
|
||||
self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
|
||||
self.attention_type = config.layer_types[layer_idx]
|
||||
|
||||
# Dual normalization for attention
|
||||
self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# Dual normalization for FFN
|
||||
self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
|
||||
# MoE or dense FFN
|
||||
self.moe_enabled = layer_idx >= config.num_dense_layers
|
||||
if self.moe_enabled:
|
||||
self.mlp = AfmoeMoE(config)
|
||||
else:
|
||||
self.mlp = AfmoeMLP(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_value: Optional[Cache] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
|
||||
# Self Attention with dual normalization
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_value,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
# FFN with dual normalization
|
||||
residual = hidden_states
|
||||
hidden_states = self.pre_mlp_layernorm(hidden_states)
|
||||
|
||||
if self.moe_enabled:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
else:
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
|
||||
hidden_states = self.post_mlp_layernorm(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class AfmoePreTrainedModel(PreTrainedModel):
|
||||
config_class = AfmoeConfig
|
||||
base_model_prefix = "model"
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_keep_in_fp32_modules = [
|
||||
"input_layernorm",
|
||||
"post_attention_layernorm",
|
||||
"pre_mlp_layernorm",
|
||||
"post_mlp_layernorm",
|
||||
"q_norm",
|
||||
"k_norm",
|
||||
"norm",
|
||||
]
|
||||
_supports_sdpa = True
|
||||
_supports_attention_backend = True
|
||||
supports_gradient_checkpointing = True
|
||||
|
||||
|
||||
class AfmoeModel(AfmoePreTrainedModel):
|
||||
_no_split_modules = ["AfmoeDecoderLayer"]
|
||||
|
||||
def __init__(self, config: AfmoeConfig):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[list[torch.FloatTensor]] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if use_cache and past_key_values is None:
|
||||
past_key_values = DynamicCache()
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if cache_position is None:
|
||||
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
cache_position = torch.arange(
|
||||
past_seen_tokens,
|
||||
past_seen_tokens + inputs_embeds.shape[1],
|
||||
device=inputs_embeds.device,
|
||||
)
|
||||
if position_ids is None:
|
||||
position_ids = cache_position.unsqueeze(0)
|
||||
|
||||
# It may already have been prepared by e.g. `generate`
|
||||
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"cache_position": cache_position,
|
||||
"past_key_values": past_key_values,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
|
||||
# Apply muP input scaling if enabled
|
||||
if self.config.mup_enabled:
|
||||
hidden_states = hidden_states * (self.config.hidden_size**0.5)
|
||||
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
||||
position_ids=position_ids,
|
||||
past_key_value=past_key_values,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
position_embeddings=position_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(
|
||||
last_hidden_state=hidden_states,
|
||||
past_key_values=past_key_values,
|
||||
)
|
||||
|
||||
|
||||
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_rep"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = AfmoeModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
# Initialize weights and apply final processing
|
||||
self.post_init()
|
||||
|
||||
def get_input_embeddings(self):
|
||||
return self.model.embed_tokens
|
||||
|
||||
def set_input_embeddings(self, value):
|
||||
self.model.embed_tokens = value
|
||||
|
||||
def get_output_embeddings(self):
|
||||
return self.lm_head
|
||||
|
||||
def set_output_embeddings(self, new_embeddings):
|
||||
self.lm_head = new_embeddings
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
|
||||
outputs: MoeModelOutputWithPast = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
cache_position=cache_position,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
# Only compute necessary logits
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
||||
|
||||
loss = None
|
||||
if labels is not None:
|
||||
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
||||
|
||||
return MoeCausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
past_key_values=outputs.past_key_values,
|
||||
hidden_states=outputs.hidden_states,
|
||||
attentions=outputs.attentions,
|
||||
router_logits=outputs.router_logits,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AfmoeForCausalLM",
|
||||
"AfmoeModel",
|
||||
"AfmoePreTrainedModel",
|
||||
]
|
||||
@@ -1,183 +0,0 @@
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeForCausalLM as PrimeRLAfmoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models.afmoe_hf_modeling.configuration_afmoe import AfmoeConfig
|
||||
from tests.unit.train.models.afmoe_hf_modeling.modeling_afmoe import (
|
||||
AfmoeForCausalLM as HFAfmoeForCausalLM,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.skip(reason="HF afmoe model does not support flash attention 2")]
|
||||
|
||||
|
||||
def get_model_pairs():
|
||||
hf_config = AfmoeConfig(
|
||||
architectures=["AfmoeForCausalLM"],
|
||||
attention_dropout=0.0,
|
||||
global_attn_every_n_layers=2,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
hidden_size=256,
|
||||
initializer_range=0.02,
|
||||
intermediate_size=512,
|
||||
layer_types=[
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
"sliding_attention",
|
||||
"full_attention",
|
||||
],
|
||||
load_balance_coeff=0.001,
|
||||
max_position_embeddings=512,
|
||||
moe_intermediate_size=128,
|
||||
mup_enabled=True,
|
||||
n_group=1,
|
||||
num_attention_heads=4,
|
||||
num_dense_layers=2,
|
||||
num_expert_groups=1,
|
||||
num_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
num_hidden_layers=4,
|
||||
num_key_value_heads=2,
|
||||
num_limited_groups=1,
|
||||
num_shared_experts=1,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_scaling=None,
|
||||
rope_theta=10000.0,
|
||||
route_norm=True,
|
||||
route_scale=2.826,
|
||||
score_func="sigmoid",
|
||||
sliding_window=128,
|
||||
tie_word_embeddings=False,
|
||||
topk_group=1,
|
||||
use_cache=True,
|
||||
use_grouped_mm=False,
|
||||
vocab_size=256,
|
||||
)
|
||||
hf_config._attn_implementation = "flash_attention_2"
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
|
||||
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
assert set(prime_state_keys) - set(state_dict.keys()) == set()
|
||||
return hf_model, prime_model
|
||||
|
||||
|
||||
class _IdentityMLP(nn.Identity):
|
||||
def forward(self, x, **kwargs):
|
||||
return super().forward(x)
|
||||
|
||||
|
||||
def test_afmoe_attn_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
for layer in hf_model.model.layers:
|
||||
layer.mlp = nn.Identity()
|
||||
for layer in prime_model.model.layers:
|
||||
layer.mlp = _IdentityMLP()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe_mlp_only() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
# HF AfmoeAttention.forward() returns a single tensor
|
||||
def identity_attn_hf(hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
||||
return hidden_states
|
||||
|
||||
# PrimeRL attention returns a tuple (output, attn_weights)
|
||||
def identity_attn_prime(hidden_states: torch.Tensor, *args, **kwargs) -> tuple[torch.Tensor, None]:
|
||||
return hidden_states, None
|
||||
|
||||
for layer in hf_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_hf
|
||||
for layer in prime_model.model.layers:
|
||||
layer.self_attn.forward = identity_attn_prime
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
def test_afmoe() -> None:
|
||||
hf_model, prime_model = get_model_pairs()
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
|
||||
position_ids = torch.arange(1, 101).unsqueeze(0)
|
||||
|
||||
hf_output = hf_model(input_ids, position_ids=position_ids)
|
||||
prime_output = prime_model(
|
||||
input_ids,
|
||||
position_ids=position_ids,
|
||||
seq_lens=torch.tensor([input_ids.shape[1]], device="cuda"),
|
||||
)
|
||||
hf_output.logits.sum().backward()
|
||||
prime_output["logits"].sum().backward()
|
||||
|
||||
logits_diff = prime_output["logits"] - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFAfmoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids=position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_afmoe()
|
||||
@@ -5,9 +5,8 @@ import torch.nn.functional as F
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher
|
||||
from prime_rl.trainer.model import compute_expert_load_stats, is_tt_moe_model
|
||||
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4Experts
|
||||
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch
|
||||
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ClampedSilu
|
||||
from prime_rl.trainer.models.layers.expert_compute import BF16ExpertCompute, GroupedGemmExpertCompute
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import (
|
||||
@@ -69,7 +68,7 @@ def test_unselected_moe_uses_bf16_without_loading_compute_backend(selection, com
|
||||
pytest.param(GroupedExperts, {"activation": "relu2"}, True, "standard SwiGLU", id="relu2"),
|
||||
pytest.param(GroupedExperts, {"activation": "clamped_swiglu"}, True, "standard SwiGLU", id="clamped-swiglu"),
|
||||
pytest.param(GroupedExperts, {"bias": True}, True, "bias-free", id="bias"),
|
||||
pytest.param(DeepseekV4Experts, {"swiglu_limit": 10.0}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
pytest.param(GroupedExperts, {"activation": ClampedSilu(10.0)}, True, "standard SwiGLU", id="deepseek-v4"),
|
||||
],
|
||||
)
|
||||
def test_set_compute_validates_sonic_expert_structure(expert_cls, kwargs, fused, error):
|
||||
|
||||
@@ -5,7 +5,7 @@ from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from prime_rl.trainer.models import cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.trainer.rl.loss import compute_entropy, shift_tensor_left, shift_tensor_right
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
|
||||
@@ -160,95 +160,6 @@ def test_fused_vs_vanilla_integration():
|
||||
torch.testing.assert_close(fused_out["entropy"], vanilla_entropy, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
@pytest.mark.gpu
|
||||
@pytest.mark.skip(reason="Produces NaNs in bf16 with FA3; needs investigation")
|
||||
def test_full_model_fused_vs_vanilla():
|
||||
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
|
||||
torch.manual_seed(123)
|
||||
|
||||
# Create tiny Qwen3 model for fast testing
|
||||
config = Qwen3Config(
|
||||
hidden_size=128,
|
||||
intermediate_size=256,
|
||||
max_position_embeddings=512,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
head_dim=32,
|
||||
num_hidden_layers=2,
|
||||
vocab_size=1000,
|
||||
rms_norm_eps=1e-5,
|
||||
rope_theta=10000.0,
|
||||
attention_bias=False,
|
||||
)
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
# Create two identical models
|
||||
model_vanilla = Qwen3ForCausalLM._from_config(config)
|
||||
model_fused = Qwen3ForCausalLM._from_config(config)
|
||||
|
||||
# Share weights between models
|
||||
model_fused.load_state_dict(model_vanilla.state_dict())
|
||||
|
||||
# Wrap with different LM heads
|
||||
inject_prime_lm_head(model_vanilla, chunk_size=None) # Vanilla
|
||||
inject_prime_lm_head(model_fused, chunk_size=32) # Fused with chunking
|
||||
|
||||
# Setup optimizers
|
||||
optimizer_vanilla = torch.optim.AdamW(model_vanilla.parameters(), lr=1e-4)
|
||||
optimizer_fused = torch.optim.AdamW(model_fused.parameters(), lr=1e-4)
|
||||
|
||||
# Run a few training steps
|
||||
num_steps = 3
|
||||
batch_size, seq_len = 2, 64
|
||||
temp_value = 1.5
|
||||
|
||||
for step in range(num_steps):
|
||||
# Generate random batch
|
||||
with torch.device("cuda"):
|
||||
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
|
||||
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
|
||||
temperature = torch.full((batch_size, seq_len), temp_value, dtype=torch.float32, device="cuda")
|
||||
seq_lens = torch.tensor([seq_len])
|
||||
|
||||
# Vanilla forward (returns logits, compute logprobs/entropy using RL train functions)
|
||||
optimizer_vanilla.zero_grad()
|
||||
out_vanilla = cast_float_and_contiguous(
|
||||
model_vanilla(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_vanilla.get("logprobs") is None:
|
||||
assert out_vanilla.get("logits") is not None
|
||||
logits = out_vanilla["logits"] / temp_value
|
||||
out_vanilla["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_vanilla["entropy"] = compute_entropy(logits)
|
||||
loss_vanilla = -out_vanilla["logprobs"].mean()
|
||||
loss_vanilla.backward()
|
||||
optimizer_vanilla.step()
|
||||
|
||||
# Fused forward (returns logprobs and entropy directly)
|
||||
optimizer_fused.zero_grad()
|
||||
out_fused = cast_float_and_contiguous(
|
||||
model_fused(labels, position_ids, labels=labels, temperature=temperature, seq_lens=seq_lens)
|
||||
)
|
||||
if out_fused.get("logprobs") is None:
|
||||
assert out_fused.get("logits") is not None
|
||||
logits = out_fused["logits"] / temp_value
|
||||
out_fused["logprobs"] = selective_log_softmax(logits, labels)
|
||||
out_fused["entropy"] = compute_entropy(logits)
|
||||
loss_fused = -out_fused["logprobs"].mean()
|
||||
loss_fused.backward()
|
||||
optimizer_fused.step()
|
||||
|
||||
# Compare outputs (should be very close since models started identical)
|
||||
torch.testing.assert_close(out_fused["logprobs"], out_vanilla["logprobs"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(out_fused["entropy"], out_vanilla["entropy"], rtol=1e-3, atol=1e-4)
|
||||
torch.testing.assert_close(loss_fused, loss_vanilla, rtol=1e-3, atol=1e-4)
|
||||
|
||||
# After training, weights should still be close (optimizer steps should be similar)
|
||||
for (name_v, param_v), (name_f, param_f) in zip(model_vanilla.named_parameters(), model_fused.named_parameters()):
|
||||
if "lm_head" not in name_v: # Compare non-lm_head params
|
||||
torch.testing.assert_close(param_f, param_v, rtol=1e-3, atol=1e-4)
|
||||
|
||||
|
||||
def test_fused_lm_head_correct_shift():
|
||||
"""
|
||||
End-to-end test that the fused LM head with shifted labels, after shift_tensor_right,
|
||||
|
||||
@@ -19,7 +19,7 @@ def setup_fake_dataloader(config: FakeDataConfig, non_dp_size: int = 1):
|
||||
seed=config.seed,
|
||||
non_dp_size=non_dp_size,
|
||||
)
|
||||
return dataset, setup_dataloader(dataset, config)
|
||||
return dataset, setup_dataloader(dataset, config, cp=1)
|
||||
|
||||
|
||||
def test_fake_dataset_single_rank_state():
|
||||
@@ -88,7 +88,7 @@ def test_fake_dataset_single_rank_resume():
|
||||
|
||||
# Reload dataloader
|
||||
state_dict = dataloader.state_dict()
|
||||
dataloader = setup_dataloader(dataset, config)
|
||||
dataloader = setup_dataloader(dataset, config, cp=1)
|
||||
dataloader.load_state_dict(state_dict)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -110,7 +110,8 @@ def test_fake_dataset_single_rank_state_with_packing():
|
||||
micro_batch = next(dataiter)
|
||||
num_packed_examples = len(micro_batch["input_ids"][micro_batch["loss_mask"]].unique())
|
||||
step += num_packed_examples
|
||||
assert micro_batch["input_ids"].shape == (1, 128)
|
||||
assert micro_batch["input_ids"].shape[0] == 1
|
||||
assert micro_batch["input_ids"].shape[1] <= 128
|
||||
assert micro_batch["seq_lens"].sum() == micro_batch["input_ids"].shape[1]
|
||||
worker_state = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]["worker_0"]["dataset_state"]
|
||||
pending_sample = worker_state.get("pending_sample")
|
||||
@@ -186,7 +187,7 @@ def test_dataloader_shards_across_ranks_and_workers(
|
||||
seq_len=config.seq_len,
|
||||
non_dp_size=non_dp_size,
|
||||
)
|
||||
return setup_dataloader(dataset, config)
|
||||
return setup_dataloader(dataset, config, cp=1)
|
||||
|
||||
dataloader = setup_epoch_dataloader()
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user