Compare commits
65
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eaf95997f7 | ||
|
|
09e11c7527 | ||
|
|
03f7feff14 | ||
|
|
87ab84b666 | ||
|
|
0b37bc923e | ||
|
|
6591943919 | ||
|
|
4748472b9f | ||
|
|
8106bf0a02 | ||
|
|
46653c1d70 | ||
|
|
c5fb9591b2 | ||
|
|
b22e768fc4 | ||
|
|
ef8f459ca0 | ||
|
|
c3c6b70f11 | ||
|
|
f18297fd7d | ||
|
|
6d80c412b6 | ||
|
|
a166a8b8df | ||
|
|
66ff00d117 | ||
|
|
ae610d9dd8 | ||
|
|
c935497d71 | ||
|
|
cd2f3daeb2 | ||
|
|
897b935cae | ||
|
|
81f9e9512b | ||
|
|
d4385029c8 | ||
|
|
c654dc1d4d | ||
|
|
6ba37c2c21 | ||
|
|
458b16ef47 | ||
|
|
b5f196a9c5 | ||
|
|
6dda4a1466 | ||
|
|
fa55779272 | ||
|
|
b2ba40b5eb | ||
|
|
e4330c2d2c | ||
|
|
4a6b45487f | ||
|
|
024abb2043 | ||
|
|
5b11b8de33 | ||
|
|
7c434ec267 | ||
|
|
469a4e6714 | ||
|
|
319af10769 | ||
|
|
d11fc90469 | ||
|
|
c9a4b3b199 | ||
|
|
a252057978 | ||
|
|
429c1bb5e5 | ||
|
|
efb874b734 | ||
|
|
2171368063 | ||
|
|
7b7bde1fa0 | ||
|
|
0fe673c23c | ||
|
|
84ccb9507d | ||
|
|
09e403b4a4 | ||
|
|
7da26cd651 | ||
|
|
5f2c004184 | ||
|
|
c0d896f3f8 | ||
|
|
bb522cce53 | ||
|
|
95af0118db | ||
|
|
d7b3ae203c | ||
|
|
229391fa27 | ||
|
|
1e9a3e9196 | ||
|
|
3b01ce9d48 | ||
|
|
38b524925d | ||
|
|
d62c7539e4 | ||
|
|
edf41113fe | ||
|
|
bcac552c3f | ||
|
|
f7a27f69dd | ||
|
|
31591b7fe8 | ||
|
|
0deb4abaa9 | ||
|
|
4be61bbd68 | ||
|
|
0660a9b3cb |
@@ -14,7 +14,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- 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 deps/pydantic-config
|
||||
- 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 deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
|
||||
# This is to allow running tests on forks without WANDB_API_KEY
|
||||
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
|
||||
WANDB_MODE: offline
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
@@ -111,4 +114,4 @@ jobs:
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest ${{ matrix.pytest_args }}
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
|
||||
- name: Build matrix from nightly test files
|
||||
id: build-matrix
|
||||
@@ -75,7 +75,11 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
submodules: false
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- 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 deps/pydantic-config
|
||||
- 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/
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
[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
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
@@ -3,6 +3,7 @@
|
||||
## Writing code
|
||||
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
|
||||
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
|
||||
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
|
||||
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
|
||||
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
|
||||
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
|
||||
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
|
||||
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
|
||||
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
|
||||
+3
-7
@@ -12,7 +12,7 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
|
||||
ENV CUDA_HOME=/usr/local/cuda
|
||||
ENV PATH=$PATH:/usr/local/cuda/bin
|
||||
|
||||
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
|
||||
# Install build tooling.
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV TZ=Etc/UTC
|
||||
@@ -22,12 +22,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
sudo \
|
||||
git \
|
||||
ninja-build \
|
||||
software-properties-common \
|
||||
&& add-apt-repository ppa:deadsnakes/ppa \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
# Download the latest installer
|
||||
@@ -48,6 +42,8 @@ COPY pyproject.toml /app/pyproject.toml
|
||||
COPY uv.lock /app/uv.lock
|
||||
COPY README.md /app/README.md
|
||||
COPY src/ /app/src/
|
||||
COPY packages/ /app/packages/
|
||||
COPY deps/ /app/deps/
|
||||
COPY configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
@@ -53,6 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
@@ -90,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
```
|
||||
|
||||
2. Install [uv](https://docs.astral.sh/uv/)
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:28:25+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 16.41977165630161,
|
||||
"std": 0.010586646038388221,
|
||||
"min": 16.407648988464405,
|
||||
"max": 16.42719598975201
|
||||
"mean": 22.77046832707997,
|
||||
"std": 0.03172890658906481,
|
||||
"min": 22.750797215697055,
|
||||
"max": 22.80707156937409
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 1960.9836648020673,
|
||||
"std": 1.2643440104327244,
|
||||
"min": 1959.5358764831926,
|
||||
"max": 1961.8703395331793
|
||||
"mean": 2719.4358949662887,
|
||||
"std": 3.7893259921987053,
|
||||
"min": 2717.086609671837,
|
||||
"max": 2723.8073540657224
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 65.87,
|
||||
"std": 0.13,
|
||||
"min": 65.74,
|
||||
"max": 66.0
|
||||
"mean": 48.285218452724315,
|
||||
"std": 0.06726350421944344,
|
||||
"min": 48.207625919021666,
|
||||
"max": 48.327002701349556
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 31.806640625,
|
||||
"pct": 67.03
|
||||
"gib": 24.248046875,
|
||||
"pct": 51.15428047554115
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:32:27+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 15.634260517326164,
|
||||
"std": 0.009817863071768202,
|
||||
"min": 15.622927380137481,
|
||||
"max": 15.640172924064188
|
||||
"mean": 21.824271379711288,
|
||||
"std": 0.07444985226850119,
|
||||
"min": 21.739369034306105,
|
||||
"max": 21.878404774433935
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 7468.685954343421,
|
||||
"std": 4.690118598479809,
|
||||
"min": 7463.271969943842,
|
||||
"max": 7471.510386564679
|
||||
"mean": 10425.733211800512,
|
||||
"std": 35.565645418564436,
|
||||
"min": 10385.174276894972,
|
||||
"max": 10451.593425935866
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 68.34095695288852,
|
||||
"std": 0.16054587555887065,
|
||||
"min": 68.16114284005016,
|
||||
"max": 68.46991707291454
|
||||
"mean": 50.39627862814814,
|
||||
"std": 0.1756523472528039,
|
||||
"min": 50.26670710090548,
|
||||
"max": 50.59620195720345
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 23.25390625,
|
||||
"pct": 49.05701678145735
|
||||
"gib": 17.490234375,
|
||||
"pct": 36.897831788841806
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,4 +45,9 @@ rollouts_per_example = 32
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -46,4 +46,9 @@ rollouts_per_example = 32
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
+7
-2
@@ -1,10 +1,10 @@
|
||||
max_steps = 10
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
@@ -22,3 +22,8 @@ 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]
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
preserve_all_thinking = true
|
||||
@@ -1,29 +0,0 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
num_infer_gpus = 1
|
||||
num_train_gpus = 1
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
+6
-1
@@ -2,6 +2,7 @@ max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -19,4 +20,8 @@ max_completion_tokens = 128
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
+6
-3
@@ -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"
|
||||
@@ -20,4 +19,8 @@ max_completion_tokens = 128
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
+6
-1
@@ -2,6 +2,7 @@ max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
@@ -30,4 +31,8 @@ id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
+6
-3
@@ -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"
|
||||
@@ -31,4 +30,8 @@ id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
+7
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
@@ -24,3 +27,7 @@ gpu_memory_utilization = 0.7
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
+4
@@ -20,3 +20,7 @@ id = "reverse-text"
|
||||
[ckpt]
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
+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]
|
||||
|
||||
@@ -28,4 +28,9 @@ args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", que
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -16,6 +16,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
use_renderer = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Training Mode — Debug Configs
|
||||
|
||||
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
|
||||
|
||||
| Config | Mode | Teacher | Notes |
|
||||
|---|---|---|---|
|
||||
| `rl.toml` | `rl` | none | |
|
||||
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
|
||||
|
||||
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
## Start the local teacher
|
||||
|
||||
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
--server.port 8001 \
|
||||
--gpu-memory-utilization 0.5 \
|
||||
--model.enforce-eager
|
||||
```
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
```bash
|
||||
# RL (no teacher)
|
||||
uv run rl @ configs/debug/training_modes/rl.toml
|
||||
|
||||
# OPD (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/opd.toml
|
||||
uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
|
||||
# SFT hard distill (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/sft.toml
|
||||
uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
# SFT hard distill from openai/gpt-5-mini via PI inference
|
||||
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
|
||||
uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
```
|
||||
|
||||
See [docs/training_modes.md](../../docs/training_modes.md) for what each mode does.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-opd"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,60 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-opd-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,41 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-rl"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,51 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,55 @@
|
||||
# SFT from openai/gpt-5-mini via PI inference.
|
||||
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
|
||||
#
|
||||
# Run with:
|
||||
# uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-external"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
extra_body = { reasoning_effort = "minimal" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "openai/gpt-5-mini"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher.client.headers_from_env]
|
||||
X-Prime-Team-ID = "PRIME_TEAM_ID"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,57 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -31,4 +31,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -6,7 +6,7 @@ project = "gsm8k-debug"
|
||||
name = "gsm8k"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
@@ -22,4 +22,9 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # Default inference config
|
||||
[inference] # Default inference config
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -36,4 +36,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
max_model_len = 8192
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
level = "debug"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -52,4 +52,8 @@ temperature = 0.5
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference] # Default inference config
|
||||
[inference] # Default inference config
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -11,6 +11,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
use_renderer = false
|
||||
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
@@ -12,6 +12,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
use_renderer = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
Submodule
+1
Submodule configs/private added at 74c1330008
+1
Submodule deps/pydantic-config added at b6a2411e44
+1
Submodule deps/renderers added at 8704f9d502
+1
Submodule deps/research-environments added at d141472268
+1
Submodule deps/verifiers added at 58b119fa1b
@@ -8,7 +8,7 @@ Checkpointing is non-standard due to trainer/orchestrator separation and natural
|
||||
|
||||
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
|
||||
|
||||
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
|
||||
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
|
||||
|
||||
## SFT
|
||||
|
||||
@@ -54,4 +54,4 @@ uv run rl \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--max-steps 20 \
|
||||
--ckpt.resume-step 10
|
||||
```
|
||||
```
|
||||
|
||||
+1
-1
@@ -30,4 +30,4 @@ name = "Qwen/Qwen-14B"
|
||||
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
|
||||
```
|
||||
|
||||
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
|
||||
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen3-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
|
||||
|
||||
## SFT
|
||||
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seamless post-training workflow.
|
||||
|
||||
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
|
||||
|
||||
|
||||
+3
-1
@@ -7,6 +7,7 @@
|
||||
"index",
|
||||
"entrypoints",
|
||||
"configs",
|
||||
"training_modes",
|
||||
"environments",
|
||||
"async",
|
||||
"logging",
|
||||
@@ -15,8 +16,9 @@
|
||||
"benchmarking",
|
||||
"deployment",
|
||||
"kubernetes",
|
||||
"testing-moe-at-small-scale",
|
||||
"troubleshooting"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
# On-Policy Distillation
|
||||
|
||||
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
|
||||
|
||||
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
```
|
||||
|
||||
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[teacher_inference.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
```
|
||||
|
||||
## Using an External Teacher Server
|
||||
|
||||
If the teacher is already running elsewhere:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
|
||||
[orchestrator.teacher_model.client]
|
||||
base_url = ["http://teacher-server:8000/v1"]
|
||||
|
||||
[orchestrator.teacher_model.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
```
|
||||
|
||||
## Pure Distillation (No Verification)
|
||||
|
||||
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 1.0
|
||||
adv_tau = 0.0 # Disable reward-based learning
|
||||
|
||||
[orchestrator.verification]
|
||||
enabled = false # Skip expensive verification
|
||||
```
|
||||
|
||||
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
|
||||
|
||||
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
|
||||
|
||||
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[orchestrator]
|
||||
use_token_client = false
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://your-openai-compatible-endpoint/v1"]
|
||||
skip_model_check = true
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "teacher-model-name"
|
||||
```
|
||||
|
||||
In this mode:
|
||||
- Rollouts are generated from `orchestrator.teacher_rollout_model`
|
||||
- The orchestrator uses text-level reconstruction with the student tokenizer
|
||||
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
|
||||
- Omit `[inference]` (no local inference server required)
|
||||
|
||||
### Image Input (VLM) Support
|
||||
|
||||
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
|
||||
|
||||
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
|
||||
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
|
||||
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
|
||||
|
||||
Notes:
|
||||
- This path currently expects `data:image/...` payloads in message content
|
||||
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
|
||||
|
||||
Reference configs:
|
||||
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
|
||||
- `examples/alphabet_sort/sft_distill_hard.toml`
|
||||
|
||||
## Parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
|
||||
## Monitoring
|
||||
|
||||
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Training Modes
|
||||
|
||||
PRIME-RL supports three training modes through our RL trainer, selected via `training_mode`:
|
||||
|
||||
- **`rl`** — reinforcement learning: student generates rollouts, no teacher
|
||||
- **`opd`** — [on-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): students generates rollouts, train to minimize the KL divergence between the student and teacher's logprobs for each token in the rollout
|
||||
- **`sft`** — supervised fine-tuning on teacher-generated rollouts
|
||||
|
||||
> Note: PRIME-RL also has a dedicated `sft` entrypoint for more traditional supervised fine-tuning from a HF dataset. When using the `sft` training mode on the orchestrator, teacher rollouts are generated on-the-fly and used for training.
|
||||
|
||||
The mode determines who generates rollouts, what role the teacher plays, and what must be configured.
|
||||
|
||||
| Mode | Student | Teacher |
|
||||
|---|---|---|
|
||||
| `rl` | required | forbidden |
|
||||
| `opd` | required | required (local vLLM) |
|
||||
| `sft` | required | required (any OAI-compatible endpoint) |
|
||||
|
||||
**SFT vs OPD teachers** differ in what the orchestrator asks of them. SFT only calls `/v1/chat/completions` to generate rollouts — any OpenAI-compatible endpoint works (PI inference, OpenAI, Anthropic, a local vLLM). OPD additionally needs token-level logprobs scored over the student's tokens, which today only vLLM's `/inference/v1/generate` with `prompt_logprobs` exposes — so the OPD teacher must be a vLLM server.
|
||||
|
||||
### Reference configs
|
||||
|
||||
Debug-scale configs for all three modes (and LoRA variants) live in [`configs/debug/training_modes/`](../configs/debug/training_modes/):
|
||||
|
||||
- `rl.toml` / `opd.toml` / `opd_lora.toml`
|
||||
- `sft.toml` / `sft_lora.toml` (local vLLM teacher)
|
||||
- `sft_external.toml` (PI inference teacher)
|
||||
|
||||
See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for run commands.
|
||||
|
||||
## Parameter reference
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
@@ -39,7 +39,7 @@ Interleaving enforces a strict invariant:
|
||||
|
||||
> The prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them
|
||||
|
||||
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation to this invariant will result in downstream problems when computing the importance sampling ratio during training.
|
||||
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation of this invariant will result in downstream problems when computing the importance sampling ratio during training.
|
||||
|
||||
For example, assume that at turn 2 the prompt is U1,A1',U2 where A1' varies from A1. In this scenario it is not clear whether to add A1 or A1' to the interleaved rollout:
|
||||
- If we add A1', the logprobs from turn 1 might be off because the inference LLM produced A1 but the trainer LLM is computing logprobs for A1'
|
||||
|
||||
@@ -12,7 +12,7 @@ ulimit -n 32000
|
||||
|
||||
Assuming this is happening on the RL or SFT trainer, you can try the following:
|
||||
- Use full activation checkpointing (`--model.ac`)
|
||||
- Reduce the the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
|
||||
- Reduce the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
|
||||
- (*Experimental*) Use context parallelism with `--model.cp`
|
||||
|
||||
> I cannot pass my TOML config file
|
||||
|
||||
@@ -94,4 +94,8 @@ args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200
|
||||
id = "aime2025"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
max_steps = 24
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
gpus_per_node = 2
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 0
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort-sft-distill"
|
||||
name = "qwen3-4b-hard-distill"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 4
|
||||
use_token_client = false
|
||||
use_sft_loss = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
temperature = 0.7
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "qwen/qwen3-235b-a22b-instruct-2507"
|
||||
|
||||
[[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 }
|
||||
@@ -34,4 +34,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -68,4 +68,8 @@ hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
|
||||
[orchestrator.renderer]
|
||||
name = "minimax-m2"
|
||||
|
||||
@@ -23,4 +23,8 @@ lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -29,3 +29,10 @@ max_completion_tokens = 1024
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -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,31 @@
|
||||
[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",
|
||||
# OrchestratorConfig validates renderer.name='auto' against
|
||||
# renderers.base.MODEL_RENDERER_MAP. Renderers itself is light; its only
|
||||
# weighty transitive (transformers) is lazy-imported via the validator,
|
||||
# so plain `from prime_rl.configs.orchestrator import OrchestratorConfig`
|
||||
# still doesn't pull it into sys.modules.
|
||||
"renderers>=0.1.8.dev4",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
+73
-24
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
@@ -16,6 +16,16 @@ class ServerConfig(BaseConfig):
|
||||
|
||||
host: Annotated[str | None, Field(description="The host to bind to.")] = None
|
||||
port: Annotated[int, Field(description="The port to bind to.")] = 8000
|
||||
liveness_timeout_seconds: Annotated[
|
||||
float,
|
||||
Field(
|
||||
gt=0,
|
||||
description=(
|
||||
"Timeout in seconds for the /liveness endpoint's internal vLLM worker RPC. "
|
||||
"If Kubernetes liveness probes are enabled, keep the probe timeoutSeconds at least this high."
|
||||
),
|
||||
),
|
||||
] = 30.0
|
||||
|
||||
|
||||
class ParallelConfig(BaseConfig):
|
||||
@@ -110,6 +120,16 @@ class WeightBroadcastConfig(BaseConfig):
|
||||
)
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for vLLM inference workers."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
cpu_bytes: Annotated[int, Field(gt=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
|
||||
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
|
||||
@@ -152,20 +172,6 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
] = "consistent_hash"
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for disaggregated serving.
|
||||
|
||||
When configured, both prefill and decode nodes use
|
||||
MultiConnector (NixlConnector + OffloadingConnector).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
cpu_bytes: Annotated[int, Field(ge=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
|
||||
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a disaggregated prefill/decode inference deployment.
|
||||
|
||||
@@ -214,11 +220,6 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
Field(description="Extra environment variables exported only on decode nodes."),
|
||||
] = {}
|
||||
|
||||
kv_cache_offload: Annotated[
|
||||
KVCacheOffloadConfig | None,
|
||||
Field(description="CPU KV cache offload config for prefill nodes. None = disabled (NixlConnector only)."),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
@@ -383,6 +384,17 @@ class InferenceConfig(BaseConfig):
|
||||
WeightBroadcastConfig()
|
||||
)
|
||||
|
||||
kv_cache_offload: Annotated[
|
||||
KVCacheOffloadConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"CPU KV cache offload config for inference workers. Standard inference uses vLLM's "
|
||||
"OffloadingConnector. Disaggregated P/D deployments combine it with NIXL through "
|
||||
"MultiConnector in the SLURM launcher."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
enable_return_routed_experts: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -390,6 +402,13 @@ class InferenceConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
enable_fp32_lm_head: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Run the lm_head projection in fp32 via a native bf16xbf16 -> fp32 GEMM (`torch.mm` with `out_dtype=torch.float32`). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's `--enable-fp32-lm-head`. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting `additional_config[\"fp32_lm_head\"] = True` on the vLLM config.",
|
||||
),
|
||||
] = False
|
||||
|
||||
vllm_extra: Annotated[
|
||||
dict[str, Any],
|
||||
Field(
|
||||
@@ -428,6 +447,16 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
if self.enable_prefix_caching is False:
|
||||
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
|
||||
if "enable_prefix_caching" not in self.model_fields_set:
|
||||
self.enable_prefix_caching = True
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_disaggregated(self):
|
||||
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
|
||||
@@ -450,10 +479,9 @@ class InferenceConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -500,6 +528,7 @@ class InferenceConfig(BaseConfig):
|
||||
to_vllm = {
|
||||
"server.host": "host",
|
||||
"server.port": "port",
|
||||
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
|
||||
"model.name": "model",
|
||||
"model.dtype": "dtype",
|
||||
"model.max_model_len": "max_model_len",
|
||||
@@ -536,6 +565,26 @@ class InferenceConfig(BaseConfig):
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
|
||||
if self.kv_cache_offload is not None:
|
||||
rsetattr(
|
||||
namespace,
|
||||
"kv_transfer_config",
|
||||
{
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
"kv_connector_extra_config": {
|
||||
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
# Pass prime-rl-specific flags through vLLM's additional_config dict;
|
||||
# workers read these via get_current_vllm_config().additional_config.
|
||||
if self.enable_fp32_lm_head:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
delattr(namespace, "chat_template")
|
||||
+241
-136
@@ -1,4 +1,5 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -17,7 +18,6 @@ from prime_rl.configs.shared import (
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class OptimizerConfig(BaseConfig):
|
||||
@@ -149,9 +149,11 @@ class TrainSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -248,9 +250,11 @@ class EvalSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -685,6 +689,52 @@ class BufferConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseModel):
|
||||
"""Length penalty by weighted token cost.
|
||||
|
||||
Effective cost = completion_weight * model_completion_tokens
|
||||
+ tool_response_weight * tool_response_tokens.
|
||||
|
||||
Tool-response tokens are read from the rollout's harness metric
|
||||
`*_total_tool_response_tokens` (e.g. `rlm_total_tool_response_tokens`); 0 if absent —
|
||||
so for envs without tool accounting, only the completion term contributes regardless of weight.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["tokens"] = "tokens"
|
||||
completion_weight: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
allow_inf_nan=False,
|
||||
description="Weight on model completion tokens. Finite and non-negative.",
|
||||
),
|
||||
] = 1.0
|
||||
tool_response_weight: Annotated[
|
||||
float,
|
||||
Field(
|
||||
ge=0,
|
||||
allow_inf_nan=False,
|
||||
description="Weight on tool-response tokens. Finite and non-negative.",
|
||||
),
|
||||
] = 1.0
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseModel):
|
||||
"""Length penalty by trajectory turn count."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseModel):
|
||||
"""Config for the default advantage."""
|
||||
|
||||
@@ -692,11 +742,11 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_penalty: Annotated[
|
||||
Literal["tokens", "turns"] | None,
|
||||
LengthPenaltyConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
|
||||
"count, `turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"Correctness-gated length penalty. `tokens` shapes by weighted token cost, "
|
||||
"`turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct "
|
||||
"rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost "
|
||||
"rollouts get advantage in [0, 1], others get 0."
|
||||
@@ -830,46 +880,60 @@ class OrchestratorExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the orchestrator."""
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
|
||||
|
||||
client: Annotated[
|
||||
ClientConfig,
|
||||
Field(description="The OAI client configuration for the teacher model."),
|
||||
] = ClientConfig()
|
||||
class RolloutModelConfig(BaseConfig):
|
||||
"""Model + client pair for a rollout participant (student or teacher)."""
|
||||
|
||||
model: Annotated[
|
||||
ModelConfig,
|
||||
Field(description="The model configuration for the teacher model."),
|
||||
Field(description="The model configuration."),
|
||||
] = ModelConfig()
|
||||
|
||||
|
||||
class TeacherRolloutModelConfig(BaseConfig):
|
||||
"""Configures an external teacher model used to generate rollout text."""
|
||||
|
||||
client: Annotated[
|
||||
ClientConfig,
|
||||
Field(description="The OAI client configuration for rollout generation."),
|
||||
Field(description="The client configuration."),
|
||||
] = ClientConfig()
|
||||
|
||||
model: Annotated[
|
||||
ModelConfig,
|
||||
Field(description="The model configuration for rollout generation."),
|
||||
] = ModelConfig()
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
"""Configures the orchestrator for RL training."""
|
||||
|
||||
# Training mode: drives validation and runtime wiring
|
||||
training_mode: Annotated[
|
||||
Literal["rl", "opd", "sft"],
|
||||
Field(
|
||||
description=(
|
||||
"Training mode. "
|
||||
"rl: student generates rollouts, no teacher. "
|
||||
"opd: student generates rollouts, teacher computes logprobs (teacher_tau > 0). "
|
||||
"sft: teacher generates rollouts, student inference pool used for evals and weight sync."
|
||||
),
|
||||
),
|
||||
] = "rl"
|
||||
|
||||
# Student model + client (the model being trained)
|
||||
student: Annotated[
|
||||
RolloutModelConfig,
|
||||
Field(
|
||||
validation_alias=AliasChoices("student", "model"),
|
||||
description="Student model configuration (the model being trained).",
|
||||
),
|
||||
] = RolloutModelConfig()
|
||||
|
||||
# Teacher model + client (optional; role determined by training_mode)
|
||||
teacher: Annotated[
|
||||
RolloutModelConfig | None,
|
||||
Field(
|
||||
validation_alias=AliasChoices("teacher", "teacher_model"),
|
||||
description=(
|
||||
"Teacher model configuration. Role depends on training_mode: "
|
||||
"opd — teacher computes logprobs; sft — teacher generates rollouts."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
# Training environments and sampling
|
||||
train: TrainConfig = TrainConfig()
|
||||
|
||||
# The OAI client configuration
|
||||
client: ClientConfig = ClientConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
@@ -879,38 +943,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The optimizer configuration (per-run LR for multi-run training)
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
|
||||
# The teacher model configuration (optional)
|
||||
teacher_model: Annotated[
|
||||
TeacherModelConfig | None,
|
||||
Field(
|
||||
description="The teacher model configuration for computing teacher logprobs (e.g. for distillation). "
|
||||
"If provided, teacher logprobs will be computed using the specified model. "
|
||||
"If None, no teacher model will be used."
|
||||
),
|
||||
] = None
|
||||
|
||||
# External teacher rollout model configuration (optional)
|
||||
teacher_rollout_model: Annotated[
|
||||
TeacherRolloutModelConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"Optional external teacher model used for rollout generation. "
|
||||
"When set, rollouts are generated from this endpoint/model instead of the student inference server."
|
||||
),
|
||||
),
|
||||
] = 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
|
||||
|
||||
@@ -976,10 +1008,11 @@ class OrchestratorConfig(BaseConfig):
|
||||
oversampling_factor: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=1,
|
||||
gt=0,
|
||||
description=(
|
||||
"Rollout-mode batching only. Multiplier used to derive max_inflight_rollouts from batch_size "
|
||||
"when max_inflight_rollouts is unset."
|
||||
"when max_inflight_rollouts is unset. Values below 1.0 intentionally cap in-flight rollout "
|
||||
"capacity below batch_size."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
@@ -1032,6 +1065,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.",
|
||||
),
|
||||
] = 3
|
||||
|
||||
max_async_level: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -1060,26 +1101,16 @@ class OrchestratorConfig(BaseConfig):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
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). 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."
|
||||
description="Whether to use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, "
|
||||
"served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block "
|
||||
"(name / tool_parser / reasoning_parser / pool_size) applies. This is the default for text-only "
|
||||
"rollouts. Set to False to fall back to MITO (``openai_chat_completions``); VLMs and external "
|
||||
"teacher rollouts require MITO."
|
||||
),
|
||||
] = False
|
||||
] = True
|
||||
|
||||
env_install_prerelease: Annotated[
|
||||
bool,
|
||||
@@ -1093,6 +1124,55 @@ class OrchestratorConfig(BaseConfig):
|
||||
Field(description="Experimental features for the orchestrator."),
|
||||
] = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def fold_student_shortcuts(cls, data: Any) -> Any:
|
||||
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
|
||||
as shorthand for the student sub-config. Useful for ergonomic rl configs
|
||||
where ``[orchestrator.student.*]`` is overkill, and required for
|
||||
pre-refactor configs that used the flat layout to keep parsing:
|
||||
|
||||
- [orchestrator.client.*] -> [orchestrator.student.client.*]
|
||||
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
|
||||
(where <k> is any ModelConfig field)
|
||||
|
||||
Teacher must always be configured under [orchestrator.teacher.*]
|
||||
(no equivalent shortcut), because rl mode forbids a teacher and we
|
||||
don't want the same shortcut to silently route to two different roles.
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
|
||||
# 1. Re-nest top-level [orchestrator.client] under student.client.
|
||||
if "client" in data:
|
||||
student = data.setdefault("student", {})
|
||||
if isinstance(student, dict) and "client" not in student:
|
||||
student["client"] = data.pop("client")
|
||||
|
||||
# 2. Consolidate the legacy `model` alias into `student` so the
|
||||
# flat-layout fix-up below sees a single target.
|
||||
legacy_model = data.pop("model", None)
|
||||
if legacy_model is not None:
|
||||
existing = data.get("student")
|
||||
if existing is None:
|
||||
data["student"] = legacy_model
|
||||
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
|
||||
for k, v in legacy_model.items():
|
||||
existing.setdefault(k, v)
|
||||
else:
|
||||
# Mismatched types - put it back and let pydantic surface the error.
|
||||
data["model"] = legacy_model
|
||||
|
||||
# 3. Re-nest flat ModelConfig keys under student.model.
|
||||
model_only_keys = set(ModelConfig.model_fields)
|
||||
student = data.get("student")
|
||||
if isinstance(student, dict):
|
||||
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
|
||||
if flat:
|
||||
student.setdefault("model", {}).update(flat)
|
||||
|
||||
return data
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
@@ -1103,15 +1183,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
|
||||
@@ -1119,9 +1203,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.model.name
|
||||
self.tokenizer.name = self.student.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -1132,61 +1216,36 @@ class OrchestratorConfig(BaseConfig):
|
||||
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)."
|
||||
)
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
|
||||
renderer client doesn't apply. Force use_renderer=False so the user
|
||||
doesn't have to remember to set it. Declared before the renderer
|
||||
validators below so they see the corrected value."""
|
||||
if self.training_mode == "sft":
|
||||
self.use_renderer = False
|
||||
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)."
|
||||
)
|
||||
def validate_training_mode(self):
|
||||
"""Enforce training mode invariants that involve only orchestrator fields."""
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
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
|
||||
chat templating, so they must use MITO — fail
|
||||
loudly when both are set."""
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
if self.use_renderer and self.student.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."
|
||||
"orchestrator.use_renderer is not supported for VLMs. Use MITO "
|
||||
"(``use_renderer=false``) so image preprocessing and chat templating stay on the "
|
||||
"inference server."
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -1207,6 +1266,12 @@ class OrchestratorConfig(BaseConfig):
|
||||
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 self.renderer.preserve_all_thinking:
|
||||
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
|
||||
if self.renderer.preserve_thinking_between_tool_calls:
|
||||
renderer_args_set.append(
|
||||
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
|
||||
)
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
@@ -1215,6 +1280,42 @@ class OrchestratorConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_auto_resolves(self):
|
||||
"""Reject the silent DefaultRenderer fallback at config time.
|
||||
|
||||
When ``use_renderer=True`` with ``renderer.name='auto'`` and the
|
||||
model isn't in ``MODEL_RENDERER_MAP``, ``create_renderer`` would
|
||||
fall back to ``DefaultRenderer``. That fallback doesn't fix the
|
||||
position-dependent chat-template bug the renderer client exists to
|
||||
solve, and rejects envs that pass tools (the rollout dies with
|
||||
"RendererPool does not support tools") unless
|
||||
``renderer.tool_parser`` is configured. Surface at config time so
|
||||
``--dry-run`` reports the error.
|
||||
"""
|
||||
if not self.use_renderer or self.renderer.name != "auto":
|
||||
return self
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
model_id = self.tokenizer.name or self.student.model.name
|
||||
if model_id in MODEL_RENDERER_MAP:
|
||||
return self
|
||||
raise ValueError(
|
||||
f"orchestrator.use_renderer=True with renderer.name='auto' but "
|
||||
f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it "
|
||||
f"would silently fall back to DefaultRenderer. Pick one: "
|
||||
f"(a) [orchestrator.renderer] name='default' — for fine-tunes / "
|
||||
f"vendored mirrors with custom chat templates (DefaultRenderer "
|
||||
f"calls apply_chat_template); pair with tool_parser=<name> if "
|
||||
f"the env uses tools. "
|
||||
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
|
||||
f"if {model_id!r} is template-identical to a mapped family "
|
||||
f"(and ideally also add it upstream to "
|
||||
f"renderers.base.MODEL_RENDERER_MAP). "
|
||||
f"(c) orchestrator.use_renderer=false — opt out of the renderer "
|
||||
f"client entirely."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def nccl_max_async_level(self):
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
@@ -1242,13 +1343,17 @@ class OrchestratorConfig(BaseConfig):
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.rollouts_per_example != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
resolved_max_inflight_rollouts = max(
|
||||
self.rollouts_per_example,
|
||||
int(self.batch_size * oversampling_factor),
|
||||
)
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_rollouts = int(self.batch_size * self.oversampling_factor)
|
||||
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
|
||||
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
|
||||
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_rollouts is None:
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
self.max_inflight_rollouts = int(self.batch_size * oversampling_factor)
|
||||
self.max_inflight_rollouts = resolved_max_inflight_rollouts
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
@@ -1279,7 +1384,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_config(self):
|
||||
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
|
||||
is_vllm = self.teacher_rollout_model is None
|
||||
is_vllm = self.training_mode != "sft"
|
||||
for env in self.train.env:
|
||||
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
|
||||
if is_vllm:
|
||||
+106
-84
@@ -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,
|
||||
@@ -367,6 +367,27 @@ class RLConfig(BaseConfig):
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
|
||||
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
|
||||
`[orchestrator.teacher]` block, inject an empty one so
|
||||
`OrchestratorConfig.validate_training_mode` (which fires during nested
|
||||
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
|
||||
`auto_setup_teacher_inference` (after) then fills in client.base_url and
|
||||
model.name from the auto-launched teacher_inference server."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if not isinstance(deployment, dict):
|
||||
return data
|
||||
if not deployment.get("num_teacher_gpus"):
|
||||
return data
|
||||
orch = data.setdefault("orchestrator", {})
|
||||
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
|
||||
orch["teacher"] = {}
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
@@ -422,32 +443,6 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_teacher_model(self):
|
||||
if (
|
||||
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
|
||||
) and not self.orchestrator.teacher_model:
|
||||
raise ValueError(
|
||||
"teacher_model must be configured when teacher_tau > 0. "
|
||||
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_external_rollout_inference(self):
|
||||
"""Forbid configuring a local inference server when rollouts come from an external teacher.
|
||||
|
||||
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."
|
||||
)
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -564,13 +559,13 @@ class RLConfig(BaseConfig):
|
||||
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
|
||||
if not inference_model_explicitly_set:
|
||||
self.inference.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.inference.model.name
|
||||
self.orchestrator.student.model.name = self.inference.model.name
|
||||
else:
|
||||
self.orchestrator.model.name = self.model.name
|
||||
self.orchestrator.student.model.name = self.model.name
|
||||
|
||||
if self.model.vlm is not None:
|
||||
self.trainer.model.vlm = self.model.vlm
|
||||
self.orchestrator.model.vlm = self.model.vlm
|
||||
self.orchestrator.student.model.vlm = self.model.vlm
|
||||
if self.inference is not None:
|
||||
self.inference.model.vlm = self.model.vlm
|
||||
|
||||
@@ -586,17 +581,21 @@ class RLConfig(BaseConfig):
|
||||
# in name/trust_remote_code from model config where still unset.
|
||||
self.trainer.tokenizer = self.tokenizer.model_copy()
|
||||
self.orchestrator.tokenizer = self.tokenizer.model_copy()
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
if component.tokenizer.name is None:
|
||||
component.tokenizer.name = component.model.name
|
||||
if component.tokenizer.trust_remote_code is None:
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
if self.trainer.tokenizer.name is None:
|
||||
self.trainer.tokenizer.name = self.trainer.model.name
|
||||
if self.trainer.tokenizer.trust_remote_code is None:
|
||||
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
|
||||
if self.orchestrator.tokenizer.name is None:
|
||||
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
|
||||
if self.orchestrator.tokenizer.trust_remote_code is None:
|
||||
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
|
||||
else:
|
||||
# No shared tokenizer: re-derive from (now-correct) model names,
|
||||
# since auto_setup_tokenizer on sub-configs already ran with defaults.
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
component.tokenizer.name = component.model.name
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
self.trainer.tokenizer.name = self.trainer.model.name
|
||||
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
|
||||
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
|
||||
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
|
||||
|
||||
# Propagate chat_template to inference (vLLM --chat-template)
|
||||
if self.inference is not None:
|
||||
@@ -681,6 +680,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:
|
||||
@@ -705,49 +719,50 @@ class RLConfig(BaseConfig):
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.model.lora is None:
|
||||
if self.orchestrator.student.model.lora is None:
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
self.orchestrator.student.model.lora = LoRAConfig()
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
self.orchestrator.student.model.lora.rank is not None
|
||||
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
self.orchestrator.student.model.lora.alpha is not None
|
||||
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
if self.orchestrator.student.model.lora.rank is None:
|
||||
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
if self.orchestrator.student.model.lora.alpha is None:
|
||||
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
if self.orchestrator.student.model.lora.name is None:
|
||||
self.orchestrator.student.model.lora.name = (
|
||||
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
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
|
||||
@@ -755,7 +770,7 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""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")
|
||||
self.orchestrator.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -763,13 +778,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
|
||||
|
||||
@@ -899,17 +916,23 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_rank_count(self):
|
||||
"""Auto-set orchestrator client dp_rank_count from inference DP size.
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure orchestrator student client from the inference server config.
|
||||
|
||||
Uses data_parallel_size_local (per-node DP) when set, since each base URL
|
||||
points to a single node whose API server only knows about its local ranks.
|
||||
Falls back to the global parallel.dp for single-node setups.
|
||||
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
|
||||
also sets base_url - rl/opd rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
|
||||
student vLLM at inference.server.port = 8000.
|
||||
"""
|
||||
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.dp_rank_count = (
|
||||
self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
)
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.student.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -922,7 +945,7 @@ class RLConfig(BaseConfig):
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.configs.orchestrator import TeacherModelConfig
|
||||
from prime_rl.configs.orchestrator import RolloutModelConfig
|
||||
|
||||
if self.teacher_inference is None:
|
||||
if self.inference is None:
|
||||
@@ -944,12 +967,12 @@ class RLConfig(BaseConfig):
|
||||
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
|
||||
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
|
||||
|
||||
if self.orchestrator.teacher_model is None:
|
||||
self.orchestrator.teacher_model = TeacherModelConfig()
|
||||
if self.orchestrator.teacher is None:
|
||||
self.orchestrator.teacher = RolloutModelConfig()
|
||||
host = self.teacher_inference.server.host or "localhost"
|
||||
port = self.teacher_inference.server.port
|
||||
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
|
||||
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
|
||||
|
||||
return self
|
||||
|
||||
@@ -957,13 +980,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
|
||||
+78
-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,61 @@ 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 self.renderer.preserve_all_thinking:
|
||||
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
|
||||
if self.renderer.preserve_thinking_between_tool_calls:
|
||||
renderer_args_set.append(
|
||||
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!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 +496,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
|
||||
+43
-1
@@ -131,11 +131,15 @@ class BaseModelConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def is_vlm(self) -> bool:
|
||||
return self.vlm is not None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
"""Configures the client-side renderer (chat-template + response parsing).
|
||||
|
||||
Only consumed when ``orchestrator.use_renderer = true``. The renderer
|
||||
Consumed when ``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``.
|
||||
@@ -186,6 +190,37 @@ class RendererConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
preserve_all_thinking: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Override flag forwarded to the renderer at construction. When "
|
||||
"True, every past-assistant turn's ``reasoning_content`` is "
|
||||
"re-emitted between ``<think>``/``</think>`` (or the model's "
|
||||
"equivalent), even if the underlying chat template would drop "
|
||||
"it. Off by default — preserves byte-identical output to the "
|
||||
"stock template. Strict superset of "
|
||||
"``preserve_thinking_between_tool_calls``."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
preserve_thinking_between_tool_calls: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Override flag forwarded to the renderer at construction. When "
|
||||
"True, preserves past-assistant ``reasoning_content`` only "
|
||||
"inside the *current* tool cycle — the contiguous "
|
||||
"assistant→tool→…→assistant block after the most recent user "
|
||||
"message, when that block contains at least one tool response. "
|
||||
"A new user turn closes the block; older blocks fall back to "
|
||||
"the template default (typically dropped). Use "
|
||||
"``preserve_all_thinking`` to keep older blocks too."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
@@ -268,6 +303,13 @@ class ClientConfig(BaseConfig):
|
||||
),
|
||||
] = {}
|
||||
|
||||
headers_from_env: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
description='Maps HTTP header names to environment variable names. At runtime each entry is resolved via os.getenv and merged into the request headers. e.g. {"X-Prime-Team-ID": "PRIME_TEAM_ID"}.',
|
||||
),
|
||||
] = {}
|
||||
|
||||
extra_headers_from_state: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
+40
-12
@@ -299,6 +299,21 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
cp_style: Annotated[
|
||||
Literal["ring", "ulysses"],
|
||||
Field(
|
||||
description=(
|
||||
"Context parallelism communication style. "
|
||||
"'ring' uses ring-attention all-gather/reduce-scatter (current default, "
|
||||
"requires custom kernels per attention type). "
|
||||
"'ulysses' uses all-to-all to redistribute Q/K/V from sequence-sharded "
|
||||
"to head-sharded, runs vanilla attention locally on the full sequence, "
|
||||
"then all-to-all back. Works out-of-the-box with any attention kernel "
|
||||
"(softmax FA, linear attention, mamba, etc.)."
|
||||
),
|
||||
),
|
||||
] = "ring"
|
||||
|
||||
impl: Annotated[
|
||||
Literal["hf", "custom", "auto"],
|
||||
Field(
|
||||
@@ -330,6 +345,14 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
fp8: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use FP8 training via DeepGEMM. Replaces nn.Linear layers with FP8 blockwise linear "
|
||||
"and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and model.impl='custom'.",
|
||||
),
|
||||
] = False
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -386,9 +409,13 @@ class ModelConfig(BaseModelConfig):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
|
||||
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
|
||||
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
|
||||
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
|
||||
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
|
||||
# `_flash_attention_forward` which only wraps FA2.
|
||||
raise ValueError(
|
||||
f"CP with {self.attn} requires model.impl='custom' "
|
||||
"(the ring-attention kernel is only implemented for the custom model path)"
|
||||
"(FA3/FA4 paths are only implemented for the custom model attention class)"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -417,6 +444,12 @@ class ModelConfig(BaseModelConfig):
|
||||
raise ValueError("Flash attention 4 is only supported with the custom implementation")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fp8_only_with_custom_impl(self):
|
||||
if self.fp8 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
@@ -649,25 +682,19 @@ class CheckpointConfig(BaseConfig):
|
||||
|
||||
|
||||
class DefaultLossConfig(BaseModel):
|
||||
"""Config for the default loss."""
|
||||
"""Knobs for the default DPPO+KL loss. Only consumed by rl-mode batches
|
||||
(``default_loss_fn``); opd and sft have their own self-contained loss fns."""
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for masking tokens.")] = 0.2
|
||||
dppo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for masking tokens.")] = 0.2
|
||||
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
|
||||
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
|
||||
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
|
||||
|
||||
|
||||
class SFTLossConfig(BaseModel):
|
||||
"""Config for SFT-style masked negative log-likelihood loss."""
|
||||
|
||||
type: Literal["sft"] = "sft"
|
||||
|
||||
|
||||
class CustomLossConfig(BaseModel):
|
||||
"""Config for a custom external loss function."""
|
||||
"""Override for the rl-mode loss fn. opd and sft are unaffected."""
|
||||
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -675,7 +702,7 @@ class CustomLossConfig(BaseModel):
|
||||
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | SFTLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -750,7 +777,8 @@ class TrainerConfig(BaseConfig):
|
||||
# The data configuration
|
||||
data: DataLoaderConfig = DataLoaderConfig()
|
||||
|
||||
# The loss configuration
|
||||
# Loss config for the rl-mode batches only. opd and sft batches dispatch to
|
||||
# opd_loss_fn / sft_loss_fn unconditionally - they don't read trainer.loss.
|
||||
loss: LossConfig = DefaultLossConfig()
|
||||
|
||||
# The optimizer configuration
|
||||
@@ -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
|
||||
+4
-4
@@ -36,18 +36,18 @@ def validate_shared_model_name(
|
||||
) -> None:
|
||||
# Orchestrator must match inference (it queries the inference server)
|
||||
if inference is not None:
|
||||
if inference.model.name != orchestrator.model.name:
|
||||
if inference.model.name != orchestrator.student.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
|
||||
"The orchestrator queries the inference server and must use the same model name."
|
||||
)
|
||||
return
|
||||
|
||||
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
|
||||
return
|
||||
if trainer.model.name != orchestrator.model.name:
|
||||
if trainer.model.name != orchestrator.student.model.name:
|
||||
raise ValueError(
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
|
||||
)
|
||||
|
||||
|
||||
+121
-62
@@ -5,24 +5,23 @@ description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
"liger-kernel>=0.5.10",
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"pydantic>=1.10.13",
|
||||
"pydantic-config",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.19.0",
|
||||
"vllm>=0.21.0",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.73",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -32,6 +31,7 @@ dependencies = [
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
@@ -51,7 +51,7 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
|
||||
]
|
||||
flash-attn-3 = ["flash_attn_3"]
|
||||
|
||||
@@ -59,20 +59,33 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"reverse-text",
|
||||
"alphabet-sort",
|
||||
"wiki-search",
|
||||
"math-python",
|
||||
"math-env",
|
||||
"code-env",
|
||||
"science-env",
|
||||
"logic-env",
|
||||
"color-codeword",
|
||||
"math500",
|
||||
"aime2024",
|
||||
"aime2025",
|
||||
"mini_swe_agent_plus",
|
||||
"deepdive"
|
||||
"alphabet-sort",
|
||||
"code-env",
|
||||
"color-codeword",
|
||||
"deepdive",
|
||||
"gpqa",
|
||||
"hle",
|
||||
"ifeval",
|
||||
"livecodebench",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
"opencode-math",
|
||||
"opencode-science",
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -85,7 +98,7 @@ gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.3.3",
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
all = [
|
||||
"prime-rl[flash-attn]",
|
||||
@@ -108,6 +121,40 @@ dev = [
|
||||
]
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
"deps/verifiers/environments/math_python",
|
||||
"deps/verifiers/environments/reverse_text",
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/research-environments/environments/aime2024",
|
||||
"deps/research-environments/environments/aime2025",
|
||||
"deps/research-environments/environments/code_env",
|
||||
"deps/research-environments/environments/color_codeword",
|
||||
"deps/research-environments/environments/deepdive",
|
||||
"deps/research-environments/environments/gpqa",
|
||||
"deps/research-environments/environments/hle",
|
||||
"deps/research-environments/environments/ifeval",
|
||||
"deps/research-environments/environments/livecodebench",
|
||||
"deps/research-environments/environments/logic_env",
|
||||
"deps/research-environments/environments/math500",
|
||||
"deps/research-environments/environments/math_env",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus",
|
||||
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
|
||||
"deps/research-environments/environments/mmlu_pro",
|
||||
"deps/research-environments/environments/opencode_cp",
|
||||
"deps/research-environments/environments/opencode_deepdive",
|
||||
"deps/research-environments/environments/opencode_math",
|
||||
"deps/research-environments/environments/opencode_science",
|
||||
"deps/research-environments/environments/opencode_swe",
|
||||
"deps/research-environments/environments/science_env",
|
||||
"deps/research-environments/environments/simpleqa_verified",
|
||||
"deps/research-environments/environments/tau2_bench",
|
||||
]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
@@ -122,34 +169,21 @@ override-dependencies = [
|
||||
"nvidia-cudnn-cu12>=9.15",
|
||||
"nvidia-cutlass-dsl>=4.4.1",
|
||||
"transformers>=5.1.0.dev0",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# pytorch-cu128 / pytorch-cu128-test indexes don't publish upload dates
|
||||
torch = false
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
tokenspeed-mla = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
@@ -158,31 +192,52 @@ deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
verifiers = { workspace = true }
|
||||
renderers = { workspace = true }
|
||||
aime2024 = { workspace = true }
|
||||
aime2025 = { workspace = true }
|
||||
alphabet-sort = { workspace = true }
|
||||
code-env = { workspace = true }
|
||||
color-codeword = { workspace = true }
|
||||
deepdive = { workspace = true }
|
||||
gpqa = { workspace = true }
|
||||
hle = { workspace = true }
|
||||
ifeval = { workspace = true }
|
||||
livecodebench = { workspace = true }
|
||||
logic-env = { workspace = true }
|
||||
math-env = { workspace = true }
|
||||
math-python = { workspace = true }
|
||||
math500 = { workspace = true }
|
||||
mini-swe-agent-plus = { workspace = true }
|
||||
mini-swe-agent-plus-rlm = { workspace = true }
|
||||
mmlu-pro = { workspace = true }
|
||||
opencode-cp = { workspace = true }
|
||||
opencode-deepdive = { workspace = true }
|
||||
opencode-math = { workspace = true }
|
||||
opencode-science = { workspace = true }
|
||||
opencode-swe = { workspace = true }
|
||||
reverse-text = { workspace = true }
|
||||
science-env = { workspace = true }
|
||||
simpleqa-verified = { workspace = true }
|
||||
tau2-bench = { workspace = true }
|
||||
wiki-search = { workspace = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
alphabet-sort = { index = "primeintellect" }
|
||||
wiki-search = { index = "primeintellect" }
|
||||
math-python = { index = "primeintellect" }
|
||||
math-env = { index = "primeintellect" }
|
||||
code-env = { index = "primeintellect" }
|
||||
science-env = { index = "primeintellect" }
|
||||
logic-env = { index = "primeintellect" }
|
||||
color-codeword = { index = "primeintellect" }
|
||||
math500 = { index = "primeintellect" }
|
||||
aime2024 = { index = "primeintellect" }
|
||||
aime2025 = { index = "primeintellect" }
|
||||
deepdive = { index = "primeintellect" }
|
||||
mini_swe_agent_plus = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
|
||||
@@ -194,17 +249,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
|
||||
[tool.uv.extra-build-variables]
|
||||
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "primeintellect"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128"
|
||||
url = "https://download.pytorch.org/whl/cu128"
|
||||
explicit = true
|
||||
|
||||
|
||||
[[tool.uv.index]]
|
||||
name = "pytorch-cu128-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu128"
|
||||
@@ -214,8 +263,15 @@ explicit = true
|
||||
select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
extend-exclude = ["deps"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "--strict-markers"
|
||||
@@ -228,5 +284,8 @@ markers = [
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
|
||||
@@ -15,9 +15,3 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
|
||||
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
|
||||
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
|
||||
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
|
||||
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
|
||||
|
||||
+115
-53
@@ -4,86 +4,148 @@ set -euo pipefail
|
||||
# Colors for output
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
|
||||
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
|
||||
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
|
||||
|
||||
REPO_ID="prime-rl"
|
||||
|
||||
# Flag defaults (can be overridden via env)
|
||||
SKIP_CLONE=${SKIP_CLONE:-0}
|
||||
|
||||
assert_supported_platform() {
|
||||
local os arch
|
||||
os="$(uname -s)"
|
||||
arch="$(uname -m)"
|
||||
|
||||
if [ "$os" != "Linux" ]; then
|
||||
log_error "Unsupported platform: ${os}/${arch}."
|
||||
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$arch" in
|
||||
x86_64 | aarch64) ;;
|
||||
*)
|
||||
log_error "Unsupported architecture: ${arch}."
|
||||
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if ! command -v apt &>/dev/null; then
|
||||
log_error "Unsupported Linux distribution: apt is required by this installer."
|
||||
log_error "Use a Debian/Ubuntu-based Linux machine on x86_64 or aarch64, or install manually."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
has_ssh_access() {
|
||||
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
|
||||
# We try a quick ls-remote to avoid cloning on failure.
|
||||
# Disable -e for the probe so the script doesn't exit on a failed test.
|
||||
set +e
|
||||
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
return $rc
|
||||
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
|
||||
# We try a quick ls-remote to avoid cloning on failure.
|
||||
# Disable -e for the probe so the script doesn't exit on a failed test.
|
||||
set +e
|
||||
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
return $rc
|
||||
}
|
||||
|
||||
ensure_known_hosts() {
|
||||
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
|
||||
mkdir -p "${HOME}/.ssh"
|
||||
chmod 700 "${HOME}/.ssh"
|
||||
# Use -H to hash hostnames; merge uniquely to avoid dupes.
|
||||
if command -v ssh-keyscan >/dev/null 2>&1; then
|
||||
ssh-keyscan -H github.com 2>/dev/null | sort -u \
|
||||
| tee -a "${HOME}/.ssh/known_hosts" >/dev/null
|
||||
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
|
||||
mkdir -p "${HOME}/.ssh"
|
||||
chmod 700 "${HOME}/.ssh"
|
||||
# Use -H to hash hostnames; merge uniquely to avoid dupes.
|
||||
if command -v ssh-keyscan >/dev/null 2>&1; then
|
||||
ssh-keyscan -H github.com 2>/dev/null | sort -u |
|
||||
tee -a "${HOME}/.ssh/known_hosts" >/dev/null
|
||||
chmod 600 "${HOME}/.ssh/known_hosts"
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
}
|
||||
|
||||
main() {
|
||||
# Ensure sudo exists
|
||||
if ! command -v sudo &>/dev/null; then
|
||||
apt update
|
||||
apt install -y sudo
|
||||
fi
|
||||
assert_supported_platform
|
||||
|
||||
log_info "Installing base packages..."
|
||||
sudo apt update && sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
|
||||
# Ensure sudo exists
|
||||
if ! command -v sudo &>/dev/null; then
|
||||
apt update
|
||||
apt install -y sudo
|
||||
fi
|
||||
|
||||
log_info "Configuring SSH known_hosts for GitHub..."
|
||||
ensure_known_hosts
|
||||
log_info "Installing base packages..."
|
||||
sudo apt update
|
||||
sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
|
||||
|
||||
if [ "$SKIP_CLONE" -eq 1 ]; then
|
||||
log_info "Skipping clone; assuming we are already inside the repo."
|
||||
log_info "Configuring SSH known_hosts for GitHub..."
|
||||
ensure_known_hosts
|
||||
|
||||
if [ "$SKIP_CLONE" -eq 1 ]; then
|
||||
log_info "Skipping clone; assuming we are already inside the repo."
|
||||
else
|
||||
log_info "Determining best way to clone (SSH vs HTTPS)..."
|
||||
if has_ssh_access; then
|
||||
log_info "SSH access to GitHub works. Cloning via SSH."
|
||||
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
|
||||
else
|
||||
log_info "Determining best way to clone (SSH vs HTTPS)..."
|
||||
if has_ssh_access; then
|
||||
log_info "SSH access to GitHub works. Cloning via SSH."
|
||||
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
|
||||
else
|
||||
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
|
||||
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
|
||||
fi
|
||||
|
||||
log_info "Entering project directory..."
|
||||
cd ${REPO_ID}
|
||||
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
|
||||
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
|
||||
fi
|
||||
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
log_info "Entering project directory..."
|
||||
cd ${REPO_ID}
|
||||
fi
|
||||
|
||||
log_info "Sourcing uv environment..."
|
||||
if ! command -v uv &> /dev/null; then
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
if ! has_ssh_access; then
|
||||
git config url."https://github.com/".insteadOf "git@github.com:"
|
||||
fi
|
||||
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
log_info "Initializing submodules..."
|
||||
init_submodules
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
log_info "Sourcing uv environment..."
|
||||
if ! command -v uv &>/dev/null; then
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
|
||||
log_info "Installation completed!"
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
|
||||
log_info "Installation completed!"
|
||||
}
|
||||
|
||||
main
|
||||
main
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference.
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
|
||||
#
|
||||
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
|
||||
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
|
||||
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
|
||||
# and is what `pyproject.toml` consumes by default; this script is for
|
||||
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
|
||||
#
|
||||
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh
|
||||
# bash scripts/install_deep_gemm.sh # build + install in-place
|
||||
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: 477618c)
|
||||
# --ref REF DeepGEMM commit hash (default: d30fc36)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
@@ -17,7 +23,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
|
||||
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
|
||||
@@ -23,6 +23,8 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna import LagunaForCausalLM as PrimeRLLagunaForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
@@ -130,6 +132,59 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
"laguna": {
|
||||
"config_class": LagunaConfig,
|
||||
"config_kwargs": dict(
|
||||
vocab_size=100352,
|
||||
hidden_size=512,
|
||||
intermediate_size=2048,
|
||||
num_hidden_layers=12,
|
||||
num_attention_heads=8,
|
||||
num_attention_heads_per_layer=[8] * 12,
|
||||
num_key_value_heads=4,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_parameters={
|
||||
"full_attention": {
|
||||
"rope_type": "yarn",
|
||||
"rope_theta": 500000.0,
|
||||
"factor": 4.0,
|
||||
"original_max_position_embeddings": 1024,
|
||||
"beta_slow": 1.0,
|
||||
"beta_fast": 64.0,
|
||||
"attention_factor": 1.0,
|
||||
"partial_rotary_factor": 0.5,
|
||||
},
|
||||
"sliding_attention": {
|
||||
"rope_type": "default",
|
||||
"rope_theta": 10000.0,
|
||||
"partial_rotary_factor": 1.0,
|
||||
},
|
||||
},
|
||||
layer_types=["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"] * 3,
|
||||
sliding_window=512,
|
||||
moe_intermediate_size=128,
|
||||
shared_expert_intermediate_size=128,
|
||||
num_experts=8,
|
||||
num_experts_per_tok=4,
|
||||
mlp_layer_types=["dense"] + ["sparse"] * 11,
|
||||
moe_routed_scaling_factor=2.5,
|
||||
use_grouped_mm=False,
|
||||
pad_token_id=9,
|
||||
bos_token_id=2,
|
||||
eos_token_id=[2, 24],
|
||||
auto_map={
|
||||
"AutoConfig": "poolside/Laguna-XS.2--configuration_laguna.LagunaConfig",
|
||||
"AutoModel": "poolside/Laguna-XS.2--modeling_laguna.LagunaModel",
|
||||
"AutoModelForCausalLM": "poolside/Laguna-XS.2--modeling_laguna.LagunaForCausalLM",
|
||||
},
|
||||
),
|
||||
"hf_model_class": None, # uses Poolside remote modeling code
|
||||
"prime_model_class": PrimeRLLagunaForCausalLM,
|
||||
"tokenizer_source": "poolside/Laguna-XS.2",
|
||||
},
|
||||
"qwen3_5_moe_vlm": {
|
||||
"config_fn": _qwen3_5_moe_vlm_config,
|
||||
"hf_model_class": HFQwen3_5MoeVLM,
|
||||
|
||||
+16
-1
@@ -116,6 +116,14 @@ id = "math-env"
|
||||
|
||||
On the CLI, list items are indexed: `--env.0.id reverse-text --env.1.id math-env`.
|
||||
|
||||
When composing multiple TOML files, list fields are replaced wholesale by the later file. To change one
|
||||
`orchestrator.filters` entry in an overlay, include the full desired filter list in that overlay.
|
||||
|
||||
For quick KL smoke runs with very small rollout batches, enforced `zero_advantage` filtering can remove
|
||||
every rollout and stop the orchestrator. If the goal is only trainer/inference mismatch KL, keep the
|
||||
filter present but set `enforce = false` in a temporary overlay and call out that the run is not a reward
|
||||
learning validation.
|
||||
|
||||
### Dict fields
|
||||
|
||||
In TOML, use a section:
|
||||
@@ -155,7 +163,13 @@ If you wish to configure values of the default variant, you don't need to set th
|
||||
|
||||
### 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.
|
||||
Set `orchestrator.training_mode = "sft"` (or top-level `training_mode = "sft"`, which auto-propagates) and configure `orchestrator.teacher` with the teacher endpoint. The orchestrator stamps each `TrainingSample.sft_loss = True` and the shared `training_mode` validator sets `trainer.loss.type = "sft"`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch.
|
||||
|
||||
`[inference]` is required (same as rl/opd) — it starts the student inference server and auto-configures `orchestrator.student.client.base_url`. The student pool is used for online evals and policy weight sync. For externally started student inference, set `orchestrator.student.client.base_url` explicitly instead.
|
||||
|
||||
### RL rollout client defaults
|
||||
|
||||
For text-only RL rollouts, the orchestrator defaults to renderer-backed TITO (`use_renderer = true`). VLM configs must explicitly fall back to MITO (`use_renderer = false`) so image preprocessing and chat templating stay server-side. External teacher rollouts must also set `use_renderer = false`.
|
||||
|
||||
### Model fields
|
||||
|
||||
@@ -177,4 +191,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
|
||||
|
||||
@@ -49,7 +49,6 @@ uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
|
||||
Always use the `inference` entrypoint — never `vllm serve` directly.
|
||||
|
||||
Custom endpoints beyond standard OpenAI API:
|
||||
- `/v1/chat/completions/tokens` — accepts token IDs as prompt input
|
||||
- `/update_weights` — hot-reload model weights from the trainer
|
||||
- `/load_lora_adapter` — load LoRA adapters at runtime
|
||||
- `/init_broadcaster` — initialize weight broadcast for distributed training
|
||||
@@ -88,4 +87,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,39 @@ 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 deps/pydantic-config
|
||||
```
|
||||
|
||||
For an existing clone, initialize the public submodules by passing explicit paths:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
```
|
||||
|
||||
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/`, `deps/research-environments/`, and `deps/pydantic-config/`. The uv workspace members among them apply source edits 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]`.
|
||||
|
||||
When intentionally bumping a package to a release newer than the workspace-wide `exclude-newer = "7 days"` window, add that package and any newly required transitive packages to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
## Advanced
|
||||
|
||||
### Mamba-SSM (NemotronH models)
|
||||
|
||||
@@ -143,8 +143,10 @@ These tell you whether training is healthy or diverging.
|
||||
|
||||
| Metric | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
|
||||
| `entropy/mean` | trainer | policy entropy |
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | trainer | KL divergence between trainer and (old) inference policy over trainable tokens (W&B) |
|
||||
| `entropy/{all,env}/{mean,std,max}` | trainer | policy entropy over trainable tokens (W&B) |
|
||||
| `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
|
||||
@@ -251,4 +253,3 @@ PRIME-RL::Launcher
|
||||
```
|
||||
|
||||
For multi-node runs, trainer and inference processes are distributed across separate nodes. Use `srun` or `ssh` to inspect processes on other nodes directly.
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported
|
||||
@@ -45,6 +45,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
kv_offload=config.kv_cache_offload is not None,
|
||||
)
|
||||
|
||||
is_multi_node = config.deployment.type == "multi_node"
|
||||
@@ -63,10 +64,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
kv_offload=config.deployment.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.deployment.kv_cache_offload.cpu_bytes)
|
||||
if config.deployment.kv_cache_offload
|
||||
else 0,
|
||||
kv_offload_cpu_bytes=int(config.kv_cache_offload.cpu_bytes) if config.kv_cache_offload else 0,
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
|
||||
@@ -12,6 +12,7 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
@@ -77,26 +78,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def check_gpus_available(gpu_ids: list[int]) -> None:
|
||||
"""Raise error if there are existing processes on the specified GPUs."""
|
||||
pynvml.nvmlInit()
|
||||
|
||||
occupied = []
|
||||
for gpu_id in gpu_ids:
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
|
||||
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
||||
if processes:
|
||||
pids = [p.pid for p in processes]
|
||||
occupied.append((gpu_id, pids))
|
||||
|
||||
if occupied:
|
||||
msg = "Existing processes found on GPUs:\n"
|
||||
for gpu_id, pids in occupied:
|
||||
msg += f" GPU {gpu_id}: PIDs {pids}\n"
|
||||
msg += "Kill these processes or use different GPUs."
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
@@ -147,21 +128,17 @@ def rl_local(config: RLConfig):
|
||||
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
|
||||
wandb_shared_env["WANDB_SHARED_RUN_ID"] = os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex)
|
||||
|
||||
# Check for existing processes on GPUs
|
||||
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
|
||||
check_gpus_available(all_gpu_ids)
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.client.is_elastic:
|
||||
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.client.base_url[0]
|
||||
base_url = config.orchestrator.student.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
raise ValueError(
|
||||
f"orchestrator.client.base_url port ({client_port}) does not match "
|
||||
f"orchestrator.student.client.base_url port ({client_port}) does not match "
|
||||
f"inference.server.port ({expected_port}). "
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
@@ -214,14 +191,13 @@ def rl_local(config: RLConfig):
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
if config.orchestrator.teacher_rollout_model is None:
|
||||
logger.warning(
|
||||
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
|
||||
)
|
||||
logger.warning(
|
||||
"No [inference] block configured - the student inference server will not be started here. "
|
||||
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
|
||||
"make sure one is running at orchestrator.student.client.base_url "
|
||||
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
|
||||
"will hang waiting for it."
|
||||
)
|
||||
|
||||
# Optionally, start teacher inference process
|
||||
if config.teacher_inference:
|
||||
@@ -229,7 +205,7 @@ def rl_local(config: RLConfig):
|
||||
raise ValueError(
|
||||
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
|
||||
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
|
||||
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
|
||||
"or omit teacher_inference and configure orchestrator.teacher to use an existing server."
|
||||
)
|
||||
|
||||
teacher_inference_cmd = ["inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
|
||||
@@ -257,12 +233,10 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
elif (
|
||||
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
|
||||
) or config.orchestrator.teacher_model:
|
||||
elif config.orchestrator.teacher:
|
||||
logger.warning(
|
||||
"No teacher_inference config specified, skipping starting teacher inference server. "
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher is configured."
|
||||
)
|
||||
|
||||
# Start orchestrator process
|
||||
@@ -348,10 +322,10 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Monitor all processes for failures
|
||||
logger.success("Startup complete. Showing trainer logs...")
|
||||
logger.success("Startup complete. Showing orchestrator logs...")
|
||||
|
||||
tail_process = Popen(
|
||||
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
|
||||
f"tail -F '{log_dir / 'orchestrator.log'}'",
|
||||
shell=True,
|
||||
)
|
||||
processes.append(tail_process)
|
||||
@@ -444,8 +418,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
kv_offload=infer_deploy.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(infer_deploy.kv_cache_offload.cpu_bytes) if infer_deploy.kv_cache_offload else 0,
|
||||
kv_offload=config.inference.kv_cache_offload is not None,
|
||||
kv_offload_cpu_bytes=int(config.inference.kv_cache_offload.cpu_bytes)
|
||||
if config.inference.kv_cache_offload
|
||||
else 0,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
@@ -469,6 +445,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
|
||||
@@ -8,6 +8,7 @@ from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
+101
-429
@@ -1,9 +1,8 @@
|
||||
import torch
|
||||
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.
|
||||
@@ -15,163 +14,38 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_ep_scatter()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_offloading_connector_cpu_block_count()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _apply_expert_map_triton(expert_id, expert_map):
|
||||
if expert_id != -1:
|
||||
expert_id = tl.load(expert_map + expert_id).to(expert_id.dtype)
|
||||
return expert_id
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwd_kernel_ep_scatter_2_int64(
|
||||
total_token_num,
|
||||
expert_start_loc,
|
||||
recv_x,
|
||||
recv_x_stride0,
|
||||
recv_x_stride1,
|
||||
recv_x_scale,
|
||||
recv_x_scale_stride0,
|
||||
recv_x_scale_stride1,
|
||||
recv_topk,
|
||||
recv_topk_stride0,
|
||||
recv_topk_stride1,
|
||||
output_tensor,
|
||||
output_tensor_stride0,
|
||||
output_tensor_stride1,
|
||||
output_tensor_scale,
|
||||
output_tensor_scale_stride0,
|
||||
output_tensor_scale_stride1,
|
||||
output_index,
|
||||
output_index_stride0,
|
||||
output_index_stride1,
|
||||
topk_num: tl.constexpr,
|
||||
expert_map,
|
||||
HAS_EXPERT_MAP: tl.constexpr,
|
||||
HIDDEN_SIZE: tl.constexpr,
|
||||
HIDDEN_SIZE_PAD: tl.constexpr,
|
||||
SCALE_HIDDEN_SIZE: tl.constexpr,
|
||||
SCALE_HIDDEN_SIZE_PAD: tl.constexpr,
|
||||
):
|
||||
start_token_id = tl.program_id(0)
|
||||
grid_num = tl.num_programs(0)
|
||||
|
||||
offset_in = tl.arange(0, HIDDEN_SIZE_PAD)
|
||||
mask = offset_in < HIDDEN_SIZE
|
||||
|
||||
offset_in_s = tl.arange(0, SCALE_HIDDEN_SIZE_PAD)
|
||||
mask_s = offset_in_s < SCALE_HIDDEN_SIZE
|
||||
|
||||
output_tensor_stride0 = output_tensor_stride0.to(tl.int64)
|
||||
|
||||
for token_id in range(start_token_id, total_token_num, grid_num):
|
||||
to_copy = tl.load(recv_x + token_id * recv_x_stride0 + offset_in, mask=mask)
|
||||
to_copy_s = tl.load(
|
||||
recv_x_scale + token_id * recv_x_scale_stride0 + offset_in_s,
|
||||
mask=mask_s,
|
||||
)
|
||||
|
||||
for topk_index in tl.range(0, topk_num, 1, num_stages=4):
|
||||
expert_id = tl.load(recv_topk + token_id * recv_topk_stride0 + topk_index)
|
||||
|
||||
if HAS_EXPERT_MAP:
|
||||
expert_id = _apply_expert_map_triton(expert_id, expert_map)
|
||||
|
||||
if expert_id >= 0:
|
||||
dest_token_index = tl.atomic_add(expert_start_loc + expert_id, 1)
|
||||
dest_token_index_i64 = dest_token_index.to(tl.int64)
|
||||
|
||||
tl.store(
|
||||
output_index + token_id * output_index_stride0 + topk_index,
|
||||
dest_token_index,
|
||||
)
|
||||
|
||||
output_tensor_ptr = output_tensor + dest_token_index_i64 * output_tensor_stride0
|
||||
output_tensor_scale_ptr = output_tensor_scale + dest_token_index * output_tensor_scale_stride0
|
||||
tl.store(output_tensor_ptr + offset_in, to_copy, mask=mask)
|
||||
tl.store(output_tensor_scale_ptr + offset_in_s, to_copy_s, mask=mask_s)
|
||||
|
||||
|
||||
def _triton_ep_scatter_int64(
|
||||
recv_x: torch.Tensor,
|
||||
recv_x_scale: torch.Tensor,
|
||||
recv_topk: torch.Tensor,
|
||||
num_recv_tokens_per_expert: torch.Tensor,
|
||||
expert_map: torch.Tensor | None,
|
||||
expert_start_loc: torch.Tensor,
|
||||
output_tensor: torch.Tensor,
|
||||
output_tensor_scale: torch.Tensor,
|
||||
m_indices: torch.Tensor,
|
||||
output_index: torch.Tensor,
|
||||
) -> None:
|
||||
from vllm.model_executor.layers.fused_moe import deep_gemm_utils
|
||||
|
||||
block_e = 128
|
||||
num_warps = 8
|
||||
num_experts = num_recv_tokens_per_expert.shape[0]
|
||||
hidden_size = recv_x.shape[1]
|
||||
|
||||
assert m_indices.shape[0] % block_e == 0
|
||||
assert expert_start_loc.shape[0] == num_experts
|
||||
|
||||
deep_gemm_utils._fwd_kernel_ep_scatter_1[(num_experts,)](
|
||||
num_recv_tokens_per_expert,
|
||||
expert_start_loc,
|
||||
m_indices,
|
||||
num_experts=num_experts,
|
||||
num_warps=num_warps,
|
||||
BLOCK_E=block_e,
|
||||
BLOCK_EXPERT_NUM=triton.next_power_of_2(num_experts),
|
||||
)
|
||||
|
||||
grid = min(recv_topk.shape[0], 1024 * 8)
|
||||
_fwd_kernel_ep_scatter_2_int64[(grid,)](
|
||||
recv_topk.shape[0],
|
||||
expert_start_loc,
|
||||
recv_x,
|
||||
recv_x.stride(0),
|
||||
recv_x.stride(1),
|
||||
recv_x_scale,
|
||||
recv_x_scale.stride(0),
|
||||
recv_x_scale.stride(1),
|
||||
recv_topk,
|
||||
recv_topk.stride(0),
|
||||
recv_topk.stride(1),
|
||||
output_tensor,
|
||||
output_tensor.stride(0),
|
||||
output_tensor.stride(1),
|
||||
output_tensor_scale,
|
||||
output_tensor_scale.stride(0),
|
||||
output_tensor_scale.stride(1),
|
||||
output_index,
|
||||
output_index.stride(0),
|
||||
output_index.stride(1),
|
||||
topk_num=recv_topk.shape[1],
|
||||
expert_map=expert_map,
|
||||
HAS_EXPERT_MAP=expert_map is not None,
|
||||
num_warps=num_warps,
|
||||
HIDDEN_SIZE=hidden_size,
|
||||
HIDDEN_SIZE_PAD=triton.next_power_of_2(hidden_size),
|
||||
SCALE_HIDDEN_SIZE=recv_x_scale.shape[1],
|
||||
SCALE_HIDDEN_SIZE_PAD=triton.next_power_of_2(recv_x_scale.shape[1]),
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_ep_scatter():
|
||||
# Temporary local carry of the upstream fix while it is under review:
|
||||
# issue: https://github.com/vllm-project/vllm/issues/39211
|
||||
# PR: https://github.com/vllm-project/vllm/pull/39213
|
||||
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.layers.fused_moe import deep_gemm_utils
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
deep_gemm_utils.ep_scatter = torch.no_grad()(_triton_ep_scatter_int64)
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM ep_scatter.")
|
||||
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.")
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
@@ -715,239 +589,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.
|
||||
|
||||
@@ -965,9 +606,9 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
- on resume, wake every DP rank and force an immediate global unfinished
|
||||
sync instead of waiting for the normal 32-step cadence
|
||||
|
||||
This keeps the upstream pause-side fix from
|
||||
https://github.com/vllm-project/vllm/pull/37024 and extends it with the
|
||||
resume-side wave-state fix.
|
||||
This also bypasses vLLM's two-phase DP pause implementation
|
||||
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
|
||||
reject states that our weight-update flow can validly hit.
|
||||
"""
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
@@ -977,7 +618,8 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
|
||||
_base_add_request = EngineCore.add_request
|
||||
_base_handle_client_request = EngineCoreProc._handle_client_request
|
||||
_base_resume_scheduler = DPEngineCoreProc.resume_scheduler
|
||||
_base_pause_complete = EngineCoreProc._pause_complete
|
||||
_base_resume_scheduler = EngineCoreProc.resume_scheduler
|
||||
|
||||
def _patched_add_request(self, request: Request, request_wave: int = 0):
|
||||
_base_add_request(self, request, request_wave)
|
||||
@@ -998,8 +640,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
else:
|
||||
_base_handle_client_request(self, request_type, request)
|
||||
|
||||
def _patched_pause_complete(self) -> bool:
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
return _base_pause_complete(self)
|
||||
|
||||
def _patched_resume_scheduler(self):
|
||||
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
_base_resume_scheduler(self)
|
||||
if was_paused:
|
||||
self.engines_running = True
|
||||
@@ -1016,50 +665,11 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
|
||||
DPEngineCoreProc.add_request = _patched_add_request
|
||||
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
|
||||
DPEngineCoreProc._pause_complete = _patched_pause_complete
|
||||
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_offloading_connector_cpu_block_count():
|
||||
"""Fix CPU block count miscalculation in OffloadingConnector.
|
||||
|
||||
CPUOffloadingSpec derives kv_bytes_per_block from page_size_bytes multiplied
|
||||
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
|
||||
already aggregated across layers in the group. The undersized CPU pool then
|
||||
produces out-of-bounds block mappings and swap_blocks segfaults.
|
||||
|
||||
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
|
||||
divided by num_blocks, matching the upstream PR.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/39617
|
||||
"""
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
_original_init = CPUOffloadingSpec.__init__
|
||||
|
||||
def _patched_init(self, vllm_config, kv_cache_config):
|
||||
_original_init(self, vllm_config, kv_cache_config)
|
||||
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
if kv_cache_config.num_blocks > 0:
|
||||
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
|
||||
kv_bytes_per_block = (
|
||||
total_gpu_kv_bytes // kv_cache_config.num_blocks
|
||||
) * vllm_config.parallel_config.world_size
|
||||
else:
|
||||
kv_bytes_per_block = 0
|
||||
|
||||
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
|
||||
self.num_blocks = (
|
||||
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
|
||||
)
|
||||
|
||||
CPUOffloadingSpec.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
@@ -1086,3 +696,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,27 +1,21 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.datastructures import State
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.openai.api_server import init_app_state
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionResponse
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.engine.serving import OpenAIServing
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.openai.utils import validate_json_request
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.entrypoints.utils import load_aware_call, with_cancellation
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateRequest
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
@@ -141,10 +135,6 @@ from prime_rl.inference.patches import (
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
from prime_rl.inference.vllm.serving_chat_with_tokens import (
|
||||
ChatCompletionRequestWithTokens,
|
||||
OpenAIServingChatWithTokens,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
@@ -153,24 +143,19 @@ monkey_patch_harmony_stop_token_propagation()
|
||||
# May be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.19 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
# Create our own router for custom endpoints
|
||||
router = APIRouter()
|
||||
LIVENESS_TIMEOUT_SECONDS = 5.0
|
||||
|
||||
|
||||
def engine_client(request: Request) -> EngineClient:
|
||||
return request.app.state.engine_client
|
||||
|
||||
|
||||
def base(request: Request) -> OpenAIServing:
|
||||
return request.app.state.openai_serving_tokenization
|
||||
|
||||
|
||||
def models(request: Request) -> OpenAIServingModels:
|
||||
return request.app.state.openai_serving_models
|
||||
|
||||
@@ -181,62 +166,6 @@ WORKER_EXTENSION_CLS = {
|
||||
}
|
||||
|
||||
|
||||
def generate_handler(request: Request):
|
||||
return request.app.state.openai_serving_generate
|
||||
|
||||
|
||||
def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/generate",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"application/json": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _generate(request: GenerateRequest, raw_request: Request):
|
||||
handler = generate_handler(raw_request)
|
||||
if handler is None:
|
||||
return JSONResponse({"error": "generate endpoint not available"}, status_code=503)
|
||||
result = await handler.generate(request, raw_request)
|
||||
if isinstance(result, dict) and "error" in result:
|
||||
return JSONResponse(result, status_code=500)
|
||||
return JSONResponse(content=result.model_dump())
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"text/event-stream": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_request: Request):
|
||||
handler = chat_with_tokens(raw_request)
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Chat Completions API")
|
||||
generator = await handler.create_chat_completion_with_tokens(request, raw_request)
|
||||
if isinstance(generator, ErrorResponse):
|
||||
return JSONResponse(content=generator.model_dump(), status_code=generator.error.code)
|
||||
|
||||
elif isinstance(generator, ChatCompletionResponse):
|
||||
return JSONResponse(content=generator.model_dump())
|
||||
|
||||
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)
|
||||
@@ -272,7 +201,7 @@ async def liveness(raw_request: Request):
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
engine_client(raw_request).collective_rpc("liveness_probe"),
|
||||
timeout=LIVENESS_TIMEOUT_SECONDS,
|
||||
timeout=raw_request.app.state.liveness_timeout_seconds,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
|
||||
@@ -303,31 +232,27 @@ async def custom_init_app_state(
|
||||
):
|
||||
"""
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state.
|
||||
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
|
||||
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
|
||||
token IDs alongside the rendered chat completion.
|
||||
3. Add ``/v1/generate`` endpoint for renderer-based token-level inference.
|
||||
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_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)
|
||||
serving_chat.__dict__.update(original_chat.__dict__)
|
||||
state.openai_serving_chat = serving_chat
|
||||
state.openai_serving_chat_with_tokens = serving_chat
|
||||
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
|
||||
|
||||
# /v1/generate endpoint — tokens + optional images, no chat template
|
||||
from prime_rl.inference.vllm.serving_generate import OpenAIServingGenerate
|
||||
|
||||
chat_handler = state.openai_serving_chat if "generate" in supported_tasks else None
|
||||
state.openai_serving_generate = OpenAIServingGenerate(engine_client, chat_handler=chat_handler)
|
||||
upstream = state.serving_tokens
|
||||
prime_serving = object.__new__(PrimeRlServingTokens)
|
||||
prime_serving.__dict__.update(upstream.__dict__)
|
||||
state.serving_tokens = prime_serving
|
||||
|
||||
|
||||
import vllm.entrypoints.openai.api_server
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
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
|
||||
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.serving import GenerationError
|
||||
from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class _RoutedExpertsCapture:
|
||||
def __init__(self, generator: AsyncGenerator[RequestOutput, None]):
|
||||
self._generator = generator
|
||||
self.routed_experts: dict[int, dict] = {}
|
||||
|
||||
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):
|
||||
for choice in response.choices:
|
||||
if choice.index in self.routed_experts:
|
||||
choice.routed_experts = self.routed_experts[choice.index]
|
||||
|
||||
|
||||
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
|
||||
field_names: ClassVar[Optional[set[str]]] = None
|
||||
tokens: list[int] = Field(description=("Prompt tokens to use for the request."))
|
||||
|
||||
|
||||
class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
|
||||
|
||||
async def chat_completion_full_generator(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
result_generator: AsyncIterator[RequestOutput],
|
||||
request_id: str,
|
||||
model_name: str,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
reasoning_parser: ReasoningParser | None = None,
|
||||
) -> ErrorResponse | ChatCompletionResponse:
|
||||
# We need to override the full_generator to be able to capture the routed experts
|
||||
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
|
||||
# How this works:
|
||||
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
|
||||
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
|
||||
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture
|
||||
else:
|
||||
capture = None
|
||||
|
||||
response = await super().chat_completion_full_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
|
||||
if capture and isinstance(response, ChatCompletionResponse):
|
||||
capture.post_process(response)
|
||||
|
||||
return response
|
||||
|
||||
async def create_chat_completion_with_tokens(
|
||||
self,
|
||||
request: ChatCompletionRequestWithTokens,
|
||||
raw_request: Optional[Request] = None,
|
||||
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
|
||||
"""
|
||||
Chat Completion API similar to OpenAI's API.
|
||||
|
||||
See https://platform.openai.com/docs/api-reference/chat/create
|
||||
for the API specification. This API mimics the OpenAI
|
||||
Chat Completion API.
|
||||
"""
|
||||
# Streaming response
|
||||
tokenizer = self.renderer.tokenizer
|
||||
assert tokenizer is not None
|
||||
reasoning_parser: ReasoningParser | None = None
|
||||
try:
|
||||
if self.reasoning_parser_cls:
|
||||
# Pass the same chat template kwargs as used in tokenization
|
||||
chat_template_kwargs = self._prepare_extra_chat_template_kwargs(
|
||||
request.chat_template_kwargs,
|
||||
self.default_chat_template_kwargs,
|
||||
)
|
||||
reasoning_parser = self.reasoning_parser_cls(
|
||||
tokenizer,
|
||||
chat_template_kwargs=chat_template_kwargs, # type: ignore[call-arg]
|
||||
)
|
||||
except RuntimeError as e:
|
||||
logger.exception("Error in reasoning parser creation.")
|
||||
return self.create_error_response(str(e))
|
||||
result = await self.render_chat_request(request)
|
||||
if isinstance(result, ErrorResponse):
|
||||
return result
|
||||
|
||||
conversation, engine_prompts = result
|
||||
|
||||
# We override prompt tokens directly.
|
||||
# VLM conversations use MITO (message-based) instead of TITO, so
|
||||
# multi_modal_data is not expected here.
|
||||
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
|
||||
|
||||
request_id = f"chatcmpl-{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
|
||||
|
||||
try:
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
|
||||
model_name = self.models.model_name(lora_request)
|
||||
except (ValueError, TypeError, RuntimeError) as e:
|
||||
logger.exception("Error preparing request components")
|
||||
return self.create_error_response(e)
|
||||
|
||||
# Extract data_parallel_rank from header (router can inject it)
|
||||
data_parallel_rank = self._get_data_parallel_rank(raw_request)
|
||||
|
||||
# Schedule the request and get the result generator.
|
||||
max_model_len = self.model_config.max_model_len
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = []
|
||||
try:
|
||||
for i, engine_prompt in enumerate(engine_prompts):
|
||||
prompt_token_ids = self._extract_prompt_components(engine_prompt).token_ids
|
||||
|
||||
# If we are creating sub requests for multiple prompts, ensure that they
|
||||
# have unique request ids.
|
||||
sub_request_id = request_id if len(engine_prompts) == 1 else f"{request_id}_{i}"
|
||||
|
||||
prompt_len = self._extract_prompt_len(engine_prompt)
|
||||
if prompt_len >= max_model_len:
|
||||
raise VLLMValidationError(
|
||||
f"This model's maximum context length is "
|
||||
f"{max_model_len} tokens. However, your request has "
|
||||
f"{prompt_len} input tokens. Please reduce the length of "
|
||||
"the input messages.",
|
||||
parameter="input_tokens",
|
||||
value=prompt_len,
|
||||
)
|
||||
|
||||
max_tokens = get_max_tokens(
|
||||
max_model_len,
|
||||
request.max_completion_tokens if request.max_completion_tokens is not None else request.max_tokens,
|
||||
self._extract_prompt_len(engine_prompt),
|
||||
self.default_sampling_params,
|
||||
self.override_max_tokens,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams | BeamSearchParams
|
||||
if request.use_beam_search:
|
||||
sampling_params = request.to_beam_search_params(max_tokens, self.default_sampling_params)
|
||||
else:
|
||||
sampling_params = request.to_sampling_params(
|
||||
max_tokens,
|
||||
self.default_sampling_params,
|
||||
)
|
||||
|
||||
self._log_inputs(
|
||||
sub_request_id,
|
||||
engine_prompt,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
if isinstance(sampling_params, BeamSearchParams):
|
||||
generator = self.beam_search(
|
||||
prompt=engine_prompt,
|
||||
request_id=sub_request_id,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
)
|
||||
else:
|
||||
reasoning_ended = (
|
||||
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
|
||||
)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
sub_request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
reasoning_ended=reasoning_ended,
|
||||
)
|
||||
|
||||
generators.append(generator)
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
|
||||
assert len(generators) == 1
|
||||
(result_generator,) = generators
|
||||
|
||||
if request.stream:
|
||||
return self.chat_completion_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
|
||||
try:
|
||||
return await self.chat_completion_full_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
except GenerationError:
|
||||
raise # Let FastAPI's global generation_error_handler handle it
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
@@ -1,225 +0,0 @@
|
||||
"""/v1/generate endpoint — accepts pre-tokenized inputs.
|
||||
|
||||
Text-only tokens in, tokens out. The Renderer does all tokenization client-side.
|
||||
No Jinja rendering, no server-side chat template application.
|
||||
|
||||
VLMs do not use this endpoint. The orchestrator routes VLMs to MITO
|
||||
(/v1/chat/completions) where vLLM handles image preprocessing and chat
|
||||
templating server-side.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import BaseModel
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.inputs.engine import tokens_input
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
# ── Request / Response schemas ───────────────────────────────────────
|
||||
|
||||
|
||||
class GenerateRequest(BaseModel):
|
||||
model: str | None = None
|
||||
prompt_token_ids: list[int]
|
||||
|
||||
# When unset, fill from max_model_len - prompt_len at request time so we
|
||||
# match /v1/chat/completions behavior. The previous 4096 hard default
|
||||
# silently truncated long completions on 8k+ context runs (e.g. hendrycks
|
||||
# reasoning rollouts capped at 4096 tokens, making rendered rollouts look
|
||||
# shorter than main's for the same model).
|
||||
max_tokens: int | None = None
|
||||
temperature: float = 1.0
|
||||
top_p: float = 1.0
|
||||
top_k: int = -1
|
||||
min_p: float = 0.0
|
||||
seed: int | None = None
|
||||
n: int = 1
|
||||
stop_token_ids: list[int] | None = None
|
||||
repetition_penalty: float = 1.0
|
||||
min_tokens: int = 0
|
||||
prompt_logprobs: bool = False
|
||||
priority: int = 0
|
||||
# Prefix-cache invalidation salt. Must match main's
|
||||
# /v1/chat/completions/tokens path: the orchestrator sets
|
||||
# `extra_body["cache_salt"] = str(ckpt_step)` on every rollout
|
||||
# request. vLLM's KV cache hashes include this salt, so when the
|
||||
# step changes the cache misses and KV is recomputed with fresh
|
||||
# weights. Without this, renderers path silently reuses stale KV
|
||||
# from before the latest weight update and its logprobs drift from
|
||||
# the trainer's forward pass (mismatch_kl grows 3x over training).
|
||||
cache_salt: str | None = None
|
||||
|
||||
|
||||
class GenerateChoiceResponse(BaseModel):
|
||||
index: int
|
||||
token_ids: list[int]
|
||||
logprobs: list[float]
|
||||
finish_reason: str | None = None
|
||||
routed_experts: dict | None = None
|
||||
|
||||
|
||||
class GenerateResponse(BaseModel):
|
||||
id: str
|
||||
model: str
|
||||
prompt_token_ids: list[int]
|
||||
choices: list[GenerateChoiceResponse]
|
||||
usage: dict
|
||||
prompt_logprobs: list[float | None] | None = None
|
||||
|
||||
|
||||
# ── Handler ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class OpenAIServingGenerate:
|
||||
"""Lightweight generate handler — tokens in, tokens out."""
|
||||
|
||||
def __init__(self, engine_client: EngineClient, chat_handler: Any | None = None):
|
||||
self.engine_client = engine_client
|
||||
self.chat_handler = chat_handler
|
||||
|
||||
async def generate(self, request: GenerateRequest, raw_request: Request) -> GenerateResponse | dict:
|
||||
# Pre-rendered TokensInput shape (type="token") — avoids vLLM's
|
||||
# "raw prompt" deprecation that targets plain lists/strings.
|
||||
engine_prompt = tokens_input(request.prompt_token_ids, cache_salt=request.cache_salt)
|
||||
|
||||
# Match /v1/chat/completions: if the client didn't ask for a specific
|
||||
# cap, let the model generate up to whatever room is left in context.
|
||||
# vLLM v1 AsyncLLM exposes model_config directly (no async getter).
|
||||
max_tokens = request.max_tokens
|
||||
if max_tokens is None:
|
||||
max_model_len = self.engine_client.model_config.max_model_len
|
||||
max_tokens = max(1, max_model_len - len(request.prompt_token_ids))
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
top_k=request.top_k,
|
||||
min_p=request.min_p,
|
||||
seed=request.seed,
|
||||
n=request.n,
|
||||
stop_token_ids=request.stop_token_ids or [],
|
||||
repetition_penalty=request.repetition_penalty,
|
||||
min_tokens=request.min_tokens,
|
||||
logprobs=1,
|
||||
prompt_logprobs=1 if request.prompt_logprobs else None,
|
||||
skip_special_tokens=False,
|
||||
)
|
||||
|
||||
request_id = f"gen-{uuid4().hex[:16]}"
|
||||
routed_experts_map: dict[int, dict] = {}
|
||||
final_output: RequestOutput | None = None
|
||||
data_parallel_rank = None
|
||||
lora_request = None
|
||||
trace_headers = None
|
||||
if self.chat_handler is not None:
|
||||
data_parallel_rank = self.chat_handler._get_data_parallel_rank(raw_request)
|
||||
trace_headers = await self.chat_handler._get_trace_headers(raw_request.headers)
|
||||
lora_request = self.chat_handler._maybe_get_adapters(request)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
)
|
||||
|
||||
# Drain the generator without polling ``raw_request.is_disconnected``
|
||||
# per decode step. That poll is one ASGI ``receive()`` await per
|
||||
# yielded token — at ~2k concurrent rollouts each producing dozens of
|
||||
# tokens, it was the single largest per-step overhead on the /generate
|
||||
# path (vLLM's own chat completions handler uses the CancelledError
|
||||
# pattern for the same reason). Starlette cancels this coroutine on
|
||||
# client disconnect, so the except branch still catches it.
|
||||
try:
|
||||
async for output in generator:
|
||||
for comp_output in output.outputs:
|
||||
if comp_output.routed_experts is not None:
|
||||
routed_experts_map[comp_output.index] = _encode_routed_experts(comp_output.routed_experts)
|
||||
final_output = output
|
||||
except asyncio.CancelledError:
|
||||
await self.engine_client.abort(request_id)
|
||||
raise
|
||||
|
||||
if final_output is None:
|
||||
return {"error": "No output generated"}
|
||||
|
||||
choices = []
|
||||
for output in final_output.outputs:
|
||||
token_ids = list(output.token_ids)
|
||||
logprobs_list: list[float] = []
|
||||
if output.logprobs:
|
||||
for i, lp_dict in enumerate(output.logprobs):
|
||||
if i < len(token_ids) and token_ids[i] in lp_dict:
|
||||
logprobs_list.append(lp_dict[token_ids[i]].logprob)
|
||||
else:
|
||||
logprobs_list.append(0.0)
|
||||
|
||||
choices.append(
|
||||
GenerateChoiceResponse(
|
||||
index=output.index,
|
||||
token_ids=token_ids,
|
||||
logprobs=logprobs_list,
|
||||
finish_reason=output.finish_reason,
|
||||
routed_experts=routed_experts_map.get(output.index),
|
||||
)
|
||||
)
|
||||
|
||||
prompt_len = len(final_output.prompt_token_ids)
|
||||
completion_len = sum(len(c.token_ids) for c in choices)
|
||||
prompt_logprobs = _extract_prompt_logprobs(final_output.prompt_logprobs)
|
||||
|
||||
return GenerateResponse(
|
||||
id=request_id,
|
||||
model=request.model or "",
|
||||
prompt_token_ids=list(final_output.prompt_token_ids),
|
||||
choices=choices,
|
||||
usage={
|
||||
"prompt_tokens": prompt_len,
|
||||
"completion_tokens": completion_len,
|
||||
"total_tokens": prompt_len + completion_len,
|
||||
},
|
||||
prompt_logprobs=prompt_logprobs,
|
||||
)
|
||||
|
||||
|
||||
def _encode_routed_experts(arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
|
||||
def _extract_prompt_logprobs(
|
||||
prompt_logprobs: list[dict[int, Any] | None] | Mapping[int, Any] | None,
|
||||
) -> list[float | None] | None:
|
||||
if prompt_logprobs is None:
|
||||
return None
|
||||
if isinstance(prompt_logprobs, Mapping):
|
||||
prompt_logprobs = [prompt_logprobs]
|
||||
|
||||
extracted: list[float | None] = []
|
||||
for token_logprobs in prompt_logprobs:
|
||||
if not token_logprobs:
|
||||
extracted.append(None)
|
||||
continue
|
||||
selected = next(iter(token_logprobs.values()))
|
||||
logprob = selected.logprob if hasattr(selected, "logprob") else selected.get("logprob")
|
||||
extracted.append(float(logprob) if logprob is not None else None)
|
||||
return extracted
|
||||
@@ -0,0 +1,318 @@
|
||||
"""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). Bridge it through ``sampling_params.extra_args`` so the
|
||||
# engine's KV connector picks the params up.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
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:
|
||||
# Wrap the result generator to capture routed_experts as it streams,
|
||||
# defer the rest to upstream, then post-process the response into our
|
||||
# PrimeRlGenerateResponse subclass so the encoded experts surface in
|
||||
# the JSON. Skipping the wrapper when the engine isn't producing routed
|
||||
# experts keeps us a no-op subclass on the common path.
|
||||
capture: _RoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture # type: ignore[assignment]
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
|
||||
return response
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
@@ -23,3 +24,6 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
else:
|
||||
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
@@ -2,7 +2,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from torch.nn import Module
|
||||
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
if TYPE_CHECKING:
|
||||
@@ -46,8 +47,9 @@ class FileSystemWeightUpdateWorker(Worker):
|
||||
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
|
||||
)
|
||||
weights_iterator = model_loader._get_weights_iterator(local_source)
|
||||
model.load_weights(weights_iterator) # type: ignore
|
||||
|
||||
# Process weights after loading (important for some models)
|
||||
device = next(model.parameters()).device
|
||||
process_weights_after_loading(model, self.model_runner.model_config, device)
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
weights_iterator,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import pickle
|
||||
from typing import TYPE_CHECKING, Callable, Generator, cast
|
||||
from typing import TYPE_CHECKING, Generator, cast
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
@@ -8,10 +8,9 @@ from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import (
|
||||
load_weights_checkpoint,
|
||||
load_weights_checkpoint_layerwise,
|
||||
load_weights_kernel,
|
||||
postprocess_weights_checkpoint,
|
||||
postprocess_weights_kernel,
|
||||
update_mla_absorbed_weights,
|
||||
)
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
|
||||
@@ -144,15 +143,14 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
assert isinstance(model, Module)
|
||||
|
||||
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
|
||||
device = next(model.parameters()).device
|
||||
loader_fn: Callable[[Module, Generator[tuple[str, torch.Tensor], None, None]], None]
|
||||
postprocess_fn: Callable[[Module, object, torch.device], None]
|
||||
if self.quantize_in_weight_transfer:
|
||||
loader_fn = load_weights_kernel
|
||||
postprocess_fn = postprocess_weights_kernel
|
||||
else:
|
||||
loader_fn = load_weights_checkpoint
|
||||
postprocess_fn = postprocess_weights_checkpoint
|
||||
load_weights_kernel(model, state_iter)
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
loader_fn(model, state_iter)
|
||||
postprocess_fn(model, self.model_runner.model_config, device)
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
|
||||
@@ -1,44 +1,94 @@
|
||||
from typing import Generator
|
||||
from typing import Generator, Iterable
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
|
||||
def load_weights_checkpoint(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
model.load_weights(state_iter) # type: ignore
|
||||
def load_weights_checkpoint_layerwise(
|
||||
model: Module,
|
||||
state_iter: Iterable[tuple[str, torch.Tensor]],
|
||||
model_config,
|
||||
vllm_config,
|
||||
) -> None:
|
||||
logger.info("Reloading checkpoint-format weights with vLLM layerwise processing")
|
||||
device = next(model.parameters()).device
|
||||
with torch.device(device), set_current_vllm_config(vllm_config):
|
||||
initialize_layerwise_reload(model)
|
||||
model.load_weights(state_iter) # type: ignore
|
||||
finalize_layerwise_reload(model, model_config)
|
||||
|
||||
|
||||
def postprocess_weights_checkpoint(model: Module, model_config, device: torch.device) -> None:
|
||||
process_weights_after_loading(model, model_config, device)
|
||||
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
|
||||
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
|
||||
physical_to_logical = torch.full(
|
||||
(num_physical_experts,),
|
||||
-1,
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)
|
||||
logical_indices = torch.arange(
|
||||
logical_to_physical_map.shape[0],
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)[:, None].expand_as(logical_to_physical_map)
|
||||
physical_indices = logical_to_physical_map.to(torch.long)
|
||||
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
|
||||
if invalid.any():
|
||||
invalid_indices = physical_indices[invalid].unique().tolist()
|
||||
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
|
||||
|
||||
valid = physical_indices >= 0
|
||||
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
|
||||
|
||||
return logical_indices.to(physical_indices.device)
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to global expert indices local to this worker."""
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
|
||||
expert_slices: dict[str, torch.Tensor] = {}
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
continue
|
||||
if module._expert_map is None:
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
if source_indices is None:
|
||||
continue
|
||||
|
||||
global_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[global_indices]
|
||||
global_indices = global_indices[local_indices.argsort()]
|
||||
expert_slices[module_name] = global_indices
|
||||
return expert_slices
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
return source_indices_by_module
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
|
||||
params = dict(model.named_parameters())
|
||||
expert_slices = build_expert_map(model)
|
||||
expert_source_indices = build_expert_map(model)
|
||||
|
||||
loaded = 0
|
||||
skipped: list[str] = []
|
||||
@@ -51,15 +101,13 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
|
||||
param = params[name]
|
||||
if param.shape != tensor.shape:
|
||||
sliced = False
|
||||
for module_name, global_indices in expert_slices.items():
|
||||
for module_name, source_indices in expert_source_indices.items():
|
||||
if not name.startswith(f"{module_name}."):
|
||||
continue
|
||||
tensor = tensor[global_indices.to(tensor.device)]
|
||||
sliced = True
|
||||
tensor = tensor[source_indices.to(tensor.device)]
|
||||
break
|
||||
|
||||
if not sliced or param.shape != tensor.shape:
|
||||
if param.shape != tensor.shape:
|
||||
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
|
||||
continue
|
||||
|
||||
@@ -102,7 +150,3 @@ def update_mla_absorbed_weights(model: Module) -> None:
|
||||
module.W_UK_T.copy_(w_uk.permute(1, 2, 0))
|
||||
|
||||
logger.debug(f"Updated MLA absorbed weights for module {name}")
|
||||
|
||||
|
||||
def postprocess_weights_kernel(model: Module, _model_config, _device: torch.device) -> None:
|
||||
update_mla_absorbed_weights(model)
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Literal
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns, get_tool_response_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
LengthPenalty = Literal["tokens", "turns"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
@@ -42,18 +46,27 @@ Expected signature:
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenalty | None = None,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
"""Default GRPO advantage: reward minus per-problem baseline.
|
||||
|
||||
if length_penalty == "tokens":
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
"""
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts], dtype=torch.float32)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[[get_model_completion_len(r) for r in group] for group in inputs.rollouts],
|
||||
[
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in group]
|
||||
for group in inputs.rollouts
|
||||
],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
if length_penalty == "turns":
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor(
|
||||
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
@@ -88,8 +101,12 @@ def _efficiency_shaping(
|
||||
correct_costs = costs * correct_mask
|
||||
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
has_cost = mean_correct_cost > 0
|
||||
safe_mean = torch.where(has_cost, mean_correct_cost, torch.ones_like(mean_correct_cost))
|
||||
bonus = (1 - costs / safe_mean).clamp(0, 1) * has_cost
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
@@ -112,10 +129,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
)
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user