Compare commits
104
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 | ||
|
|
2ff21d97e7 | ||
|
|
5e6f7ebae8 | ||
|
|
7d7bd92333 | ||
|
|
d8d214cbab | ||
|
|
a50b4079de | ||
|
|
0403c097a2 | ||
|
|
0b8c35e9b3 | ||
|
|
ca5e02c24c | ||
|
|
c37e2ca71b | ||
|
|
b1e9c7bdd2 | ||
|
|
af17a555fe | ||
|
|
a87badd65f | ||
|
|
5061b8d88e | ||
|
|
a8575d6f1c | ||
|
|
e75d8ca47f | ||
|
|
daedc1dbc6 | ||
|
|
3719abcfbb | ||
|
|
93cbc75b81 | ||
|
|
4e4390be87 | ||
|
|
8457b601d6 | ||
|
|
273524e2fc | ||
|
|
d2f36c9f65 | ||
|
|
2566de0bd5 | ||
|
|
0fca0d15c5 | ||
|
|
24a2af0054 | ||
|
|
8342ccd0c8 | ||
|
|
20454ecd7b | ||
|
|
4a42aa039e | ||
|
|
b0a7cad8a8 | ||
|
|
f1bbdf924e | ||
|
|
9bbed30eba | ||
|
|
a6a6441a3b | ||
|
|
e8abfa264b | ||
|
|
c3a24c35e2 | ||
|
|
d2718f5f65 | ||
|
|
d49f3939e7 | ||
|
|
9eeffdb6fb | ||
|
|
03689b8ac0 | ||
|
|
f29e947585 | ||
|
|
bb7449c829 | ||
|
|
82fa41f4f2 | ||
|
|
1ade129004 | ||
|
|
26ea8df85e | ||
|
|
d4bddbaed7 | ||
|
|
6bf14b80f8 | ||
|
|
586e0f8e5d | ||
|
|
18e895651e | ||
|
|
2c54d5c834 | ||
|
|
3a6b46189a | ||
|
|
ba86b9ba88 | ||
|
|
2d659eecc7 | ||
|
|
56cdd2c579 | ||
|
|
4dcf86f0ea | ||
|
|
ad3134ac03 | ||
|
|
8c5aa67aa5 | ||
|
|
fde3006470 | ||
|
|
67783e4a6c |
@@ -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
|
||||
@@ -57,7 +57,10 @@ jobs:
|
||||
runs-on: research-cluster
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
# --shm-size: vLLM V1's DP engine/API-server IPC uses POSIX shm-backed
|
||||
# MessageQueue (~160MB per queue); Docker's default 64MB /dev/shm triggers
|
||||
# SIGBUS in DP engine cores on VLM runs (mm data overflows tmpfs).
|
||||
options: --gpus all --shm-size=16g
|
||||
timeout-minutes: 1440 # 24 hours
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -72,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.
|
||||
```
|
||||
@@ -32,6 +33,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -43,6 +45,9 @@ You are responsible for maintaining the skills folder. When a workflow fails and
|
||||
|
||||
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
|
||||
|
||||
- **Conservative test additions**: don't add new tests unless the user explicitly asks for them or it's clearly necessary. Editing existing tests is fine, but adding new test files or test functions should be the exception, not the default.
|
||||
- **Test what matters**: only test code with clear, isolated logic — pure functions, abstract base classes, data transformations, well-defined algorithms. Don't test runtime-level code, framework glue, or anything that requires extensive mocking/patching just to get a test to pass. If you need to patch everything out to make it testable, it's probably not worth testing.
|
||||
|
||||
## Git
|
||||
|
||||
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
|
||||
@@ -51,4 +56,5 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
|
||||
|
||||
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
|
||||
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
|
||||
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
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)
|
||||
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
|
||||
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
|
||||
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
|
||||
|
||||
+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
|
||||
|
||||
@@ -19,11 +19,11 @@ name = "stage1"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -20,11 +20,11 @@ name = "stage2"
|
||||
batch_size = 2048
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 16384
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
@@ -13,10 +13,10 @@ lr = 1e-5
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 384
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "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 }
|
||||
@@ -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.sampling]
|
||||
max_tokens = 1024
|
||||
|
||||
[[orchestrator.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]
|
||||
+4
-3
@@ -2,6 +2,7 @@ max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -13,10 +14,10 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
+4
-5
@@ -1,8 +1,7 @@
|
||||
max_steps = 25
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -14,10 +13,10 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
+4
-3
@@ -2,6 +2,7 @@ max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -22,10 +23,10 @@ rollouts_per_example = 16
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
+4
-5
@@ -1,8 +1,7 @@
|
||||
max_steps = 25
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 20
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -23,10 +22,10 @@ rollouts_per_example = 16
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
+6
-3
@@ -9,14 +9,17 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
+3
-3
@@ -11,10 +11,10 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
[optim]
|
||||
lr = 3e-5
|
||||
|
||||
[sampling]
|
||||
max_tokens = 128
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[env]]
|
||||
[[train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[ckpt]
|
||||
+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]
|
||||
|
||||
@@ -17,11 +17,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -17,10 +17,10 @@ language_model_attr = "model.language_model"
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
|
||||
@@ -2,6 +2,6 @@ max_steps = 5
|
||||
max_async_level = 5
|
||||
batch_size = 16
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
[train.sampling]
|
||||
max_completion_tokens = 16
|
||||
|
||||
|
||||
@@ -19,11 +19,11 @@ interval = 100
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -20,11 +20,11 @@ resume_step = 500
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 16384
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -20,11 +20,11 @@ resume_step = 1000
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 24576
|
||||
max_completion_tokens = 24576
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -32,15 +32,15 @@ lr = 1e-5
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[orchestrator.client.elastic]
|
||||
hostname = "localhost"
|
||||
port = 8000
|
||||
sync_interval = 5.0
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
@@ -16,27 +16,27 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "science-env"
|
||||
name = "science"
|
||||
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math-python"
|
||||
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "PrimeIntellect/Qwen3-0.6B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -28,7 +28,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
@@ -12,7 +12,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
@@ -11,13 +11,13 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 256
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
ratio = 0.5
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-python"
|
||||
args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy" }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ language_model_attr = "model.language_model"
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 32
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
|
||||
@@ -48,10 +48,10 @@ max_inflight_activations = 5
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -64,7 +64,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
@@ -47,10 +47,10 @@ freq = 1
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 4096
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -63,7 +63,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 4096
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
Submodule
+1
Submodule configs/private added at 74c1330008
@@ -30,13 +30,13 @@ batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "wiki-search"
|
||||
|
||||
[inference.model]
|
||||
|
||||
+1
Submodule deps/renderers added at 17d0584f87
+1
Submodule deps/research-environments added at d141472268
+1
Submodule deps/verifiers added at 711a7c705e
@@ -86,10 +86,12 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
rewards: Float[Tensor, "num_examples rollouts_per_example"]
|
||||
completion_lengths: Int[Tensor, "num_examples rollouts_per_example"]
|
||||
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
```
|
||||
|
||||
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
|
||||
|
||||
#### AdvantageOutputs
|
||||
|
||||
```python
|
||||
@@ -106,9 +108,10 @@ from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
"""Normalize advantages to zero mean and unit variance per example."""
|
||||
mean = inputs.rewards.mean(dim=1, keepdim=True)
|
||||
std = inputs.rewards.std(dim=1, keepdim=True)
|
||||
advantages = (inputs.rewards - mean) / (std + eps)
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
mean = rewards.mean(dim=1, keepdim=True)
|
||||
std = rewards.std(dim=1, keepdim=True)
|
||||
advantages = (rewards - mean) / (std + eps)
|
||||
return AdvantageOutputs(advantages=advantages)
|
||||
```
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ The eviction takes effect through two mechanisms:
|
||||
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
|
||||
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
|
||||
- This surfaces the eviction reason to the user
|
||||
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
|
||||
|
||||
## LoRA Module Registration
|
||||
|
||||
|
||||
@@ -47,31 +47,31 @@ weight_decay = 0.01
|
||||
batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "deepdive"
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
|
||||
@@ -28,10 +28,10 @@ lr = 1e-5
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
|
||||
@@ -19,9 +19,6 @@ name = "qwen3-4b-hard-distill"
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
@@ -33,9 +30,10 @@ save_adapter_separately = true
|
||||
batch_size = 256
|
||||
rollouts_per_example = 4
|
||||
use_token_client = false
|
||||
use_sft_loss = true
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
temperature = 0.7
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
@@ -45,7 +43,7 @@ api_key_var = "PRIME_API_KEY"
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "qwen/qwen3-235b-a22b-instruct-2507"
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[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 }
|
||||
|
||||
@@ -16,7 +16,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # included in lock file
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
@@ -49,7 +49,7 @@ oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
@@ -38,10 +38,10 @@ freq = 1
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B Math
|
||||
# Qwen 3 30B - A3B Math
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on math tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -45,10 +45,10 @@ batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 32768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B SWE
|
||||
# Qwen 3 30B - A3B SWE
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on agentic SWE tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "reverse-text"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
|
||||
@@ -37,13 +37,13 @@ oversampling_factor = 2.0
|
||||
[orchestrator.model.lora]
|
||||
name = "qwen3-4b-wiki-search"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
@@ -18,12 +18,12 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 1024
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -207,7 +207,7 @@ spec:
|
||||
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
path: /liveness
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
|
||||
|
||||
@@ -75,7 +75,7 @@ inference:
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for inference server (requires /health endpoint)
|
||||
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows long model loading time (up to 45 min by default)
|
||||
@@ -86,7 +86,7 @@ inference:
|
||||
liveness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 60
|
||||
timeoutSeconds: 10
|
||||
readiness:
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
|
||||
@@ -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
|
||||
+1
@@ -13,6 +13,7 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
log: LogConfig = LogConfig()
|
||||
env_install_prerelease: bool = False
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
+74
-34
@@ -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):
|
||||
@@ -85,7 +95,7 @@ class ModelConfig(BaseModelConfig):
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
] = "auto"
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
@@ -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
|
||||
@@ -247,15 +248,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for inference."""
|
||||
|
||||
reset_prefix_cache_after_update: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to reset the prefix cache after weight updates (update_weights, load_lora_adapter). "
|
||||
"Ensures all KV states are recomputed with the new weights at the cost of extra prefill. "
|
||||
"When False, prefer using orchestrator.experimental.use_prefix_cache_salt to invalidate stale caches via salt instead.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
@@ -392,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(
|
||||
@@ -399,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(
|
||||
@@ -437,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."""
|
||||
@@ -459,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")
|
||||
@@ -509,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",
|
||||
@@ -545,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")
|
||||
+217
-28
@@ -1,4 +1,5 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -11,12 +12,12 @@ from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
RendererConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
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):
|
||||
@@ -148,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
|
||||
|
||||
@@ -247,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
|
||||
|
||||
@@ -324,6 +329,14 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
] = -1
|
||||
|
||||
timeout: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
validation_alias=AliasChoices("timeout", "timeout_seconds"),
|
||||
description="Per-rollout wall-clock timeout in seconds. Set to None (default) to disable.",
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
@@ -346,6 +359,12 @@ class EnvConfig(BaseConfig):
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_timeout(self):
|
||||
if self.timeout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
"""Configures a training environment."""
|
||||
@@ -670,22 +689,70 @@ 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."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_shaping: Annotated[
|
||||
bool,
|
||||
length_penalty: Annotated[
|
||||
LengthPenaltyConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"Enable correctness-gated length shaping. In mixed groups, shorter correct rollouts get "
|
||||
"amplified advantage (up to 2x), longer correct rollouts are unchanged, incorrect untouched. "
|
||||
"In all-correct groups, below-average-length rollouts get advantage in [0, 1], others get 0."
|
||||
"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."
|
||||
)
|
||||
),
|
||||
] = False
|
||||
] = None
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -715,7 +782,7 @@ class GibberishFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
token_id_threshold: Annotated[
|
||||
@@ -739,7 +806,7 @@ class RepetitionFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
window: Annotated[
|
||||
@@ -765,7 +832,7 @@ class ZeroAdvantageFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = True
|
||||
|
||||
@@ -812,15 +879,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the orchestrator."""
|
||||
|
||||
use_prefix_cache_salt: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to set a cache_salt on inference requests that changes with each weight update. "
|
||||
"This invalidates prefix-cached KV states from previous policies without resetting the entire cache, "
|
||||
"while preserving cache hits for in-flight off-policy rollouts.",
|
||||
),
|
||||
] = True
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
|
||||
@@ -865,6 +923,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
# The optimizer configuration (per-run LR for multi-run training)
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
|
||||
@@ -889,6 +950,17 @@ class OrchestratorConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
# When True, trainer uses SFT loss instead of RL loss (per-run override for hosted multi-tenant training)
|
||||
use_sft_loss: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"When True, use SFT masked NLL loss instead of the trainer's configured RL loss. "
|
||||
"Requires a teacher_rollout_model to be configured."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
# The evaluation configuration
|
||||
eval: EvalConfig | None = None
|
||||
|
||||
@@ -1010,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(
|
||||
@@ -1041,10 +1121,31 @@ class OrchestratorConfig(BaseConfig):
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. "
|
||||
"WARNING: Only use this if your environment has a linear history and the chat template has the extension "
|
||||
"property (i.e. no tokens are ever removed or inserted by the chat template). Mutually exclusive with "
|
||||
"``use_renderer``."
|
||||
),
|
||||
] = True
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the renderer client (client-side tokenization via the ``renderers`` package, "
|
||||
"served by ``/v1/generate``). Mutually exclusive with ``use_token_client``. When True, the "
|
||||
"``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) "
|
||||
"applies; when False those fields must be left at their defaults. Not supported for VLMs — "
|
||||
"VLMs must use the token client (TITO) so image preprocessing and chat templating stay server-side."
|
||||
),
|
||||
] = False
|
||||
|
||||
env_install_prerelease: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Allow pre-release versions when installing environments (e.g. verifiers>=0.1.12.dev5). Passes --prerelease to prime env install."
|
||||
),
|
||||
] = False
|
||||
|
||||
experimental: Annotated[
|
||||
OrchestratorExperimentalConfig,
|
||||
Field(description="Experimental features for the orchestrator."),
|
||||
@@ -1060,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
|
||||
@@ -1088,6 +1193,90 @@ class OrchestratorConfig(BaseConfig):
|
||||
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_sft_distill_mode(self):
|
||||
"""Enforce the SFT hard distill invariants that involve only orchestrator fields.
|
||||
|
||||
Runs at ``OrchestratorConfig`` level so hosted deployments (which load this
|
||||
config standalone via the ``orchestrator`` entrypoint) get the same guarantees
|
||||
as the combined ``rl`` entrypoint.
|
||||
"""
|
||||
has_teacher = self.teacher_rollout_model is not None
|
||||
if self.use_sft_loss and not has_teacher:
|
||||
raise ValueError(
|
||||
"orchestrator.use_sft_loss = true requires orchestrator.teacher_rollout_model to be configured."
|
||||
)
|
||||
if has_teacher and not self.use_sft_loss:
|
||||
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
|
||||
if has_teacher and self.use_token_client:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
if has_teacher and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
|
||||
"(external rollout uses MITO)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_client_mode(self):
|
||||
"""The two client toggles select among three exclusive modes:
|
||||
|
||||
- ``use_token_client=True`` + ``use_renderer=False`` → TITO (default)
|
||||
- ``use_token_client=False`` + ``use_renderer=True`` → renderer
|
||||
- ``use_token_client=False`` + ``use_renderer=False`` → MITO
|
||||
|
||||
Both True is invalid: TITO and renderer are different wire protocols
|
||||
(server-side templating vs client-side tokenization).
|
||||
"""
|
||||
if self.use_token_client and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client and orchestrator.use_renderer are mutually exclusive. "
|
||||
"Pick one: token client (TITO, server-side templating) or renderer client (client-side "
|
||||
"tokenization)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
"""The renderer client takes plain message dicts and tokenizes
|
||||
them client-side. VLMs need server-side image preprocessing and
|
||||
chat templating, so they must use the token client (TITO) — fail
|
||||
loudly when both are set."""
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer is not supported for VLMs. Use the token client "
|
||||
"(``use_token_client=true``, the default) so image preprocessing and chat "
|
||||
"templating stay on the inference server."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
"""``[orchestrator.renderer]`` knobs are only meaningful when
|
||||
``use_renderer=True``. Reject otherwise so callers don't silently
|
||||
pass them and wonder why they're ignored."""
|
||||
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 self.renderer.pool_size is not None:
|
||||
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without orchestrator.use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def nccl_max_async_level(self):
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
@@ -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,
|
||||
@@ -77,8 +77,14 @@ class SharedWandbConfig(BaseConfig):
|
||||
|
||||
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
|
||||
|
||||
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
|
||||
|
||||
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
|
||||
|
||||
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
|
||||
|
||||
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
shared: Annotated[
|
||||
@@ -428,24 +434,18 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_external_rollout_mode(self):
|
||||
if self.orchestrator.teacher_rollout_model is None:
|
||||
return self
|
||||
def validate_external_rollout_inference(self):
|
||||
"""Forbid configuring a local inference server when rollouts come from an external teacher.
|
||||
|
||||
if self.trainer.loss.type != "sft":
|
||||
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
|
||||
|
||||
if self.inference is not None:
|
||||
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
|
||||
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
|
||||
orchestrator entrypoint also enforces them.
|
||||
"""
|
||||
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
|
||||
raise ValueError(
|
||||
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
|
||||
"External rollout mode does not use the local inference server."
|
||||
)
|
||||
|
||||
if self.orchestrator.use_token_client:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
@@ -522,6 +522,10 @@ class RLConfig(BaseConfig):
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
if self.wandb.entity:
|
||||
self.trainer.wandb.entity = self.wandb.entity
|
||||
self.orchestrator.wandb.entity = self.wandb.entity
|
||||
|
||||
if self.wandb.shared:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = self.wandb.name
|
||||
@@ -531,6 +535,14 @@ class RLConfig(BaseConfig):
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
if self.wandb.group:
|
||||
self.trainer.wandb.group = self.wandb.group
|
||||
self.orchestrator.wandb.group = self.wandb.group
|
||||
|
||||
if self.wandb.tags:
|
||||
self.trainer.wandb.tags = self.wandb.tags.copy()
|
||||
self.orchestrator.wandb.tags = self.wandb.tags.copy()
|
||||
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
@@ -669,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:
|
||||
@@ -733,18 +760,18 @@ 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
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
|
||||
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -752,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
|
||||
|
||||
@@ -946,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
|
||||
+84
@@ -132,6 +132,61 @@ class BaseModelConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
"""Configures the client-side renderer (chat-template + response parsing).
|
||||
|
||||
Only consumed when ``orchestrator.use_renderer = true``. The renderer
|
||||
owns both directions: render messages → token ids on the client, and
|
||||
parse model output tokens → structured ``content`` / ``reasoning_content``
|
||||
/ ``tool_calls``.
|
||||
"""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description=(
|
||||
"Renderer to use for chat template tokenization. "
|
||||
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
|
||||
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
|
||||
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
tool_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a tool parser in renderers.parsers. Only consumed by "
|
||||
"DefaultRenderer (model-specific renderers bake their own parsing "
|
||||
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a reasoning parser in renderers.parsers. Only consumed "
|
||||
"by DefaultRenderer. Options today: 'think'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
pool_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of renderer slots shared across concurrent rollouts. "
|
||||
"None keeps the verifiers default (1). Bump for long multi-turn "
|
||||
"prompts where client-side jinja tokenization serializes."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
|
||||
@@ -184,6 +239,14 @@ class ClientConfig(BaseConfig):
|
||||
),
|
||||
] = 30.0
|
||||
|
||||
wait_for_ready_timeout: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
|
||||
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
|
||||
),
|
||||
] = 1800
|
||||
|
||||
base_url: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
@@ -354,6 +417,13 @@ class WandbConfig(BaseConfig):
|
||||
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
|
||||
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
|
||||
|
||||
entity: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B entity to log to.",
|
||||
),
|
||||
] = None
|
||||
|
||||
name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
@@ -361,6 +431,20 @@ class WandbConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
group: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B group to use for logging.",
|
||||
),
|
||||
] = None
|
||||
|
||||
tags: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="The W&B tags to attach to the run.",
|
||||
),
|
||||
] = None
|
||||
|
||||
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
|
||||
+55
-7
@@ -139,7 +139,13 @@ class LoRAConfig(BaseConfig):
|
||||
target_modules: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
description="Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') match any component in the module path. Regex patterns match anywhere in the name.",
|
||||
description=(
|
||||
"Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') "
|
||||
"match any component in the module path. Regex patterns match anywhere in the name. "
|
||||
"Names unknown to the current model are silently ignored, so defaults cover multiple architectures. "
|
||||
"NemotronH note: 'experts' matches NonGatedGroupedExperts inside LatentMoE; 'fc1_latent_proj' and "
|
||||
"'fc2_latent_proj' adapt the latent up/down projections. Add 'in_proj'/'out_proj' to also LoRA Mamba."
|
||||
),
|
||||
),
|
||||
] = [
|
||||
"q_proj",
|
||||
@@ -150,6 +156,8 @@ class LoRAConfig(BaseConfig):
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
"experts",
|
||||
"fc1_latent_proj",
|
||||
"fc2_latent_proj",
|
||||
]
|
||||
|
||||
modules_to_save: Annotated[
|
||||
@@ -175,6 +183,13 @@ class DebugModelConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
force_balanced_routing: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, override MoE token-choice routing with a round-robin assignment so every expert receives an equal share of tokens. Intended for fake-data smoke tests where untrained routing would otherwise produce severe expert imbalance and OOM. Gating scores are still gathered from the override indices so the forward pass stays consistent.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the model for training."""
|
||||
@@ -184,7 +199,7 @@ class ModelConfig(BaseModelConfig):
|
||||
attn: Annotated[
|
||||
AttnImplementation,
|
||||
Field(
|
||||
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3).",
|
||||
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3, FA4 for fa4).",
|
||||
),
|
||||
] = "flash_attention_2"
|
||||
|
||||
@@ -284,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(
|
||||
@@ -315,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(
|
||||
@@ -368,12 +406,16 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cp_only_with_flash_attn(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3"]:
|
||||
raise ValueError("CP is only supported with flash attention 2 or flash attention 3")
|
||||
if self.cp > 1 and self.attn == "flash_attention_3" and self.impl != "custom":
|
||||
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(
|
||||
"CP with flash_attention_3 requires model.impl='custom' "
|
||||
"(the FA3 ring-attention kernel is only implemented for the custom model path)"
|
||||
f"CP with {self.attn} requires model.impl='custom' "
|
||||
"(FA3/FA4 paths are only implemented for the custom model attention class)"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -402,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
|
||||
+140
-46
@@ -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",
|
||||
"wandb>=0.24.2",
|
||||
"vllm>=0.20.2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.37",
|
||||
"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'",
|
||||
@@ -91,6 +104,8 @@ all = [
|
||||
"prime-rl[flash-attn]",
|
||||
"prime-rl[disagg]",
|
||||
"prime-rl[quack]",
|
||||
"prime-rl[flash-attn-3]",
|
||||
"prime-rl[flash-attn-cute]",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
@@ -106,7 +121,42 @@ 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
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
@@ -119,34 +169,74 @@ 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]
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
flash_attn_3 = 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)
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
deep-ep = false
|
||||
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 = "0760204" }
|
||||
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 = "abd9943b" }
|
||||
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.20/vllm_router-0.1.20-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-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" }
|
||||
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" }
|
||||
|
||||
@@ -158,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"
|
||||
@@ -178,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"
|
||||
@@ -192,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
|
||||
|
||||
@@ -14,10 +14,4 @@ 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-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#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"
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
@@ -4,5 +4,13 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
|
||||
fi
|
||||
|
||||
# Execute the main command
|
||||
exec "$@"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
set -e
|
||||
|
||||
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
|
||||
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
uv pip install --reinstall --no-deps "flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# Verify installation
|
||||
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
|
||||
|
||||
+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,
|
||||
|
||||
@@ -153,6 +153,10 @@ uv run sft --data.type fake --data.batch-size 4
|
||||
|
||||
If you wish to configure values of the default variant, you don't need to set the `type` field.
|
||||
|
||||
### SFT hard distill override
|
||||
|
||||
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
|
||||
|
||||
### Model fields
|
||||
|
||||
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
|
||||
@@ -173,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
|
||||
+48
-14
@@ -1,21 +1,55 @@
|
||||
"""Compatibility shim: ring_flash_attn + transformers >= 5.4.
|
||||
"""Compatibility shims for upstream regressions.
|
||||
|
||||
ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
|
||||
`transformers.modeling_flash_attention_utils`. This symbol was removed from
|
||||
that module in transformers 5.4 (still available as a deprecated function
|
||||
in `transformers.utils.import_utils`, scheduled for removal in 5.8).
|
||||
|
||||
ring_flash_attn's except-branch is a no-op (imports the same symbol again),
|
||||
so the import crashes on transformers >= 5.4. We patch the symbol back in as
|
||||
`True` — the check is dead code since no one uses flash_attn < 2.1.0 anymore.
|
||||
|
||||
Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
|
||||
Remove this shim once ring_flash_attn ships a fixed version.
|
||||
Imported early (before any model code) by trainer and orchestrator entrypoints.
|
||||
Each shim documents the upstream issue and removal condition.
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ring_flash_attn + transformers >= 5.4
|
||||
#
|
||||
# ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
|
||||
# `transformers.modeling_flash_attention_utils`, removed in transformers 5.4.
|
||||
#
|
||||
# Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
|
||||
# Remove once ring_flash_attn ships a fixed version.
|
||||
# ---------------------------------------------------------------------------
|
||||
import transformers.modeling_flash_attention_utils as _mfau
|
||||
|
||||
if not hasattr(_mfau, "is_flash_attn_greater_or_equal_2_10"):
|
||||
# ring_flash_attn uses this as a bare value (if x:), but other code may
|
||||
# call it as a function (if x():). Use a callable that is also truthy.
|
||||
_mfau.is_flash_attn_greater_or_equal_2_10 = lambda: True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transformers >= 5.5 hub_kernels offline regression
|
||||
#
|
||||
# lazy_load_kernel() resolves kernel versions via HfApi().list_repo_refs(),
|
||||
# which raises OfflineModeIsEnabled when HF_HUB_OFFLINE=1 — even if the
|
||||
# kernel is already cached locally. Only FileNotFoundError and AssertionError
|
||||
# are caught; OfflineModeIsEnabled (a ConnectionError subclass) is not.
|
||||
#
|
||||
# This breaks Mamba-based models (NemotronH, Zamba2, Jamba, etc.) on SLURM
|
||||
# worker nodes where HF_HUB_OFFLINE=1 is set.
|
||||
#
|
||||
# Fix: patch the except clause to also catch ConnectionError.
|
||||
# Remove once huggingface/transformers fixes lazy_load_kernel offline handling.
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import transformers.integrations.hub_kernels as _hub_kernels
|
||||
except ImportError:
|
||||
_hub_kernels = None # transformers < 5.5, no patch needed
|
||||
|
||||
if _hub_kernels is not None:
|
||||
from huggingface_hub.errors import OfflineModeIsEnabled
|
||||
|
||||
_original_lazy_load_kernel = _hub_kernels.lazy_load_kernel
|
||||
|
||||
def _patched_lazy_load_kernel(kernel_name, mapping=_hub_kernels._KERNEL_MODULE_MAPPING):
|
||||
try:
|
||||
return _original_lazy_load_kernel(kernel_name, mapping)
|
||||
except OfflineModeIsEnabled:
|
||||
# Return None so NemotronH skips hub kernels; prime-rl's
|
||||
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
|
||||
mapping[kernel_name] = None
|
||||
return None
|
||||
|
||||
_hub_kernels.lazy_load_kernel = _patched_lazy_load_kernel
|
||||
|
||||
@@ -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,7 +12,9 @@ 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
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
@@ -347,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)
|
||||
@@ -443,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)),
|
||||
@@ -468,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)),
|
||||
@@ -547,15 +552,26 @@ def rl(config: RLConfig):
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clean stale artifacts from steps after the resume point
|
||||
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
|
||||
# step is stale. When training from scratch, every existing step directory is
|
||||
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
|
||||
# from a previous run and the orchestrator would see a negative async level.
|
||||
resume_step: int | None = None
|
||||
if resuming:
|
||||
resume_step = config.ckpt.resume_step
|
||||
if resume_step == -1:
|
||||
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
|
||||
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
|
||||
if resume_step is not None:
|
||||
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, resume_step)
|
||||
|
||||
if resume_step is not None:
|
||||
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, resume_step)
|
||||
else:
|
||||
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, -1)
|
||||
|
||||
if not config.dry_run:
|
||||
pre_download_model(config.trainer.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -8,7 +8,9 @@ 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
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
@@ -196,6 +198,9 @@ def sft(config: SFTConfig):
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not config.dry_run:
|
||||
pre_download_model(config.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
|
||||
+297
-280
@@ -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.
|
||||
|
||||
@@ -195,6 +360,7 @@ def _patch_qwen35_lora():
|
||||
from vllm.model_executor.models.qwen3_5 import (
|
||||
Qwen3_5ForCausalLMBase,
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
Qwen3_5MoeForConditionalGeneration,
|
||||
)
|
||||
|
||||
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
|
||||
@@ -202,6 +368,8 @@ def _patch_qwen35_lora():
|
||||
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
|
||||
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
|
||||
|
||||
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
|
||||
|
||||
@classmethod
|
||||
@@ -302,10 +470,14 @@ def _patch_lora_key_prefix():
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Fix: always compare just the last component of the path.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
if expert_suffix not in expected_lora_modules:
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
@@ -478,6 +650,65 @@ def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
|
||||
|
||||
|
||||
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
|
||||
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
|
||||
# recompiling regex patterns inside is_supported_lora_module — purely to emit
|
||||
# logger.warning_once about modules that will be ignored. Adapter validity is
|
||||
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
|
||||
def monkey_patch_skip_lora_module_warnings():
|
||||
from vllm.exceptions import LoRAAdapterNotFoundError
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.lora.utils import get_adapter_absolute_path
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
|
||||
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
|
||||
try:
|
||||
supported_lora_modules = self._adapter_manager.supported_lora_modules
|
||||
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
|
||||
expected_lora_lst: list[str] = []
|
||||
for module in supported_lora_modules:
|
||||
if module in packed_modules_mapping:
|
||||
expected_lora_lst.extend(packed_modules_mapping[module])
|
||||
else:
|
||||
expected_lora_lst.append(module)
|
||||
if module == "experts":
|
||||
expected_lora_lst.append(module)
|
||||
expected_lora_modules = set(expected_lora_lst)
|
||||
lora_path = get_adapter_absolute_path(lora_request.lora_path)
|
||||
|
||||
peft_helper = PEFTHelper.from_local_dir(
|
||||
lora_path,
|
||||
self.max_position_embeddings,
|
||||
lora_request.tensorizer_config_dict,
|
||||
)
|
||||
peft_helper.validate_legal(self.lora_config)
|
||||
|
||||
model = self._adapter_manager.model
|
||||
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
|
||||
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
|
||||
|
||||
lora = self._lora_model_cls.from_local_checkpoint(
|
||||
lora_path,
|
||||
expected_lora_modules,
|
||||
peft_helper=peft_helper,
|
||||
lora_model_id=lora_request.lora_int_id,
|
||||
device="cpu",
|
||||
dtype=self.lora_config.lora_dtype,
|
||||
model_vocab_size=self.vocab_size,
|
||||
tensorizer_config_dict=lora_request.tensorizer_config_dict,
|
||||
weights_mapper=hf_to_vllm_mapper,
|
||||
skip_prefixes=lora_skip_prefixes,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
|
||||
|
||||
return lora
|
||||
|
||||
WorkerLoRAManager._load_adapter = _patched_load_adapter
|
||||
|
||||
|
||||
# Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
def monkey_patch_tokenize_params_validation():
|
||||
"""
|
||||
@@ -649,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.
|
||||
|
||||
@@ -954,49 +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 erroneously multiplies page_size_bytes by
|
||||
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
|
||||
For UniformTypeKVCacheSpecs the page_size is already the total per-block
|
||||
size across all layers, so the extra multiplier makes num_blocks far too
|
||||
small. When the OffloadingManager later allocates block IDs past the
|
||||
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
|
||||
invalid pinned address.
|
||||
|
||||
Fix: remove the num_tensors multiplier.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/38395
|
||||
Related: https://github.com/vllm-project/vllm/issues/39500
|
||||
"""
|
||||
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)
|
||||
|
||||
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
|
||||
assert len(page_sizes) == 1
|
||||
page_size_bytes = page_sizes.pop()
|
||||
|
||||
# page_size_bytes already covers all layers in the group.
|
||||
# Only multiply by world_size (each TP rank stores its own copy).
|
||||
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
|
||||
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.
|
||||
|
||||
@@ -1023,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).")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
@@ -151,7 +152,7 @@ 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")
|
||||
@@ -182,59 +183,6 @@ def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume(request: Request):
|
||||
await engine_client(request).resume_generation()
|
||||
return {"status": "resumed"}
|
||||
|
||||
|
||||
@router.post("/update_weights")
|
||||
async def update_weights(request: Request):
|
||||
data = await request.json()
|
||||
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
|
||||
if request.app.state.reset_prefix_cache_after_update:
|
||||
await engine_client(request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Load a LoRA adapter, optionally resetting the prefix cache.
|
||||
|
||||
Wrapper around vLLM's /v1/load_lora_adapter that also resets the prefix cache
|
||||
to invalidate KV states computed with old weights (unless disabled via config).
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
if raw_request.app.state.reset_prefix_cache_after_update:
|
||||
await engine_client(raw_request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/init_broadcaster")
|
||||
async def init_broadcaster(request: Request):
|
||||
data = await request.json()
|
||||
host = data.get("host")
|
||||
port = data.get("port")
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
@@ -261,6 +209,64 @@ async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_reques
|
||||
return StreamingResponse(content=generator, media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume(request: Request):
|
||||
await engine_client(request).resume_generation()
|
||||
return {"status": "resumed"}
|
||||
|
||||
|
||||
@router.post("/update_weights")
|
||||
async def update_weights(request: Request):
|
||||
data = await request.json()
|
||||
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
handler = models(raw_request)
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/liveness")
|
||||
async def liveness(raw_request: Request):
|
||||
"""Check that the engine event loop can service a no-op worker RPC."""
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
engine_client(raw_request).collective_rpc("liveness_probe"),
|
||||
timeout=raw_request.app.state.liveness_timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/init_broadcaster")
|
||||
async def init_broadcaster(request: Request):
|
||||
data = await request.json()
|
||||
host = data.get("host")
|
||||
port = data.get("port")
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def custom_init_app_state(
|
||||
engine_client: EngineClient,
|
||||
state: State,
|
||||
@@ -269,13 +275,21 @@ async def custom_init_app_state(
|
||||
):
|
||||
"""
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state.
|
||||
2. Replace the serving_chat with our OpenAIServingChatWithTokens wrapper.
|
||||
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. 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:
|
||||
original_chat = state.openai_serving_chat
|
||||
serving_chat = object.__new__(OpenAIServingChatWithTokens)
|
||||
@@ -285,6 +299,17 @@ async def custom_init_app_state(
|
||||
else:
|
||||
state.openai_serving_chat_with_tokens = None
|
||||
|
||||
# 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
|
||||
|
||||
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
|
||||
import vllm.v1.utils
|
||||
@@ -342,7 +367,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
|
||||
|
||||
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
|
||||
args.enable_auto_tool_choice = args.tool_call_parser is not None
|
||||
args.reset_prefix_cache_after_update = config.experimental.reset_prefix_cache_after_update
|
||||
if args.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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,15 +2,20 @@ 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,
|
||||
monkey_patch_skip_lora_module_warnings,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
|
||||
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
|
||||
monkey_patch_skip_lora_module_warnings()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
@@ -19,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()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user