Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c935497d71 | ||
|
|
cd2f3daeb2 | ||
|
|
897b935cae | ||
|
|
81f9e9512b | ||
|
|
d4385029c8 | ||
|
|
c654dc1d4d | ||
|
|
6ba37c2c21 | ||
|
|
458b16ef47 | ||
|
|
b5f196a9c5 | ||
|
|
6dda4a1466 | ||
|
|
fa55779272 | ||
|
|
b2ba40b5eb | ||
|
|
e4330c2d2c | ||
|
|
4a6b45487f | ||
|
|
024abb2043 | ||
|
|
5b11b8de33 | ||
|
|
7c434ec267 | ||
|
|
469a4e6714 | ||
|
|
319af10769 | ||
|
|
d11fc90469 | ||
|
|
c9a4b3b199 | ||
|
|
a252057978 | ||
|
|
429c1bb5e5 | ||
|
|
efb874b734 | ||
|
|
2171368063 | ||
|
|
7b7bde1fa0 | ||
|
|
0fe673c23c | ||
|
|
84ccb9507d | ||
|
|
09e403b4a4 | ||
|
|
7da26cd651 | ||
|
|
5f2c004184 | ||
|
|
c0d896f3f8 | ||
|
|
bb522cce53 | ||
|
|
95af0118db | ||
|
|
d7b3ae203c | ||
|
|
229391fa27 | ||
|
|
1e9a3e9196 | ||
|
|
3b01ce9d48 | ||
|
|
38b524925d | ||
|
|
d62c7539e4 | ||
|
|
edf41113fe | ||
|
|
bcac552c3f | ||
|
|
f7a27f69dd | ||
|
|
31591b7fe8 | ||
|
|
0deb4abaa9 | ||
|
|
4be61bbd68 | ||
|
|
0660a9b3cb |
@@ -14,7 +14,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
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/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
@@ -38,3 +42,59 @@ jobs:
|
||||
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/unit -m "not gpu"
|
||||
- name: Cleanup output_dir
|
||||
run: rm -rf /tmp/outputs
|
||||
|
||||
slim-configs-install:
|
||||
name: Slim install (prime-rl-configs only)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Build the slim wheel
|
||||
run: uv build --wheel ./packages/prime-rl-configs --out-dir /tmp/slim-wheel
|
||||
- name: Install slim wheel from a directory with no workspace context
|
||||
# Build the wheel and install it from /tmp so uv can't discover the
|
||||
# repo's root pyproject.toml [tool.uv.sources] and silently apply
|
||||
# them. This mirrors what an external pip-only user gets.
|
||||
run: |
|
||||
uv venv --python 3.12 /tmp/slim
|
||||
cd /tmp && uv pip install --python /tmp/slim/bin/python /tmp/slim-wheel/*.whl
|
||||
- name: Verify configs import without heavy deps
|
||||
run: |
|
||||
/tmp/slim/bin/python - <<'PY'
|
||||
import sys
|
||||
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import validate_shared_ckpt_config
|
||||
|
||||
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
|
||||
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
|
||||
leaked = [m for m in forbidden if m in sys.modules]
|
||||
if leaked:
|
||||
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
|
||||
|
||||
# Slim wheel does not ship the templates/ data dir; resolver returns None.
|
||||
assert find_package_resource("templates") is None, "templates should not be in slim wheel"
|
||||
print("slim install OK — configs import with no heavy deps loaded")
|
||||
PY
|
||||
- name: Verify a real config (with [slurm]) parses on slim install
|
||||
run: |
|
||||
/tmp/slim/bin/python - <<'PY'
|
||||
from pydantic_config import cli
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
rl = cli(RLConfig, args=["@", "examples/Intellect-3.1/rl.toml"])
|
||||
assert rl.slurm is not None, "expected [slurm] in example config"
|
||||
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
|
||||
assert rl.slurm.template_path is None, f"unexpected template_path on slim: {rl.slurm.template_path}"
|
||||
print("slim parse OK")
|
||||
PY
|
||||
|
||||
@@ -28,23 +28,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
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/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
@@ -63,21 +60,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- test: base
|
||||
- test: reverse_text_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
|
||||
- test: rl_lora
|
||||
pytest_args: "tests/integration/test_reverse_text_sft.py"
|
||||
- test: reverse_text_sft_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
|
||||
- test: rl_multi_run
|
||||
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: reverse_text_multi_run
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
|
||||
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
@@ -87,23 +93,20 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
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/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
@@ -111,4 +114,4 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
|
||||
- name: Build matrix from nightly test files
|
||||
id: build-matrix
|
||||
@@ -75,7 +75,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
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/research-environments
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -24,6 +24,12 @@ jobs:
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
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/research-environments
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: crazy-max/ghaction-docker-meta@v2
|
||||
|
||||
@@ -16,8 +16,9 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Run ruff
|
||||
uses: astral-sh/ruff-action@v3
|
||||
with:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.vscode/*
|
||||
.claude/scheduled_tasks.lock
|
||||
*.ipynb
|
||||
*.jsonl
|
||||
configs/endpoints.py
|
||||
@@ -199,3 +200,5 @@ debug_I2_zero_band
|
||||
.idea
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
[submodule "verifiers"]
|
||||
path = deps/verifiers
|
||||
url = git@github.com:PrimeIntellect-ai/verifiers.git
|
||||
[submodule "renderers"]
|
||||
path = deps/renderers
|
||||
url = git@github.com:PrimeIntellect-ai/renderers.git
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
@@ -3,6 +3,7 @@
|
||||
## Writing code
|
||||
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
|
||||
+3
-7
@@ -12,7 +12,7 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH=$PATH:/usr/local/cuda/bin
|
||||
|
||||
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
|
||||
# Install build tooling.
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV TZ=Etc/UTC
|
||||
@@ -22,12 +22,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
sudo \
|
||||
git \
|
||||
ninja-build \
|
||||
software-properties-common \
|
||||
&& add-apt-repository ppa:deadsnakes/ppa \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# Download the latest installer
|
||||
@@ -48,6 +42,8 @@ COPY pyproject.toml /app/pyproject.toml
|
||||
COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
@@ -53,6 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
@@ -90,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
```
|
||||
|
||||
2. Install [uv](https://docs.astral.sh/uv/)
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
3. Install [uv](https://docs.astral.sh/uv/)
|
||||
|
||||
```bash
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
source $HOME/.local/bin/env
|
||||
```
|
||||
|
||||
3. Install dependencies from the lock file
|
||||
4. Install dependencies from the lock file
|
||||
|
||||
```bash
|
||||
uv sync --all-extras
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
@@ -1,29 +0,0 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_infer_gpus = 1
|
||||
num_train_gpus = 1
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
max_steps = 25
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 20
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
+3
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
+1
@@ -1,6 +1,7 @@
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 5
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
max_steps = 20
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
max_steps = 20
|
||||
max_steps = 10
|
||||
|
||||
[ckpt]
|
||||
resume_step = 10
|
||||
resume_step = 5
|
||||
|
||||
[ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
|
||||
[ckpt]
|
||||
|
||||
Submodule
+1
Submodule configs/private added at 74c1330008
+1
Submodule deps/renderers added at 17d0584f87
+1
Submodule deps/research-environments added at d141472268
+1
Submodule deps/verifiers added at 711a7c705e
@@ -0,0 +1,26 @@
|
||||
# prime-rl-configs
|
||||
|
||||
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
|
||||
|
||||
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
pip install git+https://github.com/PrimeIntellect-ai/prime-rl.git#subdirectory=packages/prime-rl-configs
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The pip *distribution name* (`prime-rl-configs`) and the *import path* (`prime_rl.configs.*`) are different on purpose: this package contributes submodules to the shared `prime_rl` namespace.
|
||||
|
||||
```python
|
||||
from pydantic_config import cli
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
|
||||
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
|
||||
```
|
||||
|
||||
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
|
||||
|
||||
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
|
||||
@@ -0,0 +1,25 @@
|
||||
[project]
|
||||
name = "prime-rl-configs"
|
||||
version = "0.4.0"
|
||||
description = "Slim config schema for prime-rl (no GPU/ML deps)."
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
# The PyPI package named `pydantic-config` is a different project that
|
||||
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
|
||||
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
|
||||
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
+73
-24
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
@@ -16,6 +16,16 @@ class ServerConfig(BaseConfig):
|
||||
|
||||
host: Annotated[str | None, Field(description="The host to bind to.")] = None
|
||||
port: Annotated[int, Field(description="The port to bind to.")] = 8000
|
||||
liveness_timeout_seconds: Annotated[
|
||||
float,
|
||||
Field(
|
||||
gt=0,
|
||||
description=(
|
||||
"Timeout in seconds for the /liveness endpoint's internal vLLM worker RPC. "
|
||||
"If Kubernetes liveness probes are enabled, keep the probe timeoutSeconds at least this high."
|
||||
),
|
||||
),
|
||||
] = 30.0
|
||||
|
||||
|
||||
class ParallelConfig(BaseConfig):
|
||||
@@ -110,6 +120,16 @@ class WeightBroadcastConfig(BaseConfig):
|
||||
)
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for vLLM inference workers."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
cpu_bytes: Annotated[int, Field(gt=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
@@ -152,20 +172,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
] = "consistent_hash"
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for disaggregated serving.
|
||||
|
||||
When configured, both prefill and decode nodes use
|
||||
MultiConnector (NixlConnector + OffloadingConnector).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
cpu_bytes: Annotated[int, Field(ge=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
|
||||
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a disaggregated prefill/decode inference deployment.
|
||||
|
||||
@@ -214,11 +220,6 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
Field(description="Extra environment variables exported only on decode nodes."),
|
||||
] = {}
|
||||
|
||||
kv_cache_offload: Annotated[
|
||||
KVCacheOffloadConfig | None,
|
||||
Field(description="CPU KV cache offload config for prefill nodes. None = disabled (NixlConnector only)."),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
@@ -383,6 +384,17 @@ class InferenceConfig(BaseConfig):
|
||||
WeightBroadcastConfig()
|
||||
)
|
||||
|
||||
kv_cache_offload: Annotated[
|
||||
KVCacheOffloadConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"CPU KV cache offload config for inference workers. Standard inference uses vLLM's "
|
||||
"OffloadingConnector. Disaggregated P/D deployments combine it with NIXL through "
|
||||
"MultiConnector in the SLURM launcher."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
enable_return_routed_experts: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -390,6 +402,13 @@ class InferenceConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
enable_fp32_lm_head: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Run the lm_head projection in fp32 via a native bf16xbf16 -> fp32 GEMM (`torch.mm` with `out_dtype=torch.float32`). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's `--enable-fp32-lm-head`. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting `additional_config[\"fp32_lm_head\"] = True` on the vLLM config.",
|
||||
),
|
||||
] = False
|
||||
|
||||
vllm_extra: Annotated[
|
||||
dict[str, Any],
|
||||
Field(
|
||||
@@ -428,6 +447,16 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
if self.enable_prefix_caching is False:
|
||||
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
|
||||
if "enable_prefix_caching" not in self.model_fields_set:
|
||||
self.enable_prefix_caching = True
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_disaggregated(self):
|
||||
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
|
||||
@@ -450,10 +479,9 @@ class InferenceConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -500,6 +528,7 @@ class InferenceConfig(BaseConfig):
|
||||
to_vllm = {
|
||||
"server.host": "host",
|
||||
"server.port": "port",
|
||||
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
|
||||
"model.name": "model",
|
||||
"model.dtype": "dtype",
|
||||
"model.max_model_len": "max_model_len",
|
||||
@@ -536,6 +565,26 @@ class InferenceConfig(BaseConfig):
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
|
||||
if self.kv_cache_offload is not None:
|
||||
rsetattr(
|
||||
namespace,
|
||||
"kv_transfer_config",
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {
|
||||
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
# Pass prime-rl-specific flags through vLLM's additional_config dict;
|
||||
# workers read these via get_current_vllm_config().additional_config.
|
||||
if self.enable_fp32_lm_head:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
delattr(namespace, "chat_template")
|
||||
+74
-12
@@ -1,4 +1,5 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -17,7 +18,6 @@ from prime_rl.configs.shared import (
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class OptimizerConfig(BaseConfig):
|
||||
@@ -149,9 +149,11 @@ class TrainSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -248,9 +250,11 @@ class EvalSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -685,6 +689,52 @@ class BufferConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseModel):
|
||||
"""Length penalty by weighted token cost.
|
||||
|
||||
Effective cost = completion_weight * model_completion_tokens
|
||||
+ tool_response_weight * tool_response_tokens.
|
||||
|
||||
Tool-response tokens are read from the rollout's harness metric
|
||||
`*_total_tool_response_tokens` (e.g. `rlm_total_tool_response_tokens`); 0 if absent —
|
||||
so for envs without tool accounting, only the completion term contributes regardless of weight.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["tokens"] = "tokens"
|
||||
completion_weight: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
allow_inf_nan=False,
|
||||
description="Weight on model completion tokens. Finite and non-negative.",
|
||||
),
|
||||
] = 1.0
|
||||
tool_response_weight: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
allow_inf_nan=False,
|
||||
description="Weight on tool-response tokens. Finite and non-negative.",
|
||||
),
|
||||
] = 1.0
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseModel):
|
||||
"""Length penalty by trajectory turn count."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseModel):
|
||||
"""Config for the default advantage."""
|
||||
|
||||
@@ -692,11 +742,11 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_penalty: Annotated[
|
||||
Literal["tokens", "turns"] | None,
|
||||
LengthPenaltyConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
|
||||
"count, `turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"Correctness-gated length penalty. `tokens` shapes by weighted token cost, "
|
||||
"`turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct "
|
||||
"rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost "
|
||||
"rollouts get advantage in [0, 1], others get 0."
|
||||
@@ -1032,6 +1082,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
),
|
||||
] = 8
|
||||
|
||||
max_error_reschedule_attempts: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The group is dropped from the current step's batch once this many of its dispatch rounds have returned errored or empty rollouts (the trainer proceeds with the rollouts from other groups). Counts rounds, not individual rollouts: a non-group-scoring env that dispatches `rollouts_per_example` rollouts at once still only counts one round per failed batch. `None` means retry indefinitely (legacy behavior). Useful for unblocking single-example hangs in agent envs.",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -1103,15 +1161,19 @@ class OrchestratorConfig(BaseConfig):
|
||||
train = data.setdefault("train", {})
|
||||
if isinstance(train, dict):
|
||||
if "env" in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("env", data.pop("env"))
|
||||
if "sampling" in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("sampling", data.pop("sampling"))
|
||||
return data
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
@@ -38,8 +39,7 @@ from prime_rl.configs.trainer import (
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
@@ -681,6 +681,21 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.enable_eplb:
|
||||
return self
|
||||
|
||||
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
|
||||
trainer_weight_broadcast = self.trainer.weight_broadcast
|
||||
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
|
||||
raise ValueError(
|
||||
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"weight_broadcast.quantize_in_weight_transfer = true."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
@@ -745,9 +760,10 @@ class RLConfig(BaseConfig):
|
||||
self.inference.enable_lora = True
|
||||
self.inference.max_lora_rank = self.trainer.model.lora.rank
|
||||
else:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank."
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
return self
|
||||
@@ -763,13 +779,15 @@ class RLConfig(BaseConfig):
|
||||
if self.trainer.enable_router_replay:
|
||||
if self.inference is not None:
|
||||
if self.inference.enable_return_routed_experts is False:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
|
||||
stacklevel=2,
|
||||
)
|
||||
self.inference.enable_return_routed_experts = True
|
||||
else:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -957,13 +975,12 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_slurm_template(self):
|
||||
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
|
||||
return self
|
||||
|
||||
### Warnings
|
||||
+72
-8
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
RendererConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
WandbConfig,
|
||||
@@ -21,7 +22,7 @@ from prime_rl.configs.trainer import (
|
||||
SchedulerConfig,
|
||||
TokenizerConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseModel):
|
||||
@@ -172,6 +173,21 @@ class SFTConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"If True, tokenize SFT samples through the `renderers` library "
|
||||
"(single render() + message_indices mask) instead of the default "
|
||||
"`build_incremental_token_mask` path. Required for chat templates "
|
||||
"that render position-dependently (e.g. Qwen3, Qwen3.5)."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
# The data configuration
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
@@ -357,6 +373,55 @@ class SFTConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"use_renderer is not supported for VLMs. The renderer tokenizes "
|
||||
"text-only message dicts client-side and cannot handle image inputs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
# pool_size is orchestrator-only. An in-process renderer pool exists
|
||||
# to amortize tokenization across concurrent rollouts in the
|
||||
# orchestrator (many async requests render at once, HF fast
|
||||
# tokenizers release the GIL during Rust encoding, so a pool of N
|
||||
# tokenizer copies parallelizes well). SFT has no such concurrency:
|
||||
# the StatefulDataLoader is constructed with num_workers=0, so the
|
||||
# main process tokenizes one example at a time, between training
|
||||
# steps. Across DP, each rank already owns its own renderer — an
|
||||
# implicit pool of size world_size. Pooling within a rank gives
|
||||
# nothing on top of that. Reject so callers don't silently set a
|
||||
# knob that does nothing; if SFT tokenization ever becomes a
|
||||
# bottleneck the fix is num_workers on the dataloader, not a pool.
|
||||
if self.renderer.pool_size is not None:
|
||||
raise ValueError(
|
||||
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
|
||||
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
|
||||
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
|
||||
"num_workers on the dataloader instead."
|
||||
)
|
||||
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_adapter_saving(self):
|
||||
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
|
||||
@@ -425,11 +490,10 @@ class SFTConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
return self
|
||||
+34
-1
@@ -299,6 +299,21 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
cp_style: Annotated[
|
||||
Literal["ring", "ulysses"],
|
||||
Field(
|
||||
description=(
|
||||
"Context parallelism communication style. "
|
||||
"'ring' uses ring-attention all-gather/reduce-scatter (current default, "
|
||||
"requires custom kernels per attention type). "
|
||||
"'ulysses' uses all-to-all to redistribute Q/K/V from sequence-sharded "
|
||||
"to head-sharded, runs vanilla attention locally on the full sequence, "
|
||||
"then all-to-all back. Works out-of-the-box with any attention kernel "
|
||||
"(softmax FA, linear attention, mamba, etc.)."
|
||||
),
|
||||
),
|
||||
] = "ring"
|
||||
|
||||
impl: Annotated[
|
||||
Literal["hf", "custom", "auto"],
|
||||
Field(
|
||||
@@ -330,6 +345,14 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
fp8: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use FP8 training via DeepGEMM. Replaces nn.Linear layers with FP8 blockwise linear "
|
||||
"and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and model.impl='custom'.",
|
||||
),
|
||||
] = False
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -386,9 +409,13 @@ class ModelConfig(BaseModelConfig):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
|
||||
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
|
||||
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
|
||||
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
|
||||
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
|
||||
# `_flash_attention_forward` which only wraps FA2.
|
||||
raise ValueError(
|
||||
f"CP with {self.attn} requires model.impl='custom' "
|
||||
"(the ring-attention kernel is only implemented for the custom model path)"
|
||||
"(FA3/FA4 paths are only implemented for the custom model attention class)"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -417,6 +444,12 @@ class ModelConfig(BaseModelConfig):
|
||||
raise ValueError("Flash attention 4 is only supported with the custom implementation")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fp8_only_with_custom_impl(self):
|
||||
if self.fp8 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
@@ -0,0 +1,56 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def find_package_resource(subdir: str) -> Path | None:
|
||||
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
|
||||
|
||||
Returns None if `subdir` is not present in any wheel — e.g. on a slim
|
||||
`prime-rl-configs`-only install where `prime-rl`'s shipped resources
|
||||
(templates, etc.) are absent.
|
||||
"""
|
||||
import prime_rl
|
||||
|
||||
for p in prime_rl.__path__:
|
||||
candidate = Path(p) / subdir
|
||||
if candidate.is_dir():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def rgetattr(obj: Any, attr_path: str) -> Any:
|
||||
"""Recursive getattr for dotted paths: rgetattr(cfg, "trainer.model.name")."""
|
||||
current = obj
|
||||
for attr in attr_path.split("."):
|
||||
if not hasattr(current, attr):
|
||||
raise AttributeError(f"'{type(current).__name__}' object has no attribute '{attr}'")
|
||||
current = getattr(current, attr)
|
||||
return current
|
||||
|
||||
|
||||
def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
|
||||
"""Recursive setattr for dotted paths: rsetattr(cfg, "trainer.model.name", "foo")."""
|
||||
if "." not in attr_path:
|
||||
return setattr(obj, attr_path, value)
|
||||
parent_path, attr = attr_path.rsplit(".", 1)
|
||||
setattr(rgetattr(obj, parent_path), attr, value)
|
||||
|
||||
|
||||
def get_all_fields(model: BaseModel | type) -> list[str]:
|
||||
if isinstance(model, BaseModel):
|
||||
model_cls = model.__class__
|
||||
else:
|
||||
model_cls = model
|
||||
|
||||
fields = []
|
||||
for name, field in model_cls.model_fields.items():
|
||||
field_type = field.annotation
|
||||
fields.append(name)
|
||||
if field_type is not None and hasattr(field_type, "model_fields"):
|
||||
sub_fields = get_all_fields(field_type)
|
||||
fields.extend(f"{name}.{sub}" for sub in sub_fields)
|
||||
return fields
|
||||
+119
-61
@@ -5,24 +5,23 @@ description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
"liger-kernel>=0.5.10",
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"pydantic>=1.10.13",
|
||||
"pydantic-config",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.19.0",
|
||||
"vllm>=0.20.2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.73",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -32,6 +31,7 @@ dependencies = [
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
@@ -51,7 +51,7 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3"]
|
||||
|
||||
@@ -59,20 +59,33 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
"alphabet-sort",
|
||||
"wiki-search",
|
||||
"math-python",
|
||||
"math-env",
|
||||
"code-env",
|
||||
"science-env",
|
||||
"logic-env",
|
||||
"color-codeword",
|
||||
"math500",
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"mini_swe_agent_plus",
|
||||
"deepdive"
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -108,6 +121,40 @@ dev = [
|
||||
]
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
@@ -122,34 +169,20 @@ override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# pytorch-cu128 / pytorch-cu128-test indexes don't publish upload dates
|
||||
torch = false
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
@@ -158,31 +191,52 @@ deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
alphabet-sort = { index = "primeintellect" }
|
||||
wiki-search = { index = "primeintellect" }
|
||||
math-python = { index = "primeintellect" }
|
||||
math-env = { index = "primeintellect" }
|
||||
code-env = { index = "primeintellect" }
|
||||
science-env = { index = "primeintellect" }
|
||||
logic-env = { index = "primeintellect" }
|
||||
color-codeword = { index = "primeintellect" }
|
||||
math500 = { index = "primeintellect" }
|
||||
aime2024 = { index = "primeintellect" }
|
||||
aime2025 = { index = "primeintellect" }
|
||||
deepdive = { index = "primeintellect" }
|
||||
mini_swe_agent_plus = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
|
||||
@@ -194,17 +248,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "primeintellect"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
explicit = true
|
||||
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
@@ -214,8 +262,15 @@ explicit = true
|
||||
select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
extend-exclude = ["deps"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--strict-markers"
|
||||
@@ -228,5 +283,8 @@ markers = [
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
|
||||
@@ -15,9 +15,3 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
|
||||
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
|
||||
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
|
||||
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
|
||||
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
|
||||
|
||||
+115
-53
@@ -4,86 +4,148 @@ set -euo pipefail
|
||||
# Colors for output
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
|
||||
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
|
||||
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
|
||||
|
||||
REPO_ID="prime-rl"
|
||||
|
||||
# Flag defaults (can be overridden via env)
|
||||
SKIP_CLONE=${SKIP_CLONE:-0}
|
||||
|
||||
assert_supported_platform() {
|
||||
local os arch
|
||||
os="$(uname -s)"
|
||||
arch="$(uname -m)"
|
||||
|
||||
if [ "$os" != "Linux" ]; then
|
||||
log_error "Unsupported platform: ${os}/${arch}."
|
||||
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$arch" in
|
||||
x86_64 | aarch64) ;;
|
||||
*)
|
||||
log_error "Unsupported architecture: ${arch}."
|
||||
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if ! command -v apt &>/dev/null; then
|
||||
log_error "Unsupported Linux distribution: apt is required by this installer."
|
||||
log_error "Use a Debian/Ubuntu-based Linux machine on x86_64 or aarch64, or install manually."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
has_ssh_access() {
|
||||
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
|
||||
# We try a quick ls-remote to avoid cloning on failure.
|
||||
# Disable -e for the probe so the script doesn't exit on a failed test.
|
||||
set +e
|
||||
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
return $rc
|
||||
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
|
||||
# We try a quick ls-remote to avoid cloning on failure.
|
||||
# Disable -e for the probe so the script doesn't exit on a failed test.
|
||||
set +e
|
||||
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
return $rc
|
||||
}
|
||||
|
||||
ensure_known_hosts() {
|
||||
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
|
||||
mkdir -p "${HOME}/.ssh"
|
||||
chmod 700 "${HOME}/.ssh"
|
||||
# Use -H to hash hostnames; merge uniquely to avoid dupes.
|
||||
if command -v ssh-keyscan >/dev/null 2>&1; then
|
||||
ssh-keyscan -H github.com 2>/dev/null | sort -u \
|
||||
| tee -a "${HOME}/.ssh/known_hosts" >/dev/null
|
||||
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
|
||||
mkdir -p "${HOME}/.ssh"
|
||||
chmod 700 "${HOME}/.ssh"
|
||||
# Use -H to hash hostnames; merge uniquely to avoid dupes.
|
||||
if command -v ssh-keyscan >/dev/null 2>&1; then
|
||||
ssh-keyscan -H github.com 2>/dev/null | sort -u |
|
||||
tee -a "${HOME}/.ssh/known_hosts" >/dev/null
|
||||
chmod 600 "${HOME}/.ssh/known_hosts"
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
# Ensure sudo exists
|
||||
if ! command -v sudo &>/dev/null; then
|
||||
apt update
|
||||
apt install -y sudo
|
||||
fi
|
||||
assert_supported_platform
|
||||
|
||||
log_info "Installing base packages..."
|
||||
sudo apt update && sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
|
||||
# Ensure sudo exists
|
||||
if ! command -v sudo &>/dev/null; then
|
||||
apt update
|
||||
apt install -y sudo
|
||||
fi
|
||||
|
||||
log_info "Configuring SSH known_hosts for GitHub..."
|
||||
ensure_known_hosts
|
||||
log_info "Installing base packages..."
|
||||
sudo apt update
|
||||
sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
|
||||
|
||||
if [ "$SKIP_CLONE" -eq 1 ]; then
|
||||
log_info "Skipping clone; assuming we are already inside the repo."
|
||||
log_info "Configuring SSH known_hosts for GitHub..."
|
||||
ensure_known_hosts
|
||||
|
||||
if [ "$SKIP_CLONE" -eq 1 ]; then
|
||||
log_info "Skipping clone; assuming we are already inside the repo."
|
||||
else
|
||||
log_info "Determining best way to clone (SSH vs HTTPS)..."
|
||||
if has_ssh_access; then
|
||||
log_info "SSH access to GitHub works. Cloning via SSH."
|
||||
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
|
||||
else
|
||||
log_info "Determining best way to clone (SSH vs HTTPS)..."
|
||||
if has_ssh_access; then
|
||||
log_info "SSH access to GitHub works. Cloning via SSH."
|
||||
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
|
||||
else
|
||||
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
|
||||
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
|
||||
fi
|
||||
|
||||
log_info "Entering project directory..."
|
||||
cd ${REPO_ID}
|
||||
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
|
||||
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
|
||||
fi
|
||||
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
log_info "Entering project directory..."
|
||||
cd ${REPO_ID}
|
||||
fi
|
||||
|
||||
log_info "Sourcing uv environment..."
|
||||
if ! command -v uv &> /dev/null; then
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
if ! has_ssh_access; then
|
||||
git config url."https://github.com/".insteadOf "git@github.com:"
|
||||
fi
|
||||
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
log_info "Initializing submodules..."
|
||||
init_submodules
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
log_info "Sourcing uv environment..."
|
||||
if ! command -v uv &>/dev/null; then
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
|
||||
log_info "Installation completed!"
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
|
||||
log_info "Installation completed!"
|
||||
}
|
||||
|
||||
main
|
||||
main
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference.
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
|
||||
#
|
||||
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
|
||||
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
|
||||
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
|
||||
# and is what `pyproject.toml` consumes by default; this script is for
|
||||
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
|
||||
#
|
||||
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh
|
||||
# bash scripts/install_deep_gemm.sh # build + install in-place
|
||||
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: 477618c)
|
||||
# --ref REF DeepGEMM commit hash (default: d30fc36)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
@@ -17,7 +23,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
|
||||
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
|
||||
@@ -23,6 +23,8 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna import LagunaForCausalLM as PrimeRLLagunaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
@@ -130,6 +132,59 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
"laguna": {
|
||||
"config_class": LagunaConfig,
|
||||
"config_kwargs": dict(
|
||||
vocab_size=100352,
|
||||
hidden_size=512,
|
||||
intermediate_size=2048,
|
||||
num_hidden_layers=12,
|
||||
num_attention_heads=8,
|
||||
num_attention_heads_per_layer=[8] * 12,
|
||||
num_key_value_heads=4,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_parameters={
|
||||
"full_attention": {
|
||||
"rope_type": "yarn",
|
||||
"rope_theta": 500000.0,
|
||||
"factor": 4.0,
|
||||
"original_max_position_embeddings": 1024,
|
||||
"beta_slow": 1.0,
|
||||
"beta_fast": 64.0,
|
||||
"attention_factor": 1.0,
|
||||
"partial_rotary_factor": 0.5,
|
||||
},
|
||||
"sliding_attention": {
|
||||
"rope_type": "default",
|
||||
"rope_theta": 10000.0,
|
||||
"partial_rotary_factor": 1.0,
|
||||
},
|
||||
},
|
||||
layer_types=["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"] * 3,
|
||||
sliding_window=512,
|
||||
moe_intermediate_size=128,
|
||||
shared_expert_intermediate_size=128,
|
||||
num_experts=8,
|
||||
num_experts_per_tok=4,
|
||||
mlp_layer_types=["dense"] + ["sparse"] * 11,
|
||||
moe_routed_scaling_factor=2.5,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=9,
|
||||
bos_token_id=2,
|
||||
eos_token_id=[2, 24],
|
||||
auto_map={
|
||||
"AutoConfig": "poolside/Laguna-XS.2--configuration_laguna.LagunaConfig",
|
||||
"AutoModel": "poolside/Laguna-XS.2--modeling_laguna.LagunaModel",
|
||||
"AutoModelForCausalLM": "poolside/Laguna-XS.2--modeling_laguna.LagunaForCausalLM",
|
||||
},
|
||||
),
|
||||
"hf_model_class": None, # uses Poolside remote modeling code
|
||||
"prime_model_class": PrimeRLLagunaForCausalLM,
|
||||
"tokenizer_source": "poolside/Laguna-XS.2",
|
||||
},
|
||||
"qwen3_5_moe_vlm": {
|
||||
"config_fn": _qwen3_5_moe_vlm_config,
|
||||
"hf_model_class": HFQwen3_5MoeVLM,
|
||||
|
||||
@@ -177,4 +177,5 @@ In TOML, an empty section header does the same:
|
||||
- `src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
|
||||
- `src/prime_rl/configs/` — all domain-specific config classes
|
||||
- `configs/debug/` — minimal debug configs for testing
|
||||
- `configs/private/` — private configs via git submodule (internal only)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -88,4 +88,5 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- `src/prime_rl/entrypoints/` — top-level entrypoints (`rl`, `sft`, `inference`)
|
||||
- `src/prime_rl/configs/` — all config classes
|
||||
- `configs/debug/` — minimal configs for quick testing
|
||||
- `configs/private/` — private configs submodule (if access granted)
|
||||
- `examples/` — full example configs for various tasks
|
||||
|
||||
@@ -5,13 +5,37 @@ description: How to install prime-rl and its optional dependencies. Use when set
|
||||
|
||||
# Installation
|
||||
|
||||
## Cloning
|
||||
|
||||
prime-rl is a monorepo with submodules. Clone the repo first, then initialize submodules explicitly:
|
||||
|
||||
```bash
|
||||
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
For an existing clone, initialize the public submodules by passing explicit paths:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
```
|
||||
|
||||
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
|
||||
|
||||
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
|
||||
|
||||
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
|
||||
|
||||
## Basic
|
||||
```bash
|
||||
uv sync # core dependencies only
|
||||
uv sync --group dev # dev tools: pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: includes flash-attn, flash-attn-cute, etc.
|
||||
uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
|
||||
|
||||
## Advanced
|
||||
|
||||
### Mamba-SSM (NemotronH models)
|
||||
|
||||
@@ -145,6 +145,8 @@ These tell you whether training is healthy or diverging.
|
||||
|--------|--------|-------------|
|
||||
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
|
||||
| `entropy/mean` | trainer | policy entropy |
|
||||
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
|
||||
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
|
||||
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
|
||||
|
||||
#### Performance
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported
|
||||
@@ -45,6 +45,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
kv_offload=config.kv_cache_offload is not None,
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
@@ -63,10 +64,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
kv_offload=config.deployment.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.deployment.kv_cache_offload.cpu_bytes)
|
||||
if config.deployment.kv_cache_offload
|
||||
else 0,
|
||||
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
|
||||
@@ -12,6 +12,7 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
@@ -348,10 +349,10 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
@@ -444,8 +445,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
kv_offload=infer_deploy.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(infer_deploy.kv_cache_offload.cpu_bytes) if infer_deploy.kv_cache_offload else 0,
|
||||
kv_offload=config.inference.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
|
||||
if config.inference.kv_cache_offload
|
||||
else 0,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
@@ -469,6 +472,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
|
||||
@@ -8,6 +8,7 @@ from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
+229
-275
@@ -3,7 +3,7 @@ from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
@@ -16,8 +16,39 @@ def transformers_v5_compat():
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_ep_scatter()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_offloading_connector_cpu_block_count()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
# vLLM's layerwise reload materializes each buffer as an independent tensor
|
||||
# and then copies it back into the original kernel storage. When a buffer
|
||||
# aliases a parameter (e.g. NemotronH Mamba's mixer.conv_weights, a view of
|
||||
# mixer.conv1d.weight), the buffer copy stamps garbage into the parameter's
|
||||
# storage *after* the parameter has been correctly reloaded. Skip the copy
|
||||
# for any buffer that shares storage with a parameter; _place_kernel_tensors
|
||||
# re-registers the original view, which trivially reflects the parameter.
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
def _copy_and_restore_kernel_tensors(layer: torch.nn.Module, info: reload_layerwise.LayerReloadingInfo):
|
||||
assert info.kernel_tensors is not None
|
||||
parameters, buffers = info.kernel_tensors
|
||||
param_storage_ptrs = {p.untyped_storage().data_ptr() for p in layer.parameters(recurse=True)}
|
||||
for name, param in parameters.items():
|
||||
param.data.copy_(getattr(layer, name))
|
||||
for name, buffer in buffers.items():
|
||||
if buffer.untyped_storage().data_ptr() in param_storage_ptrs:
|
||||
continue
|
||||
buffer.data.copy_(getattr(layer, name))
|
||||
|
||||
reload_layerwise._place_kernel_tensors(layer, info)
|
||||
|
||||
reload_layerwise._copy_and_restore_kernel_tensors = _copy_and_restore_kernel_tensors
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -174,6 +205,140 @@ def monkey_patch_deep_gemm_ep_scatter():
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM ep_scatter.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
y_q_ptr,
|
||||
y_s_ptr,
|
||||
M: tl.int64,
|
||||
N: tl.int64,
|
||||
y_s_col_stride: tl.int64,
|
||||
eps,
|
||||
fp8_min: tl.constexpr,
|
||||
fp8_max: tl.constexpr,
|
||||
use_ue8m0: tl.constexpr,
|
||||
GROUP_SIZE: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
N_2 = N // 2
|
||||
|
||||
m_offset = (pid_m * BLOCK_M).to(tl.int64)
|
||||
n_offset = (pid_n * BLOCK_N).to(tl.int64)
|
||||
if m_offset >= M:
|
||||
return
|
||||
|
||||
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
|
||||
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
|
||||
|
||||
base_y_ptr = y_ptr + m_offset * N + n_offset
|
||||
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
|
||||
|
||||
act_in = tl.load(act_in_ptrs)
|
||||
mul_in = tl.load(act_in_ptrs + N_2)
|
||||
|
||||
act_in = act_in.to(tl.float32)
|
||||
one_f32 = tl.cast(1, tl.float32)
|
||||
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
|
||||
y = (silu_out * mul_in).to(tl.float32)
|
||||
|
||||
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
|
||||
scale_raw = absmax * (1.0 / fp8_max)
|
||||
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
|
||||
y_s = tl.reshape(y_s, (BLOCK_M, 1))
|
||||
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
|
||||
|
||||
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
|
||||
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
|
||||
tl.store(y_q_ptrs, y_q)
|
||||
|
||||
group_id = n_offset // GROUP_SIZE
|
||||
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
|
||||
y_s_ptrs = base_y_s_ptr + offs_m
|
||||
y_s = tl.reshape(y_s, (BLOCK_M,))
|
||||
tl.store(y_s_ptrs, y_s)
|
||||
|
||||
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
|
||||
input: torch.Tensor,
|
||||
output: torch.Tensor | None = None,
|
||||
use_ue8m0: bool | None = None,
|
||||
eps: float = 1e-10,
|
||||
):
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
|
||||
|
||||
group_size = 128
|
||||
assert input.ndim == 2
|
||||
if output is not None:
|
||||
assert output.ndim == 2
|
||||
assert input.size(0) % group_size == 0
|
||||
assert input.size(1) % (group_size * 2) == 0
|
||||
|
||||
if use_ue8m0 is None:
|
||||
use_ue8m0 = is_deep_gemm_e8m0_used()
|
||||
|
||||
M, N = input.size()
|
||||
N_2 = N // 2
|
||||
|
||||
fp8_dtype = current_platform.fp8_dtype()
|
||||
if output is None:
|
||||
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
|
||||
|
||||
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
|
||||
|
||||
block_m = 8
|
||||
block_n = group_size
|
||||
assert M % block_m == 0
|
||||
assert N_2 % block_n == 0
|
||||
|
||||
finfo = torch.finfo(fp8_dtype)
|
||||
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
|
||||
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
|
||||
|
||||
grid = (M // block_m, N_2 // block_n)
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
|
||||
input,
|
||||
output,
|
||||
output_scales,
|
||||
M,
|
||||
N,
|
||||
output_scales.stride(-1),
|
||||
eps,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
use_ue8m0,
|
||||
group_size,
|
||||
block_m,
|
||||
block_n,
|
||||
)
|
||||
|
||||
return output, output_scales
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_silu_mul_quant_int64():
|
||||
# Temporary local carry for large DeepGEMM profile shapes whose row offsets
|
||||
# exceed signed int32 address arithmetic in vLLM's Triton kernel.
|
||||
import sys
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
|
||||
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
|
||||
if deep_gemm_moe_module is not None:
|
||||
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
)
|
||||
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
@@ -715,239 +880,6 @@ def monkey_patch_harmony_stop_token_propagation():
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_fused_moe_lora_dp():
|
||||
"""Fix: LoRA + MoE + DP>1 produces corrupted output in vLLM 0.17.0.
|
||||
|
||||
Two bugs:
|
||||
1. LoRA injection sets supports_internal_mk=True (via moe_kernel not None),
|
||||
causing the MoE runner to skip DP dispatch/combine. But the LoRA kernel
|
||||
uses NoDPEP and doesn't handle DP internally.
|
||||
2. LoRA decorators capture full-batch tensors but fire per-chunk inside the
|
||||
kernel's chunk loop. At DP>=3, dispatched batch > CHUNK_SIZE causes
|
||||
shape mismatches.
|
||||
|
||||
Fix: Replace _inject_lora_into_fused_moe with a version that:
|
||||
(a) sets moe_kernel=None so the runner correctly dispatches
|
||||
(b) makes decorators chunk-aware by tracking chunk offsets
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/23244
|
||||
"""
|
||||
import types
|
||||
|
||||
from vllm import envs
|
||||
from vllm.distributed.utils import divide
|
||||
from vllm.lora.layers.fused_moe import FusedMoEWithLoRA
|
||||
from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str
|
||||
from vllm.model_executor.layers.fused_moe.fused_marlin_moe import MarlinExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import FusedMoEModularMethod
|
||||
from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import UnfusedOAITritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
|
||||
from vllm.model_executor.layers.fused_moe.prepare_finalize import MoEPrepareAndFinalizeNoDPEPModular
|
||||
|
||||
def _fixed_inject(self):
|
||||
moe_state_dict = {}
|
||||
top_k = self.base_layer.top_k
|
||||
|
||||
self.base_layer.ensure_moe_quant_config_init()
|
||||
quant_config = self.base_layer.quant_method.moe_quant_config
|
||||
|
||||
if getattr(self.base_layer.quant_method, "supports_internal_mk", False):
|
||||
m_fused_moe_fn = self.base_layer.quant_method.moe_kernel
|
||||
m_fused_moe_fn.shared_experts = None
|
||||
else:
|
||||
prepare_finalize = MoEPrepareAndFinalizeNoDPEPModular()
|
||||
m_fused_moe_fn = FusedMoEKernel(
|
||||
prepare_finalize,
|
||||
self.base_layer.quant_method.select_gemm_impl(prepare_finalize, self.base_layer),
|
||||
)
|
||||
|
||||
if quant_config.use_mxfp4_w4a16:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, (MarlinExperts, UnfusedOAITritonExperts))
|
||||
else:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, TritonExperts)
|
||||
|
||||
# --- Decorators (chunk-aware) ---
|
||||
|
||||
def fwd_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
moe_state_dict["hidden_states"] = kwargs["hidden_states"]
|
||||
moe_state_dict["topk_ids"] = kwargs["topk_ids"]
|
||||
moe_state_dict["topk_weights"] = kwargs["topk_weights"]
|
||||
moe_state_dict["expert_map"] = kwargs["expert_map"]
|
||||
moe_state_dict["apply_router_weight_on_input"] = kwargs["apply_router_weight_on_input"]
|
||||
moe_state_dict["_chunk_offset"] = 0
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def act_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
_, output, input = args
|
||||
chunk_M = input.view(-1, top_k, input.shape[-1]).shape[0]
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
curr_topk_ids = moe_state_dict["topk_ids"][chunk_offset : chunk_offset + chunk_M]
|
||||
expert_map = moe_state_dict["expert_map"]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w13_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w13",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=self._w13_slices,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
SPARSITY_FACTOR = 8
|
||||
naive_block_assignment = (
|
||||
expert_map is None
|
||||
and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras
|
||||
)
|
||||
token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora = (
|
||||
self.punica_wrapper.moe_lora_align_block_size(
|
||||
curr_topk_ids,
|
||||
num_tokens,
|
||||
shrink_config["BLOCK_SIZE_M"],
|
||||
self.base_layer.local_num_experts,
|
||||
self.max_loras,
|
||||
self.adapter_enabled,
|
||||
expert_map,
|
||||
naive_block_assignment=naive_block_assignment,
|
||||
)
|
||||
)
|
||||
moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora
|
||||
moe_state_dict["expert_ids_lora"] = expert_ids_lora
|
||||
moe_state_dict["num_tokens_post_padded_lora"] = num_tokens_post_padded_lora
|
||||
moe_state_dict["token_lora_mapping"] = token_lora_mapping
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
input.view(-1, top_k, input.shape[-1]),
|
||||
hidden_states,
|
||||
self.w13_lora_a_stacked,
|
||||
self.w13_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
fully_sharded=self.fully_sharded,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["intermediate_cache2"] = output
|
||||
moe_state_dict["_chunk_M"] = chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
def moe_sum_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
chunk_M = moe_state_dict.get("_chunk_M", moe_state_dict["hidden_states"].size(0))
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w2_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w2",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=1,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"]
|
||||
expert_ids_lora = moe_state_dict["expert_ids_lora"]
|
||||
num_tokens_post_padded_lora = moe_state_dict["num_tokens_post_padded_lora"]
|
||||
token_lora_mapping = moe_state_dict.get("token_lora_mapping")
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
intermediate_cache2 = moe_state_dict["intermediate_cache2"]
|
||||
intermediate_cache3 = args[0]
|
||||
shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
intermediate_cache3,
|
||||
intermediate_cache2,
|
||||
self.w2_lora_a_stacked,
|
||||
self.w2_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
True,
|
||||
fully_sharded=self.fully_sharded,
|
||||
offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["_chunk_offset"] = chunk_offset + chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
# --- Install decorators and replace quant method ---
|
||||
|
||||
fused_experts = m_fused_moe_fn.impl.fused_experts
|
||||
m_fused_moe_fn.apply = fwd_decorator(self.base_layer, m_fused_moe_fn.apply)
|
||||
fused_experts.activation = act_decorator(self.base_layer, fused_experts.activation)
|
||||
fused_experts.moe_sum = moe_sum_decorator(self.base_layer, fused_experts.moe_sum)
|
||||
|
||||
new_method = FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn)
|
||||
|
||||
# Bug 1 fix: NoDPEP kernel makes supports_internal_mk=True, causing the
|
||||
# runner to skip DP dispatch/combine. Set moe_kernel=None and patch apply().
|
||||
if isinstance(m_fused_moe_fn.prepare_finalize, MoEPrepareAndFinalizeNoDPEPModular):
|
||||
saved_kernel = new_method.moe_kernel
|
||||
saved_disable_expert_map = new_method.disable_expert_map
|
||||
new_method.moe_kernel = None
|
||||
|
||||
def _apply_with_saved_kernel(self, layer, x, topk_weights, topk_ids, shared_experts_input):
|
||||
return saved_kernel.apply(
|
||||
hidden_states=x,
|
||||
w1=layer.w13_weight,
|
||||
w2=layer.w2_weight,
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
activation=layer.activation,
|
||||
global_num_experts=layer.global_num_experts,
|
||||
apply_router_weight_on_input=layer.apply_router_weight_on_input,
|
||||
expert_map=None if saved_disable_expert_map else layer.expert_map,
|
||||
shared_experts_input=shared_experts_input,
|
||||
)
|
||||
|
||||
new_method.apply = types.MethodType(_apply_with_saved_kernel, new_method)
|
||||
|
||||
self.base_layer._replace_quant_method(new_method)
|
||||
|
||||
FusedMoEWithLoRA._inject_lora_into_fused_moe = _fixed_inject
|
||||
|
||||
|
||||
def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
"""Fix DP pause/resume deadlocks around weight updates.
|
||||
|
||||
@@ -1020,46 +952,6 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_offloading_connector_cpu_block_count():
|
||||
"""Fix CPU block count miscalculation in OffloadingConnector.
|
||||
|
||||
CPUOffloadingSpec derives kv_bytes_per_block from page_size_bytes multiplied
|
||||
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
|
||||
already aggregated across layers in the group. The undersized CPU pool then
|
||||
produces out-of-bounds block mappings and swap_blocks segfaults.
|
||||
|
||||
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
|
||||
divided by num_blocks, matching the upstream PR.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/39617
|
||||
"""
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
_original_init = CPUOffloadingSpec.__init__
|
||||
|
||||
def _patched_init(self, vllm_config, kv_cache_config):
|
||||
_original_init(self, vllm_config, kv_cache_config)
|
||||
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
if kv_cache_config.num_blocks > 0:
|
||||
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
|
||||
kv_bytes_per_block = (
|
||||
total_gpu_kv_bytes // kv_cache_config.num_blocks
|
||||
) * vllm_config.parallel_config.world_size
|
||||
else:
|
||||
kv_bytes_per_block = 0
|
||||
|
||||
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
|
||||
self.num_blocks = (
|
||||
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
|
||||
)
|
||||
|
||||
CPUOffloadingSpec.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
@@ -1086,3 +978,65 @@ def monkey_patch_no_moe_lora():
|
||||
self.is_lora_enabled = False
|
||||
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
|
||||
|
||||
def monkey_patch_fp32_lm_head():
|
||||
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
|
||||
|
||||
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
|
||||
matmul accumulates and emits fp32 directly without zero-padding the bf16
|
||||
operands or maintaining a separate fp32 weight copy. This avoids the
|
||||
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
|
||||
where lm_head precision actually leaks before the sampler's softmax.
|
||||
|
||||
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
|
||||
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
|
||||
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
|
||||
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
|
||||
instance — reading it from ``_get_logits`` during serving doesn't work
|
||||
because vLLM doesn't keep the context set during forwards.
|
||||
|
||||
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
|
||||
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
|
||||
and just as correct.
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = LogitsProcessor.__init__
|
||||
_original_get_logits = LogitsProcessor._get_logits
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
vllm_config = get_current_vllm_config()
|
||||
additional_config = vllm_config.additional_config or {}
|
||||
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
|
||||
if self._fp32_lm_head_enabled:
|
||||
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
|
||||
|
||||
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
|
||||
if not getattr(self, "_fp32_lm_head_enabled", False):
|
||||
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
|
||||
|
||||
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
|
||||
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
|
||||
# flatten defensively in case some future caller passes 3D.
|
||||
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
|
||||
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
|
||||
if embedding_bias is not None:
|
||||
logits = logits + embedding_bias.to(torch.float32)
|
||||
if hidden_states.dim() > 2:
|
||||
logits = logits.reshape(*hidden_states.shape[:-1], -1)
|
||||
|
||||
logits = self._gather_logits(logits)
|
||||
if logits is not None:
|
||||
logits = logits[..., : self.org_vocab_size]
|
||||
return logits
|
||||
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
@@ -21,7 +21,6 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateRequest
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
@@ -153,14 +152,13 @@ monkey_patch_harmony_stop_token_propagation()
|
||||
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.19 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
# Create our own router for custom endpoints
|
||||
router = APIRouter()
|
||||
LIVENESS_TIMEOUT_SECONDS = 5.0
|
||||
|
||||
|
||||
def engine_client(request: Request) -> EngineClient:
|
||||
@@ -181,36 +179,10 @@ WORKER_EXTENSION_CLS = {
|
||||
}
|
||||
|
||||
|
||||
def generate_handler(request: Request):
|
||||
return request.app.state.openai_serving_generate
|
||||
|
||||
|
||||
def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/generate",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"application/json": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _generate(request: GenerateRequest, raw_request: Request):
|
||||
handler = generate_handler(raw_request)
|
||||
if handler is None:
|
||||
return JSONResponse({"error": "generate endpoint not available"}, status_code=503)
|
||||
result = await handler.generate(request, raw_request)
|
||||
if isinstance(result, dict) and "error" in result:
|
||||
return JSONResponse(result, status_code=500)
|
||||
return JSONResponse(content=result.model_dump())
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
@@ -272,7 +244,7 @@ async def liveness(raw_request: Request):
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
engine_client(raw_request).collective_rpc("liveness_probe"),
|
||||
timeout=LIVENESS_TIMEOUT_SECONDS,
|
||||
timeout=raw_request.app.state.liveness_timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
|
||||
@@ -303,15 +275,19 @@ async def custom_init_app_state(
|
||||
):
|
||||
"""
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state.
|
||||
1. Call the original init_app_state to set up standard state, including
|
||||
vLLM 0.20's ``serving_tokens`` for ``/inference/v1/generate``.
|
||||
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
|
||||
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
|
||||
token IDs alongside the rendered chat completion.
|
||||
3. Add ``/v1/generate`` endpoint for renderer-based token-level inference.
|
||||
3. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
|
||||
routing and ``routed_experts`` export survive the migration off the
|
||||
legacy ``/v1/generate`` endpoint.
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
state.liveness_timeout_seconds = args.liveness_timeout_seconds
|
||||
|
||||
# TITO: server-side chat templating + token IDs.
|
||||
if "generate" in supported_tasks and state.openai_serving_chat is not None:
|
||||
@@ -323,11 +299,16 @@ async def custom_init_app_state(
|
||||
else:
|
||||
state.openai_serving_chat_with_tokens = None
|
||||
|
||||
# /v1/generate endpoint — tokens + optional images, no chat template
|
||||
from prime_rl.inference.vllm.serving_generate import OpenAIServingGenerate
|
||||
# Swap in our ServingTokens subclass for /inference/v1/generate so the
|
||||
# X-data-parallel-rank header and routed_experts response field — both
|
||||
# used by prime-RL's renderer / router-replay paths — keep working.
|
||||
if "generate" in supported_tasks and state.serving_tokens is not None:
|
||||
from prime_rl.inference.vllm.serving_tokens import PrimeRlServingTokens
|
||||
|
||||
chat_handler = state.openai_serving_chat if "generate" in supported_tasks else None
|
||||
state.openai_serving_generate = OpenAIServingGenerate(engine_client, chat_handler=chat_handler)
|
||||
upstream = state.serving_tokens
|
||||
prime_serving = object.__new__(PrimeRlServingTokens)
|
||||
prime_serving.__dict__.update(upstream.__dict__)
|
||||
state.serving_tokens = prime_serving
|
||||
|
||||
|
||||
import vllm.entrypoints.openai.api_server
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import base64
|
||||
from collections.abc import AsyncGenerator, AsyncIterator
|
||||
from typing import ClassVar, Optional, Union
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
|
||||
@@ -16,28 +14,17 @@ from vllm.outputs import RequestOutput
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.serving_tokens import _RoutedExpertsCaptureBase
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class _RoutedExpertsCapture:
|
||||
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
|
||||
self._generator = generator
|
||||
self.routed_experts: dict[int, dict] = {}
|
||||
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
|
||||
"""Chat-endpoint variant: mutates choices in-place because
|
||||
``ChatCompletionResponseChoice`` is ``extra='allow'``, so an extra
|
||||
``routed_experts`` attribute survives serialization."""
|
||||
|
||||
def _encode_routed_experts(self, arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
async def __aiter__(self):
|
||||
async for request_output in self._generator:
|
||||
for output in request_output.outputs:
|
||||
if output.routed_experts is not None:
|
||||
self.routed_experts[output.index] = self._encode_routed_experts(output.routed_experts)
|
||||
yield request_output
|
||||
|
||||
def post_process(self, response: ChatCompletionResponse):
|
||||
def post_process(self, response: ChatCompletionResponse) -> None:
|
||||
for choice in response.choices:
|
||||
if choice.index in self.routed_experts:
|
||||
choice.routed_experts = self.routed_experts[choice.index]
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
"""/v1/generate endpoint — accepts pre-tokenized inputs.
|
||||
|
||||
Text-only tokens in, tokens out. The Renderer does all tokenization client-side.
|
||||
No Jinja rendering, no server-side chat template application.
|
||||
|
||||
VLMs do not use this endpoint. The orchestrator routes VLMs to MITO
|
||||
(/v1/chat/completions) where vLLM handles image preprocessing and chat
|
||||
templating server-side.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import BaseModel
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.inputs.engine import tokens_input
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
# ── Request / Response schemas ───────────────────────────────────────
|
||||
|
||||
|
||||
class GenerateRequest(BaseModel):
|
||||
model: str | None = None
|
||||
prompt_token_ids: list[int]
|
||||
|
||||
# When unset, fill from max_model_len - prompt_len at request time so we
|
||||
# match /v1/chat/completions behavior. The previous 4096 hard default
|
||||
# silently truncated long completions on 8k+ context runs (e.g. hendrycks
|
||||
# reasoning rollouts capped at 4096 tokens, making rendered rollouts look
|
||||
# shorter than main's for the same model).
|
||||
max_tokens: int | None = None
|
||||
temperature: float = 1.0
|
||||
top_p: float = 1.0
|
||||
top_k: int = -1
|
||||
min_p: float = 0.0
|
||||
seed: int | None = None
|
||||
n: int = 1
|
||||
stop_token_ids: list[int] | None = None
|
||||
repetition_penalty: float = 1.0
|
||||
min_tokens: int = 0
|
||||
prompt_logprobs: bool = False
|
||||
priority: int = 0
|
||||
# Prefix-cache invalidation salt. Must match main's
|
||||
# /v1/chat/completions/tokens path: the orchestrator sets
|
||||
# `extra_body["cache_salt"] = str(ckpt_step)` on every rollout
|
||||
# request. vLLM's KV cache hashes include this salt, so when the
|
||||
# step changes the cache misses and KV is recomputed with fresh
|
||||
# weights. Without this, renderers path silently reuses stale KV
|
||||
# from before the latest weight update and its logprobs drift from
|
||||
# the trainer's forward pass (mismatch_kl grows 3x over training).
|
||||
cache_salt: str | None = None
|
||||
|
||||
|
||||
class GenerateChoiceResponse(BaseModel):
|
||||
index: int
|
||||
token_ids: list[int]
|
||||
logprobs: list[float]
|
||||
finish_reason: str | None = None
|
||||
routed_experts: dict | None = None
|
||||
|
||||
|
||||
class GenerateResponse(BaseModel):
|
||||
id: str
|
||||
model: str
|
||||
prompt_token_ids: list[int]
|
||||
choices: list[GenerateChoiceResponse]
|
||||
usage: dict
|
||||
prompt_logprobs: list[float | None] | None = None
|
||||
|
||||
|
||||
# ── Handler ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class OpenAIServingGenerate:
|
||||
"""Lightweight generate handler — tokens in, tokens out."""
|
||||
|
||||
def __init__(self, engine_client: EngineClient, chat_handler: Any | None = None):
|
||||
self.engine_client = engine_client
|
||||
self.chat_handler = chat_handler
|
||||
|
||||
async def generate(self, request: GenerateRequest, raw_request: Request) -> GenerateResponse | dict:
|
||||
# Pre-rendered TokensInput shape (type="token") — avoids vLLM's
|
||||
# "raw prompt" deprecation that targets plain lists/strings.
|
||||
engine_prompt = tokens_input(request.prompt_token_ids, cache_salt=request.cache_salt)
|
||||
|
||||
# Match /v1/chat/completions: if the client didn't ask for a specific
|
||||
# cap, let the model generate up to whatever room is left in context.
|
||||
# vLLM v1 AsyncLLM exposes model_config directly (no async getter).
|
||||
max_tokens = request.max_tokens
|
||||
if max_tokens is None:
|
||||
max_model_len = self.engine_client.model_config.max_model_len
|
||||
max_tokens = max(1, max_model_len - len(request.prompt_token_ids))
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
top_k=request.top_k,
|
||||
min_p=request.min_p,
|
||||
seed=request.seed,
|
||||
n=request.n,
|
||||
stop_token_ids=request.stop_token_ids or [],
|
||||
repetition_penalty=request.repetition_penalty,
|
||||
min_tokens=request.min_tokens,
|
||||
logprobs=1,
|
||||
prompt_logprobs=1 if request.prompt_logprobs else None,
|
||||
skip_special_tokens=False,
|
||||
)
|
||||
|
||||
request_id = f"gen-{uuid4().hex[:16]}"
|
||||
routed_experts_map: dict[int, dict] = {}
|
||||
final_output: RequestOutput | None = None
|
||||
data_parallel_rank = None
|
||||
lora_request = None
|
||||
trace_headers = None
|
||||
if self.chat_handler is not None:
|
||||
data_parallel_rank = self.chat_handler._get_data_parallel_rank(raw_request)
|
||||
trace_headers = await self.chat_handler._get_trace_headers(raw_request.headers)
|
||||
lora_request = self.chat_handler._maybe_get_adapters(request)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
)
|
||||
|
||||
# Drain the generator without polling ``raw_request.is_disconnected``
|
||||
# per decode step. That poll is one ASGI ``receive()`` await per
|
||||
# yielded token — at ~2k concurrent rollouts each producing dozens of
|
||||
# tokens, it was the single largest per-step overhead on the /generate
|
||||
# path (vLLM's own chat completions handler uses the CancelledError
|
||||
# pattern for the same reason). Starlette cancels this coroutine on
|
||||
# client disconnect, so the except branch still catches it.
|
||||
try:
|
||||
async for output in generator:
|
||||
for comp_output in output.outputs:
|
||||
if comp_output.routed_experts is not None:
|
||||
routed_experts_map[comp_output.index] = _encode_routed_experts(comp_output.routed_experts)
|
||||
final_output = output
|
||||
except asyncio.CancelledError:
|
||||
await self.engine_client.abort(request_id)
|
||||
raise
|
||||
|
||||
if final_output is None:
|
||||
return {"error": "No output generated"}
|
||||
|
||||
choices = []
|
||||
for output in final_output.outputs:
|
||||
token_ids = list(output.token_ids)
|
||||
logprobs_list: list[float] = []
|
||||
if output.logprobs:
|
||||
for i, lp_dict in enumerate(output.logprobs):
|
||||
if i < len(token_ids) and token_ids[i] in lp_dict:
|
||||
logprobs_list.append(lp_dict[token_ids[i]].logprob)
|
||||
else:
|
||||
logprobs_list.append(0.0)
|
||||
|
||||
choices.append(
|
||||
GenerateChoiceResponse(
|
||||
index=output.index,
|
||||
token_ids=token_ids,
|
||||
logprobs=logprobs_list,
|
||||
finish_reason=output.finish_reason,
|
||||
routed_experts=routed_experts_map.get(output.index),
|
||||
)
|
||||
)
|
||||
|
||||
prompt_len = len(final_output.prompt_token_ids)
|
||||
completion_len = sum(len(c.token_ids) for c in choices)
|
||||
prompt_logprobs = _extract_prompt_logprobs(final_output.prompt_logprobs)
|
||||
|
||||
return GenerateResponse(
|
||||
id=request_id,
|
||||
model=request.model or "",
|
||||
prompt_token_ids=list(final_output.prompt_token_ids),
|
||||
choices=choices,
|
||||
usage={
|
||||
"prompt_tokens": prompt_len,
|
||||
"completion_tokens": completion_len,
|
||||
"total_tokens": prompt_len + completion_len,
|
||||
},
|
||||
prompt_logprobs=prompt_logprobs,
|
||||
)
|
||||
|
||||
|
||||
def _encode_routed_experts(arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
|
||||
def _extract_prompt_logprobs(
|
||||
prompt_logprobs: list[dict[int, Any] | None] | Mapping[int, Any] | None,
|
||||
) -> list[float | None] | None:
|
||||
if prompt_logprobs is None:
|
||||
return None
|
||||
if isinstance(prompt_logprobs, Mapping):
|
||||
prompt_logprobs = [prompt_logprobs]
|
||||
|
||||
extracted: list[float | None] = []
|
||||
for token_logprobs in prompt_logprobs:
|
||||
if not token_logprobs:
|
||||
extracted.append(None)
|
||||
continue
|
||||
selected = next(iter(token_logprobs.values()))
|
||||
logprob = selected.logprob if hasattr(selected, "logprob") else selected.get("logprob")
|
||||
extracted.append(float(logprob) if logprob is not None else None)
|
||||
return extracted
|
||||
@@ -0,0 +1,321 @@
|
||||
"""Prime-RL extensions to vLLM's `/inference/v1/generate` handler.
|
||||
|
||||
vLLM 0.20 ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.serve.disagg.serving.ServingTokens`` that already covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs and
|
||||
priority. Three prime-RL features are not in the upstream protocol though, so
|
||||
we subclass it to add them back:
|
||||
|
||||
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
|
||||
header and forwarded to ``engine_client.generate``. The DP-replicated
|
||||
inference servers prime-RL runs need this to target a specific replica.
|
||||
|
||||
2. ``routed_experts`` per-token export — when the engine emits routing
|
||||
decisions (``enable_return_routed_experts``), surface them on each choice.
|
||||
This is what the trainer's router-replay path consumes.
|
||||
|
||||
3. Server-side ``max_tokens`` defaulting — ``ServingTokens`` hands the
|
||||
client-supplied ``SamplingParams`` to the engine verbatim, and
|
||||
``SamplingParams.max_tokens`` defaults to ``16`` (a dataclass-level
|
||||
default that predates the OpenAI-compat layer). Every other vLLM
|
||||
endpoint masks this server-side via
|
||||
``vllm.entrypoints.utils.get_max_tokens`` (see e.g.
|
||||
``OpenAIServingChat`` at ``serving.py:284``); the disagg endpoint
|
||||
skips that path. Mirror it here so callers that omit ``max_tokens``
|
||||
don't silently truncate at 16. Drop once vLLM patches upstream.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import AsyncGenerator
|
||||
from functools import cached_property
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.serving import ServingTokens
|
||||
from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
routed_experts: dict | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Per-token expert routing decisions (base85-encoded int32 array + shape). "
|
||||
"Populated only when the engine was launched with "
|
||||
"``enable_return_routed_experts=True``; otherwise ``None``."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
|
||||
|
||||
def encode_routed_experts(arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
|
||||
class _RoutedExpertsCaptureBase:
|
||||
"""Wraps the engine result generator and accumulates a
|
||||
``{output_index: encoded_experts}`` map as outputs stream. Subclasses
|
||||
implement ``post_process`` to fold the captured map into the response
|
||||
in whatever shape the endpoint returns (in-place vs rebuilt)."""
|
||||
|
||||
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
|
||||
self._generator = generator
|
||||
self.routed_experts: dict[int, dict] = {}
|
||||
|
||||
async def __aiter__(self):
|
||||
async for request_output in self._generator:
|
||||
for output in request_output.outputs:
|
||||
if output.routed_experts is not None:
|
||||
self.routed_experts[output.index] = encode_routed_experts(output.routed_experts)
|
||||
yield request_output
|
||||
|
||||
|
||||
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
|
||||
"""Generate-endpoint variant: rebuilds the response with
|
||||
``PrimeRlGenerateResponseChoice`` because upstream's
|
||||
``GenerateResponseChoice`` isn't ``extra='allow'``, so an attribute
|
||||
set after construction wouldn't survive serialization."""
|
||||
|
||||
def post_process(self, response: GenerateResponse) -> PrimeRlGenerateResponse:
|
||||
new_choices = [
|
||||
PrimeRlGenerateResponseChoice(
|
||||
**choice.model_dump(),
|
||||
routed_experts=self.routed_experts.get(choice.index),
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=new_choices,
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
|
||||
instance, which means an unset ``max_tokens`` is indistinguishable from
|
||||
an explicit ``max_tokens=16`` once the request reaches the handler —
|
||||
both surface as ``sampling_params.max_tokens == 16``. We re-read the
|
||||
cached body to recover that distinction. When we can't (no raw_request,
|
||||
non-JSON body, or read error), pessimistically assume the client did
|
||||
set it so we never clobber an explicit value.
|
||||
"""
|
||||
if raw_request is None:
|
||||
return True
|
||||
try:
|
||||
body = await raw_request.json()
|
||||
except Exception:
|
||||
return True
|
||||
if not isinstance(body, dict):
|
||||
return True
|
||||
sp = body.get("sampling_params")
|
||||
return isinstance(sp, dict) and "max_tokens" in sp
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + DP-rank routing + routed_experts export + max_tokens defaulting."""
|
||||
|
||||
@cached_property
|
||||
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
|
||||
"""Server-side ``max_tokens`` defaulting inputs, mirroring ``OpenAIServingChat``.
|
||||
|
||||
Computed lazily because ``custom_init_app_state`` swaps in this
|
||||
subclass via ``object.__new__`` + ``__dict__.update`` (so our
|
||||
``__init__`` never runs).
|
||||
"""
|
||||
diff = self.model_config.get_diff_sampling_param()
|
||||
mc = self.model_config
|
||||
override = (
|
||||
diff.get("max_tokens")
|
||||
if mc.generation_config not in ("auto", "vllm")
|
||||
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
|
||||
# in case a downstream caller ever sets the attribute to ``None``
|
||||
# (``getattr``'s default only fires when the attribute is missing,
|
||||
# not when it exists with a ``None`` value).
|
||||
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
|
||||
)
|
||||
return diff, override
|
||||
|
||||
async def serve_tokens(
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Mirrors upstream ``ServingTokens.serve_tokens`` (vllm 0.20). Diffs:
|
||||
# (a) inject ``data_parallel_rank`` from the inbound header into
|
||||
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
|
||||
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
|
||||
# (c) dispatch to our overridden response builder so ``routed_experts``
|
||||
# makes it into the JSON.
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
return error_check_ret
|
||||
|
||||
if self.engine_client.errored:
|
||||
raise self.engine_client.dead_error
|
||||
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
model_name = self.models.model_name(lora_request)
|
||||
|
||||
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
|
||||
request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = request_metadata
|
||||
|
||||
# Build the engine input — features-aware (MM) or text-only fallback.
|
||||
# Identical to upstream so we keep tracking it.
|
||||
if features := request.features:
|
||||
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
|
||||
from vllm.inputs import mm_input
|
||||
from vllm.multimodal.inputs import (
|
||||
MultiModalKwargsItem,
|
||||
PlaceholderRange,
|
||||
)
|
||||
|
||||
mm_placeholders = {
|
||||
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
|
||||
for modality, ranges in features.mm_placeholders.items()
|
||||
}
|
||||
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
|
||||
if features.kwargs_data is not None:
|
||||
for modality, items in features.kwargs_data.items():
|
||||
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
|
||||
else:
|
||||
for modality, hashes in features.mm_hashes.items():
|
||||
mm_kwargs[modality] = [None] * len(hashes)
|
||||
engine_input = mm_input(
|
||||
prompt_token_ids=request.token_ids,
|
||||
mm_kwargs=mm_kwargs, # type: ignore[arg-type]
|
||||
mm_hashes=features.mm_hashes,
|
||||
mm_placeholders=mm_placeholders,
|
||||
cache_salt=request.cache_salt,
|
||||
)
|
||||
else:
|
||||
(engine_input,) = await self.openai_serving_render.preprocess_completion(
|
||||
request,
|
||||
prompt_input=request.token_ids,
|
||||
prompt_embeds=None,
|
||||
skip_mm_cache=True,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
|
||||
# Upstream ``ServingTokens.serve_tokens`` parses ``request.kv_transfer_params``
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). The chat path bridges this via
|
||||
# ``ChatCompletionRequestWithTokens.to_sampling_params``; we mirror that
|
||||
# bridge here so the engine's KV connector picks the params up out of
|
||||
# ``sampling_params.extra_args``.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
sampling_params.extra_args = extra
|
||||
|
||||
# Server-side ``max_tokens`` defaulting — see module docstring.
|
||||
# Mirrors ``OpenAIServingChat`` (vllm/entrypoints/openai/chat_completion/
|
||||
# serving.py:284) so callers that omit ``max_tokens`` don't get capped
|
||||
# at vLLM's 16-token ``SamplingParams`` default.
|
||||
if not await _client_set_max_tokens(raw_request):
|
||||
diff_sp, override = self._max_tokens_defaults
|
||||
sampling_params.max_tokens = get_max_tokens(
|
||||
max_model_len=self.model_config.max_model_len,
|
||||
max_tokens=None,
|
||||
input_length=len(request.token_ids),
|
||||
default_sampling_params=diff_sp,
|
||||
override_max_tokens=override,
|
||||
)
|
||||
|
||||
if self.force_no_detokenize:
|
||||
sampling_params.detokenize = False
|
||||
if request.stream:
|
||||
sampling_params.output_kind = RequestOutputKind.DELTA
|
||||
|
||||
self._log_inputs(
|
||||
request_id,
|
||||
engine_input,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
result_generator = self.engine_client.generate(
|
||||
engine_input,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=self._get_data_parallel_rank(raw_request),
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
# Streaming path: defer to upstream — prime-RL's renderer client
|
||||
# only consumes the full response, so adding routed_experts to the
|
||||
# streaming choice schema is unnecessary churn.
|
||||
return self.serve_tokens_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
return await self.serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
result_generator: AsyncGenerator[RequestOutput, None],
|
||||
request_id: str,
|
||||
model_name: str,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
# Mirror serving_chat_with_tokens: wrap the result generator to capture
|
||||
# routed_experts as it streams, defer the rest to upstream, then post-
|
||||
# process the response into our PrimeRlGenerateResponse subclass so the
|
||||
# encoded experts surface in the JSON. Skipping the wrapper when the
|
||||
# engine isn't producing routed experts keeps us a no-op subclass on
|
||||
# the common path.
|
||||
capture: _RoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture # type: ignore[assignment]
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
|
||||
return response
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
@@ -23,3 +24,6 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
else:
|
||||
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
@@ -2,7 +2,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from torch.nn import Module
|
||||
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
if TYPE_CHECKING:
|
||||
@@ -46,8 +47,9 @@ class FileSystemWeightUpdateWorker(Worker):
|
||||
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
|
||||
)
|
||||
weights_iterator = model_loader._get_weights_iterator(local_source)
|
||||
model.load_weights(weights_iterator) # type: ignore
|
||||
|
||||
# Process weights after loading (important for some models)
|
||||
device = next(model.parameters()).device
|
||||
process_weights_after_loading(model, self.model_runner.model_config, device)
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
weights_iterator,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import pickle
|
||||
from typing import TYPE_CHECKING, Callable, Generator, cast
|
||||
from typing import TYPE_CHECKING, Generator, cast
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
@@ -8,10 +8,9 @@ from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import (
|
||||
load_weights_checkpoint,
|
||||
load_weights_checkpoint_layerwise,
|
||||
load_weights_kernel,
|
||||
postprocess_weights_checkpoint,
|
||||
postprocess_weights_kernel,
|
||||
update_mla_absorbed_weights,
|
||||
)
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
|
||||
@@ -144,15 +143,14 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
assert isinstance(model, Module)
|
||||
|
||||
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
|
||||
device = next(model.parameters()).device
|
||||
loader_fn: Callable[[Module, Generator[tuple[str, torch.Tensor], None, None]], None]
|
||||
postprocess_fn: Callable[[Module, object, torch.device], None]
|
||||
if self.quantize_in_weight_transfer:
|
||||
loader_fn = load_weights_kernel
|
||||
postprocess_fn = postprocess_weights_kernel
|
||||
else:
|
||||
loader_fn = load_weights_checkpoint
|
||||
postprocess_fn = postprocess_weights_checkpoint
|
||||
load_weights_kernel(model, state_iter)
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
loader_fn(model, state_iter)
|
||||
postprocess_fn(model, self.model_runner.model_config, device)
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
|
||||
@@ -1,44 +1,94 @@
|
||||
from typing import Generator
|
||||
from typing import Generator, Iterable
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
|
||||
def load_weights_checkpoint(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
model.load_weights(state_iter) # type: ignore
|
||||
def load_weights_checkpoint_layerwise(
|
||||
model: Module,
|
||||
state_iter: Iterable[tuple[str, torch.Tensor]],
|
||||
model_config,
|
||||
vllm_config,
|
||||
) -> None:
|
||||
logger.info("Reloading checkpoint-format weights with vLLM layerwise processing")
|
||||
device = next(model.parameters()).device
|
||||
with torch.device(device), set_current_vllm_config(vllm_config):
|
||||
initialize_layerwise_reload(model)
|
||||
model.load_weights(state_iter) # type: ignore
|
||||
finalize_layerwise_reload(model, model_config)
|
||||
|
||||
|
||||
def postprocess_weights_checkpoint(model: Module, model_config, device: torch.device) -> None:
|
||||
process_weights_after_loading(model, model_config, device)
|
||||
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
|
||||
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
|
||||
physical_to_logical = torch.full(
|
||||
(num_physical_experts,),
|
||||
-1,
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)
|
||||
logical_indices = torch.arange(
|
||||
logical_to_physical_map.shape[0],
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)[:, None].expand_as(logical_to_physical_map)
|
||||
physical_indices = logical_to_physical_map.to(torch.long)
|
||||
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
|
||||
if invalid.any():
|
||||
invalid_indices = physical_indices[invalid].unique().tolist()
|
||||
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
|
||||
|
||||
valid = physical_indices >= 0
|
||||
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
|
||||
|
||||
return logical_indices.to(physical_indices.device)
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to global expert indices local to this worker."""
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
|
||||
expert_slices: dict[str, torch.Tensor] = {}
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
continue
|
||||
if module._expert_map is None:
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
if source_indices is None:
|
||||
continue
|
||||
|
||||
global_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[global_indices]
|
||||
global_indices = global_indices[local_indices.argsort()]
|
||||
expert_slices[module_name] = global_indices
|
||||
return expert_slices
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
return source_indices_by_module
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
|
||||
params = dict(model.named_parameters())
|
||||
expert_slices = build_expert_map(model)
|
||||
expert_source_indices = build_expert_map(model)
|
||||
|
||||
loaded = 0
|
||||
skipped: list[str] = []
|
||||
@@ -51,15 +101,13 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
|
||||
param = params[name]
|
||||
if param.shape != tensor.shape:
|
||||
sliced = False
|
||||
for module_name, global_indices in expert_slices.items():
|
||||
for module_name, source_indices in expert_source_indices.items():
|
||||
if not name.startswith(f"{module_name}."):
|
||||
continue
|
||||
tensor = tensor[global_indices.to(tensor.device)]
|
||||
sliced = True
|
||||
tensor = tensor[source_indices.to(tensor.device)]
|
||||
break
|
||||
|
||||
if not sliced or param.shape != tensor.shape:
|
||||
if param.shape != tensor.shape:
|
||||
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
|
||||
continue
|
||||
|
||||
@@ -102,7 +150,3 @@ def update_mla_absorbed_weights(model: Module) -> None:
|
||||
module.W_UK_T.copy_(w_uk.permute(1, 2, 0))
|
||||
|
||||
logger.debug(f"Updated MLA absorbed weights for module {name}")
|
||||
|
||||
|
||||
def postprocess_weights_kernel(model: Module, _model_config, _device: torch.device) -> None:
|
||||
update_mla_absorbed_weights(model)
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Literal
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns, get_tool_response_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
LengthPenalty = Literal["tokens", "turns"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
@@ -42,18 +46,27 @@ Expected signature:
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenalty | None = None,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
"""Default GRPO advantage: reward minus per-problem baseline.
|
||||
|
||||
if length_penalty == "tokens":
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
"""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts], dtype=torch.float32)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[[get_model_completion_len(r) for r in group] for group in inputs.rollouts],
|
||||
[
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in group]
|
||||
for group in inputs.rollouts
|
||||
],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
if length_penalty == "turns":
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor(
|
||||
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
@@ -88,8 +101,12 @@ def _efficiency_shaping(
|
||||
correct_costs = costs * correct_mask
|
||||
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
has_cost = mean_correct_cost > 0
|
||||
safe_mean = torch.where(has_cost, mean_correct_cost, torch.ones_like(mean_correct_cost))
|
||||
bonus = (1 - costs / safe_mean).clamp(0, 1) * has_cost
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
@@ -112,10 +129,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
)
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import time
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.orchestrator.advantage import compute_advantages
|
||||
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
|
||||
@@ -32,6 +32,8 @@ class InflightRequest:
|
||||
env_name: str
|
||||
group_id: int | None = None
|
||||
rollout_count: int = 1
|
||||
# Dispatch round the request belongs to (see GroupState.current_round).
|
||||
round_id: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -42,6 +44,19 @@ class GroupState:
|
||||
rollouts_to_schedule: int
|
||||
completed_rollouts: list[vf.RolloutOutput] = field(default_factory=list)
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
# Number of dispatch rounds in which at least one rollout returned errored
|
||||
# or empty trajectories. Compared against
|
||||
# config.max_error_reschedule_attempts to decide when to drop a
|
||||
# permanently-stuck group. Counts rounds, not rollouts: a failed round in
|
||||
# an individual-scoring env that happens to dispatch N rollouts at once
|
||||
# still only counts as 1.
|
||||
failed_attempts: int = 0
|
||||
# Round id assigned to newly-dispatched rollouts. Advances after a failure
|
||||
# is counted so the resulting reschedule starts a new round.
|
||||
current_round: int = 0
|
||||
# Highest round already counted as failed; used to dedupe failures from
|
||||
# multiple rollouts in the same round.
|
||||
last_failed_round: int = -1
|
||||
|
||||
|
||||
class Scheduler:
|
||||
@@ -114,6 +129,7 @@ class Scheduler:
|
||||
self.empty_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.errored_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.total_rollouts_by_env: dict[str, int] = defaultdict(int)
|
||||
self.dropped_groups_by_env: dict[str, int] = defaultdict(int)
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
@property
|
||||
@@ -229,6 +245,7 @@ class Scheduler:
|
||||
env_name=env_name,
|
||||
group_id=group_id,
|
||||
rollout_count=rollout_count,
|
||||
round_id=group.current_round,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -434,18 +451,21 @@ class Scheduler:
|
||||
# Check for empty/errored rollouts and reschedule
|
||||
valid_rollouts = []
|
||||
has_failures = False
|
||||
last_failure_reason: str | None = None
|
||||
for rollout in rollouts:
|
||||
if rollout["error"] is not None:
|
||||
self.errored_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = rollout["error"]["error_chain_repr"]
|
||||
self.logger.warning(
|
||||
f"Rollout error in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
|
||||
f"{rollout['error']['error_chain_repr']}"
|
||||
f"{last_failure_reason}"
|
||||
)
|
||||
elif len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
last_failure_reason = "empty trajectory"
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
@@ -454,6 +474,32 @@ class Scheduler:
|
||||
rollout["env_name"] = env_name
|
||||
valid_rollouts.append(rollout)
|
||||
|
||||
if has_failures:
|
||||
# Dedupe failures within the same dispatch round: an
|
||||
# individual-scoring env dispatches N rollouts at once,
|
||||
# so a single failed round can produce up to N failed
|
||||
# tasks. We only count the round once.
|
||||
if rollout_info.round_id > group.last_failed_round:
|
||||
group.failed_attempts += 1
|
||||
group.last_failed_round = rollout_info.round_id
|
||||
group.current_round = rollout_info.round_id + 1
|
||||
max_attempts = self.config.max_error_reschedule_attempts
|
||||
if max_attempts is not None and group.failed_attempts >= max_attempts:
|
||||
# Permanently-stuck group: drop it from this step and let the
|
||||
# rest of the batch proceed. Avoids a single bad example (e.g.
|
||||
# an agent rollout whose sandbox poll keeps timing out)
|
||||
# blocking step progress forever.
|
||||
self.dropped_groups_by_env[env_name] += 1
|
||||
self.logger.warning(
|
||||
f"Dropping group {group_id} ({env_name}) after {group.failed_attempts} "
|
||||
f"failed dispatch rounds ({len(group.completed_rollouts)}/{self.rollouts_per_example} "
|
||||
f"complete). Last failure: {last_failure_reason}. Set "
|
||||
f"orchestrator.max_error_reschedule_attempts higher (or to None) "
|
||||
f"to retry more aggressively."
|
||||
)
|
||||
await self.drop_group(group_id)
|
||||
continue
|
||||
|
||||
if has_failures and env.requires_group_scoring:
|
||||
# Group scoring requires all rollouts — discard partial results, reschedule full group
|
||||
group.completed_rollouts.clear()
|
||||
@@ -530,6 +576,7 @@ class Scheduler:
|
||||
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
|
||||
"empty_rollouts/all": sum(self.empty_rollouts_by_env.values()) / max(total_rollouts, 1),
|
||||
"errored_rollouts/all": sum(self.errored_rollouts_by_env.values()) / max(total_rollouts, 1),
|
||||
"dropped_groups/all": sum(self.dropped_groups_by_env.values()),
|
||||
"off_policy_level/all/max": self.max_off_policy_level,
|
||||
"off_policy_level/all/mean": self.mean_off_policy_level,
|
||||
}
|
||||
@@ -537,6 +584,8 @@ class Scheduler:
|
||||
env_total = max(self.total_rollouts_by_env[env_name], 1)
|
||||
metrics[f"empty_rollouts/{env_name}"] = self.empty_rollouts_by_env.get(env_name, 0) / env_total
|
||||
metrics[f"errored_rollouts/{env_name}"] = self.errored_rollouts_by_env.get(env_name, 0) / env_total
|
||||
for env_name, count in self.dropped_groups_by_env.items():
|
||||
metrics[f"dropped_groups/{env_name}"] = count
|
||||
by_env: dict[str, list[int]] = {}
|
||||
for info in self.inflight_requests.values():
|
||||
by_env.setdefault(info.env_name, []).append(info.off_policy_steps)
|
||||
@@ -547,6 +596,7 @@ class Scheduler:
|
||||
self.empty_rollouts_by_env.clear()
|
||||
self.errored_rollouts_by_env.clear()
|
||||
self.total_rollouts_by_env.clear()
|
||||
self.dropped_groups_by_env.clear()
|
||||
|
||||
# Add inference pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.inference_pool.get_metrics())
|
||||
|
||||
@@ -84,24 +84,52 @@ async def compute_teacher_logprobs(
|
||||
samples: list[TrainingSample],
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateResponse
|
||||
import httpx
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_openai_client(client_config)
|
||||
|
||||
response = await client.post(
|
||||
"/generate",
|
||||
cast_to=GenerateResponse,
|
||||
# Two escape hatches from ``AsyncOpenAI.post``:
|
||||
# 1. URL — ``/inference/v1/generate`` is mounted at server root, not
|
||||
# under ``/v1``. Pass an absolute URL so the SDK's
|
||||
# ``_prepare_url`` skips the base-url merge (it short-circuits
|
||||
# when the path passes ``httpx.URL.is_relative_url`` as False).
|
||||
# 2. Parse — vLLM's ``GenerateResponse`` is a plain
|
||||
# ``pydantic.BaseModel`` and the SDK's parse layer rejects any
|
||||
# ``cast_to`` that doesn't subclass ``openai.BaseModel``. Use
|
||||
# ``cast_to=httpx.Response`` so the SDK still builds the request
|
||||
# (preserving ``auth_headers``, retries, timeouts, idempotency
|
||||
# keys) and just hands us the raw response to validate ourselves.
|
||||
base = str(client.base_url).rstrip("/").removesuffix("/v1")
|
||||
http_response = await client.post(
|
||||
f"{base}/inference/v1/generate",
|
||||
cast_to=httpx.Response,
|
||||
body={
|
||||
"model": model_name,
|
||||
"prompt_token_ids": sample.prompt_ids + sample.completion_ids,
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"prompt_logprobs": True,
|
||||
"token_ids": list(sample.prompt_ids) + list(sample.completion_ids),
|
||||
"sampling_params": {
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"prompt_logprobs": 1,
|
||||
},
|
||||
},
|
||||
)
|
||||
return [0.0 if lp is None else float(lp) for lp in response.prompt_logprobs or []]
|
||||
response = GenerateResponse.model_validate_json(http_response.content)
|
||||
# ``prompt_logprobs[i]`` is a ``{token_id: Logprob}`` dict for tokens
|
||||
# the engine could score, or ``None`` for the leading token which has
|
||||
# no preceding context. Flatten to ``list[float]`` with 0.0 in the
|
||||
# unscored slot.
|
||||
flat: list[float] = []
|
||||
for entry in response.prompt_logprobs or []:
|
||||
if not entry:
|
||||
flat.append(0.0)
|
||||
continue
|
||||
first = next(iter(entry.values()))
|
||||
lp = first.logprob if hasattr(first, "logprob") else first.get("logprob")
|
||||
flat.append(float(lp) if lp is not None else 0.0)
|
||||
return flat
|
||||
|
||||
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
|
||||
|
||||
|
||||
@@ -64,6 +64,21 @@ def get_num_turns(output: vf.RolloutOutput) -> int:
|
||||
return len(output["trajectory"])
|
||||
|
||||
|
||||
def get_tool_response_len(output: vf.RolloutOutput) -> int:
|
||||
"""
|
||||
Total tool-response tokens consumed across the whole rollout.
|
||||
|
||||
Read from a harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`,
|
||||
deduped across turns/branches/sub-RLMs). Returns 0 if no harness metric is
|
||||
present, which makes this a no-op for envs without tool-response accounting.
|
||||
"""
|
||||
metrics = output.get("metrics") or {}
|
||||
for key, value in metrics.items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -52,6 +52,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
export VLLM_CACHE_ROOT=/tmp/.vllm_cache_$(whoami)
|
||||
|
||||
# Setup environment
|
||||
@@ -112,11 +113,11 @@ echo "INFER_URLS=${INFER_URLS}"
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
@@ -141,6 +142,10 @@ srun bash -c '
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
{%- endif %}
|
||||
|
||||
{% if disaggregated -%}
|
||||
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
|
||||
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
|
||||
@@ -166,7 +171,6 @@ srun bash -c '
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
|
||||
@@ -66,6 +66,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
|
||||
{% if wandb_shared -%}
|
||||
export WANDB_SHARED_MODE=1
|
||||
@@ -156,11 +157,11 @@ uv sync --all-extras
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
@@ -196,6 +197,10 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||
LOCAL_IP=$(hostname -I | awk "{print \$1}")
|
||||
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
{%- endif %}
|
||||
|
||||
REPLICA_IDX=$((INFER_NODE_RANK / NODES_PER_INFER_REPLICA))
|
||||
RANK_IN_REPLICA=$((INFER_NODE_RANK % NODES_PER_INFER_REPLICA))
|
||||
|
||||
@@ -218,7 +223,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
ulimit -l unlimited
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
@@ -334,9 +338,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
INFER_DP_START_RANK=$((RANK_IN_REPLICA * INFERENCE_DP_LOCAL))
|
||||
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$LOCAL_IP\", \"data_parallel_hybrid_lb\": true}"
|
||||
else
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$REPLICA_HEAD_HOST\", \"data_parallel_start_rank\": $INFER_DP_START_RANK}"
|
||||
VLLM_EXTRA="{\"data_parallel_address\": \"$REPLICA_HEAD_HOST\", \"data_parallel_start_rank\": $INFER_DP_START_RANK, \"data_parallel_hybrid_lb\": true}"
|
||||
fi
|
||||
|
||||
uv run inference \
|
||||
|
||||
@@ -36,6 +36,7 @@ ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
@@ -63,11 +64,11 @@ cd $PROJECT_DIR && uv sync --all-extras
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
|
||||
@@ -43,6 +43,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
@@ -470,6 +471,7 @@ def get_model(
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
model_config.fp8 = config.fp8
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
@@ -1040,6 +1042,9 @@ def setup_model(
|
||||
|
||||
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
|
||||
|
||||
if config.fp8:
|
||||
replace_linear_with_fp8_blockwise_linear(model)
|
||||
|
||||
# Apply LoRA before FSDP setup
|
||||
if config.lora is not None:
|
||||
apply_lora_to_model(model, config.lora)
|
||||
|
||||
@@ -13,6 +13,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
|
||||
from prime_rl.trainer.models.laguna import LagunaConfig, LagunaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
@@ -24,6 +25,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
|
||||
AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
@@ -35,6 +37,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
|
||||
@@ -353,6 +353,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=getattr(config, "load_balance_coeff", None),
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
|
||||
@@ -68,6 +68,7 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -188,11 +188,18 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
if key in state_dict:
|
||||
add_maybe_fp8(key, state_dict[key])
|
||||
|
||||
for suffix in ["indexer.wq_b.weight", "indexer.wk.weight"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add_maybe_fp8(key, state_dict[key])
|
||||
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias", "indexer.weights_proj.weight"]:
|
||||
indexer_wq_b_key = f"{prefix}.self_attn.indexer.wq_b.weight"
|
||||
if indexer_wq_b_key in state_dict:
|
||||
add_maybe_fp8(indexer_wq_b_key, state_dict[indexer_wq_b_key])
|
||||
|
||||
indexer_wk_key = f"{prefix}.self_attn.indexer.wk.weight"
|
||||
indexer_weights_proj_key = f"{prefix}.self_attn.indexer.weights_proj.weight"
|
||||
if indexer_wk_key in state_dict and indexer_weights_proj_key in state_dict:
|
||||
add(
|
||||
f"{prefix}.self_attn.indexer.wk_weights_proj.weight",
|
||||
torch.cat([state_dict[indexer_wk_key], state_dict[indexer_weights_proj_key]], dim=0),
|
||||
)
|
||||
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add(key, state_dict[key])
|
||||
|
||||
@@ -65,6 +65,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -83,6 +83,9 @@ class GptOssMoE(nn.Module):
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
|
||||
# current FP8 grouped-GEMM path doesn't model that yet.
|
||||
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.router = GptOssTopKRouter(config)
|
||||
@@ -304,6 +307,10 @@ class GptOssForCausalLM(GptOssPreTrainedModel, GenerationMixin):
|
||||
temperature: torch.Tensor | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
|
||||
"""
|
||||
assert use_cache is None or not use_cache, "use_cache is not supported for custom GPT-OSS"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom GPT-OSS"
|
||||
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
FP8_MAX = 448.0
|
||||
MIN_SCALE = 1e-4
|
||||
GROUP_ALIGNMENT = 128
|
||||
|
||||
|
||||
def ceil_div(x: int, y: int) -> int:
|
||||
return (x + y - 1) // y
|
||||
|
||||
|
||||
def align(x: int, y: int) -> int:
|
||||
return ceil_div(x, y) * y
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout building
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def build_grouped_layout(offs: torch.Tensor, *, total_m: int | None = None):
|
||||
assert offs.dim() == 1
|
||||
assert offs.dtype == torch.int32
|
||||
device = offs.device
|
||||
total_m = (total_m if total_m is not None else int(offs[-1].item())) if offs.numel() else 0
|
||||
starts_tensor = torch.empty_like(offs)
|
||||
if offs.numel() > 0:
|
||||
starts_tensor[0] = 0
|
||||
if offs.numel() > 1:
|
||||
starts_tensor[1:] = offs[:-1]
|
||||
actual_ms_tensor = offs - starts_tensor
|
||||
aligned_ms_tensor = ((actual_ms_tensor + GROUP_ALIGNMENT - 1) // GROUP_ALIGNMENT) * GROUP_ALIGNMENT
|
||||
padded_ends = aligned_ms_tensor.cumsum(0)
|
||||
block_starts_tensor = (padded_ends - aligned_ms_tensor) // GROUP_ALIGNMENT
|
||||
ks_tensor = aligned_ms_tensor.contiguous()
|
||||
padded_total_m = int(padded_ends[-1].item()) if offs.numel() else 0
|
||||
total_blocks = padded_total_m // GROUP_ALIGNMENT
|
||||
grouped_layout = torch.empty((padded_total_m,), dtype=torch.int32, device=device)
|
||||
block_to_group = torch.empty((total_blocks,), dtype=torch.int32, device=device)
|
||||
if offs.numel():
|
||||
_build_grouped_layout_triton(
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
aligned_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
return (
|
||||
total_m,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
|
||||
def _build_grouped_layout_triton(
|
||||
grouped_layout: torch.Tensor,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
aligned_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
) -> None:
|
||||
_build_grouped_layout_kernel[(actual_ms_tensor.numel(),)](
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
aligned_ms_tensor,
|
||||
block_starts_tensor,
|
||||
BLOCK_M=128,
|
||||
num_warps=4,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Triton kernels
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _build_grouped_layout_kernel(
|
||||
grouped_layout_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
aligned_ms_ptr,
|
||||
block_starts_ptr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_g = tl.program_id(axis=0)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
aligned_m = tl.load(aligned_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
dst_start = block_start * BLOCK_M
|
||||
block_idx = 0
|
||||
while block_idx < (aligned_m // BLOCK_M):
|
||||
row_offsets = block_idx * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
values = tl.where(row_offsets < actual_m, pid_g, -1)
|
||||
tl.store(grouped_layout_ptr + dst_start + row_offsets, values)
|
||||
tl.store(block_to_group_ptr + block_start + block_idx, pid_g)
|
||||
block_idx += 1
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _unpack_grouped_rows_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
GROUP_BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_sub = tl.program_id(axis=1)
|
||||
pid_n = tl.program_id(axis=2)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
dst_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
row_offsets = (pid_blk - block_start) * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
src_rows_i64 = (pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)).to(tl.int64)
|
||||
dst_rows_i64 = (dst_start + row_offsets).to(tl.int64)
|
||||
col_offsets_i64 = col_offsets.to(tl.int64)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
x = tl.load(
|
||||
x_ptr + src_rows_i64[:, None] * stride_xm + col_offsets_i64[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
tl.store(
|
||||
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
|
||||
x,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _per_token_fp8_kernel(
|
||||
x_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
rows,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sm,
|
||||
stride_sk,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(axis=0)
|
||||
pid_k = tl.program_id(axis=1)
|
||||
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
row_offsets_i64 = row_offsets.to(tl.int64)
|
||||
col_offsets_i64 = col_offsets.to(tl.int64)
|
||||
mask = (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
|
||||
x = tl.load(
|
||||
x_ptr + row_offsets_i64[:, None] * stride_xm + col_offsets_i64[None, :] * stride_xn,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
tl.store(
|
||||
out_ptr + row_offsets_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(sf_ptr + row_offsets_i64 * stride_sm + pid_k * stride_sk, scale, mask=row_offsets < rows)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_token_fp8_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sm,
|
||||
stride_sk,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
GROUP_BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_sub = tl.program_id(axis=1)
|
||||
pid_k = tl.program_id(axis=2)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
src_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
local_block = pid_blk - block_start
|
||||
row_offsets = local_block * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
src_rows_i64 = (src_start + row_offsets).to(tl.int64)
|
||||
dst_rows_i64 = (pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)).to(tl.int64)
|
||||
col_offsets_i64 = col_offsets.to(tl.int64)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
x = tl.load(
|
||||
x_ptr + src_rows_i64[:, None] * stride_xm + col_offsets_i64[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
tl.store(
|
||||
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
)
|
||||
tl.store(sf_ptr + dst_rows_i64 * stride_sm + pid_k * stride_sk, scale, mask=valid_rows)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
aligned_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_sf0,
|
||||
stride_sf1,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_n = tl.program_id(axis=1)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
src_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
aligned_m = tl.load(aligned_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
local_block = pid_blk - block_start
|
||||
row_offsets = local_block * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
src_rows_i64 = (src_start + row_offsets).to(tl.int64)
|
||||
row_offsets_i64 = row_offsets.to(tl.int64)
|
||||
col_offsets_i64 = col_offsets.to(tl.int64)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
x = tl.load(
|
||||
x_ptr + src_rows_i64[:, None] * stride_xm + col_offsets_i64[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=0)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[None, :]
|
||||
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
|
||||
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
|
||||
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
|
||||
tl.store(
|
||||
sf_ptr + pid_blk * stride_sf0 + col_offsets_i64 * stride_sf1,
|
||||
scale,
|
||||
mask=valid_cols,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_block_fp8_kernel(
|
||||
x_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
groups,
|
||||
rows,
|
||||
cols,
|
||||
stride_xg,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_yg,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sg,
|
||||
stride_sm,
|
||||
stride_sn,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_g = tl.program_id(axis=0)
|
||||
pid_m = tl.program_id(axis=1)
|
||||
pid_n = tl.program_id(axis=2)
|
||||
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
mask = (pid_g < groups) & (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
|
||||
x = tl.load(
|
||||
x_ptr + pid_g * stride_xg + row_offsets[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x))
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale
|
||||
tl.store(
|
||||
out_ptr + pid_g * stride_yg + row_offsets[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(sf_ptr + pid_g * stride_sg + pid_m * stride_sm + pid_n * stride_sn, scale, mask=pid_g < groups)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public quantization functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def unpack_rows_triton(
|
||||
x: torch.Tensor,
|
||||
total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
out = torch.empty((total_m, x.size(1)), device=x.device, dtype=x.dtype)
|
||||
if total_m == 0:
|
||||
return out
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), 128))
|
||||
_unpack_grouped_rows_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
BLOCK_M=32,
|
||||
BLOCK_N=128,
|
||||
GROUP_BLOCK_M=GROUP_ALIGNMENT,
|
||||
num_warps=4,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def per_token_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
rows, cols = x.shape
|
||||
out = torch.empty_like(x, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty((rows, ceil_div(cols, gran_k)), device=x.device, dtype=torch.float32)
|
||||
grid = lambda meta: (ceil_div(rows, meta["BLOCK_M"]), ceil_div(cols, meta["BLOCK_K"]))
|
||||
_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
sf,
|
||||
rows,
|
||||
cols,
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_K=gran_k,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def grouped_per_token_cast_to_fp8_triton(
|
||||
x: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
use_ue8m0: bool,
|
||||
gran_k: int = GROUP_ALIGNMENT,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty(
|
||||
(padded_total_m, ceil_div(x.size(1), gran_k)),
|
||||
device=x.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
|
||||
_grouped_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
sf,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_K=gran_k,
|
||||
GROUP_BLOCK_M=GROUP_ALIGNMENT,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
use_ue8m0: bool,
|
||||
gran_k: int = GROUP_ALIGNMENT,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
out = torch.empty((padded_total_m * x.size(1),), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
total_blocks = padded_total_m // gran_k
|
||||
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf.T
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
sf,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf.T
|
||||
|
||||
|
||||
def grouped_per_block_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 3
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
groups, rows, cols = x.shape
|
||||
out = torch.empty((groups, rows, cols), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty(
|
||||
(groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k)),
|
||||
device=x.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
grid = (groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
|
||||
_grouped_per_block_fp8_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
sf,
|
||||
groups,
|
||||
rows,
|
||||
cols,
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
x.stride(2),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
out.stride(2),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
sf.stride(2),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=gran_k,
|
||||
BLOCK_N=gran_k,
|
||||
num_warps=8,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def per_block_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
out, sf = grouped_per_block_cast_to_fp8_triton(
|
||||
x.unsqueeze(0),
|
||||
use_ue8m0,
|
||||
gran_k,
|
||||
)
|
||||
return out[0], sf[0]
|
||||
@@ -1,5 +1,18 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
@@ -78,7 +91,8 @@ def postprocess(
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
|
||||
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.modeling_laguna import (
|
||||
LagunaForCausalLM,
|
||||
LagunaModel,
|
||||
LagunaPreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"LagunaConfig",
|
||||
"LagunaForCausalLM",
|
||||
"LagunaModel",
|
||||
"LagunaPreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,190 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
|
||||
class LagunaConfig(PretrainedConfig):
|
||||
"""Configuration for Poolside Laguna MoE models."""
|
||||
|
||||
model_type = "laguna"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
attribute_map = {"num_local_experts": "num_experts"}
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_proj": "colwise",
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.g_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
"layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
|
||||
"layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
|
||||
"layers.*.mlp.gate_proj": "colwise",
|
||||
"layers.*.mlp.up_proj": "colwise",
|
||||
"layers.*.mlp.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts.gate_up_proj": "packed_colwise",
|
||||
"layers.*.mlp.experts.down_proj": "rowwise",
|
||||
"layers.*.mlp.experts": "moe_tp_experts",
|
||||
"layers.*.shared_expert.w1": "colwise",
|
||||
"layers.*.shared_expert.w2": "rowwise",
|
||||
"layers.*.shared_expert.w3": "colwise",
|
||||
}
|
||||
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,
|
||||
vocab_size: int = 100352,
|
||||
hidden_size: int = 2048,
|
||||
intermediate_size: int = 8192,
|
||||
num_hidden_layers: int = 40,
|
||||
num_attention_heads: int = 48,
|
||||
num_key_value_heads: int = 8,
|
||||
hidden_act: str = "silu",
|
||||
max_position_embeddings: int = 131072,
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
use_cache: bool = True,
|
||||
tie_word_embeddings: bool = False,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
rope_scaling: dict[str, Any] | None = None,
|
||||
sliding_window: int | None = 512,
|
||||
attention_dropout: float = 0.0,
|
||||
moe_intermediate_size: int = 512,
|
||||
shared_expert_intermediate_size: int = 512,
|
||||
num_experts_per_tok: int = 8,
|
||||
num_experts: int = 256,
|
||||
output_router_logits: bool = False,
|
||||
router_aux_loss_coef: float = 0.001,
|
||||
layer_types: list[str] | None = None,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = None,
|
||||
eos_token_id: int | list[int] | None = None,
|
||||
head_dim: int = 128,
|
||||
attention_bias: bool = False,
|
||||
partial_rotary_factor: float | None = None,
|
||||
num_attention_heads_per_layer: list[int] | None = None,
|
||||
mlp_layer_types: list[str] | None = None,
|
||||
moe_routed_scaling_factor: float = 1.0,
|
||||
moe_apply_router_weight_on_input: bool = False,
|
||||
moe_router_logit_softcapping: float = 0.0,
|
||||
load_balance_coeff: float | None = 1e-3,
|
||||
use_grouped_mm: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.sliding_window = sliding_window
|
||||
self.attention_dropout = attention_dropout
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.shared_expert_intermediate_size = shared_expert_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.num_experts = num_experts
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.layer_types = layer_types or ["full_attention"] * num_hidden_layers
|
||||
self.head_dim = head_dim
|
||||
self.attention_bias = attention_bias
|
||||
self.partial_rotary_factor = partial_rotary_factor
|
||||
self.num_attention_heads_per_layer = num_attention_heads_per_layer or [num_attention_heads] * num_hidden_layers
|
||||
self.mlp_layer_types = mlp_layer_types or ["dense"] + ["sparse"] * (num_hidden_layers - 1)
|
||||
self.moe_routed_scaling_factor = moe_routed_scaling_factor
|
||||
self.moe_apply_router_weight_on_input = moe_apply_router_weight_on_input
|
||||
self.moe_router_logit_softcapping = moe_router_logit_softcapping
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
self.rope_parameters = raw_rope_parameters
|
||||
self._normalize_rope_parameters()
|
||||
self.rope_scaling = self.rope_parameters
|
||||
self.validate_architecture()
|
||||
|
||||
def _normalize_rope_parameters(self) -> None:
|
||||
default_rope_params: dict[Literal["full_attention", "sliding_attention"], dict[str, Any]] = {
|
||||
"full_attention": {"rope_type": "default", "rope_theta": 500000.0},
|
||||
"sliding_attention": {"rope_type": "default", "rope_theta": 10000.0},
|
||||
}
|
||||
layer_types = set(self.layer_types)
|
||||
rope_params = self.rope_parameters or {}
|
||||
is_nested = isinstance(rope_params, dict) and any(key in layer_types for key in rope_params)
|
||||
if is_nested:
|
||||
nested = {}
|
||||
for layer_type in layer_types:
|
||||
params = dict(default_rope_params.get(layer_type, {}))
|
||||
params.update(rope_params.get(layer_type, {}))
|
||||
nested[layer_type] = params
|
||||
else:
|
||||
nested = {}
|
||||
for layer_type in layer_types:
|
||||
params = dict(default_rope_params.get(layer_type, {}))
|
||||
params.update(rope_params)
|
||||
nested[layer_type] = params
|
||||
|
||||
if self.partial_rotary_factor is not None:
|
||||
for params in nested.values():
|
||||
params.setdefault("partial_rotary_factor", self.partial_rotary_factor)
|
||||
|
||||
for params in nested.values():
|
||||
params.setdefault("rope_type", "default")
|
||||
|
||||
self.rope_parameters = nested
|
||||
self.partial_rotary_factor = None
|
||||
|
||||
def convert_rope_params_to_dict(self, **kwargs):
|
||||
return kwargs
|
||||
|
||||
def _validate_yarn_rope_parameters(self, rope_parameters: dict, ignore_keys=None) -> None:
|
||||
flat_rope_parameters = self.rope_parameters
|
||||
self.rope_parameters = rope_parameters
|
||||
try:
|
||||
super()._validate_yarn_rope_parameters(rope_parameters, ignore_keys=ignore_keys)
|
||||
finally:
|
||||
self.rope_parameters = flat_rope_parameters
|
||||
|
||||
def validate_architecture(self) -> None:
|
||||
if self.moe_apply_router_weight_on_input:
|
||||
raise NotImplementedError("moe_apply_router_weight_on_input=True is not supported by PrimeRL Laguna.")
|
||||
if len(self.num_attention_heads_per_layer) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"num_attention_heads_per_layer length ({len(self.num_attention_heads_per_layer)}) "
|
||||
f"must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
for num_heads in self.num_attention_heads_per_layer:
|
||||
if num_heads % self.num_key_value_heads != 0:
|
||||
raise ValueError(
|
||||
f"Per-layer attention head count ({num_heads}) must be divisible by "
|
||||
f"num_key_value_heads ({self.num_key_value_heads})."
|
||||
)
|
||||
if len(self.layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"layer_types length ({len(self.layer_types)}) must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
if len(self.mlp_layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"mlp_layer_types length ({len(self.mlp_layer_types)}) "
|
||||
f"must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["LagunaConfig"]
|
||||
@@ -0,0 +1,120 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
|
||||
|
||||
|
||||
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
|
||||
for key in keys:
|
||||
if key in state_dict:
|
||||
return state_dict.pop(key)
|
||||
return None
|
||||
|
||||
|
||||
def convert_hf_layer_to_prime(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
gate_key = f"{prefix}.mlp.gate.weight"
|
||||
if gate_key not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
|
||||
|
||||
expert_bias = _pop_first(
|
||||
state_dict,
|
||||
(
|
||||
f"{prefix}.mlp.experts.e_score_correction_bias",
|
||||
f"{prefix}.mlp.gate.e_score_correction_bias",
|
||||
),
|
||||
)
|
||||
if expert_bias is not None:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = expert_bias
|
||||
|
||||
fused_key = f"{prefix}.mlp.experts.gate_up_proj"
|
||||
if fused_key in state_dict:
|
||||
gate_up_proj = state_dict.pop(fused_key)
|
||||
down_proj = state_dict.pop(f"{prefix}.mlp.experts.down_proj")
|
||||
moe_dim = gate_up_proj.shape[1] // 2
|
||||
w1 = gate_up_proj[:, :moe_dim, :]
|
||||
w3 = gate_up_proj[:, moe_dim:, :]
|
||||
w2 = down_proj
|
||||
else:
|
||||
expert_ids = sorted(
|
||||
int(key[len(f"{prefix}.mlp.experts.") :].split(".")[0])
|
||||
for key in state_dict
|
||||
if key.startswith(f"{prefix}.mlp.experts.") and key.endswith(".gate_proj.weight")
|
||||
)
|
||||
if not expert_ids:
|
||||
return
|
||||
|
||||
first_down = state_dict[f"{prefix}.mlp.experts.{expert_ids[0]}.down_proj.weight"]
|
||||
dim, moe_dim = first_down.shape
|
||||
w1 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w2 = torch.empty((len(expert_ids), dim, moe_dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w3 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
for out_idx, expert_idx in enumerate(expert_ids):
|
||||
w1[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"))
|
||||
w2[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"))
|
||||
w3[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"))
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
|
||||
shared_prefix = None
|
||||
for candidate in (f"{prefix}.mlp.shared_expert", f"{prefix}.mlp.shared_experts"):
|
||||
if f"{candidate}.gate_proj.weight" in state_dict:
|
||||
shared_prefix = candidate
|
||||
break
|
||||
|
||||
if shared_prefix is not None:
|
||||
state_dict[f"{prefix}.shared_expert.w1.weight"] = state_dict.pop(f"{shared_prefix}.gate_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w2.weight"] = state_dict.pop(f"{shared_prefix}.down_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w3.weight"] = state_dict.pop(f"{shared_prefix}.up_proj.weight")
|
||||
|
||||
|
||||
def convert_prime_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key not in state_dict:
|
||||
return
|
||||
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.mlp.experts.e_score_correction_bias"] = state_dict.pop(f"{prefix}.mlp.expert_bias")
|
||||
|
||||
state_dict[f"{prefix}.mlp.gate.weight"] = state_dict.pop(router_key)
|
||||
|
||||
w1 = state_dict.pop(f"{prefix}.mlp.experts.w1")
|
||||
w2 = state_dict.pop(f"{prefix}.mlp.experts.w2")
|
||||
w3 = state_dict.pop(f"{prefix}.mlp.experts.w3")
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"] = w1[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"] = w2[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"] = w3[expert_idx]
|
||||
|
||||
shared_key = f"{prefix}.shared_expert.w1.weight"
|
||||
if shared_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(shared_key)
|
||||
state_dict[f"{prefix}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w2.weight")
|
||||
state_dict[f"{prefix}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w3.weight")
|
||||
|
||||
|
||||
def convert_hf_to_prime(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_prime_to_hf(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"convert_hf_layer_to_prime",
|
||||
"convert_hf_to_prime",
|
||||
"convert_prime_layer_to_hf",
|
||||
"convert_prime_to_hf",
|
||||
]
|
||||
@@ -0,0 +1,482 @@
|
||||
from collections.abc import Callable
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import MoeModelOutputWithPast
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, can_return_tuple
|
||||
from transformers.utils.generic import maybe_autocast
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.converting_laguna import (
|
||||
convert_hf_layer_to_prime,
|
||||
convert_hf_to_prime,
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention, SDPAAttention
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class LagunaRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: LagunaConfig, device=None):
|
||||
super().__init__()
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
self.config = config
|
||||
self.layer_types = list(dict.fromkeys(config.layer_types))
|
||||
self.rope_type = {}
|
||||
|
||||
for layer_type in self.layer_types:
|
||||
rope_params = self.config.rope_parameters[layer_type]
|
||||
self.rope_type[layer_type] = rope_params["rope_type"]
|
||||
rope_init_fn: Callable = self.compute_default_rope_parameters
|
||||
if self.rope_type[layer_type] != "default":
|
||||
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
|
||||
inv_freq, attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)
|
||||
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
|
||||
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
@staticmethod
|
||||
def compute_default_rope_parameters(
|
||||
config: LagunaConfig | None = None,
|
||||
device: Optional[torch.device] = None,
|
||||
seq_len: int | None = None,
|
||||
layer_type: str | None = None,
|
||||
) -> tuple[torch.Tensor, float]:
|
||||
rope_params = config.rope_parameters[layer_type]
|
||||
base = rope_params["rope_theta"]
|
||||
partial_rotary_factor = rope_params.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.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
|
||||
|
||||
@torch.no_grad()
|
||||
@dynamic_rope_update
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
position_ids: torch.LongTensor,
|
||||
layer_type: str,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
||||
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
|
||||
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
||||
with maybe_autocast(device_type=device_type, enabled=False):
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos() * attention_scaling
|
||||
sin = emb.sin() * attention_scaling
|
||||
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
||||
|
||||
|
||||
def _laguna_attention_config(config: LagunaConfig, num_heads: int) -> AttentionConfig:
|
||||
return AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=num_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=True,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
qk_norm_type="per_head",
|
||||
)
|
||||
|
||||
|
||||
class LagunaFlashAttention(FlashAttention):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int, flash_attn_version: int = 2):
|
||||
super().__init__(_laguna_attention_config(config, num_heads), flash_attn_version=flash_attn_version)
|
||||
self.num_heads = num_heads
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
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.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
|
||||
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
class LagunaSDPAAttention(SDPAAttention):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int, num_heads: int):
|
||||
super().__init__(_laguna_attention_config(config, num_heads))
|
||||
self.num_heads = num_heads
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
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.g_proj = nn.Linear(config.hidden_size, num_heads, bias=False)
|
||||
self.o_proj = nn.Linear(num_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
|
||||
|
||||
def _attention_core(
|
||||
self,
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
key_states = key_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
value_states = value_states.repeat_interleave(self.num_key_value_groups, dim=1)
|
||||
dropout_p = 0.0 if not self.training else self.attention_dropout
|
||||
out = F.scaled_dot_product_attention(
|
||||
query_states,
|
||||
key_states,
|
||||
value_states,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=dropout_p,
|
||||
is_causal=attention_mask is None,
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
return out.view(out.shape[0], out.shape[1], -1)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
query_states, key_states, value_states = self.attn_projections(hidden_states, position_embeddings)
|
||||
attn_output = self._attention_core(query_states, key_states, value_states, attention_mask=attention_mask)
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
attn_output = attn_output.view(*input_shape, self.num_heads, self.head_dim)
|
||||
gate = F.softplus(self.g_proj(hidden_states).float()).to(attn_output.dtype)
|
||||
attn_output = (attn_output * gate.unsqueeze(-1)).view(*input_shape, -1)
|
||||
return self.o_proj(attn_output), None
|
||||
|
||||
|
||||
def _get_laguna_attention(config: LagunaConfig, layer_idx: int):
|
||||
attn_impl = config._attn_implementation
|
||||
if attn_impl == "eager":
|
||||
attn_impl = "sdpa"
|
||||
num_heads = config.num_attention_heads_per_layer[layer_idx]
|
||||
match attn_impl:
|
||||
case "flash_attention_2":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=2)
|
||||
case "flash_attention_3":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=3)
|
||||
case "fa4":
|
||||
return LagunaFlashAttention(config, layer_idx, num_heads, flash_attn_version=4)
|
||||
case "sdpa":
|
||||
return LagunaSDPAAttention(config, layer_idx, num_heads)
|
||||
case _:
|
||||
raise ValueError(f"Laguna attention does not support '{config._attn_implementation}'.")
|
||||
|
||||
|
||||
class LagunaDecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: LagunaConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
self.mlp_layer_type = config.mlp_layer_types[layer_idx]
|
||||
self.self_attn = _get_laguna_attention(config, layer_idx)
|
||||
|
||||
if self.mlp_layer_type == "sparse":
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_experts,
|
||||
num_shared_experts=0,
|
||||
score_func="sigmoid",
|
||||
route_norm=True,
|
||||
route_scale=config.moe_routed_scaling_factor,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if config.moe_router_logit_softcapping:
|
||||
raise NotImplementedError("Laguna router logit softcapping is not supported by PrimeRL MoE yet.")
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
self.shared_expert = FeedForward(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.shared_expert_intermediate_size,
|
||||
)
|
||||
else:
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.shared_expert = None
|
||||
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
mlp_input = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(mlp_input, routed_experts=routed_experts)
|
||||
if self.shared_expert is not None:
|
||||
bs, slen, dim = hidden_states.shape
|
||||
shared_output = self.shared_expert(mlp_input.view(-1, dim)).view(bs, slen, dim)
|
||||
hidden_states = hidden_states + shared_output
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: LagunaConfig
|
||||
config_class = LagunaConfig
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["LagunaDecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = False
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {
|
||||
"hidden_states": LagunaDecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(
|
||||
"mlp.experts.0.gate_proj.weight" in name or "mlp.experts.gate_up_proj" in name or "mlp.gate.weight" in name
|
||||
for name in state_dict
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_prime_to_hf(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_prime(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
|
||||
class LagunaModel(LagunaPreTrainedModel):
|
||||
def __init__(self, config: LagunaConfig):
|
||||
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([LagunaDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)])
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = LagunaRotaryEmbedding(config=config)
|
||||
self.gradient_checkpointing = False
|
||||
self.post_init()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
) -> 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 inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = dict.fromkeys(set(self.config.layer_types), None)
|
||||
else:
|
||||
cu_seqlens = None
|
||||
max_seqlen = None
|
||||
if isinstance(attention_mask, dict):
|
||||
causal_mask_mapping = attention_mask
|
||||
else:
|
||||
mask_kwargs = {
|
||||
"config": self.config,
|
||||
"inputs_embeds": inputs_embeds,
|
||||
"attention_mask": attention_mask,
|
||||
"past_key_values": None,
|
||||
"position_ids": position_ids,
|
||||
}
|
||||
causal_mask_mapping = {
|
||||
"full_attention": create_causal_mask(**mask_kwargs),
|
||||
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
|
||||
}
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = {
|
||||
layer_type: self.rotary_emb(hidden_states, position_ids, layer_type)
|
||||
for layer_type in set(self.config.layer_types)
|
||||
}
|
||||
|
||||
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
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
|
||||
position_embeddings=position_embeddings[self.config.layer_types[layer_idx]],
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
class LagunaForCausalLM(LagunaPreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config: LagunaConfig):
|
||||
super().__init__(config)
|
||||
self.model = LagunaModel(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.router_aux_loss_coef = config.router_aux_loss_coef
|
||||
self.num_experts = config.num_experts
|
||||
self.num_experts_per_tok = config.num_experts_per_tok
|
||||
self.post_init()
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
@can_return_tuple
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
past_key_values: Cache | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
use_cache: bool | None = None,
|
||||
output_router_logits: bool | None = None,
|
||||
cache_position: torch.LongTensor | None = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
assert use_cache is None, "use_cache is not supported for custom Laguna"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom Laguna"
|
||||
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
for layer_type in rotary_emb.layer_types:
|
||||
rope_init_fn = rotary_emb.compute_default_rope_parameters
|
||||
if rotary_emb.rope_type[layer_type] != "default":
|
||||
rope_init_fn = ROPE_INIT_FUNCTIONS[rotary_emb.rope_type[layer_type]]
|
||||
inv_freq, attention_scaling = rope_init_fn(
|
||||
rotary_emb.config,
|
||||
getattr(rotary_emb, f"{layer_type}_inv_freq").device,
|
||||
layer_type=layer_type,
|
||||
)
|
||||
getattr(rotary_emb, f"{layer_type}_inv_freq").copy_(inv_freq)
|
||||
getattr(rotary_emb, f"{layer_type}_original_inv_freq").copy_(inv_freq)
|
||||
setattr(rotary_emb, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
for module in self.modules():
|
||||
if isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
if module.expert_bias is not None:
|
||||
module.expert_bias.zero_()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"LagunaForCausalLM",
|
||||
"LagunaModel",
|
||||
"LagunaPreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,224 @@
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
GROUP_ALIGNMENT,
|
||||
build_grouped_layout,
|
||||
grouped_per_block_cast_to_fp8_triton,
|
||||
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
|
||||
grouped_per_token_cast_to_fp8_triton,
|
||||
unpack_rows_triton,
|
||||
)
|
||||
|
||||
|
||||
def _compute_grad_weight(
|
||||
x: torch.Tensor,
|
||||
grad_output: torch.Tensor,
|
||||
weight_shape: torch.Size,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
aligned_ms: list[int],
|
||||
) -> torch.Tensor:
|
||||
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
|
||||
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
|
||||
x_k_major,
|
||||
dy_k_major,
|
||||
grad_weight,
|
||||
aligned_ms,
|
||||
ks_tensor,
|
||||
grad_weight,
|
||||
)
|
||||
return grad_weight.to(torch.bfloat16)
|
||||
|
||||
|
||||
class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
(
|
||||
total_m,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
|
||||
x_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
out_padded = torch.empty(
|
||||
(padded_total_m, weight.size(2)),
|
||||
device=x.device,
|
||||
dtype=x.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
x_fp8,
|
||||
weight_fp8,
|
||||
out_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
out = unpack_rows_triton(
|
||||
out_padded,
|
||||
total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
ctx.padded_total_m = padded_total_m
|
||||
ctx.aligned_ms = ks_tensor.tolist()
|
||||
ctx.save_for_backward(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor):
|
||||
(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = ctx.saved_tensors
|
||||
padded_total_m = ctx.padded_total_m
|
||||
aligned_ms = ctx.aligned_ms
|
||||
grad_output = grad_output.contiguous()
|
||||
|
||||
grad_x = grad_weight = None
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
grad_weight = _compute_grad_weight(
|
||||
x,
|
||||
grad_output,
|
||||
weight.shape,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
aligned_ms,
|
||||
)
|
||||
|
||||
if ctx.needs_input_grad[0]:
|
||||
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_x_padded = torch.empty(
|
||||
(padded_total_m, weight.size(1)),
|
||||
device=grad_output.device,
|
||||
dtype=grad_output.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
dy_fp8,
|
||||
weight_dx_fp8,
|
||||
grad_x_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
grad_x = unpack_rows_triton(
|
||||
grad_x_padded,
|
||||
x.size(0),
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
return grad_x, grad_weight, None
|
||||
|
||||
|
||||
def grouped_fp8_gemm(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""FP8 grouped GEMM, drop-in replacement for torch._grouped_mm.
|
||||
|
||||
Args:
|
||||
x: (M, K) concatenated token activations in bfloat16.
|
||||
weight: (G, K, N) expert weights in bfloat16.
|
||||
offs: (G,) int32 cumulative token counts per expert.
|
||||
|
||||
Returns:
|
||||
(M, N) output tensor in bfloat16.
|
||||
"""
|
||||
return _GroupedFP8Gemm.apply(x, weight, offs)
|
||||
@@ -0,0 +1,179 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_triton,
|
||||
per_token_cast_to_fp8_triton,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
|
||||
x_shape = x.shape
|
||||
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
|
||||
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
|
||||
ctx.save_for_backward(x_2d, weight)
|
||||
ctx.x_shape = x_shape
|
||||
ctx.block_size = block_size
|
||||
return out.reshape(*x_shape[:-1], out.size(-1))
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
x_2d, weight = ctx.saved_tensors
|
||||
block_size = ctx.block_size
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
|
||||
weight_t = weight.transpose(0, 1).contiguous()
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
# deep_gemm.fp8_gemm_nt with recipe=(1, 1, 128) requires the K (token)
|
||||
# dim to be a multiple of 128. Zero-pad along the token axis so non-
|
||||
# aligned per-rank batches (from sequence packing) don't trip the kernel.
|
||||
M_tok = grad_output_2d.size(0)
|
||||
M_pad = (M_tok + block_size - 1) // block_size * block_size
|
||||
if M_pad != M_tok:
|
||||
pad_rows = M_pad - M_tok
|
||||
grad_output_2d_padded = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
|
||||
x_2d_padded = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
|
||||
x_t = x_2d_padded.transpose(0, 1).contiguous()
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
x_t_fp8,
|
||||
grad_weight_fp32,
|
||||
c=grad_weight_fp32,
|
||||
recipe=(1, 1, 128),
|
||||
)
|
||||
grad_weight = grad_weight_fp32.to(weight.dtype)
|
||||
|
||||
return grad_x, grad_weight, None, None
|
||||
|
||||
|
||||
class Float8BlockwiseLinear(nn.Linear):
|
||||
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
|
||||
|
||||
Requires:
|
||||
- SM90 (Hopper) GPU
|
||||
- bfloat16 inputs/weights
|
||||
- No bias
|
||||
- in_features and out_features divisible by 128
|
||||
"""
|
||||
|
||||
def __init__(self, *args, block_size: int = 128, dtype=torch.bfloat16, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.block_size = block_size
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return _FP8BlockwiseMM.apply(x, self.weight, self.block_size, torch.bfloat16)
|
||||
|
||||
@classmethod
|
||||
def from_linear(cls, mod: nn.Linear) -> "Float8BlockwiseLinear":
|
||||
"""Convert an existing nn.Linear to Float8BlockwiseLinear."""
|
||||
with torch.device("meta"):
|
||||
new_mod = cls(
|
||||
mod.in_features,
|
||||
mod.out_features,
|
||||
bias=mod.bias is not None,
|
||||
)
|
||||
new_mod.weight = mod.weight
|
||||
new_mod.bias = mod.bias
|
||||
return new_mod
|
||||
|
||||
|
||||
DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
"lm_head",
|
||||
"router",
|
||||
# Use escaped dots — re.search treats `.` as any-char, so the previous
|
||||
# "mlp.gate." pattern was also matching dense MLP `mlp.gate_proj` (the
|
||||
# trailing `.` was matching `_`). That left the dense MLP gate projection
|
||||
# in BF16 on the trainer while inference quantized it to FP8, causing
|
||||
# hidden-state drift before the MoE router.
|
||||
r"mlp\.gate\.",
|
||||
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"in_proj_a",
|
||||
"in_proj_b",
|
||||
]
|
||||
|
||||
|
||||
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str] | None = None) -> None:
|
||||
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
|
||||
module whose qualified name matches an ignore pattern (substring or regex).
|
||||
|
||||
The default ignore list covers layers that should never be quantized:
|
||||
- lm_head
|
||||
- MoE routers and gates (router, mlp.gate., shared_expert_gate)
|
||||
- sparse-MLA scalar projection (weights_proj)
|
||||
- GLM-5.1 MTP head (eh_proj)
|
||||
- hybrid-Mamba projections (in_proj_a, in_proj_b)
|
||||
|
||||
Independently of the name-based ignore list, we also skip any nn.Linear
|
||||
whose in_features or out_features is not a multiple of 128. Float8BlockwiseLinear
|
||||
documents that requirement and DeepGEMM's fp8_gemm_nt crashes at runtime
|
||||
on unaligned dims — better to keep them in BF16 with a clear log line than
|
||||
silently break in the kernel.
|
||||
|
||||
Conv1d, layer norms, and embedding tables are not nn.Linear and are
|
||||
skipped automatically by the type check; we don't need to list them.
|
||||
"""
|
||||
if ignore_modules is None:
|
||||
ignore_modules = list(DEFAULT_FP8_IGNORE_PATTERNS)
|
||||
logger = get_logger()
|
||||
logger.info(f"Replacing linear layers with FP8 blockwise linear layers (ignore={ignore_modules})")
|
||||
replaced_modules = []
|
||||
skipped_modules = []
|
||||
skipped_unaligned: list[str] = []
|
||||
named_modules = dict(model.named_modules())
|
||||
for name, module in named_modules.items():
|
||||
if not isinstance(module, nn.Linear):
|
||||
continue
|
||||
if any(re.search(pattern, name) for pattern in ignore_modules):
|
||||
skipped_modules.append(name)
|
||||
continue
|
||||
if module.in_features % 128 != 0 or module.out_features % 128 != 0:
|
||||
skipped_unaligned.append(f"{name}({module.in_features}->{module.out_features})")
|
||||
continue
|
||||
parent_name, attr_name = name.rsplit(".", 1) if "." in name else ("", name)
|
||||
parent = model.get_submodule(parent_name) if parent_name else model
|
||||
setattr(parent, attr_name, Float8BlockwiseLinear.from_linear(module))
|
||||
replaced_modules.append(name)
|
||||
|
||||
logger.info(
|
||||
f"Replaced {len(replaced_modules)} linear layers with FP8 blockwise linear "
|
||||
f"(skipped {len(skipped_modules)} by name, "
|
||||
f"{len(skipped_unaligned)} by 128-divisibility); "
|
||||
f"first replaced={replaced_modules[:3]}, "
|
||||
f"first skipped(name)={skipped_modules[:3]}, "
|
||||
f"first skipped(unaligned)={skipped_unaligned[:3]}"
|
||||
)
|
||||
@@ -30,6 +30,7 @@ class MoEArgs:
|
||||
top_k: int = 1
|
||||
use_grouped_mm: bool = True # grouped mm or for-loop for the experts computation
|
||||
load_balance_coeff: float | None = 1e-3
|
||||
fp8: bool = False # use FP8 grouped GEMM via DeepGEMM (requires SM90)
|
||||
|
||||
|
||||
# can be used as dense FFN layer or shared experts in MoE layers
|
||||
@@ -144,20 +145,39 @@ def _run_experts_grouped_mm(
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
|
||||
def _run_experts_grouped_mm_impl(
|
||||
@expert_parallel
|
||||
def _run_experts_fp8_grouped_mm(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=True)
|
||||
|
||||
|
||||
def _run_experts_grouped_mm_impl(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
fp8: bool = False,
|
||||
) -> torch.Tensor:
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
# grouped mm between a 2D tensor and a 3D tensor
|
||||
assert x.dim() == 2
|
||||
|
||||
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
if fp8:
|
||||
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
|
||||
|
||||
h = F.silu(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
|
||||
h = h * grouped_fp8_gemm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offsets)
|
||||
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
|
||||
else:
|
||||
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
|
||||
return out
|
||||
|
||||
@@ -169,6 +189,7 @@ class GroupedExperts(nn.Module):
|
||||
hidden_dim: int,
|
||||
num_experts: int,
|
||||
use_grouped_mm: bool,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.num_experts = num_experts
|
||||
@@ -176,6 +197,7 @@ class GroupedExperts(nn.Module):
|
||||
self.w2 = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
|
||||
self.w3 = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.fp8 = fp8
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
@@ -186,7 +208,7 @@ class GroupedExperts(nn.Module):
|
||||
w2 = self.w2.to_local()
|
||||
w3 = self.w3.to_local()
|
||||
if self.use_grouped_mm:
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
|
||||
return _run_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
def forward(
|
||||
@@ -198,6 +220,8 @@ class GroupedExperts(nn.Module):
|
||||
return self._forward_deepep(x, num_tokens_per_expert)
|
||||
|
||||
if self.use_grouped_mm:
|
||||
if self.fp8:
|
||||
return _run_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
return _run_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
else:
|
||||
return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
@@ -534,6 +558,7 @@ class MoE(nn.Module):
|
||||
hidden_dim=hidden_dim,
|
||||
num_experts=num_experts,
|
||||
use_grouped_mm=moe_args.use_grouped_mm,
|
||||
fp8=moe_args.fp8,
|
||||
)
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
self.experts.set_ep_comm_backend(self.ep_comm_backend)
|
||||
@@ -799,12 +824,19 @@ def _run_nongated_experts_grouped_mm_impl(
|
||||
_w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
fp8: bool = False,
|
||||
) -> torch.Tensor:
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
assert x.dim() == 2
|
||||
|
||||
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
if fp8:
|
||||
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
|
||||
|
||||
h = relu2(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
|
||||
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
|
||||
else:
|
||||
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
return out
|
||||
|
||||
|
||||
@@ -819,6 +851,17 @@ def _run_nongated_experts_grouped_mm(
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert)
|
||||
|
||||
|
||||
@expert_parallel
|
||||
def _run_nongated_experts_fp8_grouped_mm(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
_w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert, fp8=True)
|
||||
|
||||
|
||||
class NonGatedGroupedExperts(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -826,6 +869,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
intermediate_dim: int,
|
||||
num_experts: int,
|
||||
use_grouped_mm: bool,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.num_experts = num_experts
|
||||
@@ -834,6 +878,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
# Dummy w3 for @expert_parallel decorator compatibility (expects w1, w2, w3 signature)
|
||||
self.w3 = nn.Parameter(torch.empty(0))
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.fp8 = fp8
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
@@ -844,7 +889,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
w2 = self.w2.to_local()
|
||||
w3 = self.w3.to_local()
|
||||
if self.use_grouped_mm:
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
|
||||
return _run_nongated_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
def forward(
|
||||
@@ -855,6 +900,8 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
if self.ep_comm_backend == "deepep":
|
||||
return self._forward_deepep(x, num_tokens_per_expert)
|
||||
if self.use_grouped_mm:
|
||||
if self.fp8:
|
||||
return _run_nongated_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
return _run_nongated_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
else:
|
||||
return _run_nongated_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
@@ -971,6 +1018,7 @@ class LatentMoE(nn.Module):
|
||||
routed_scaling_factor: float,
|
||||
use_grouped_mm: bool,
|
||||
load_balance_coeff: float | None,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
effective_latent_dim = latent_dim if latent_dim is not None else dim
|
||||
@@ -988,6 +1036,7 @@ class LatentMoE(nn.Module):
|
||||
intermediate_dim=moe_intermediate_size,
|
||||
num_experts=num_experts,
|
||||
use_grouped_mm=use_grouped_mm,
|
||||
fp8=fp8,
|
||||
)
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
self.experts.set_ep_comm_backend(self.ep_comm_backend)
|
||||
|
||||
@@ -1,10 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
|
||||
import prime_rl._compat # noqa: F401
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from ring_flash_attn.utils import AllGatherComm, get_default_args
|
||||
|
||||
|
||||
def _set_fa3_signature_params(params: dict, causal: bool, window_size: tuple[int, int]) -> None:
|
||||
if "is_causal" in params:
|
||||
params["is_causal"] = causal
|
||||
else:
|
||||
params["causal"] = causal
|
||||
|
||||
if "window_size" in params:
|
||||
params["window_size"] = window_size
|
||||
else:
|
||||
params["window_size_left"] = window_size[0]
|
||||
params["window_size_right"] = window_size[1]
|
||||
|
||||
|
||||
def _fa3_varlen_forward(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -30,11 +46,9 @@ def _fa3_varlen_forward(
|
||||
"max_seqlen_q": max_seqlen_q,
|
||||
"max_seqlen_k": max_seqlen_k,
|
||||
"softmax_scale": softmax_scale,
|
||||
"is_causal": causal,
|
||||
"window_size_left": window_size[0],
|
||||
"window_size_right": window_size[1],
|
||||
}
|
||||
)
|
||||
_set_fa3_signature_params(params, causal, window_size)
|
||||
out, lse, _, _ = _flash_attn_forward(**params)
|
||||
return out, lse
|
||||
|
||||
@@ -76,11 +90,9 @@ def _fa3_varlen_backward(
|
||||
"dk": dk,
|
||||
"dv": dv,
|
||||
"softmax_scale": softmax_scale,
|
||||
"is_causal": causal,
|
||||
"window_size_left": window_size[0],
|
||||
"window_size_right": window_size[1],
|
||||
}
|
||||
)
|
||||
_set_fa3_signature_params(params, causal, window_size)
|
||||
_flash_attn_backward(**params)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
"""Ulysses-style context parallelism via all-to-all on the head/seq dimensions.
|
||||
|
||||
Ulysses is the simpler alternative to ring attention for context parallelism:
|
||||
|
||||
sequence-sharded Q/K/V head-sharded Q/K/V
|
||||
[S/cp, H, D] ── all-to-all ──▶ [S, H/cp, D]
|
||||
(heads ↔ seq)
|
||||
│
|
||||
▼
|
||||
run vanilla local attention
|
||||
on the *full* sequence with
|
||||
*fewer* heads (any kernel works)
|
||||
│
|
||||
▼
|
||||
[S/cp, H, D] ◀── all-to-all ── [S, H/cp, D]
|
||||
(seq ↔ heads)
|
||||
|
||||
Key benefit: the attention kernel itself does not need to be CP-aware. The
|
||||
all-to-all is purely on Q/K/V tensors, so this works out of the box with
|
||||
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
|
||||
|
||||
Constraints:
|
||||
- cp_size must divide both num_attention_heads and num_key_value_heads.
|
||||
- Sequence length must be divisible by cp_size.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.nn.functional as dist_nn
|
||||
|
||||
# Populated by `update_ulysses_params` before each forward pass. Mirrors
|
||||
# ring_flash_attn's DATA_PARAMS pattern so the patched attention path can
|
||||
# reach the *full* (un-sharded) cu_seqlens / max_seqlen at call time.
|
||||
ULYSSES_PARAMS: dict = {}
|
||||
|
||||
|
||||
def update_ulysses_params(cu_seqlens: torch.Tensor, max_seqlen: int) -> None:
|
||||
ULYSSES_PARAMS["cu_seqlens"] = cu_seqlens
|
||||
ULYSSES_PARAMS["max_seqlen"] = int(max_seqlen)
|
||||
|
||||
|
||||
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
|
||||
|
||||
Splits the head dim into cp_size groups and exchanges them so each rank
|
||||
ends up with the full sequence but only H/cp_size heads. Differentiable.
|
||||
"""
|
||||
s_local, h, d = t.shape
|
||||
assert h % cp_size == 0, f"num_heads ({h}) must be divisible by cp_size ({cp_size})"
|
||||
h_local = h // cp_size
|
||||
|
||||
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
|
||||
t = t.reshape(s_local, cp_size, h_local, d).transpose(0, 1).contiguous()
|
||||
output = torch.empty_like(t)
|
||||
out = dist_nn.all_to_all_single(output, t, group=cp_group)
|
||||
# out[i] is the chunk that source-rank i had at position my_rank, i.e.
|
||||
# source-rank i's local sequence shard for *my* head slice.
|
||||
return out.reshape(cp_size * s_local, h_local, d)
|
||||
|
||||
|
||||
def _all_to_all_head_to_seq(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
"""Inverse of `_all_to_all_seq_to_head`: [S_global, H_local, D] -> [S_local, H, D]."""
|
||||
s_global, h_local, d = t.shape
|
||||
assert s_global % cp_size == 0
|
||||
s_local = s_global // cp_size
|
||||
h = h_local * cp_size
|
||||
|
||||
t = t.reshape(cp_size, s_local, h_local, d).contiguous()
|
||||
output = torch.empty_like(t)
|
||||
out = dist_nn.all_to_all_single(output, t, group=cp_group)
|
||||
# out[s']: original chunk for sequence-rank s' (which now becomes head-rank s').
|
||||
return out.transpose(0, 1).contiguous().reshape(s_local, h, d)
|
||||
|
||||
|
||||
def ulysses_flash_attn_varlen_func(
|
||||
flash_fn,
|
||||
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,
|
||||
causal: bool,
|
||||
cp_group: dist.ProcessGroup,
|
||||
cp_size: int,
|
||||
flash_attn_version: int = 2,
|
||||
window_size: tuple[int, int] = (-1, -1),
|
||||
softmax_scale: float | None = None,
|
||||
dropout_p: float = 0.0,
|
||||
deterministic: bool | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run varlen flash attention under Ulysses CP.
|
||||
|
||||
`cu_seqlens_*` and `max_seqlen_*` describe the *full* (un-sharded) sequence,
|
||||
because after the seq->head all-to-all each rank holds the full sequence.
|
||||
"""
|
||||
q = _all_to_all_seq_to_head(q, cp_size, cp_group)
|
||||
k = _all_to_all_seq_to_head(k, cp_size, cp_group)
|
||||
v = _all_to_all_seq_to_head(v, cp_size, cp_group)
|
||||
|
||||
kwargs: dict = {"causal": causal}
|
||||
if window_size != (-1, -1):
|
||||
kwargs["window_size"] = window_size
|
||||
if softmax_scale is not None:
|
||||
kwargs["softmax_scale"] = softmax_scale
|
||||
if dropout_p:
|
||||
kwargs["dropout_p"] = dropout_p
|
||||
if deterministic is not None:
|
||||
kwargs["deterministic"] = deterministic
|
||||
|
||||
if flash_attn_version == 4:
|
||||
# FA4 takes cu_seqlens as keyword args (qv positional collides otherwise).
|
||||
kwargs["cu_seqlens_q"] = cu_seqlens_q
|
||||
kwargs["cu_seqlens_k"] = cu_seqlens_k
|
||||
out = flash_fn(q, k, v, **kwargs)
|
||||
else:
|
||||
out = flash_fn(q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, **kwargs)
|
||||
if isinstance(out, tuple):
|
||||
out = out[0]
|
||||
|
||||
return _all_to_all_head_to_seq(out, cp_size, cp_group)
|
||||
|
||||
|
||||
def substitute_ulysses_attn(
|
||||
process_group: dist.ProcessGroup,
|
||||
attn_impl: str = "flash_attention_2",
|
||||
) -> None:
|
||||
"""Patch FlashAttention._compute_attention to do Ulysses all-to-all + local FA.
|
||||
|
||||
Mirrors `substitute_ring_attn` so swapping CP styles is a one-line change
|
||||
in the trainer.
|
||||
"""
|
||||
cp_size = dist.get_world_size(group=process_group)
|
||||
|
||||
# Resolve flash kernel + version from attn_impl.
|
||||
if attn_impl == "fa4":
|
||||
from flash_attn.cute import flash_attn_varlen_func as flash_fn
|
||||
|
||||
flash_attn_version = 4
|
||||
flash_fn = torch._dynamo.disable(flash_fn)
|
||||
elif attn_impl == "flash_attention_3":
|
||||
from flash_attn_interface import flash_attn_varlen_func as flash_fn
|
||||
|
||||
flash_attn_version = 3
|
||||
else:
|
||||
from flash_attn import flash_attn_varlen_func as flash_fn
|
||||
|
||||
flash_attn_version = 2
|
||||
|
||||
def _ulysses_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
|
||||
# cu_seqlens / max_seqlen passed in are for the *local* sharded sequence;
|
||||
# ulysses needs the *full* ones (each rank holds the full seq after a2a).
|
||||
cu_seqlens_full = ULYSSES_PARAMS["cu_seqlens"]
|
||||
max_seqlen_full = ULYSSES_PARAMS["max_seqlen"]
|
||||
|
||||
window_size = (-1, -1)
|
||||
sliding_window = getattr(self, "sliding_window", None)
|
||||
if sliding_window is not None:
|
||||
window_size = (sliding_window - 1, 0)
|
||||
|
||||
return ulysses_flash_attn_varlen_func(
|
||||
flash_fn,
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
cu_seqlens_q=cu_seqlens_full,
|
||||
cu_seqlens_k=cu_seqlens_full,
|
||||
max_seqlen_q=max_seqlen_full,
|
||||
max_seqlen_k=max_seqlen_full,
|
||||
causal=True,
|
||||
cp_group=process_group,
|
||||
cp_size=cp_size,
|
||||
flash_attn_version=flash_attn_version,
|
||||
window_size=window_size,
|
||||
)
|
||||
|
||||
from prime_rl.trainer.models.layers.attn import FlashAttention
|
||||
|
||||
FlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
|
||||
|
||||
AfmoeFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
|
||||
|
||||
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
|
||||
|
||||
|
||||
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
|
||||
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
|
||||
|
||||
Used for HF (non-custom) model paths, e.g. qwen2/qwen3 dense models. Mirrors
|
||||
ring_flash_attn's `substitute_hf_flash_attn` but with all-to-all instead of
|
||||
ring all-gather.
|
||||
"""
|
||||
import transformers
|
||||
import transformers.modeling_flash_attention_utils
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
|
||||
cp_size = dist.get_world_size(group=process_group)
|
||||
|
||||
def _ulysses_flash_attention_forward(
|
||||
query_states: torch.Tensor,
|
||||
key_states: torch.Tensor,
|
||||
value_states: torch.Tensor,
|
||||
attention_mask,
|
||||
query_length: int,
|
||||
is_causal: bool,
|
||||
dropout: float = 0.0,
|
||||
position_ids=None,
|
||||
softmax_scale=None,
|
||||
sliding_window=None,
|
||||
use_top_left_mask: bool = False,
|
||||
softcap=None,
|
||||
deterministic=None,
|
||||
**kwargs,
|
||||
):
|
||||
assert is_causal, "ulysses CP only supports causal attention"
|
||||
assert softcap is None, "ulysses CP path does not support softcap"
|
||||
assert query_states.size(0) == 1, "varlen data should be processed with batch=1"
|
||||
|
||||
cu_seqlens = ULYSSES_PARAMS["cu_seqlens"]
|
||||
max_seqlen = ULYSSES_PARAMS["max_seqlen"]
|
||||
|
||||
window_size = (-1, -1)
|
||||
if sliding_window is not None and key_states.shape[1] > sliding_window:
|
||||
window_size = (sliding_window, sliding_window)
|
||||
|
||||
out = ulysses_flash_attn_varlen_func(
|
||||
flash_attn_varlen_func,
|
||||
query_states.squeeze(0),
|
||||
key_states.squeeze(0),
|
||||
value_states.squeeze(0),
|
||||
cu_seqlens_q=cu_seqlens,
|
||||
cu_seqlens_k=cu_seqlens,
|
||||
max_seqlen_q=max_seqlen,
|
||||
max_seqlen_k=max_seqlen,
|
||||
causal=True,
|
||||
cp_group=process_group,
|
||||
cp_size=cp_size,
|
||||
flash_attn_version=2,
|
||||
window_size=window_size,
|
||||
softmax_scale=softmax_scale,
|
||||
dropout_p=dropout,
|
||||
deterministic=deterministic,
|
||||
)
|
||||
return out.unsqueeze(0)
|
||||
|
||||
transformers.modeling_flash_attention_utils._flash_attention_forward = _ulysses_flash_attention_forward
|
||||
|
||||
# Newer transformers route attention through ALL_ATTENTION_FUNCTIONS["flash_attention_2"].
|
||||
try:
|
||||
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
||||
except ImportError:
|
||||
ALL_ATTENTION_FUNCTIONS = None
|
||||
|
||||
if ALL_ATTENTION_FUNCTIONS is not None:
|
||||
|
||||
def _ulysses_flash_attention_forward_v2(
|
||||
module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attention_mask=None,
|
||||
dropout: float = 0.0,
|
||||
scaling=None,
|
||||
sliding_window=None,
|
||||
softcap=None,
|
||||
**kw,
|
||||
):
|
||||
# Match HF v2 entrypoint: query/key/value arrive as [B, H, S, D].
|
||||
seq_len = query.shape[2]
|
||||
query = query.transpose(1, 2)
|
||||
key = key.transpose(1, 2)
|
||||
value = value.transpose(1, 2)
|
||||
|
||||
kw.pop("is_causal", None)
|
||||
attn_out = _ulysses_flash_attention_forward(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attention_mask,
|
||||
query_length=seq_len,
|
||||
is_causal=module.is_causal,
|
||||
dropout=dropout,
|
||||
softmax_scale=scaling,
|
||||
sliding_window=sliding_window,
|
||||
softcap=softcap,
|
||||
)
|
||||
return attn_out, None
|
||||
|
||||
ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = _ulysses_flash_attention_forward_v2
|
||||
@@ -55,6 +55,7 @@ class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=1e-3 if config.use_routing_bias else None,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
|
||||
|
||||
|
||||
@@ -257,6 +257,7 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
routed_scaling_factor=config.routed_scaling_factor,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
|
||||
def forward(
|
||||
|
||||
@@ -613,6 +613,7 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -127,11 +127,14 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
probs_diff = trainer_probs - inference_probs
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
dppo_invalid_mask = torch.where(advantages > 0, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = (advantages > 0) & dppo_invalid_mask_high
|
||||
is_masked_low = (advantages < 0) & dppo_invalid_mask_low
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
@@ -156,6 +159,8 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
if teacher_kl is not None:
|
||||
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
|
||||
|
||||
@@ -186,13 +186,32 @@ def train(config: TrainerConfig):
|
||||
if parallel_dims.cp_enabled:
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
|
||||
if config.model.cp_style == "ring":
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
else:
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import (
|
||||
substitute_hf_ulysses_attn,
|
||||
substitute_ulysses_attn,
|
||||
)
|
||||
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import (
|
||||
assert_cp_style_supports_model,
|
||||
setup_hybrid_cp,
|
||||
setup_nemotron_h_cp,
|
||||
setup_sparse_mla_cp,
|
||||
)
|
||||
|
||||
assert_cp_style_supports_model(config.model.cp_style, model)
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
# Optionally, resume training from a checkpoint
|
||||
progress = Progress()
|
||||
@@ -371,7 +390,9 @@ def train(config: TrainerConfig):
|
||||
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
|
||||
|
||||
if cp_enabled:
|
||||
input_ids, forward_position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
|
||||
input_ids, forward_position_ids = setup_cp_params(
|
||||
input_ids, position_ids, cp_rank, cp_size, cp_group, cp_style=config.model.cp_style
|
||||
)
|
||||
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
if routed_experts is not None:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Literal, TypedDict, cast
|
||||
import torch
|
||||
from datasets import Dataset, interleave_datasets, load_dataset
|
||||
from jaxtyping import Bool, Int
|
||||
from renderers.base import Renderer, build_training_sample
|
||||
from torch import Tensor
|
||||
from torch.distributed.checkpoint.stateful import Stateful
|
||||
from torch.utils.data import IterableDataset, get_worker_info
|
||||
@@ -127,6 +128,7 @@ class SFTDataset(StatefulIterableDataset):
|
||||
loss_mask_config: LossMaskConfig = LossMaskConfig(),
|
||||
max_examples: int | None = None,
|
||||
max_epochs: int | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.logger = get_logger()
|
||||
@@ -139,6 +141,8 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.loss_mask_config = loss_mask_config
|
||||
self.max_examples = max_examples
|
||||
self.max_epochs = max_epochs
|
||||
self.renderer = renderer
|
||||
self._warned_chat_template_kwargs = False
|
||||
|
||||
if self.tokenizer is None:
|
||||
self.logger.warning("No tokenizer provided, will not process examples")
|
||||
@@ -190,7 +194,30 @@ class SFTDataset(StatefulIterableDataset):
|
||||
|
||||
# Parse available tools, if present - assumes OAI format
|
||||
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
|
||||
tools = json.loads(example.get("tools") or "[]")
|
||||
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
|
||||
# as either a JSON-encoded string of a list or a list of dicts. Tools
|
||||
# arriving in the verifiers shape are converted to OAI form so any
|
||||
# downstream chat template can consume them.
|
||||
raw_tools = example.get("tools", example.get("tool_defs"))
|
||||
if not raw_tools:
|
||||
tools = []
|
||||
else:
|
||||
if isinstance(raw_tools, str):
|
||||
raw_tools = json.loads(raw_tools)
|
||||
tools = [
|
||||
t
|
||||
if isinstance(t, dict) and t.get("type") == "function" and "function" in t
|
||||
else {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name"),
|
||||
"description": t.get("description"),
|
||||
"parameters": t.get("parameters"),
|
||||
**({} if t.get("strict") is None else {"strict": t["strict"]}),
|
||||
},
|
||||
}
|
||||
for t in raw_tools
|
||||
]
|
||||
|
||||
def should_mask(message: dict) -> bool:
|
||||
assert "role" in message, "Message must have a role"
|
||||
@@ -206,18 +233,35 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
if self.renderer is not None:
|
||||
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
|
||||
self.logger.warning(
|
||||
"Example carries chat_template_kwargs but use_renderer=True; "
|
||||
"renderers don't forward chat_template_kwargs (model-specific "
|
||||
"renderers bake their template behavior in). These kwargs will "
|
||||
"be ignored. Further warnings suppressed for this dataset."
|
||||
)
|
||||
self._warned_chat_template_kwargs = True
|
||||
|
||||
input_ids, loss_mask = build_training_sample(
|
||||
self.renderer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
|
||||
# If EOS token is not found, manually append it
|
||||
if not self.tokenizer.eos_token_id in input_ids:
|
||||
@@ -537,6 +581,7 @@ def setup_dataset(
|
||||
*,
|
||||
max_epochs: int | None = None,
|
||||
raw_dataset: Dataset | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
return FakeDataset(
|
||||
@@ -554,6 +599,7 @@ def setup_dataset(
|
||||
loss_mask_config=config.loss_mask,
|
||||
non_dp_size=non_dp_size,
|
||||
max_epochs=max_epochs,
|
||||
renderer=renderer,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
@@ -4,6 +4,8 @@ import time
|
||||
from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from renderers.base import create_renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
@@ -107,8 +109,17 @@ def train(config: SFTConfig):
|
||||
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
if config.model.cp_style == "ring":
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
else:
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import (
|
||||
substitute_hf_ulysses_attn,
|
||||
substitute_ulysses_attn,
|
||||
)
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
|
||||
|
||||
# Set up checkpoint manager
|
||||
@@ -129,9 +140,16 @@ def train(config: SFTConfig):
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later, fused_cross_entropy=fused_cross_entropy)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
from prime_rl.utils.cp import assert_cp_style_supports_model
|
||||
|
||||
assert_cp_style_supports_model(config.model.cp_style, model)
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
if config.model.lora is not None:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
@@ -141,6 +159,24 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
renderer = None
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
f"use_renderer=True for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
|
||||
"fix position-dependent chat templates — the bug use_renderer is meant to solve. "
|
||||
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or set use_renderer=false."
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
optimizer = setup_optimizer(
|
||||
@@ -159,7 +195,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
logger.info(f"Initializing data ({config.data})")
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp)
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
@@ -213,7 +249,9 @@ def train(config: SFTConfig):
|
||||
loss_mask = micro_batch["loss_mask"].to("cuda")
|
||||
|
||||
if cp_enabled:
|
||||
input_ids, position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
|
||||
input_ids, position_ids = setup_cp_params(
|
||||
input_ids, position_ids, cp_rank, cp_size, cp_group, cp_style=config.model.cp_style
|
||||
)
|
||||
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
@@ -265,7 +303,12 @@ def train(config: SFTConfig):
|
||||
|
||||
def run_validation(step: int) -> None:
|
||||
val_dataset = setup_dataset(
|
||||
tokenizer, config.val.data, config.model.cp, max_epochs=1, raw_dataset=val_raw_dataset
|
||||
tokenizer,
|
||||
config.val.data,
|
||||
config.model.cp,
|
||||
max_epochs=1,
|
||||
raw_dataset=val_raw_dataset,
|
||||
renderer=renderer,
|
||||
)
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
|
||||
@@ -422,9 +465,14 @@ def train(config: SFTConfig):
|
||||
if memory_profiler is not None:
|
||||
memory_profiler.step()
|
||||
|
||||
# Compute step metrics
|
||||
# Divide by CP since those ranks process the same data
|
||||
num_tokens = config.data.batch_size * config.data.seq_len // config.model.cp
|
||||
# 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
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples = dataset.step
|
||||
perf_counter = get_perf_counter(model, config.data.seq_len)
|
||||
|
||||
@@ -389,6 +389,8 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
"is_masked/",
|
||||
"is_masked_low/",
|
||||
"is_masked_high/",
|
||||
"masked_advantage_positive/",
|
||||
"masked_advantage_negative/",
|
||||
"mismatch_kl/",
|
||||
"masked_mismatch_kl/",
|
||||
"unmasked_mismatch_kl/",
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def get_all_fields(model: BaseModel | type) -> list[str]:
|
||||
if isinstance(model, BaseModel):
|
||||
model_cls = model.__class__
|
||||
else:
|
||||
model_cls = model
|
||||
|
||||
fields = []
|
||||
for name, field in model_cls.model_fields.items():
|
||||
field_type = field.annotation
|
||||
fields.append(name)
|
||||
if field_type is not None and hasattr(field_type, "model_fields"):
|
||||
sub_fields = get_all_fields(field_type)
|
||||
fields.extend(f"{name}.{sub}" for sub in sub_fields)
|
||||
return fields
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user