Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
229391fa27 | ||
|
|
1e9a3e9196 | ||
|
|
3b01ce9d48 | ||
|
|
38b524925d | ||
|
|
d62c7539e4 | ||
|
|
edf41113fe | ||
|
|
bcac552c3f | ||
|
|
f7a27f69dd | ||
|
|
31591b7fe8 | ||
|
|
0deb4abaa9 | ||
|
|
4be61bbd68 | ||
|
|
0660a9b3cb | ||
|
|
2ff21d97e7 | ||
|
|
5e6f7ebae8 | ||
|
|
7d7bd92333 | ||
|
|
d8d214cbab | ||
|
|
a50b4079de | ||
|
|
0403c097a2 | ||
|
|
0b8c35e9b3 | ||
|
|
ca5e02c24c | ||
|
|
c37e2ca71b | ||
|
|
b1e9c7bdd2 | ||
|
|
af17a555fe | ||
|
|
a87badd65f | ||
|
|
5061b8d88e | ||
|
|
a8575d6f1c | ||
|
|
e75d8ca47f | ||
|
|
daedc1dbc6 | ||
|
|
3719abcfbb | ||
|
|
93cbc75b81 | ||
|
|
4e4390be87 | ||
|
|
8457b601d6 | ||
|
|
273524e2fc | ||
|
|
d2f36c9f65 | ||
|
|
2566de0bd5 | ||
|
|
0fca0d15c5 | ||
|
|
24a2af0054 | ||
|
|
8342ccd0c8 | ||
|
|
20454ecd7b | ||
|
|
4a42aa039e | ||
|
|
b0a7cad8a8 | ||
|
|
f1bbdf924e | ||
|
|
9bbed30eba | ||
|
|
a6a6441a3b | ||
|
|
e8abfa264b | ||
|
|
c3a24c35e2 | ||
|
|
d2718f5f65 | ||
|
|
d49f3939e7 | ||
|
|
9eeffdb6fb | ||
|
|
03689b8ac0 | ||
|
|
f29e947585 | ||
|
|
bb7449c829 | ||
|
|
82fa41f4f2 | ||
|
|
1ade129004 | ||
|
|
26ea8df85e | ||
|
|
d4bddbaed7 | ||
|
|
6bf14b80f8 | ||
|
|
586e0f8e5d | ||
|
|
18e895651e | ||
|
|
2c54d5c834 | ||
|
|
3a6b46189a | ||
|
|
ba86b9ba88 | ||
|
|
2d659eecc7 | ||
|
|
56cdd2c579 | ||
|
|
4dcf86f0ea | ||
|
|
ad3134ac03 | ||
|
|
8c5aa67aa5 | ||
|
|
fde3006470 | ||
|
|
67783e4a6c |
@@ -38,3 +38,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
|
||||
|
||||
@@ -57,7 +57,10 @@ jobs:
|
||||
runs-on: research-cluster
|
||||
container:
|
||||
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
|
||||
options: --gpus all
|
||||
# --shm-size: vLLM V1's DP engine/API-server IPC uses POSIX shm-backed
|
||||
# MessageQueue (~160MB per queue); Docker's default 64MB /dev/shm triggers
|
||||
# SIGBUS in DP engine cores on VLM runs (mm data overflows tmpfs).
|
||||
options: --gpus all --shm-size=16g
|
||||
timeout-minutes: 1440 # 24 hours
|
||||
strategy:
|
||||
fail-fast: false
|
||||
|
||||
@@ -32,6 +32,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -43,6 +44,9 @@ You are responsible for maintaining the skills folder. When a workflow fails and
|
||||
|
||||
Write tests as plain functions with pytest fixtures. Don't use class-based tests.
|
||||
|
||||
- **Conservative test additions**: don't add new tests unless the user explicitly asks for them or it's clearly necessary. Editing existing tests is fine, but adding new test files or test functions should be the exception, not the default.
|
||||
- **Test what matters**: only test code with clear, isolated logic — pure functions, abstract base classes, data transformations, well-defined algorithms. Don't test runtime-level code, framework glue, or anything that requires extensive mocking/patching just to get a test to pass. If you need to patch everything out to make it testable, it's probably not worth testing.
|
||||
|
||||
## Git
|
||||
|
||||
- **Branch prefixes**: use the following prefixes for branches: `feat/`, `fix/`, `chore/`
|
||||
@@ -51,4 +55,5 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
|
||||
|
||||
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
|
||||
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
|
||||
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
|
||||
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
|
||||
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
|
||||
|
||||
+2
-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,7 @@ 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 configs /app/configs
|
||||
COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
@@ -19,11 +19,11 @@ name = "stage1"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -20,11 +20,11 @@ name = "stage2"
|
||||
batch_size = 2048
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 16384
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
@@ -13,10 +13,10 @@ lr = 1e-5
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 384
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
@@ -18,10 +18,10 @@ lr = 1e-5
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 1024
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
@@ -14,10 +14,10 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
@@ -13,10 +13,10 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
@@ -23,10 +23,10 @@ rollouts_per_example = 16
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -22,10 +22,10 @@ rollouts_per_example = 16
|
||||
[orchestrator.model.lora]
|
||||
name = "r8-1e-4"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -13,10 +13,10 @@ lr = 3e-6
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -11,10 +11,10 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
[optim]
|
||||
lr = 3e-5
|
||||
|
||||
[sampling]
|
||||
max_tokens = 128
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[env]]
|
||||
[[train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[ckpt]
|
||||
|
||||
@@ -17,11 +17,11 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -17,10 +17,10 @@ language_model_attr = "model.language_model"
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
|
||||
@@ -2,6 +2,6 @@ max_steps = 5
|
||||
max_async_level = 5
|
||||
batch_size = 16
|
||||
|
||||
[sampling]
|
||||
max_tokens = 16
|
||||
[train.sampling]
|
||||
max_completion_tokens = 16
|
||||
|
||||
|
||||
@@ -19,11 +19,11 @@ interval = 100
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 8192
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -20,11 +20,11 @@ resume_step = 500
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 16384
|
||||
max_completion_tokens = 16384
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -20,11 +20,11 @@ resume_step = 1000
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 0.6
|
||||
max_tokens = 24576
|
||||
max_completion_tokens = 24576
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "deepscaler"
|
||||
args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset = "default", question_key = "problem", answer_key = "solution", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -32,15 +32,15 @@ lr = 1e-5
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[orchestrator.client.elastic]
|
||||
hostname = "localhost"
|
||||
port = 8000
|
||||
sync_interval = 5.0
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
@@ -16,27 +16,27 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
args = { min_avg_reward = 0.1, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "science-env"
|
||||
name = "science"
|
||||
args = { min_avg_reward = 0.1, pool_size = 128, rubric_max_workers = 128 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
args = { min_avg_reward = 0.1 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math-python"
|
||||
args = { min_avg_reward = 0.1, sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy", python_tool = true, rubric_max_workers = 128 }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "PrimeIntellect/Qwen3-0.6B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -28,7 +28,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
@@ -12,7 +12,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
@@ -11,13 +11,13 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 256
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
ratio = 0.5
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "acereason-math"
|
||||
args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", question_key = "problem" }
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-python"
|
||||
args = { sandbox_client_max_workers = 128, sandbox_timeout_minutes = 10, sandbox_memory_gb = 1, sandbox_disk_size_gb = 1, pip_install_packages = "numpy sympy" }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
|
||||
@@ -13,10 +13,10 @@ language_model_attr = "model.language_model"
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 32
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 2, num_examples = 100, seed = 42 }
|
||||
|
||||
|
||||
@@ -48,10 +48,10 @@ max_inflight_activations = 5
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -64,7 +64,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 2048
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
@@ -47,10 +47,10 @@ freq = 1
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 4096
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
@@ -63,7 +63,7 @@ hard_threshold = 0.0
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_tokens = 4096
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math500"
|
||||
|
||||
@@ -30,13 +30,13 @@ batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "wiki-search"
|
||||
|
||||
[inference.model]
|
||||
|
||||
@@ -86,10 +86,12 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
rewards: Float[Tensor, "num_examples rollouts_per_example"]
|
||||
completion_lengths: Int[Tensor, "num_examples rollouts_per_example"]
|
||||
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
```
|
||||
|
||||
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
|
||||
|
||||
#### AdvantageOutputs
|
||||
|
||||
```python
|
||||
@@ -106,9 +108,10 @@ from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
"""Normalize advantages to zero mean and unit variance per example."""
|
||||
mean = inputs.rewards.mean(dim=1, keepdim=True)
|
||||
std = inputs.rewards.std(dim=1, keepdim=True)
|
||||
advantages = (inputs.rewards - mean) / (std + eps)
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
mean = rewards.mean(dim=1, keepdim=True)
|
||||
std = rewards.std(dim=1, keepdim=True)
|
||||
advantages = (rewards - mean) / (std + eps)
|
||||
return AdvantageOutputs(advantages=advantages)
|
||||
```
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ The eviction takes effect through two mechanisms:
|
||||
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
|
||||
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
|
||||
- This surfaces the eviction reason to the user
|
||||
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
|
||||
|
||||
## LoRA Module Registration
|
||||
|
||||
|
||||
@@ -47,31 +47,31 @@ weight_decay = 0.01
|
||||
batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "deepdive"
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
|
||||
@@ -28,10 +28,10 @@ lr = 1e-5
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
|
||||
@@ -19,9 +19,6 @@ name = "qwen3-4b-hard-distill"
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
@@ -33,9 +30,10 @@ save_adapter_separately = true
|
||||
batch_size = 256
|
||||
rollouts_per_example = 4
|
||||
use_token_client = false
|
||||
use_sft_loss = true
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
temperature = 0.7
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
@@ -45,7 +43,7 @@ api_key_var = "PRIME_API_KEY"
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "qwen/qwen3-235b-a22b-instruct-2507"
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
@@ -16,7 +16,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
batch_size = 512
|
||||
rollouts_per_example = 8
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env" # included in lock file
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
|
||||
@@ -49,7 +49,7 @@ oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
@@ -38,10 +38,10 @@ freq = 1
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B Math
|
||||
# Qwen 3 30B - A3B Math
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on math tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -45,10 +45,10 @@ batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 32768
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B SWE
|
||||
# Qwen 3 30B - A3B SWE
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on agentic SWE tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe"
|
||||
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
|
||||
|
||||
@@ -12,10 +12,10 @@ name = "reverse-text"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
|
||||
@@ -37,13 +37,13 @@ oversampling_factor = 2.0
|
||||
[orchestrator.model.lora]
|
||||
name = "qwen3-4b-wiki-search"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 512
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[orchestrator.buffer]
|
||||
online_difficulty_filtering = true
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
@@ -18,12 +18,12 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 1024
|
||||
rollouts_per_example = 16
|
||||
|
||||
[[orchestrator.env]]
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 1024
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -207,7 +207,7 @@ spec:
|
||||
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
path: /liveness
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
|
||||
|
||||
@@ -75,7 +75,7 @@ inference:
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for inference server (requires /health endpoint)
|
||||
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows long model loading time (up to 45 min by default)
|
||||
@@ -86,7 +86,7 @@ inference:
|
||||
liveness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 60
|
||||
timeoutSeconds: 10
|
||||
readiness:
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# prime-rl-configs
|
||||
|
||||
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
|
||||
|
||||
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
pip install git+https://github.com/PrimeIntellect-ai/prime-rl.git#subdirectory=packages/prime-rl-configs
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
The pip *distribution name* (`prime-rl-configs`) and the *import path* (`prime_rl.configs.*`) are different on purpose: this package contributes submodules to the shared `prime_rl` namespace.
|
||||
|
||||
```python
|
||||
from pydantic_config import cli
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
|
||||
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
|
||||
```
|
||||
|
||||
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
|
||||
|
||||
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
|
||||
@@ -0,0 +1,25 @@
|
||||
[project]
|
||||
name = "prime-rl-configs"
|
||||
version = "0.4.0"
|
||||
description = "Slim config schema for prime-rl (no GPU/ML deps)."
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
# The PyPI package named `pydantic-config` is a different project that
|
||||
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
|
||||
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
|
||||
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
+1
@@ -13,6 +13,7 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
log: LogConfig = LogConfig()
|
||||
env_install_prerelease: bool = False
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
+5
-15
@@ -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
|
||||
|
||||
@@ -85,7 +85,7 @@ class ModelConfig(BaseModelConfig):
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
] = "auto"
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
@@ -247,15 +247,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for inference."""
|
||||
|
||||
reset_prefix_cache_after_update: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to reset the prefix cache after weight updates (update_weights, load_lora_adapter). "
|
||||
"Ensures all KV states are recomputed with the new weights at the cost of extra prefill. "
|
||||
"When False, prefer using orchestrator.experimental.use_prefix_cache_salt to invalidate stale caches via salt instead.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
@@ -459,10 +450,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")
|
||||
+163
-28
@@ -1,4 +1,5 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
@@ -11,12 +12,12 @@ from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
RendererConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class OptimizerConfig(BaseConfig):
|
||||
@@ -148,9 +149,11 @@ class TrainSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -247,9 +250,11 @@ class EvalSamplingConfig(BaseConfig):
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
@@ -324,6 +329,14 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
] = -1
|
||||
|
||||
timeout: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
validation_alias=AliasChoices("timeout", "timeout_seconds"),
|
||||
description="Per-rollout wall-clock timeout in seconds. Set to None (default) to disable.",
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
@@ -346,6 +359,12 @@ class EnvConfig(BaseConfig):
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_timeout(self):
|
||||
if self.timeout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
"""Configures a training environment."""
|
||||
@@ -676,16 +695,18 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_shaping: Annotated[
|
||||
bool,
|
||||
length_penalty: Annotated[
|
||||
Literal["tokens", "turns"] | None,
|
||||
Field(
|
||||
description=(
|
||||
"Enable correctness-gated length shaping. In mixed groups, shorter correct rollouts get "
|
||||
"amplified advantage (up to 2x), longer correct rollouts are unchanged, incorrect untouched. "
|
||||
"In all-correct groups, below-average-length rollouts get advantage in [0, 1], others get 0."
|
||||
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
|
||||
"count, `turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct "
|
||||
"rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost "
|
||||
"rollouts get advantage in [0, 1], others get 0."
|
||||
)
|
||||
),
|
||||
] = False
|
||||
] = None
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -715,7 +736,7 @@ class GibberishFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
token_id_threshold: Annotated[
|
||||
@@ -739,7 +760,7 @@ class RepetitionFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
window: Annotated[
|
||||
@@ -765,7 +786,7 @@ class ZeroAdvantageFilterConfig(BaseModel):
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = True
|
||||
|
||||
@@ -812,15 +833,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the orchestrator."""
|
||||
|
||||
use_prefix_cache_salt: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to set a cache_salt on inference requests that changes with each weight update. "
|
||||
"This invalidates prefix-cached KV states from previous policies without resetting the entire cache, "
|
||||
"while preserving cache hits for in-flight off-policy rollouts.",
|
||||
),
|
||||
] = True
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
|
||||
@@ -865,6 +877,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
# The optimizer configuration (per-run LR for multi-run training)
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
|
||||
@@ -889,6 +904,17 @@ class OrchestratorConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
# When True, trainer uses SFT loss instead of RL loss (per-run override for hosted multi-tenant training)
|
||||
use_sft_loss: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"When True, use SFT masked NLL loss instead of the trainer's configured RL loss. "
|
||||
"Requires a teacher_rollout_model to be configured."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
|
||||
# The evaluation configuration
|
||||
eval: EvalConfig | None = None
|
||||
|
||||
@@ -1041,10 +1067,31 @@ class OrchestratorConfig(BaseConfig):
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. "
|
||||
"WARNING: Only use this if your environment has a linear history and the chat template has the extension "
|
||||
"property (i.e. no tokens are ever removed or inserted by the chat template). Mutually exclusive with "
|
||||
"``use_renderer``."
|
||||
),
|
||||
] = True
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the renderer client (client-side tokenization via the ``renderers`` package, "
|
||||
"served by ``/v1/generate``). Mutually exclusive with ``use_token_client``. When True, the "
|
||||
"``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) "
|
||||
"applies; when False those fields must be left at their defaults. Not supported for VLMs — "
|
||||
"VLMs must use the token client (TITO) so image preprocessing and chat templating stay server-side."
|
||||
),
|
||||
] = False
|
||||
|
||||
env_install_prerelease: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Allow pre-release versions when installing environments (e.g. verifiers>=0.1.12.dev5). Passes --prerelease to prime env install."
|
||||
),
|
||||
] = False
|
||||
|
||||
experimental: Annotated[
|
||||
OrchestratorExperimentalConfig,
|
||||
Field(description="Experimental features for the orchestrator."),
|
||||
@@ -1060,15 +1107,19 @@ class OrchestratorConfig(BaseConfig):
|
||||
train = data.setdefault("train", {})
|
||||
if isinstance(train, dict):
|
||||
if "env" in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("env", data.pop("env"))
|
||||
if "sampling" in data:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release."
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("sampling", data.pop("sampling"))
|
||||
return data
|
||||
@@ -1088,6 +1139,90 @@ class OrchestratorConfig(BaseConfig):
|
||||
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_sft_distill_mode(self):
|
||||
"""Enforce the SFT hard distill invariants that involve only orchestrator fields.
|
||||
|
||||
Runs at ``OrchestratorConfig`` level so hosted deployments (which load this
|
||||
config standalone via the ``orchestrator`` entrypoint) get the same guarantees
|
||||
as the combined ``rl`` entrypoint.
|
||||
"""
|
||||
has_teacher = self.teacher_rollout_model is not None
|
||||
if self.use_sft_loss and not has_teacher:
|
||||
raise ValueError(
|
||||
"orchestrator.use_sft_loss = true requires orchestrator.teacher_rollout_model to be configured."
|
||||
)
|
||||
if has_teacher and not self.use_sft_loss:
|
||||
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
|
||||
if has_teacher and self.use_token_client:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
if has_teacher and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
|
||||
"(external rollout uses MITO)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_client_mode(self):
|
||||
"""The two client toggles select among three exclusive modes:
|
||||
|
||||
- ``use_token_client=True`` + ``use_renderer=False`` → TITO (default)
|
||||
- ``use_token_client=False`` + ``use_renderer=True`` → renderer
|
||||
- ``use_token_client=False`` + ``use_renderer=False`` → MITO
|
||||
|
||||
Both True is invalid: TITO and renderer are different wire protocols
|
||||
(server-side templating vs client-side tokenization).
|
||||
"""
|
||||
if self.use_token_client and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client and orchestrator.use_renderer are mutually exclusive. "
|
||||
"Pick one: token client (TITO, server-side templating) or renderer client (client-side "
|
||||
"tokenization)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
"""The renderer client takes plain message dicts and tokenizes
|
||||
them client-side. VLMs need server-side image preprocessing and
|
||||
chat templating, so they must use the token client (TITO) — fail
|
||||
loudly when both are set."""
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer is not supported for VLMs. Use the token client "
|
||||
"(``use_token_client=true``, the default) so image preprocessing and chat "
|
||||
"templating stay on the inference server."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
"""``[orchestrator.renderer]`` knobs are only meaningful when
|
||||
``use_renderer=True``. Reject otherwise so callers don't silently
|
||||
pass them and wonder why they're ignored."""
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
if self.renderer.pool_size is not None:
|
||||
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without orchestrator.use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def nccl_max_async_level(self):
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
@@ -1,3 +1,4 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
@@ -38,8 +39,7 @@ from prime_rl.configs.trainer import (
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
@@ -77,8 +77,14 @@ class SharedWandbConfig(BaseConfig):
|
||||
|
||||
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
|
||||
|
||||
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
|
||||
|
||||
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
|
||||
|
||||
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
|
||||
|
||||
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
shared: Annotated[
|
||||
@@ -428,24 +434,18 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_external_rollout_mode(self):
|
||||
if self.orchestrator.teacher_rollout_model is None:
|
||||
return self
|
||||
def validate_external_rollout_inference(self):
|
||||
"""Forbid configuring a local inference server when rollouts come from an external teacher.
|
||||
|
||||
if self.trainer.loss.type != "sft":
|
||||
raise ValueError('orchestrator.teacher_rollout_model is only supported when trainer.loss.type = "sft".')
|
||||
|
||||
if self.inference is not None:
|
||||
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
|
||||
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
|
||||
orchestrator entrypoint also enforces them.
|
||||
"""
|
||||
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
|
||||
raise ValueError(
|
||||
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
|
||||
"External rollout mode does not use the local inference server."
|
||||
)
|
||||
|
||||
if self.orchestrator.use_token_client:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
@@ -522,6 +522,10 @@ class RLConfig(BaseConfig):
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
if self.wandb.entity:
|
||||
self.trainer.wandb.entity = self.wandb.entity
|
||||
self.orchestrator.wandb.entity = self.wandb.entity
|
||||
|
||||
if self.wandb.shared:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = self.wandb.name
|
||||
@@ -531,6 +535,14 @@ class RLConfig(BaseConfig):
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
if self.wandb.group:
|
||||
self.trainer.wandb.group = self.wandb.group
|
||||
self.orchestrator.wandb.group = self.wandb.group
|
||||
|
||||
if self.wandb.tags:
|
||||
self.trainer.wandb.tags = self.wandb.tags.copy()
|
||||
self.orchestrator.wandb.tags = self.wandb.tags.copy()
|
||||
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
@@ -733,18 +745,18 @@ class RLConfig(BaseConfig):
|
||||
self.inference.enable_lora = True
|
||||
self.inference.max_lora_rank = self.trainer.model.lora.rank
|
||||
else:
|
||||
get_logger().warning(
|
||||
warnings.warn(
|
||||
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
|
||||
"make sure to set --enable_lora and --max-lora-rank."
|
||||
"make sure to set --enable_lora and --max-lora-rank.",
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
|
||||
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -752,13 +764,15 @@ class RLConfig(BaseConfig):
|
||||
if self.trainer.enable_router_replay:
|
||||
if self.inference is not None:
|
||||
if self.inference.enable_return_routed_experts is False:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True."
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
|
||||
stacklevel=2,
|
||||
)
|
||||
self.inference.enable_return_routed_experts = True
|
||||
else:
|
||||
get_logger().warning(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server."
|
||||
warnings.warn(
|
||||
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
|
||||
stacklevel=2,
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -946,13 +960,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
|
||||
@@ -21,7 +21,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):
|
||||
@@ -425,11 +425,10 @@ class SFTConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_template(self):
|
||||
if self.slurm is not None and self.slurm.template_path is None:
|
||||
import prime_rl
|
||||
|
||||
templates_dir = Path(prime_rl.__file__).parent / "templates"
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
templates_dir = find_package_resource("templates")
|
||||
if templates_dir is not None:
|
||||
if self.deployment.type == "single_node":
|
||||
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
|
||||
else:
|
||||
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
|
||||
return self
|
||||
+84
@@ -132,6 +132,61 @@ class BaseModelConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
"""Configures the client-side renderer (chat-template + response parsing).
|
||||
|
||||
Only consumed when ``orchestrator.use_renderer = true``. The renderer
|
||||
owns both directions: render messages → token ids on the client, and
|
||||
parse model output tokens → structured ``content`` / ``reasoning_content``
|
||||
/ ``tool_calls``.
|
||||
"""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description=(
|
||||
"Renderer to use for chat template tokenization. "
|
||||
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
|
||||
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
|
||||
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
tool_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a tool parser in renderers.parsers. Only consumed by "
|
||||
"DefaultRenderer (model-specific renderers bake their own parsing "
|
||||
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a reasoning parser in renderers.parsers. Only consumed "
|
||||
"by DefaultRenderer. Options today: 'think'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
pool_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of renderer slots shared across concurrent rollouts. "
|
||||
"None keeps the verifiers default (1). Bump for long multi-turn "
|
||||
"prompts where client-side jinja tokenization serializes."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
|
||||
@@ -184,6 +239,14 @@ class ClientConfig(BaseConfig):
|
||||
),
|
||||
] = 30.0
|
||||
|
||||
wait_for_ready_timeout: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
|
||||
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
|
||||
),
|
||||
] = 1800
|
||||
|
||||
base_url: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
@@ -354,6 +417,13 @@ class WandbConfig(BaseConfig):
|
||||
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
|
||||
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
|
||||
|
||||
entity: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B entity to log to.",
|
||||
),
|
||||
] = None
|
||||
|
||||
name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
@@ -361,6 +431,20 @@ class WandbConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
group: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B group to use for logging.",
|
||||
),
|
||||
] = None
|
||||
|
||||
tags: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="The W&B tags to attach to the run.",
|
||||
),
|
||||
] = None
|
||||
|
||||
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
|
||||
+36
-7
@@ -139,7 +139,13 @@ class LoRAConfig(BaseConfig):
|
||||
target_modules: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
description="Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') match any component in the module path. Regex patterns match anywhere in the name.",
|
||||
description=(
|
||||
"Module names or regex patterns for modules to apply LoRA to. Simple names (e.g., 'q_proj') "
|
||||
"match any component in the module path. Regex patterns match anywhere in the name. "
|
||||
"Names unknown to the current model are silently ignored, so defaults cover multiple architectures. "
|
||||
"NemotronH note: 'experts' matches NonGatedGroupedExperts inside LatentMoE; 'fc1_latent_proj' and "
|
||||
"'fc2_latent_proj' adapt the latent up/down projections. Add 'in_proj'/'out_proj' to also LoRA Mamba."
|
||||
),
|
||||
),
|
||||
] = [
|
||||
"q_proj",
|
||||
@@ -150,6 +156,8 @@ class LoRAConfig(BaseConfig):
|
||||
"up_proj",
|
||||
"down_proj",
|
||||
"experts",
|
||||
"fc1_latent_proj",
|
||||
"fc2_latent_proj",
|
||||
]
|
||||
|
||||
modules_to_save: Annotated[
|
||||
@@ -175,6 +183,13 @@ class DebugModelConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
force_balanced_routing: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, override MoE token-choice routing with a round-robin assignment so every expert receives an equal share of tokens. Intended for fake-data smoke tests where untrained routing would otherwise produce severe expert imbalance and OOM. Gating scores are still gathered from the override indices so the forward pass stays consistent.",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the model for training."""
|
||||
@@ -184,7 +199,7 @@ class ModelConfig(BaseModelConfig):
|
||||
attn: Annotated[
|
||||
AttnImplementation,
|
||||
Field(
|
||||
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3).",
|
||||
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3, FA4 for fa4).",
|
||||
),
|
||||
] = "flash_attention_2"
|
||||
|
||||
@@ -315,6 +330,14 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
fp8: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use FP8 training via DeepGEMM. Replaces nn.Linear layers with FP8 blockwise linear "
|
||||
"and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and model.impl='custom'.",
|
||||
),
|
||||
] = False
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -368,12 +391,12 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def cp_only_with_flash_attn(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3"]:
|
||||
raise ValueError("CP is only supported with flash attention 2 or flash attention 3")
|
||||
if self.cp > 1 and self.attn == "flash_attention_3" and self.impl != "custom":
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
|
||||
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
|
||||
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
|
||||
raise ValueError(
|
||||
"CP with flash_attention_3 requires model.impl='custom' "
|
||||
"(the FA3 ring-attention kernel is only implemented for the custom model path)"
|
||||
f"CP with {self.attn} requires model.impl='custom' "
|
||||
"(the ring-attention kernel is only implemented for the custom model path)"
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -402,6 +425,12 @@ class ModelConfig(BaseModelConfig):
|
||||
raise ValueError("Flash attention 4 is only supported with the custom implementation")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fp8_only_with_custom_impl(self):
|
||||
if self.fp8 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
@@ -0,0 +1,56 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def find_package_resource(subdir: str) -> Path | None:
|
||||
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
|
||||
|
||||
Returns None if `subdir` is not present in any wheel — e.g. on a slim
|
||||
`prime-rl-configs`-only install where `prime-rl`'s shipped resources
|
||||
(templates, etc.) are absent.
|
||||
"""
|
||||
import prime_rl
|
||||
|
||||
for p in prime_rl.__path__:
|
||||
candidate = Path(p) / subdir
|
||||
if candidate.is_dir():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def rgetattr(obj: Any, attr_path: str) -> Any:
|
||||
"""Recursive getattr for dotted paths: rgetattr(cfg, "trainer.model.name")."""
|
||||
current = obj
|
||||
for attr in attr_path.split("."):
|
||||
if not hasattr(current, attr):
|
||||
raise AttributeError(f"'{type(current).__name__}' object has no attribute '{attr}'")
|
||||
current = getattr(current, attr)
|
||||
return current
|
||||
|
||||
|
||||
def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
|
||||
"""Recursive setattr for dotted paths: rsetattr(cfg, "trainer.model.name", "foo")."""
|
||||
if "." not in attr_path:
|
||||
return setattr(obj, attr_path, value)
|
||||
parent_path, attr = attr_path.rsplit(".", 1)
|
||||
setattr(rgetattr(obj, parent_path), attr, value)
|
||||
|
||||
|
||||
def get_all_fields(model: BaseModel | type) -> list[str]:
|
||||
if isinstance(model, BaseModel):
|
||||
model_cls = model.__class__
|
||||
else:
|
||||
model_cls = model
|
||||
|
||||
fields = []
|
||||
for name, field in model_cls.model_fields.items():
|
||||
field_type = field.annotation
|
||||
fields.append(name)
|
||||
if field_type is not None and hasattr(field_type, "model_fields"):
|
||||
sub_fields = get_all_fields(field_type)
|
||||
fields.extend(f"{name}.{sub}" for sub in sub_fields)
|
||||
return fields
|
||||
+66
-14
@@ -5,24 +5,23 @@ description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"prime-rl-configs",
|
||||
"beartype>=0.21.0",
|
||||
"datasets>=4.0.0",
|
||||
"jaxtyping>=0.3.2",
|
||||
"liger-kernel>=0.5.10",
|
||||
"loguru>=0.7.3",
|
||||
"pyarrow>=21.0.0",
|
||||
"pydantic>=1.10.13",
|
||||
"pydantic-config",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"numpy>=2.2.6",
|
||||
"torch>=2.9.0",
|
||||
"torchvision",
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.19.0",
|
||||
"wandb>=0.24.2",
|
||||
"vllm>=0.20.1",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.37",
|
||||
"prime>=0.5.73",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -51,7 +50,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"]
|
||||
|
||||
@@ -91,6 +90,8 @@ all = [
|
||||
"prime-rl[flash-attn]",
|
||||
"prime-rl[disagg]",
|
||||
"prime-rl[quack]",
|
||||
"prime-rl[flash-attn-3]",
|
||||
"prime-rl[flash-attn-cute]",
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
@@ -106,7 +107,11 @@ dev = [
|
||||
]
|
||||
|
||||
|
||||
[tool.uv.workspace]
|
||||
members = ["packages/*"]
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
@@ -121,15 +126,51 @@ override-dependencies = [
|
||||
"transformers>=5.1.0.dev0",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { workspace = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0760204" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "abd9943b" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
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" }
|
||||
@@ -144,9 +185,11 @@ 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" }
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
|
||||
# DeepGEMM bumped from 477618c to d30fc36 (newer kernel APIs needed by the
|
||||
# FP8 grouped-GEMM training path). Rebuild via scripts/install_deep_gemm.sh.
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-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" }
|
||||
|
||||
@@ -178,6 +221,12 @@ 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
|
||||
|
||||
@@ -192,5 +241,8 @@ markers = [
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/prime_rl"]
|
||||
|
||||
[tool.hatch.metadata]
|
||||
allow-direct-references = true
|
||||
|
||||
@@ -14,7 +14,7 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
"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 ==="
|
||||
|
||||
@@ -4,5 +4,13 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
|
||||
fi
|
||||
|
||||
# Execute the main command
|
||||
exec "$@"
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
set -e
|
||||
|
||||
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
|
||||
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
uv pip install --reinstall --no-deps "flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# Verify installation
|
||||
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
|
||||
|
||||
+86
-54
@@ -4,86 +4,118 @@ 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
|
||||
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
|
||||
log_info "Installing uv..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
log_info "Sourcing uv environment..."
|
||||
if ! command -v uv &>/dev/null; then
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
|
||||
log_info "Installing pre-commit hooks..."
|
||||
uv run pre-commit install
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
|
||||
log_info "Installation completed!"
|
||||
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
|
||||
|
||||
@@ -153,6 +153,10 @@ uv run sft --data.type fake --data.batch-size 4
|
||||
|
||||
If you wish to configure values of the default variant, you don't need to set the `type` field.
|
||||
|
||||
### SFT hard distill override
|
||||
|
||||
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
|
||||
|
||||
### Model fields
|
||||
|
||||
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported
|
||||
+48
-14
@@ -1,21 +1,55 @@
|
||||
"""Compatibility shim: ring_flash_attn + transformers >= 5.4.
|
||||
"""Compatibility shims for upstream regressions.
|
||||
|
||||
ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
|
||||
`transformers.modeling_flash_attention_utils`. This symbol was removed from
|
||||
that module in transformers 5.4 (still available as a deprecated function
|
||||
in `transformers.utils.import_utils`, scheduled for removal in 5.8).
|
||||
|
||||
ring_flash_attn's except-branch is a no-op (imports the same symbol again),
|
||||
so the import crashes on transformers >= 5.4. We patch the symbol back in as
|
||||
`True` — the check is dead code since no one uses flash_attn < 2.1.0 anymore.
|
||||
|
||||
Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
|
||||
Remove this shim once ring_flash_attn ships a fixed version.
|
||||
Imported early (before any model code) by trainer and orchestrator entrypoints.
|
||||
Each shim documents the upstream issue and removal condition.
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ring_flash_attn + transformers >= 5.4
|
||||
#
|
||||
# ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
|
||||
# `transformers.modeling_flash_attention_utils`, removed in transformers 5.4.
|
||||
#
|
||||
# Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
|
||||
# Remove once ring_flash_attn ships a fixed version.
|
||||
# ---------------------------------------------------------------------------
|
||||
import transformers.modeling_flash_attention_utils as _mfau
|
||||
|
||||
if not hasattr(_mfau, "is_flash_attn_greater_or_equal_2_10"):
|
||||
# ring_flash_attn uses this as a bare value (if x:), but other code may
|
||||
# call it as a function (if x():). Use a callable that is also truthy.
|
||||
_mfau.is_flash_attn_greater_or_equal_2_10 = lambda: True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# transformers >= 5.5 hub_kernels offline regression
|
||||
#
|
||||
# lazy_load_kernel() resolves kernel versions via HfApi().list_repo_refs(),
|
||||
# which raises OfflineModeIsEnabled when HF_HUB_OFFLINE=1 — even if the
|
||||
# kernel is already cached locally. Only FileNotFoundError and AssertionError
|
||||
# are caught; OfflineModeIsEnabled (a ConnectionError subclass) is not.
|
||||
#
|
||||
# This breaks Mamba-based models (NemotronH, Zamba2, Jamba, etc.) on SLURM
|
||||
# worker nodes where HF_HUB_OFFLINE=1 is set.
|
||||
#
|
||||
# Fix: patch the except clause to also catch ConnectionError.
|
||||
# Remove once huggingface/transformers fixes lazy_load_kernel offline handling.
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import transformers.integrations.hub_kernels as _hub_kernels
|
||||
except ImportError:
|
||||
_hub_kernels = None # transformers < 5.5, no patch needed
|
||||
|
||||
if _hub_kernels is not None:
|
||||
from huggingface_hub.errors import OfflineModeIsEnabled
|
||||
|
||||
_original_lazy_load_kernel = _hub_kernels.lazy_load_kernel
|
||||
|
||||
def _patched_lazy_load_kernel(kernel_name, mapping=_hub_kernels._KERNEL_MODULE_MAPPING):
|
||||
try:
|
||||
return _original_lazy_load_kernel(kernel_name, mapping)
|
||||
except OfflineModeIsEnabled:
|
||||
# Return None so NemotronH skips hub kernels; prime-rl's
|
||||
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
|
||||
mapping[kernel_name] = None
|
||||
return None
|
||||
|
||||
_hub_kernels.lazy_load_kernel = _patched_lazy_load_kernel
|
||||
|
||||
@@ -12,7 +12,9 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
@@ -547,15 +549,26 @@ def rl(config: RLConfig):
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clean stale artifacts from steps after the resume point
|
||||
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
|
||||
# step is stale. When training from scratch, every existing step directory is
|
||||
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
|
||||
# from a previous run and the orchestrator would see a negative async level.
|
||||
resume_step: int | None = None
|
||||
if resuming:
|
||||
resume_step = config.ckpt.resume_step
|
||||
if resume_step == -1:
|
||||
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
|
||||
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
|
||||
if resume_step is not None:
|
||||
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, resume_step)
|
||||
|
||||
if resume_step is not None:
|
||||
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, resume_step)
|
||||
else:
|
||||
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
|
||||
clean_future_steps(config.output_dir, -1)
|
||||
|
||||
if not config.dry_run:
|
||||
pre_download_model(config.trainer.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -8,7 +8,9 @@ from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
@@ -196,6 +198,9 @@ def sft(config: SFTConfig):
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not config.dry_run:
|
||||
pre_download_model(config.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
|
||||
@@ -3,7 +3,7 @@ from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
@@ -17,7 +17,6 @@ def transformers_v5_compat():
|
||||
_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()
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -195,6 +194,7 @@ def _patch_qwen35_lora():
|
||||
from vllm.model_executor.models.qwen3_5 import (
|
||||
Qwen3_5ForCausalLMBase,
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
Qwen3_5MoeForConditionalGeneration,
|
||||
)
|
||||
|
||||
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
|
||||
@@ -202,6 +202,8 @@ def _patch_qwen35_lora():
|
||||
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
|
||||
Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = False
|
||||
|
||||
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
|
||||
|
||||
@classmethod
|
||||
@@ -302,10 +304,14 @@ def _patch_lora_key_prefix():
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Fix: always compare just the last component of the path.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
if expert_suffix not in expected_lora_modules:
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
@@ -478,6 +484,65 @@ def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
LRUCacheWorkerLoRAManager.add_adapter = _patched_add_adapter
|
||||
|
||||
|
||||
# Monkeypatch WorkerLoRAManager._load_adapter to skip the per-module regex
|
||||
# warning loop. On wide MoE models (Qwen3.5-35B-A3B) it spends minutes
|
||||
# recompiling regex patterns inside is_supported_lora_module — purely to emit
|
||||
# logger.warning_once about modules that will be ignored. Adapter validity is
|
||||
# already enforced by from_local_checkpoint, so dropping the warnings is safe.
|
||||
def monkey_patch_skip_lora_module_warnings():
|
||||
from vllm.exceptions import LoRAAdapterNotFoundError
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.lora.utils import get_adapter_absolute_path
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
|
||||
def _patched_load_adapter(self: WorkerLoRAManager, lora_request: LoRARequest) -> LoRAModel:
|
||||
try:
|
||||
supported_lora_modules = self._adapter_manager.supported_lora_modules
|
||||
packed_modules_mapping = self._adapter_manager.packed_modules_mapping
|
||||
expected_lora_lst: list[str] = []
|
||||
for module in supported_lora_modules:
|
||||
if module in packed_modules_mapping:
|
||||
expected_lora_lst.extend(packed_modules_mapping[module])
|
||||
else:
|
||||
expected_lora_lst.append(module)
|
||||
if module == "experts":
|
||||
expected_lora_lst.append(module)
|
||||
expected_lora_modules = set(expected_lora_lst)
|
||||
lora_path = get_adapter_absolute_path(lora_request.lora_path)
|
||||
|
||||
peft_helper = PEFTHelper.from_local_dir(
|
||||
lora_path,
|
||||
self.max_position_embeddings,
|
||||
lora_request.tensorizer_config_dict,
|
||||
)
|
||||
peft_helper.validate_legal(self.lora_config)
|
||||
|
||||
model = self._adapter_manager.model
|
||||
hf_to_vllm_mapper = getattr(model, "hf_to_vllm_mapper", None)
|
||||
lora_skip_prefixes = getattr(model, "lora_skip_prefixes", None)
|
||||
|
||||
lora = self._lora_model_cls.from_local_checkpoint(
|
||||
lora_path,
|
||||
expected_lora_modules,
|
||||
peft_helper=peft_helper,
|
||||
lora_model_id=lora_request.lora_int_id,
|
||||
device="cpu",
|
||||
dtype=self.lora_config.lora_dtype,
|
||||
model_vocab_size=self.vocab_size,
|
||||
tensorizer_config_dict=lora_request.tensorizer_config_dict,
|
||||
weights_mapper=hf_to_vllm_mapper,
|
||||
skip_prefixes=lora_skip_prefixes,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise LoRAAdapterNotFoundError(lora_request.lora_name, lora_request.lora_path) from e
|
||||
|
||||
return lora
|
||||
|
||||
WorkerLoRAManager._load_adapter = _patched_load_adapter
|
||||
|
||||
|
||||
# Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
def monkey_patch_tokenize_params_validation():
|
||||
"""
|
||||
@@ -649,239 +714,6 @@ def monkey_patch_harmony_stop_token_propagation():
|
||||
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
|
||||
|
||||
|
||||
def monkey_patch_fused_moe_lora_dp():
|
||||
"""Fix: LoRA + MoE + DP>1 produces corrupted output in vLLM 0.17.0.
|
||||
|
||||
Two bugs:
|
||||
1. LoRA injection sets supports_internal_mk=True (via moe_kernel not None),
|
||||
causing the MoE runner to skip DP dispatch/combine. But the LoRA kernel
|
||||
uses NoDPEP and doesn't handle DP internally.
|
||||
2. LoRA decorators capture full-batch tensors but fire per-chunk inside the
|
||||
kernel's chunk loop. At DP>=3, dispatched batch > CHUNK_SIZE causes
|
||||
shape mismatches.
|
||||
|
||||
Fix: Replace _inject_lora_into_fused_moe with a version that:
|
||||
(a) sets moe_kernel=None so the runner correctly dispatches
|
||||
(b) makes decorators chunk-aware by tracking chunk offsets
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/23244
|
||||
"""
|
||||
import types
|
||||
|
||||
from vllm import envs
|
||||
from vllm.distributed.utils import divide
|
||||
from vllm.lora.layers.fused_moe import FusedMoEWithLoRA
|
||||
from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str
|
||||
from vllm.model_executor.layers.fused_moe.fused_marlin_moe import MarlinExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe import TritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.fused_moe_modular_method import FusedMoEModularMethod
|
||||
from vllm.model_executor.layers.fused_moe.gpt_oss_triton_kernels_moe import UnfusedOAITritonExperts
|
||||
from vllm.model_executor.layers.fused_moe.modular_kernel import FusedMoEKernel
|
||||
from vllm.model_executor.layers.fused_moe.prepare_finalize import MoEPrepareAndFinalizeNoDPEPModular
|
||||
|
||||
def _fixed_inject(self):
|
||||
moe_state_dict = {}
|
||||
top_k = self.base_layer.top_k
|
||||
|
||||
self.base_layer.ensure_moe_quant_config_init()
|
||||
quant_config = self.base_layer.quant_method.moe_quant_config
|
||||
|
||||
if getattr(self.base_layer.quant_method, "supports_internal_mk", False):
|
||||
m_fused_moe_fn = self.base_layer.quant_method.moe_kernel
|
||||
m_fused_moe_fn.shared_experts = None
|
||||
else:
|
||||
prepare_finalize = MoEPrepareAndFinalizeNoDPEPModular()
|
||||
m_fused_moe_fn = FusedMoEKernel(
|
||||
prepare_finalize,
|
||||
self.base_layer.quant_method.select_gemm_impl(prepare_finalize, self.base_layer),
|
||||
)
|
||||
|
||||
if quant_config.use_mxfp4_w4a16:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, (MarlinExperts, UnfusedOAITritonExperts))
|
||||
else:
|
||||
assert isinstance(m_fused_moe_fn.impl.fused_experts, TritonExperts)
|
||||
|
||||
# --- Decorators (chunk-aware) ---
|
||||
|
||||
def fwd_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
moe_state_dict["hidden_states"] = kwargs["hidden_states"]
|
||||
moe_state_dict["topk_ids"] = kwargs["topk_ids"]
|
||||
moe_state_dict["topk_weights"] = kwargs["topk_weights"]
|
||||
moe_state_dict["expert_map"] = kwargs["expert_map"]
|
||||
moe_state_dict["apply_router_weight_on_input"] = kwargs["apply_router_weight_on_input"]
|
||||
moe_state_dict["_chunk_offset"] = 0
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def act_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
_, output, input = args
|
||||
chunk_M = input.view(-1, top_k, input.shape[-1]).shape[0]
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
curr_topk_ids = moe_state_dict["topk_ids"][chunk_offset : chunk_offset + chunk_M]
|
||||
expert_map = moe_state_dict["expert_map"]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w13_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w13",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=self._w13_slices,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
SPARSITY_FACTOR = 8
|
||||
naive_block_assignment = (
|
||||
expert_map is None
|
||||
and num_tokens * top_k * SPARSITY_FACTOR <= self.base_layer.local_num_experts * self.max_loras
|
||||
)
|
||||
token_lora_mapping, sorted_token_ids_lora, expert_ids_lora, num_tokens_post_padded_lora = (
|
||||
self.punica_wrapper.moe_lora_align_block_size(
|
||||
curr_topk_ids,
|
||||
num_tokens,
|
||||
shrink_config["BLOCK_SIZE_M"],
|
||||
self.base_layer.local_num_experts,
|
||||
self.max_loras,
|
||||
self.adapter_enabled,
|
||||
expert_map,
|
||||
naive_block_assignment=naive_block_assignment,
|
||||
)
|
||||
)
|
||||
moe_state_dict["sorted_token_ids_lora"] = sorted_token_ids_lora
|
||||
moe_state_dict["expert_ids_lora"] = expert_ids_lora
|
||||
moe_state_dict["num_tokens_post_padded_lora"] = num_tokens_post_padded_lora
|
||||
moe_state_dict["token_lora_mapping"] = token_lora_mapping
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
input.view(-1, top_k, input.shape[-1]),
|
||||
hidden_states,
|
||||
self.w13_lora_a_stacked,
|
||||
self.w13_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
fully_sharded=self.fully_sharded,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["intermediate_cache2"] = output
|
||||
moe_state_dict["_chunk_M"] = chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
def moe_sum_decorator(layer, func):
|
||||
def wrapper(*args, **kwargs):
|
||||
chunk_offset = moe_state_dict.get("_chunk_offset", 0)
|
||||
chunk_M = moe_state_dict.get("_chunk_M", moe_state_dict["hidden_states"].size(0))
|
||||
hidden_states = moe_state_dict["hidden_states"][chunk_offset : chunk_offset + chunk_M]
|
||||
topk_weights = moe_state_dict["topk_weights"][chunk_offset : chunk_offset + chunk_M]
|
||||
config_dtype = _get_config_dtype_str(
|
||||
dtype=hidden_states.dtype, use_fp8_w8a8=False, use_int8_w8a16=False, use_int4_w4a16=False
|
||||
)
|
||||
num_tokens = hidden_states.size(0)
|
||||
M = min(num_tokens, envs.VLLM_FUSED_MOE_CHUNK_SIZE)
|
||||
max_lora_rank = self.w2_lora_a_stacked[0].shape[-2]
|
||||
shrink_config, expand_config = self._get_lora_moe_configs(
|
||||
op_prefix="w2",
|
||||
num_loras=self.max_loras,
|
||||
rank=max_lora_rank,
|
||||
num_slices=1,
|
||||
M=M,
|
||||
layer=layer,
|
||||
top_k=top_k,
|
||||
config_dtype=config_dtype,
|
||||
)
|
||||
sorted_token_ids_lora = moe_state_dict["sorted_token_ids_lora"]
|
||||
expert_ids_lora = moe_state_dict["expert_ids_lora"]
|
||||
num_tokens_post_padded_lora = moe_state_dict["num_tokens_post_padded_lora"]
|
||||
token_lora_mapping = moe_state_dict.get("token_lora_mapping")
|
||||
if sorted_token_ids_lora is not None:
|
||||
expert_ids_lora = expert_ids_lora.view(self.max_loras, -1)
|
||||
sorted_token_ids_lora = sorted_token_ids_lora.view(self.max_loras, -1)
|
||||
intermediate_cache2 = moe_state_dict["intermediate_cache2"]
|
||||
intermediate_cache3 = args[0]
|
||||
shard_size_w2 = divide(self.base_layer.hidden_size, self.tp_size)
|
||||
self.punica_wrapper.add_lora_fused_moe(
|
||||
intermediate_cache3,
|
||||
intermediate_cache2,
|
||||
self.w2_lora_a_stacked,
|
||||
self.w2_lora_b_stacked,
|
||||
topk_weights,
|
||||
sorted_token_ids_lora,
|
||||
expert_ids_lora,
|
||||
num_tokens_post_padded_lora,
|
||||
max_lora_rank,
|
||||
top_k,
|
||||
shrink_config,
|
||||
expand_config,
|
||||
self.adapter_enabled,
|
||||
True,
|
||||
fully_sharded=self.fully_sharded,
|
||||
offset=shard_size_w2 * self.tp_rank if self.fully_sharded else 0,
|
||||
token_lora_mapping=token_lora_mapping,
|
||||
)
|
||||
result = func(*args, **kwargs)
|
||||
moe_state_dict["_chunk_offset"] = chunk_offset + chunk_M
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
# --- Install decorators and replace quant method ---
|
||||
|
||||
fused_experts = m_fused_moe_fn.impl.fused_experts
|
||||
m_fused_moe_fn.apply = fwd_decorator(self.base_layer, m_fused_moe_fn.apply)
|
||||
fused_experts.activation = act_decorator(self.base_layer, fused_experts.activation)
|
||||
fused_experts.moe_sum = moe_sum_decorator(self.base_layer, fused_experts.moe_sum)
|
||||
|
||||
new_method = FusedMoEModularMethod(self.base_layer.quant_method, m_fused_moe_fn)
|
||||
|
||||
# Bug 1 fix: NoDPEP kernel makes supports_internal_mk=True, causing the
|
||||
# runner to skip DP dispatch/combine. Set moe_kernel=None and patch apply().
|
||||
if isinstance(m_fused_moe_fn.prepare_finalize, MoEPrepareAndFinalizeNoDPEPModular):
|
||||
saved_kernel = new_method.moe_kernel
|
||||
saved_disable_expert_map = new_method.disable_expert_map
|
||||
new_method.moe_kernel = None
|
||||
|
||||
def _apply_with_saved_kernel(self, layer, x, topk_weights, topk_ids, shared_experts_input):
|
||||
return saved_kernel.apply(
|
||||
hidden_states=x,
|
||||
w1=layer.w13_weight,
|
||||
w2=layer.w2_weight,
|
||||
topk_weights=topk_weights,
|
||||
topk_ids=topk_ids,
|
||||
activation=layer.activation,
|
||||
global_num_experts=layer.global_num_experts,
|
||||
apply_router_weight_on_input=layer.apply_router_weight_on_input,
|
||||
expert_map=None if saved_disable_expert_map else layer.expert_map,
|
||||
shared_experts_input=shared_experts_input,
|
||||
)
|
||||
|
||||
new_method.apply = types.MethodType(_apply_with_saved_kernel, new_method)
|
||||
|
||||
self.base_layer._replace_quant_method(new_method)
|
||||
|
||||
FusedMoEWithLoRA._inject_lora_into_fused_moe = _fixed_inject
|
||||
|
||||
|
||||
def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
"""Fix DP pause/resume deadlocks around weight updates.
|
||||
|
||||
@@ -954,49 +786,6 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_offloading_connector_cpu_block_count():
|
||||
"""Fix CPU block count miscalculation in OffloadingConnector.
|
||||
|
||||
CPUOffloadingSpec erroneously multiplies page_size_bytes by
|
||||
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
|
||||
For UniformTypeKVCacheSpecs the page_size is already the total per-block
|
||||
size across all layers, so the extra multiplier makes num_blocks far too
|
||||
small. When the OffloadingManager later allocates block IDs past the
|
||||
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
|
||||
invalid pinned address.
|
||||
|
||||
Fix: remove the num_tensors multiplier.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/38395
|
||||
Related: https://github.com/vllm-project/vllm/issues/39500
|
||||
"""
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
_original_init = CPUOffloadingSpec.__init__
|
||||
|
||||
def _patched_init(self, vllm_config, kv_cache_config):
|
||||
_original_init(self, vllm_config, kv_cache_config)
|
||||
|
||||
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
|
||||
assert len(page_sizes) == 1
|
||||
page_size_bytes = page_sizes.pop()
|
||||
|
||||
# page_size_bytes already covers all layers in the group.
|
||||
# Only multiply by world_size (each TP rank stores its own copy).
|
||||
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
|
||||
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
|
||||
self.num_blocks = (
|
||||
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
|
||||
)
|
||||
|
||||
CPUOffloadingSpec.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
@@ -20,6 +21,7 @@ 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] = {
|
||||
@@ -151,13 +153,14 @@ 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:
|
||||
@@ -178,61 +181,34 @@ 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("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume(request: Request):
|
||||
await engine_client(request).resume_generation()
|
||||
return {"status": "resumed"}
|
||||
|
||||
|
||||
@router.post("/update_weights")
|
||||
async def update_weights(request: Request):
|
||||
data = await request.json()
|
||||
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
|
||||
if request.app.state.reset_prefix_cache_after_update:
|
||||
await engine_client(request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Load a LoRA adapter, optionally resetting the prefix cache.
|
||||
|
||||
Wrapper around vLLM's /v1/load_lora_adapter that also resets the prefix cache
|
||||
to invalidate KV states computed with old weights (unless disabled via config).
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
if raw_request.app.state.reset_prefix_cache_after_update:
|
||||
await engine_client(raw_request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/init_broadcaster")
|
||||
async def init_broadcaster(request: Request):
|
||||
data = await request.json()
|
||||
host = data.get("host")
|
||||
port = data.get("port")
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
@router.post(
|
||||
"/v1/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(
|
||||
@@ -261,6 +237,64 @@ async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_reques
|
||||
return StreamingResponse(content=generator, media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
return {"status": "paused"}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume(request: Request):
|
||||
await engine_client(request).resume_generation()
|
||||
return {"status": "resumed"}
|
||||
|
||||
|
||||
@router.post("/update_weights")
|
||||
async def update_weights(request: Request):
|
||||
data = await request.json()
|
||||
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
handler = models(raw_request)
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/liveness")
|
||||
async def liveness(raw_request: Request):
|
||||
"""Check that the engine event loop can service a no-op worker RPC."""
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
engine_client(raw_request).collective_rpc("liveness_probe"),
|
||||
timeout=LIVENESS_TIMEOUT_SECONDS,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/init_broadcaster")
|
||||
async def init_broadcaster(request: Request):
|
||||
data = await request.json()
|
||||
host = data.get("host")
|
||||
port = data.get("port")
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
async def custom_init_app_state(
|
||||
engine_client: EngineClient,
|
||||
state: State,
|
||||
@@ -270,12 +304,16 @@ async def custom_init_app_state(
|
||||
"""
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state.
|
||||
2. Replace the serving_chat with our OpenAIServingChatWithTokens wrapper.
|
||||
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.
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
|
||||
# TITO: server-side chat templating + token IDs.
|
||||
if "generate" in supported_tasks and state.openai_serving_chat is not None:
|
||||
original_chat = state.openai_serving_chat
|
||||
serving_chat = object.__new__(OpenAIServingChatWithTokens)
|
||||
@@ -285,6 +323,12 @@ async def custom_init_app_state(
|
||||
else:
|
||||
state.openai_serving_chat_with_tokens = None
|
||||
|
||||
# /v1/generate endpoint — tokens + optional images, no chat template
|
||||
from prime_rl.inference.vllm.serving_generate import OpenAIServingGenerate
|
||||
|
||||
chat_handler = state.openai_serving_chat if "generate" in supported_tasks else None
|
||||
state.openai_serving_generate = OpenAIServingGenerate(engine_client, chat_handler=chat_handler)
|
||||
|
||||
|
||||
import vllm.entrypoints.openai.api_server
|
||||
import vllm.v1.utils
|
||||
@@ -342,7 +386,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
|
||||
|
||||
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
|
||||
args.enable_auto_tool_choice = args.tool_call_parser is not None
|
||||
args.reset_prefix_cache_after_update = config.experimental.reset_prefix_cache_after_update
|
||||
if args.tool_call_parser is not None:
|
||||
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""/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
|
||||
@@ -5,12 +5,16 @@ from prime_rl.inference.patches import (
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
monkey_patch_skip_lora_module_warnings,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Skip the per-module regex warning loop in WorkerLoRAManager._load_adapter
|
||||
# (minutes-long stall on wide MoE models like Qwen3.5-35B-A3B)
|
||||
monkey_patch_skip_lora_module_warnings()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
# Disable LoRA on MoE layers so vLLM picks better kernels (e.g. TRTLLMFlashInfer on Blackwell)
|
||||
|
||||
@@ -20,6 +20,10 @@ class FileSystemWeightUpdateWorker(Worker):
|
||||
"""Initialize the broadcaster."""
|
||||
...
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
def update_weights_from_path(self, weight_path: str) -> None:
|
||||
"""Update weights from a specified path in shared filesystem containing a HF-compatible checkpoint."""
|
||||
# Get vLLM model runner and model
|
||||
|
||||
@@ -130,6 +130,10 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
def update_weights_from_path(self, weight_dir: str) -> None:
|
||||
"""Update weights with the nccl communicator."""
|
||||
model_runner = self.model_runner
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
from typing import Callable, Literal
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float, Int
|
||||
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
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
LengthPenalty = Literal["tokens", "turns"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
"""Inputs for advantage computation."""
|
||||
"""Inputs for advantage computation.
|
||||
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"]
|
||||
completion_lengths: Int[Tensor, "num_problems rollouts_per_example"]
|
||||
`rollouts` is grouped by problem: `rollouts[i][j]` is the j-th rollout for problem i,
|
||||
so `len(rollouts) == num_problems` and `len(rollouts[0]) == rollouts_per_example`.
|
||||
"""
|
||||
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -37,30 +42,40 @@ Expected signature:
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_shaping: bool = False,
|
||||
length_penalty: LengthPenalty | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
rewards = inputs.rewards
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
|
||||
if length_shaping:
|
||||
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_length_shaping(rewards, completion_lengths))
|
||||
if length_penalty == "tokens":
|
||||
costs = torch.tensor(
|
||||
[[get_model_completion_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":
|
||||
costs = torch.tensor(
|
||||
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
return AdvantageOutputs(advantages=rewards - baseline)
|
||||
|
||||
|
||||
def _efficiency_length_shaping(
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
completion_lengths: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
costs: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
) -> Float[Tensor, "num_problems rollouts_per_example"]:
|
||||
"""Correctness-gated length shaping with bounded advantages.
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded brevity bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group.
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group. `costs` is a per-rollout cost (e.g.,
|
||||
completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative brevity.
|
||||
Incorrect rollouts are untouched. Shorter correct rollouts get higher advantage.
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max(dim=1, keepdim=True).values
|
||||
correct_mask = rewards >= max_reward
|
||||
@@ -69,12 +84,12 @@ def _efficiency_length_shaping(
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
has_correct = max_reward > 0
|
||||
|
||||
# Mean length of correct rollouts per problem
|
||||
correct_lengths = completion_lengths * correct_mask
|
||||
mean_correct_len = correct_lengths.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
# Mean cost of correct rollouts per problem
|
||||
correct_costs = costs * correct_mask
|
||||
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded brevity bonus: [0, 1], positive for below-average length, zero for above
|
||||
bonus = (1 - completion_lengths / mean_correct_len).clamp(0, 1)
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
@@ -99,7 +114,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_shaping=config.length_shaping,
|
||||
length_penalty=config.length_penalty,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
@@ -127,12 +142,8 @@ def compute_advantages(
|
||||
return
|
||||
|
||||
advantage_fn = setup_advantage_fn(advantage_config)
|
||||
completion_lengths = [get_model_completion_len(r) for r in rollouts]
|
||||
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor(rewards).view(-1, samples_per_problem),
|
||||
completion_lengths=torch.tensor(completion_lengths).view(-1, samples_per_problem),
|
||||
)
|
||||
grouped = [rollouts[i : i + samples_per_problem] for i in range(0, len(rollouts), samples_per_problem)]
|
||||
inputs = AdvantageInputs(rollouts=grouped)
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
advantages = result.advantages.flatten().tolist()
|
||||
|
||||
@@ -18,7 +18,7 @@ def run_server(config: EnvServerConfig):
|
||||
env_ids_to_install = set()
|
||||
env_ids_to_install.update(get_env_ids_to_install([config.env]))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
|
||||
|
||||
|
||||
@@ -104,9 +104,7 @@ class Env:
|
||||
self._env_server_process = process
|
||||
return address
|
||||
|
||||
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
|
||||
if cache_salt is None:
|
||||
return self.sampling_args
|
||||
def _sampling_args_with_salt(self, cache_salt: str) -> dict:
|
||||
sampling_args = {**self.sampling_args}
|
||||
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
sampling_args["extra_body"] = extra_body
|
||||
@@ -117,7 +115,7 @@ class Env:
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
cache_salt: str | None = None,
|
||||
cache_salt: str,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Run a single rollout for an example."""
|
||||
return await self.env.run_rollout(
|
||||
@@ -136,7 +134,7 @@ class Env:
|
||||
example: dict,
|
||||
model_name: str,
|
||||
rollouts_per_example: int,
|
||||
cache_salt: str | None = None,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Run a group of rollouts for an example. Required for group-scoring envs."""
|
||||
return await self.env.run_group(
|
||||
@@ -181,7 +179,7 @@ class EvalEnv(Env):
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
ckpt_step: int,
|
||||
step: int,
|
||||
cache_salt: str | None = None,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
num_examples = len(self.examples)
|
||||
rollouts_per_example = self.config.rollouts_per_example
|
||||
@@ -352,10 +350,13 @@ class Envs(Generic[EnvT]):
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> None:
|
||||
"""Spawn env servers (where needed) and connect all env clients in parallel."""
|
||||
await asyncio.gather(
|
||||
*(env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging) for env in self)
|
||||
)
|
||||
"""Spawn env servers (where needed) and connect env clients one at a time.
|
||||
|
||||
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
|
||||
until it returns, so parallel spawns can hand the same port to two children.
|
||||
"""
|
||||
for env in self:
|
||||
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
atexit.register(self.shutdown)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
|
||||
Filters run after rollouts complete, inspecting token IDs and logprobs to
|
||||
detect gibberish or repetition. Detection metrics are always tracked.
|
||||
When enforce=True, detected rollouts get their completion mask cleared so
|
||||
they don't contribute to training. Reward is kept as-is for baseline
|
||||
calculation.
|
||||
When enforce=True, detected rollouts are skipped entirely during training and
|
||||
are not sent to the trainer. Reward is kept as-is for baseline calculation.
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -149,63 +148,41 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutF
|
||||
return filters
|
||||
|
||||
|
||||
def apply_filters(
|
||||
filters: list[RolloutFilter],
|
||||
rollouts: list[vf.RolloutOutput],
|
||||
) -> dict[str, float]:
|
||||
"""Apply filters to rollouts. Detection metrics are always tracked.
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list[vf.RolloutOutput]) -> None:
|
||||
"""Flag rollouts in-place with per-filter detection and drop decision.
|
||||
|
||||
When a filter has enforce=True, detected rollouts get their completion
|
||||
mask cleared and stop_condition set. Reward is kept as-is for baseline
|
||||
calculation.
|
||||
|
||||
First matching filter wins per rollout (no double-counting).
|
||||
|
||||
Returns aggregate metrics dict for logging.
|
||||
Each rollout gets a `filters` dict with per-filter detection booleans and
|
||||
an `is_filtered` bool that is True iff an enforcing filter detected it.
|
||||
First matching filter wins per rollout (no double-counting). Reward and
|
||||
trajectory tokens are left untouched so the rollout can still contribute
|
||||
to baseline calculations and metric aggregation.
|
||||
"""
|
||||
for rollout in rollouts:
|
||||
rollout["filters"] = {f.name: False for f in filters}
|
||||
rollout["is_filtered"] = False
|
||||
|
||||
if not filters:
|
||||
return {}
|
||||
return
|
||||
|
||||
counts: dict[str, int] = {f.name: 0 for f in filters}
|
||||
total_detected = 0
|
||||
total_enforced = 0
|
||||
|
||||
for rollout in rollouts:
|
||||
if rollout.get("metrics") is None:
|
||||
rollout["metrics"] = {}
|
||||
for filt in filters:
|
||||
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
|
||||
|
||||
for filt in filters:
|
||||
result = filt.check(rollout)
|
||||
if result.detected:
|
||||
counts[filt.name] += 1
|
||||
total_detected += 1
|
||||
rollout["metrics"][f"filter/{filt.name}"] = 1.0
|
||||
|
||||
rollout["filters"][filt.name] = True
|
||||
if filt.enforce:
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is not None:
|
||||
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
|
||||
rollout["stop_condition"] = filt.name
|
||||
rollout["is_filtered"] = True
|
||||
total_enforced += 1
|
||||
|
||||
break
|
||||
|
||||
n = len(rollouts)
|
||||
metrics: dict[str, float] = {}
|
||||
for f in filters:
|
||||
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
|
||||
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
|
||||
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
|
||||
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
|
||||
|
||||
if total_detected > 0:
|
||||
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
|
||||
get_logger().info(
|
||||
f"Detected {total_detected}/{n} rollouts "
|
||||
f"Detected {total_detected}/{len(rollouts)} rollouts "
|
||||
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
|
||||
)
|
||||
|
||||
return metrics
|
||||
|
||||
@@ -5,6 +5,7 @@ import time
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.orchestrator.advantage import compute_advantages
|
||||
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
@@ -31,6 +32,7 @@ monkey_patch_chat_completion_logprobs()
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from renderers.base import create_renderer
|
||||
from transformers import AutoProcessor
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
@@ -76,6 +78,11 @@ from prime_rl.utils.utils import (
|
||||
# and artifacts are persisted *before* this point, so a forced exit is safe.
|
||||
SHUTDOWN_TIMEOUT_S = 300
|
||||
|
||||
# Maximum number of times to attempt generating a training batch when all
|
||||
# rollouts are filtered out. After this many attempts, the orchestrator crashes
|
||||
# rather than silently skipping training steps.
|
||||
MAX_EMPTY_BATCH_ATTEMPTS = 3
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def orchestrate(config: OrchestratorConfig):
|
||||
@@ -108,19 +115,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
|
||||
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
# Setup rollout inference pool (handles both static and elastic modes)
|
||||
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
|
||||
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
logger.info(
|
||||
@@ -149,6 +148,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
renderer, inference_pool = await setup_rollout_inference_pool(
|
||||
config=config,
|
||||
rollout_client_config=rollout_client_config,
|
||||
rollout_model_name=rollout_model_name,
|
||||
tokenizer=tokenizer,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Setup monitor (may register the run and set RUN_ID in the environment)
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -157,6 +164,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
output_dir=config.output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
)
|
||||
|
||||
# Read run_id AFTER setup_monitor so that newly registered runs are captured
|
||||
@@ -236,7 +244,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
enable_policy_updates=enable_policy_updates,
|
||||
lora_name=config.model.lora.name if config.model.lora else None,
|
||||
config=config,
|
||||
use_prefix_cache_salt=config.experimental.use_prefix_cache_salt,
|
||||
)
|
||||
scheduler.model_name = rollout_model_name
|
||||
|
||||
@@ -380,7 +387,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
|
||||
await scheduler.cancel_inflight_rollouts()
|
||||
|
||||
eval_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
@@ -388,7 +394,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=eval_cache_salt,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
for eval_env in envs_to_eval
|
||||
]
|
||||
@@ -398,7 +404,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_rollouts = [o for outputs in eval_results for o in outputs]
|
||||
if eval_rollouts:
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
|
||||
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Resume weight updates
|
||||
scheduler.checkpoint_ready.set()
|
||||
@@ -406,17 +414,61 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Update prev_ckpt_step for next iteration
|
||||
prev_ckpt_step = ckpt_step
|
||||
|
||||
# Schedule generating the training batch
|
||||
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
|
||||
# Schedule generating the training batch. Retry on empty-after-filter
|
||||
# batches so the trainer never receives an empty batch.
|
||||
generate_completions_time = 0.0
|
||||
train_rollouts: list[vf.RolloutOutput] = []
|
||||
num_rollouts = 0
|
||||
num_unique_examples = 0
|
||||
n_trainable = 0
|
||||
for attempt in range(MAX_EMPTY_BATCH_ATTEMPTS):
|
||||
train_rollouts = await scheduler.generate_batch(step=progress.step)
|
||||
generate_completions_time += scheduler.last_batch_generation_time
|
||||
|
||||
# Await train rollouts
|
||||
await train_task
|
||||
generate_completions_time = scheduler.last_batch_generation_time
|
||||
train_rollouts = train_task.result()
|
||||
# Compute advantages (in-place)
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len({(r["env_name"], r["example_id"]) for r in train_rollouts})
|
||||
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
|
||||
|
||||
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
|
||||
apply_filters(rollout_filters, train_rollouts)
|
||||
|
||||
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
|
||||
if n_trainable > 0:
|
||||
break
|
||||
|
||||
if attempt == MAX_EMPTY_BATCH_ATTEMPTS - 1:
|
||||
logger.error(
|
||||
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
|
||||
f"filtered out all {num_rollouts} rollouts - crashing orchestrator"
|
||||
)
|
||||
reason = (
|
||||
f"All {num_rollouts} rollouts were filtered out on "
|
||||
f"{MAX_EMPTY_BATCH_ATTEMPTS} consecutive attempts at step {progress.step}"
|
||||
)
|
||||
evicted_path = config.output_dir / "control" / "evicted.txt"
|
||||
evicted_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
evicted_path.write_text(reason)
|
||||
raise RuntimeError(reason)
|
||||
|
||||
logger.warning(
|
||||
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
|
||||
f"filtered out all {num_rollouts} rollouts - retrying batch generation"
|
||||
)
|
||||
|
||||
trainable_ratio = n_trainable / num_rollouts
|
||||
if trainable_ratio <= 0.1:
|
||||
logger.warning(
|
||||
f"Only {n_trainable}/{num_rollouts} rollouts in the batch are trainable "
|
||||
f"({trainable_ratio:.1%}) - this can mean the tasks are too easy or too hard for the "
|
||||
"model, consider reviewing the task difficulty of your environment(s)"
|
||||
)
|
||||
|
||||
# Save train rollouts to disk (fire-and-forget background thread)
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
|
||||
await asyncio.to_thread(save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# VLM: offload base64 images to disk immediately to free memory
|
||||
if is_vlm:
|
||||
@@ -427,52 +479,64 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
|
||||
)
|
||||
|
||||
# Compute advantages (in-place)
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len(set(example_ids))
|
||||
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
|
||||
|
||||
# Apply rollout filters (zeros reward/mask for degenerate generations)
|
||||
filter_metrics = apply_filters(rollout_filters, train_rollouts)
|
||||
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
|
||||
# Pretokenize before VLM image cache build (which strips image data from messages)
|
||||
for rollout in train_rollouts:
|
||||
pretokenize_rollout_trajectory(rollout, tokenizer, processor=processor)
|
||||
# Stage 1: pretokenize + (for VLM) build image cache concurrently.
|
||||
# Pretokenize is a no-op when the renderer client already populated
|
||||
# `tokens` on each trajectory step, but the fallback-tokenizer path
|
||||
# and image-cache build are both CPU-heavy. Running them on threads
|
||||
# and awaiting a single gather lets whichever finishes first free
|
||||
# the event loop immediately and, with max_async_level >= 2, overlaps
|
||||
# this whole stage with inference for the next batch.
|
||||
async def _pretokenize_all() -> None:
|
||||
await asyncio.gather(
|
||||
*(
|
||||
asyncio.to_thread(
|
||||
pretokenize_rollout_trajectory,
|
||||
rollout,
|
||||
tokenizer,
|
||||
processor=processor,
|
||||
renderer=renderer,
|
||||
)
|
||||
for rollout in train_rollouts
|
||||
)
|
||||
)
|
||||
|
||||
# VLM: build image cache in a thread so it doesn't block the event loop.
|
||||
# This lets the scheduler continue servicing inflight rollout requests
|
||||
# and — with max_async_level >= 2 — overlap with the next batch's inference.
|
||||
if is_vlm:
|
||||
vlm_cache = await asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor)
|
||||
mm_token_type_ids_mapping = {}
|
||||
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
|
||||
mm_token_type_ids_mapping[processor.image_token_id] = 1
|
||||
if hasattr(processor, "video_token_id") and processor.video_token_id is not None:
|
||||
mm_token_type_ids_mapping[processor.video_token_id] = 2
|
||||
|
||||
_, vlm_cache = await asyncio.gather(
|
||||
_pretokenize_all(),
|
||||
asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor),
|
||||
)
|
||||
logger.info(
|
||||
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s "
|
||||
f"({vlm_cache.num_unique_images} unique images from {vlm_cache.num_unique_examples} examples)"
|
||||
)
|
||||
else:
|
||||
await _pretokenize_all()
|
||||
vlm_cache = None
|
||||
mm_token_type_ids_mapping = None
|
||||
|
||||
# Process rollouts in parallel
|
||||
def process_rollout(rollout: vf.RolloutOutput, rollout_idx: int) -> list[TrainingSample] | None:
|
||||
return interleave_rollout(
|
||||
rollout, vlm_cache=vlm_cache, cache_key=rollout_idx, mm_token_type_ids_mapping=mm_token_type_ids_mapping
|
||||
rollout,
|
||||
vlm_cache=vlm_cache,
|
||||
cache_key=rollout_idx,
|
||||
mm_token_type_ids_mapping=mm_token_type_ids_mapping,
|
||||
)
|
||||
|
||||
results = await asyncio.gather(
|
||||
*(asyncio.to_thread(process_rollout, r, rollout_idx) for rollout_idx, r in enumerate(train_rollouts))
|
||||
)
|
||||
|
||||
# Collect results and assign advantages
|
||||
# Collect results and assign advantages. Metrics are computed over all
|
||||
# rollouts; only non-filtered samples are sent to the trainer.
|
||||
train_examples: list[TrainingSample] = []
|
||||
rollout_prefill_lens: list[int] = []
|
||||
rollout_decode_lens: list[int] = []
|
||||
@@ -482,18 +546,20 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
for rollout, samples in zip(train_rollouts, results):
|
||||
rollout_prefill_tokens = 0
|
||||
rollout_decode_tokens = 0
|
||||
if samples is not None:
|
||||
rollout_samples_per_rollout.append(len(samples))
|
||||
for sample in samples:
|
||||
sample.advantage = rollout["advantage"]
|
||||
sample.reward = rollout["reward"]
|
||||
sample_decode_tokens = sum(sample.completion_mask)
|
||||
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
if samples is None:
|
||||
samples = []
|
||||
rollout_samples_per_rollout.append(len(samples))
|
||||
for sample in samples:
|
||||
sample.advantage = rollout["advantage"]
|
||||
sample.reward = rollout["reward"]
|
||||
if config.use_sft_loss:
|
||||
sample.sft_loss = True
|
||||
sample_decode_tokens = sum(sample.completion_mask)
|
||||
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
if not rollout["is_filtered"]:
|
||||
train_examples.append(sample)
|
||||
else:
|
||||
rollout_samples_per_rollout.append(0)
|
||||
rollout_prefill_lens.append(rollout_prefill_tokens)
|
||||
rollout_decode_lens.append(rollout_decode_tokens)
|
||||
num_prefill_tokens += rollout_prefill_tokens
|
||||
@@ -536,19 +602,34 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"env_name": [rollout["env_name"] for rollout in train_rollouts],
|
||||
"reward": [rollout["reward"] for rollout in train_rollouts],
|
||||
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
|
||||
"is_filtered": [rollout["is_filtered"] for rollout in train_rollouts],
|
||||
"stop_condition": [rollout.get("stop_condition") for rollout in train_rollouts],
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
"decode_len": rollout_decode_lens,
|
||||
"samples_per_rollout": rollout_samples_per_rollout,
|
||||
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
|
||||
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
|
||||
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
|
||||
}
|
||||
)
|
||||
|
||||
# Separate DataFrame for env reward function metrics to avoid column name collisions
|
||||
# Separate DataFrames for env reward function metrics, filter flags, and per-rollout timings
|
||||
# to avoid column name collisions
|
||||
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
|
||||
filter_df = pd.DataFrame([rollout["filters"] for rollout in train_rollouts])
|
||||
timing_df = pd.DataFrame(
|
||||
[
|
||||
{
|
||||
"total": rollout["timing"]["total"],
|
||||
"setup": rollout["timing"]["setup"]["duration"],
|
||||
"generation": rollout["timing"]["generation"]["duration"],
|
||||
"model": rollout["timing"]["model"]["duration"],
|
||||
"env": rollout["timing"]["env"]["duration"],
|
||||
"scoring": rollout["timing"]["scoring"]["duration"],
|
||||
"overhead": rollout["timing"]["overhead"],
|
||||
}
|
||||
for rollout in train_rollouts
|
||||
]
|
||||
)
|
||||
|
||||
# Update progress metrics
|
||||
num_tokens = int(results_df.seq_len.sum())
|
||||
@@ -558,13 +639,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
def compute_solve_rates(df):
|
||||
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
|
||||
reward_per_problem = df.groupby("example_id").reward.sum()
|
||||
reward_per_problem = df.groupby(["env_name", "example_id"]).reward.sum()
|
||||
solve_none = (reward_per_problem == 0).mean()
|
||||
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
|
||||
return solve_none, solve_all, 1 - solve_none - solve_all
|
||||
|
||||
# Group by example_id to average across rollouts within each problem
|
||||
by_example = results_df.groupby("example_id")
|
||||
# Group by (env_name, example_id) to average across rollouts within each problem
|
||||
by_example = results_df.groupby(["env_name", "example_id"])
|
||||
|
||||
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
|
||||
to_log = {
|
||||
@@ -603,12 +684,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"num_turns/all/mean": by_example.num_turns.mean().mean(),
|
||||
"num_turns/all/max": by_example.num_turns.mean().max(),
|
||||
"num_turns/all/min": by_example.num_turns.mean().min(),
|
||||
"generation_ms/all/mean": by_example.generation_ms.mean().mean(),
|
||||
"generation_ms/all/max": by_example.generation_ms.mean().max(),
|
||||
"generation_ms/all/min": by_example.generation_ms.mean().min(),
|
||||
"scoring_ms/all/mean": by_example.scoring_ms.mean().mean(),
|
||||
"scoring_ms/all/max": by_example.scoring_ms.mean().max(),
|
||||
"scoring_ms/all/min": by_example.scoring_ms.mean().min(),
|
||||
**{
|
||||
f"timing/all/{key}/{stat}": getattr(
|
||||
timing_df[key].groupby([results_df.env_name, results_df.example_id]).mean(),
|
||||
stat,
|
||||
)()
|
||||
for key in timing_df.columns
|
||||
for stat in ("mean", "max", "min")
|
||||
},
|
||||
# Train reward
|
||||
"reward/all/mean": by_example.reward.mean().mean(),
|
||||
"reward/all/max": by_example.reward.mean().max(),
|
||||
@@ -630,8 +713,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
**buffer.get_metrics(),
|
||||
# Event loop lag metrics
|
||||
**event_loop_lag_monitor.get_metrics(),
|
||||
# Rollout filter metrics
|
||||
**filter_metrics,
|
||||
# Rollout filter metrics (detection rate per filter + overall drop rate)
|
||||
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
|
||||
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
|
||||
# W&B axis
|
||||
"step": progress.step,
|
||||
}
|
||||
@@ -644,8 +728,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"is_truncated",
|
||||
"samples_per_rollout",
|
||||
"num_turns",
|
||||
"generation_ms",
|
||||
"scoring_ms",
|
||||
]
|
||||
|
||||
for env, env_df in results_df.groupby("env_name"):
|
||||
@@ -655,6 +737,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
|
||||
if col != "is_truncated":
|
||||
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
|
||||
env_timing_df = timing_df.loc[env_df.index]
|
||||
for key in timing_df.columns:
|
||||
per_example = env_timing_df.groupby(env_df["example_id"])[key].mean()
|
||||
to_log[f"timing/{env}/{key}/mean"] = per_example.mean()
|
||||
to_log[f"timing/{env}/{key}/max"] = per_example.max()
|
||||
to_log[f"timing/{env}/{key}/min"] = per_example.min()
|
||||
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
|
||||
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
|
||||
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
|
||||
@@ -670,6 +758,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
env_metrics_df = metrics_df.loc[env_df.index]
|
||||
for metric in metrics_df.columns:
|
||||
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["example_id"])[metric].mean().mean()
|
||||
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
|
||||
env_filter_df = filter_df.loc[env_df.index]
|
||||
for name in filter_df.columns:
|
||||
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
|
||||
|
||||
# Log metrics to monitor(s)
|
||||
monitor.log(to_log, step=progress.step)
|
||||
@@ -694,7 +786,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
|
||||
reward_mean = by_example.reward.mean().mean()
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {reward_mean:.4f} | Seq. Length: {by_example.seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {reward_mean:.4f} | Seq. Length: {by_example.seq_len.mean().mean():.1f} tokens/sample | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
|
||||
logger.success(step_message)
|
||||
|
||||
# Increment step
|
||||
@@ -714,7 +806,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
if config.eval and eval_envs is not None:
|
||||
logger.info("Running final evals")
|
||||
final_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
@@ -722,7 +813,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=final_cache_salt,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
for eval_env in eval_envs
|
||||
]
|
||||
@@ -732,10 +823,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_rollouts = [o for outputs in eval_results for o in outputs]
|
||||
if eval_rollouts:
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
|
||||
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Log final (immutable) samples and distributions to monitor(s)
|
||||
monitor.log_final_samples()
|
||||
monitor.save_final_summary()
|
||||
|
||||
# Write final checkpoint
|
||||
@@ -795,5 +886,74 @@ def main():
|
||||
asyncio.run(orchestrate(cli(OrchestratorConfig)))
|
||||
|
||||
|
||||
async def setup_rollout_inference_pool(
|
||||
*,
|
||||
config: OrchestratorConfig,
|
||||
rollout_client_config,
|
||||
rollout_model_name: str,
|
||||
tokenizer,
|
||||
logger,
|
||||
):
|
||||
"""Set up rollout inference.
|
||||
|
||||
Routing policy is driven by ``config.use_token_client`` and
|
||||
``config.use_renderer`` (mutually exclusive — config-level validators
|
||||
block both being True):
|
||||
|
||||
- external teacher rollout → MITO (``openai_chat_completions``),
|
||||
forced regardless of the toggles (config-level validator
|
||||
rejects ``use_token_client`` / ``use_renderer`` in that case)
|
||||
- ``use_renderer=True`` → renderer client (``/v1/generate``).
|
||||
Not allowed for VLMs (validated at config time).
|
||||
- ``use_token_client=True`` → TITO
|
||||
(``openai_chat_completions_token``, ``/v1/chat/completions/tokens``).
|
||||
Default. VLMs land here too.
|
||||
- both False → MITO (``openai_chat_completions``).
|
||||
"""
|
||||
if config.teacher_rollout_model is not None:
|
||||
logger.info("Using external rollout model (MITO) without renderer client")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.model.name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
renderer_pool_size=config.renderer.pool_size,
|
||||
)
|
||||
logger.info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.info("Using token client (TITO) for rollouts — server-side templating, /v1/chat/completions/tokens")
|
||||
else:
|
||||
logger.info("Using MITO (openai_chat_completions) for rollouts")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -68,7 +68,6 @@ class Scheduler:
|
||||
tasks_per_minute: int | None,
|
||||
enable_policy_updates: bool = True,
|
||||
lora_name: str | None = None,
|
||||
use_prefix_cache_salt: bool = False,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
if tasks_per_minute is not None:
|
||||
@@ -87,7 +86,6 @@ class Scheduler:
|
||||
self.strict_async_level = strict_async_level
|
||||
self.enable_policy_updates = enable_policy_updates
|
||||
self.lora_name = lora_name
|
||||
self.use_prefix_cache_salt = use_prefix_cache_salt
|
||||
self.model_name = self.config.model.name
|
||||
self.json_logging = config.log.json_logging
|
||||
|
||||
@@ -150,7 +148,10 @@ class Scheduler:
|
||||
|
||||
@staticmethod
|
||||
def _client_identity(c: vf.ClientConfig) -> tuple[str, str | None]:
|
||||
return (c.api_base_url, c.extra_headers.get("X-data-parallel-rank"))
|
||||
return (
|
||||
c.api_base_url,
|
||||
c.extra_headers.get("X-data-parallel-rank"),
|
||||
)
|
||||
|
||||
async def _select_least_loaded_client(self) -> vf.ClientConfig:
|
||||
"""Select the client with the fewest in-flight tasks.
|
||||
@@ -198,7 +199,7 @@ class Scheduler:
|
||||
env_name = group.example["env_name"]
|
||||
env = self.train_envs.get(env_name)
|
||||
|
||||
cache_salt = str(self.ckpt_step) if self.use_prefix_cache_salt else None
|
||||
cache_salt = str(self.ckpt_step)
|
||||
if env.requires_group_scoring:
|
||||
rollout_count = group.rollouts_to_schedule
|
||||
group.rollouts_to_schedule = 0
|
||||
@@ -434,14 +435,7 @@ class Scheduler:
|
||||
valid_rollouts = []
|
||||
has_failures = False
|
||||
for rollout in rollouts:
|
||||
if len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
)
|
||||
elif rollout["error"] is not None:
|
||||
if rollout["error"] is not None:
|
||||
self.errored_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
self.logger.warning(
|
||||
@@ -449,6 +443,13 @@ class Scheduler:
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
|
||||
f"{rollout['error']['error_chain_repr']}"
|
||||
)
|
||||
elif len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_env[env_name] += 1
|
||||
has_failures = True
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
)
|
||||
else:
|
||||
rollout["env_name"] = env_name
|
||||
valid_rollouts.append(rollout)
|
||||
|
||||
@@ -199,12 +199,32 @@ def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None
|
||||
]
|
||||
|
||||
|
||||
def _tokenize_step_with_renderer(
|
||||
step: vf.TrajectoryStep,
|
||||
renderer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize a trajectory step using a Renderer."""
|
||||
from renderers.base import build_trajectory_step
|
||||
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
return build_trajectory_step(renderer, prompt, completion, tools=tools)
|
||||
|
||||
|
||||
def pretokenize_rollout_trajectory(
|
||||
output: vf.RolloutOutput,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
processor=None,
|
||||
renderer=None,
|
||||
) -> bool:
|
||||
"""Populate missing step tokens from prompt/completion messages."""
|
||||
"""Populate missing step tokens from prompt/completion messages.
|
||||
|
||||
When a renderer is provided, uses it for tokenization (faster, deterministic).
|
||||
Otherwise falls back to the tokenizer + apply_chat_template path.
|
||||
"""
|
||||
logger = get_logger()
|
||||
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
|
||||
|
||||
@@ -212,17 +232,19 @@ def pretokenize_rollout_trajectory(
|
||||
if step["tokens"] is not None:
|
||||
continue
|
||||
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
if renderer is not None:
|
||||
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
|
||||
else:
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
|
||||
return True
|
||||
|
||||
@@ -384,7 +406,11 @@ def interleave_rollout(
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples.append((new_prefix, make_sample(tokens), step_idx))
|
||||
|
||||
# Attach images once per sample using only the last merged step
|
||||
# Attach images once per sample using only the last merged step. Prompt
|
||||
# tokens already contain fully expanded <|image_pad|> placeholders because
|
||||
# VLMs go through MITO (chat completions), which runs apply_chat_template
|
||||
# server-side; the orchestrator re-tokenizes via the same processor in the
|
||||
# fallback path so features and tokens stay 1:1.
|
||||
if vlm_cache is not None:
|
||||
key = output["example_id"] if cache_key is None else cache_key
|
||||
for _, sample, last_step_idx in active_samples:
|
||||
@@ -797,7 +823,7 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
|
||||
Caches per rollout to keep images aligned with divergent multi-turn trajectories.
|
||||
"""
|
||||
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
|
||||
unique_example_ids = {rollout["example_id"] for rollout in rollouts}
|
||||
unique_example_ids = {(rollout.get("env_name"), rollout["example_id"]) for rollout in rollouts}
|
||||
|
||||
# Extract images (also strips base64 data from rollout prompts to free memory)
|
||||
extract_start = time.perf_counter()
|
||||
|
||||
@@ -7,7 +7,6 @@ from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from openai.types.chat.chat_completion import ChatCompletion
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
@@ -85,28 +84,24 @@ async def compute_teacher_logprobs(
|
||||
samples: list[TrainingSample],
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateResponse
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_openai_client(client_config)
|
||||
|
||||
response = await client.post(
|
||||
"/chat/completions/tokens",
|
||||
"/generate",
|
||||
cast_to=GenerateResponse,
|
||||
body={
|
||||
"model": model_name,
|
||||
"messages": [{"role": "user", "content": ""}],
|
||||
"tokens": sample.prompt_ids + sample.completion_ids,
|
||||
"prompt_token_ids": sample.prompt_ids + sample.completion_ids,
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"skip_special_tokens": False,
|
||||
"prompt_logprobs": True,
|
||||
},
|
||||
cast_to=ChatCompletion,
|
||||
)
|
||||
return [
|
||||
0.0 if lp is None else float(next(iter(lp.values()))["logprob"])
|
||||
for lp in getattr(response, "prompt_logprobs", [])
|
||||
]
|
||||
return [0.0 if lp is None else float(lp) for lp in response.prompt_logprobs or []]
|
||||
|
||||
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
|
||||
|
||||
|
||||
@@ -59,12 +59,18 @@ def get_model_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path) -> None:
|
||||
def get_num_turns(output: vf.RolloutOutput) -> int:
|
||||
"""Number of turns (trajectory steps) in a rollout."""
|
||||
return len(output["trajectory"])
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
for rollout in rollouts:
|
||||
json.dump(rollout, f, default=make_serializable)
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
json.dump(row, f, default=make_serializable)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
export VLLM_CACHE_ROOT=/tmp/.vllm_cache_$(whoami)
|
||||
|
||||
# Setup environment
|
||||
@@ -107,6 +108,27 @@ echo "INFER_URLS=${INFER_URLS}"
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
|
||||
# Run inference
|
||||
srun bash -c '
|
||||
cd $PROJECT_DIR
|
||||
|
||||
@@ -66,6 +66,7 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
|
||||
{% if wandb_shared -%}
|
||||
export WANDB_SHARED_MODE=1
|
||||
@@ -151,6 +152,27 @@ uv sync --all-extras
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang (e.g. decode engines stuck at
|
||||
# "Waiting for READY message from DP Coordinator"). Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
|
||||
# Run RL
|
||||
srun bash -c '
|
||||
# Source environment
|
||||
|
||||
@@ -36,6 +36,7 @@ ln -sfn trainer/node_0.log $OUTPUT_DIR/logs/trainer.log
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
@@ -59,6 +60,26 @@ cd $PROJECT_DIR && uv sync --all-extras
|
||||
{{ pre_run_command }}
|
||||
{% endif %}
|
||||
|
||||
# Cleanup stale node-local state from prior jobs. Orphan python/torchrun/vllm
|
||||
# processes and vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM
|
||||
# termination and cause the next launch to hang. Harmless on clean nodes.
|
||||
srun bash -c '
|
||||
pkill -9 -f "python.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "torchrun" 2>/dev/null
|
||||
pkill -9 -f "vllm-router" 2>/dev/null
|
||||
pkill -9 -f "vllm" 2>/dev/null
|
||||
pkill -9 -f "prime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
# which pkill -f does not see because -f only matches the cmdline.
|
||||
pkill -9 "vllm" 2>/dev/null
|
||||
pkill -9 "vllm::.*" 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
'
|
||||
|
||||
# Run SFT
|
||||
srun bash -c '
|
||||
# Setup environment
|
||||
|
||||
@@ -76,6 +76,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
pixel_values=training_example.pixel_values,
|
||||
pixel_values_shape=training_example.pixel_values_shape,
|
||||
image_grid_thw=training_example.image_grid_thw,
|
||||
sft_loss=training_example.sft_loss,
|
||||
)
|
||||
|
||||
|
||||
@@ -115,7 +116,10 @@ def packed_samples_into_micro_bs(
|
||||
if _is_multimodal_sample(bin_content):
|
||||
continue
|
||||
# Check if sequence fits in this bin
|
||||
if len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len:
|
||||
if (
|
||||
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
|
||||
and bin_content.sft_loss == sample.sft_loss
|
||||
):
|
||||
bin_content.input_ids.extend(sample.input_ids)
|
||||
bin_content.loss_mask.extend(sample.loss_mask)
|
||||
bin_content.advantages.extend(sample.advantages)
|
||||
|
||||
@@ -6,8 +6,12 @@ import torch.nn as nn
|
||||
|
||||
from prime_rl.configs.trainer import LoRAConfig
|
||||
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
|
||||
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
from prime_rl.trainer.models.layers.lora.multi_moe import (
|
||||
MultiLoRAGptOssGroupedExperts,
|
||||
MultiLoRAGroupedExperts,
|
||||
MultiLoRANonGatedGroupedExperts,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.moe import GptOssGroupedExperts, GroupedExperts, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -74,8 +78,8 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
|
||||
target_modules = []
|
||||
|
||||
for name, module in model.named_modules():
|
||||
# Check if module is Linear or GroupedExperts
|
||||
if not (isinstance(module, nn.Linear) or isinstance(module, GroupedExperts)):
|
||||
# Check if module is Linear or one of the supported expert classes
|
||||
if not isinstance(module, (nn.Linear, GroupedExperts, NonGatedGroupedExperts, GptOssGroupedExperts)):
|
||||
continue
|
||||
|
||||
for pattern in target_patterns:
|
||||
@@ -137,6 +141,10 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
config: LoRA configuration
|
||||
"""
|
||||
logger = get_logger()
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
|
||||
if isinstance(model, PreTrainedModelPrimeRL):
|
||||
get_multi_run_manager().register_adapter_state_dict_converter(type(model).convert_adapter_to_hf)
|
||||
n_loras = get_multi_run_manager().max_runs
|
||||
|
||||
from torch.distributed.fsdp import FSDPModule
|
||||
@@ -178,10 +186,28 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle NonGatedGroupedExperts (relu2 experts used by NemotronH's LatentMoE)
|
||||
elif isinstance(base_module, NonGatedGroupedExperts):
|
||||
lora_module = MultiLoRANonGatedGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
# Handle GptOssGroupedExperts (gpt-oss fused gate_up + biases)
|
||||
elif isinstance(base_module, GptOssGroupedExperts):
|
||||
lora_module = MultiLoRAGptOssGroupedExperts(
|
||||
base_layer=base_module,
|
||||
rank=config.rank,
|
||||
n_adapters=n_loras,
|
||||
alpha=config.alpha,
|
||||
dropout=config.dropout,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Module {module_name} is type {type(base_module).__name__}, "
|
||||
f"expected nn.Linear or GroupedExperts. Skipping."
|
||||
f"expected nn.Linear, GroupedExperts, NonGatedGroupedExperts, or GptOssGroupedExperts. Skipping."
|
||||
)
|
||||
continue
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
@@ -53,9 +54,24 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
|
||||
def pre_download_model(model_name: str) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
|
||||
if Path(model_name).exists():
|
||||
get_logger().info(f"Model {model_name} found at local path, skipping download")
|
||||
return
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
t0 = time.perf_counter()
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
get_logger().debug(
|
||||
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
|
||||
def _patch_qwen3_5_moe_conversion_mapping():
|
||||
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
|
||||
|
||||
@@ -112,6 +128,171 @@ def _patch_qwen3_5_text_position_ids():
|
||||
decoder_layer_cls.forward = _make_patched_forward(_original_forward)
|
||||
|
||||
|
||||
def _patch_qwen3_5_linear_attn_varlen():
|
||||
"""Thread cu_seqlens through Qwen3.5 GatedDeltaNet so packed batches don't
|
||||
leak conv/SSM state across sequences.
|
||||
|
||||
HF's forward hardcodes seq_idx=None for causal_conv1d and omits cu_seqlens
|
||||
for chunk_gated_delta_rule, so packed RL training sees ~0.23 Mismatch KL vs
|
||||
vLLM (target <0.01). Mirrors the NemotronH mamba fix.
|
||||
"""
|
||||
import torch.nn.functional as F
|
||||
from transformers.models.qwen3_5.modeling_qwen3_5 import (
|
||||
Qwen3_5DecoderLayer,
|
||||
Qwen3_5GatedDeltaNet,
|
||||
Qwen3_5TextModel,
|
||||
apply_mask_to_padding_states,
|
||||
)
|
||||
|
||||
if getattr(Qwen3_5GatedDeltaNet.forward, "_prl_varlen_patched", False):
|
||||
return
|
||||
|
||||
_gdn_orig = Qwen3_5GatedDeltaNet.forward
|
||||
|
||||
def _gdn_forward(self, hidden_states, cache_params=None, attention_mask=None, cu_seqlens=None):
|
||||
if cu_seqlens is None or cache_params is not None:
|
||||
return _gdn_orig(self, hidden_states, cache_params=cache_params, attention_mask=attention_mask)
|
||||
|
||||
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
|
||||
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
|
||||
z = self.in_proj_z(hidden_states).reshape(batch_size, seq_len, -1, self.head_v_dim)
|
||||
b = self.in_proj_b(hidden_states)
|
||||
a = self.in_proj_a(hidden_states)
|
||||
|
||||
if self.causal_conv1d_fn is not None:
|
||||
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
|
||||
seq_idx = torch.repeat_interleave(
|
||||
torch.arange(seg_lens.numel(), dtype=torch.int32, device=hidden_states.device),
|
||||
seg_lens,
|
||||
).unsqueeze(0)
|
||||
mixed_qkv = self.causal_conv1d_fn(
|
||||
x=mixed_qkv,
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
seq_idx=seq_idx,
|
||||
)
|
||||
else:
|
||||
# Per-segment conv1d so the kernel-1 left pad only draws from within each sequence.
|
||||
cu = cu_seqlens.tolist()
|
||||
conv_outs = []
|
||||
for i in range(len(cu) - 1):
|
||||
s, e = cu[i], cu[i + 1]
|
||||
if s == e:
|
||||
continue
|
||||
conv_outs.append(self.conv1d(mixed_qkv[:, :, s:e])[:, :, : e - s])
|
||||
mixed_qkv = F.silu(torch.cat(conv_outs, dim=-1))
|
||||
|
||||
mixed_qkv = mixed_qkv.transpose(1, 2)
|
||||
query, key, value = torch.split(mixed_qkv, [self.key_dim, self.key_dim, self.value_dim], dim=-1)
|
||||
query = query.reshape(batch_size, seq_len, -1, self.head_k_dim)
|
||||
key = key.reshape(batch_size, seq_len, -1, self.head_k_dim)
|
||||
value = value.reshape(batch_size, seq_len, -1, self.head_v_dim)
|
||||
|
||||
beta = b.sigmoid()
|
||||
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
||||
if self.num_v_heads // self.num_k_heads > 1:
|
||||
query = query.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
|
||||
|
||||
core_attn_out, _ = self.chunk_gated_delta_rule(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
initial_state=None,
|
||||
output_final_state=False,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
core_attn_out = core_attn_out.reshape(-1, self.head_v_dim)
|
||||
z = z.reshape(-1, self.head_v_dim)
|
||||
core_attn_out = self.norm(core_attn_out, z)
|
||||
core_attn_out = core_attn_out.reshape(batch_size, seq_len, -1)
|
||||
return self.out_proj(core_attn_out)
|
||||
|
||||
_gdn_forward._prl_varlen_patched = True
|
||||
Qwen3_5GatedDeltaNet.forward = _gdn_forward
|
||||
|
||||
_dec_orig = Qwen3_5DecoderLayer.forward
|
||||
|
||||
def _dec_forward(
|
||||
self,
|
||||
hidden_states,
|
||||
position_embeddings,
|
||||
attention_mask=None,
|
||||
position_ids=None,
|
||||
past_key_values=None,
|
||||
cu_seqlens=None,
|
||||
**kwargs,
|
||||
):
|
||||
if position_ids is not None and position_ids.ndim == 3:
|
||||
position_ids = position_ids[0]
|
||||
if self.layer_type != "linear_attention":
|
||||
return _dec_orig(
|
||||
self,
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.linear_attn(
|
||||
hidden_states=hidden_states,
|
||||
cache_params=past_key_values,
|
||||
attention_mask=attention_mask,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
return residual + hidden_states
|
||||
|
||||
Qwen3_5DecoderLayer.forward = _dec_forward
|
||||
|
||||
_text_orig = Qwen3_5TextModel.forward
|
||||
|
||||
def _text_forward(
|
||||
self,
|
||||
input_ids=None,
|
||||
attention_mask=None,
|
||||
position_ids=None,
|
||||
past_key_values=None,
|
||||
inputs_embeds=None,
|
||||
use_cache=None,
|
||||
**kwargs,
|
||||
):
|
||||
attn_impl = getattr(self.config, "_attn_implementation", None)
|
||||
cu_seqlens = None
|
||||
if attn_impl in ("flash_attention_2", "flash_attention_3", "fa4") and position_ids is not None:
|
||||
pids = position_ids
|
||||
if pids.ndim == 3:
|
||||
pids = pids[0]
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(pids)
|
||||
kwargs["cu_seqlens"] = cu_seqlens
|
||||
return _text_orig(
|
||||
self,
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
past_key_values=past_key_values,
|
||||
inputs_embeds=inputs_embeds,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
Qwen3_5TextModel.forward = _text_forward
|
||||
|
||||
|
||||
# Add filter to the standard logging module for transformers.modeling_utils to supress the
|
||||
# flash attention dtype warnings since FSDP is used to handle mixed precision.
|
||||
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
|
||||
@@ -170,6 +351,27 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_routers = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if isinstance(mlp, (MoE, LatentMoE)):
|
||||
mlp.router.force_balanced = True
|
||||
num_routers += 1
|
||||
|
||||
if num_routers == 0:
|
||||
raise ValueError("No MoE routers found to force-balance. Is this a custom-impl MoE model?")
|
||||
|
||||
logger.warning(
|
||||
f"Forced balanced routing on {num_routers} MoE layers (debug.force_balanced_routing=True). "
|
||||
"Expert assignment is round-robin; gradient flow through the router is broken."
|
||||
)
|
||||
|
||||
|
||||
def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
|
||||
@@ -224,6 +426,7 @@ def get_model(
|
||||
if "Qwen3.5" in config.name or "qwen3_5" in config.name.lower():
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
|
||||
model_config = cast(
|
||||
PretrainedConfig,
|
||||
@@ -262,11 +465,13 @@ def get_model(
|
||||
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
_patch_qwen3_5_moe_conversion_mapping()
|
||||
_patch_qwen3_5_linear_attn_varlen()
|
||||
for subconfig_key in getattr(model_config, "sub_configs", {}):
|
||||
subconfig = getattr(model_config, subconfig_key, None)
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
model_config.fp8 = config.fp8
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
@@ -837,6 +1042,9 @@ def setup_model(
|
||||
|
||||
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
|
||||
|
||||
if config.fp8:
|
||||
replace_linear_with_fp8_blockwise_linear(model)
|
||||
|
||||
# Apply LoRA before FSDP setup
|
||||
if config.lora is not None:
|
||||
apply_lora_to_model(model, config.lora)
|
||||
@@ -844,6 +1052,9 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, config, parallel_dims)
|
||||
# EP replaces params with DTensors that default to requires_grad=True,
|
||||
@@ -889,6 +1100,24 @@ def setup_model(
|
||||
return model
|
||||
|
||||
|
||||
def _get_qwen3_vl_mm_token_type_ids(model: nn.Module, input_ids: Tensor) -> Tensor | None:
|
||||
config = getattr(model, "config", None)
|
||||
if getattr(config, "model_type", None) != "qwen3_vl":
|
||||
return None
|
||||
|
||||
mm_token_type_ids = torch.zeros_like(input_ids)
|
||||
|
||||
image_token_id = getattr(config, "image_token_id", None)
|
||||
if image_token_id is not None:
|
||||
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == image_token_id, 1)
|
||||
|
||||
video_token_id = getattr(config, "video_token_id", None)
|
||||
if video_token_id is not None:
|
||||
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == video_token_id, 2)
|
||||
|
||||
return mm_token_type_ids
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
def forward(
|
||||
model: nn.Module,
|
||||
@@ -915,7 +1144,9 @@ def forward(
|
||||
assert image_grid_thw is not None, "pixel_values requires image_grid_thw for MRoPE computation"
|
||||
kwargs["pixel_values"] = pixel_values
|
||||
kwargs["image_grid_thw"] = image_grid_thw
|
||||
kwargs["mm_token_type_ids"] = mm_token_type_ids
|
||||
mm_token_type_ids = _get_qwen3_vl_mm_token_type_ids(model, input_ids)
|
||||
if mm_token_type_ids is not None:
|
||||
kwargs["mm_token_type_ids"] = mm_token_type_ids
|
||||
else:
|
||||
kwargs["position_ids"] = position_ids
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
@@ -27,6 +28,7 @@ AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
@@ -37,6 +39,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbeddingConfig,
|
||||
apply_rotary_pos_emb,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
@@ -352,6 +353,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=getattr(config, "load_balance_coeff", None),
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
@@ -489,16 +491,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
|
||||
if use_flash:
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = None
|
||||
else:
|
||||
|
||||
@@ -103,6 +103,21 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
"""
|
||||
raise NotImplementedError(f"convert_layer_to_prime is not implemented for {cls.__name__}")
|
||||
|
||||
@classmethod
|
||||
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert a LoRA adapter state dict from PrimeRL training format to HuggingFace format.
|
||||
|
||||
Unlike convert_to_hf, this operates on a partial state dict containing only LoRA
|
||||
adapter parameters (e.g. `model.layers.N.<submodule>.<proj>.lora_A.weight`). Models
|
||||
whose HF naming differs from PrimeRL naming at the submodule level (e.g. NemotronH's
|
||||
unified `mixer` attribute) should override this to perform the rename.
|
||||
|
||||
Implementations may mutate state_dict in-place or return a new dict; callers must
|
||||
use the returned value. Default implementation is a no-op.
|
||||
"""
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
cls,
|
||||
|
||||
@@ -39,6 +39,7 @@ from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
@@ -67,6 +68,7 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
@@ -215,16 +217,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
@@ -278,6 +271,10 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
perform autoregressive decoding, so this argument is unused.
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
|
||||
If not provided, the wrapped LM head returns logits only.
|
||||
|
||||
@@ -27,7 +27,6 @@ from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.cp import gather_for_cp, shard_for_cp
|
||||
|
||||
|
||||
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
|
||||
@@ -66,6 +65,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
@@ -86,22 +86,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return hasattr(self, "_cp_group") and hasattr(self, "_cp_rank") and hasattr(self, "_cp_world_size")
|
||||
|
||||
def shard_to_cp(self, t: torch.Tensor) -> torch.Tensor:
|
||||
if not self.cp_enabled:
|
||||
return t
|
||||
|
||||
return shard_for_cp(t, self._cp_rank, self._cp_world_size)
|
||||
|
||||
def gather_for_cp(self, t: torch.Tensor) -> torch.Tensor:
|
||||
if not self.cp_enabled:
|
||||
return t
|
||||
|
||||
return gather_for_cp(t, self._cp_group)
|
||||
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
@@ -114,14 +99,12 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.gather_for_cp(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
)
|
||||
hidden_states = self.shard_to_cp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
@@ -246,19 +229,32 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cp_group, _, cp_world_size = self._context_parallel_state()
|
||||
cp_group, cp_rank, cp_world_size = self._context_parallel_state()
|
||||
if cp_group is not None and cp_world_size > 1:
|
||||
position_ids_for_attn = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
else:
|
||||
position_ids_for_attn = position_ids
|
||||
position_ids_full = position_ids
|
||||
|
||||
flat_position_ids = position_ids_for_attn.view(-1)
|
||||
S = flat_position_ids.shape[0]
|
||||
ks = torch.arange(S, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(torch.int32)
|
||||
ke = torch.arange(1, S + 1, dtype=torch.int32, device=flat_position_ids.device)
|
||||
flat_position_ids = position_ids_full.view(-1)
|
||||
S_full = flat_position_ids.shape[0]
|
||||
ks_full = torch.arange(S_full, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(
|
||||
torch.int32
|
||||
)
|
||||
ke_full = torch.arange(1, S_full + 1, dtype=torch.int32, device=flat_position_ids.device)
|
||||
|
||||
# Position embeddings are computed over the full sequence: K uses cos/sin[0:S_full]
|
||||
# while Q uses the local CP slice. ks/ke are computed in K's global coordinate
|
||||
# system and then sharded to the local Q range so the indexer's per-token
|
||||
# causal/varlen mask aligns with the gathered K.
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids_for_attn)
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids_full)
|
||||
|
||||
if cp_world_size > 1:
|
||||
s_local = S_full // cp_world_size
|
||||
ks = ks_full[cp_rank * s_local : (cp_rank + 1) * s_local].contiguous()
|
||||
ke = ke_full[cp_rank * s_local : (cp_rank + 1) * s_local].contiguous()
|
||||
else:
|
||||
ks, ke = ks_full, ke_full
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
@@ -307,6 +303,10 @@ class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, GenerationMixin):
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility — prime-rl asserts `use_cache is None` since training does not
|
||||
perform autoregressive decoding, so this argument is unused.
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user