Compare commits
64
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
961c11f4cf | ||
|
|
b7b1f874b5 | ||
|
|
d334ea5294 | ||
|
|
57d2b84330 | ||
|
|
4f5e06fcb6 | ||
|
|
390dfdc556 | ||
|
|
2fdffa7d3d | ||
|
|
7cbc77a27f | ||
|
|
21c072a8f9 | ||
|
|
cb43db2ad1 | ||
|
|
2c6ac2bd47 | ||
|
|
4d64d38a60 | ||
|
|
d3fe2a8044 | ||
|
|
df5f991bf4 | ||
|
|
546fd69709 | ||
|
|
321c8aa825 | ||
|
|
84b413fd73 | ||
|
|
9e0d242cd0 | ||
|
|
b127f0375b | ||
|
|
4bbf967a57 | ||
|
|
cdb1480c66 | ||
|
|
f34efdbf49 | ||
|
|
9b47b777aa | ||
|
|
1877714656 | ||
|
|
77766bb59c | ||
|
|
1caebf8a1b | ||
|
|
db04385acf | ||
|
|
2bc136cf85 | ||
|
|
6bfbd64aef | ||
|
|
b453f40d8c | ||
|
|
1b028ca1d1 | ||
|
|
e96bbae2dd | ||
|
|
df2acf4874 | ||
|
|
5ff9abd8b5 | ||
|
|
5448f5a722 | ||
|
|
8a977ecc9c | ||
|
|
1ab29c0587 | ||
|
|
5e6b641574 | ||
|
|
16f5c7222b | ||
|
|
5c0a6dbdba | ||
|
|
dbe95b799a | ||
|
|
07e6bec87a | ||
|
|
9fede0ac78 | ||
|
|
d16981b533 | ||
|
|
b2b4f3f711 | ||
|
|
50aeb3c7d6 | ||
|
|
4beb553525 | ||
|
|
51dc60a895 | ||
|
|
a8f090b444 | ||
|
|
cdea189e3d | ||
|
|
d5f218f708 | ||
|
|
a03c70f55b | ||
|
|
e48a53853e | ||
|
|
f3c85a947a | ||
|
|
f19ba721a9 | ||
|
|
fd5db5df6a | ||
|
|
7b7c7efdfa | ||
|
|
2e2accb121 | ||
|
|
436873190d | ||
|
|
f0c339a234 | ||
|
|
9f425fffcb | ||
|
|
16efd8afda | ||
|
|
7d5f2d74a6 | ||
|
|
2a0007f51d |
@@ -25,7 +25,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --extra flash-attn --all-packages --locked
|
||||
- name: Run tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
@@ -90,14 +90,24 @@ jobs:
|
||||
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
|
||||
- name: Verify real configs (with [slurm]) parse on slim install
|
||||
run: |
|
||||
/tmp/slim/bin/python - <<'PY'
|
||||
from pydantic_config import cli
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
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}"
|
||||
# Configs that don't pull in a v1 env package parse on the slim
|
||||
# (prime-rl-configs-only) install: the SFT config has no env sections, and the
|
||||
# reverse_text RL recipe uses a v0 env id (resolved lazily, not imported at parse).
|
||||
# RL configs on a v1 taskset can't parse here because vf.EnvServerConfig imports the
|
||||
# (uninstalled) env package at parse time.
|
||||
for cfg_cls, args in [
|
||||
(SFTConfig, ["@", "examples/reverse_text/slurm_sft.toml"]),
|
||||
(RLConfig, ["@", "examples/reverse_text/rl.toml", "@", "examples/reverse_text/slurm_rl.toml"]),
|
||||
]:
|
||||
cfg = cli(cfg_cls, args=args)
|
||||
assert cfg.slurm is not None, f"expected [slurm] in {args}"
|
||||
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
|
||||
assert cfg.slurm.template_path is None, f"unexpected template_path on slim: {cfg.slurm.template_path}"
|
||||
print("slim parse OK")
|
||||
PY
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run unit tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run integration tests
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
enable-cache: true
|
||||
cache-dependency-glob: "uv.lock"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras --locked
|
||||
run: uv sync --all-extras --all-packages --locked
|
||||
- name: Run experiment
|
||||
env:
|
||||
USERNAME_CI: CI_RUNNER
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
|
||||
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
|
||||
|
||||
+11
-6
@@ -32,6 +32,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
|
||||
libnl-route-3-dev \
|
||||
libibverbs-dev \
|
||||
librdmacm-dev \
|
||||
python3.12 \
|
||||
python3.12-venv \
|
||||
python3.12-dev \
|
||||
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
|
||||
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
ARG UCX_VERSION=1.19.1
|
||||
@@ -60,8 +64,13 @@ ADD https://astral.sh/uv/install.sh /uv-installer.sh
|
||||
# Set install dir to location accessible to non-root users
|
||||
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
|
||||
ENV PATH="/usr/local/bin:$PATH"
|
||||
ENV UV_PYTHON_INSTALL_DIR="/usr/local/share/uv/python"
|
||||
# Build .venv against the system CPython, so the venv's recorded interpreter
|
||||
# matches the runtime interpreter and no bin/python relink is needed at runtime.
|
||||
ENV UV_PYTHON_PREFERENCE=only-system
|
||||
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
|
||||
# Explicity set venv dir inside /app so to ensure it gets copied over during
|
||||
# the runtime stage's `COPY /app`
|
||||
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
|
||||
|
||||
# Install Python dependencies (The gradual copies help with caching)
|
||||
WORKDIR /app
|
||||
@@ -102,7 +111,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
&& \
|
||||
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
|
||||
&& \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
@@ -219,10 +228,6 @@ COPY --from=builder /opt/ucx /opt/ucx
|
||||
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
|
||||
RUN rm /app/.venv/bin/python && ln -s /usr/local/bin/python /app/.venv/bin/python
|
||||
RUN rm /app/.venv/bin/python3 && ln -s /usr/local/bin/python /app/.venv/bin/python3
|
||||
RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/python3.12
|
||||
|
||||
# Place executables in the environment at the front of the path
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
ENV UCX_HOME=/opt/ucx
|
||||
|
||||
@@ -111,6 +111,8 @@ source $HOME/.local/bin/env
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
4.1. On aarch64 hosts: build flash-attn from source for your GPU
|
||||
|
||||
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
resume_step = 15
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
|
||||
@@ -8,3 +8,6 @@ gpu_memory_utilization = 0.7
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
max_model_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ id = "reverse-text"
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -16,3 +16,6 @@ freq = 1
|
||||
|
||||
[model.compile]
|
||||
fullgraph = false
|
||||
|
||||
[weight_broadcast]
|
||||
type = "filesystem"
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
max_steps = 15
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
|
||||
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
|
||||
# path is fixed. See CI RL integration test failures on main.
|
||||
type = "filesystem"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ max_inflight_rollouts = 512
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
@@ -41,8 +41,8 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
|
||||
|
||||
@@ -36,7 +36,7 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -41,8 +41,8 @@ name = "qwen3"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
|
||||
taskset = { id = "general-agent-v1", tools = { colocated = true } }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -23,7 +23,7 @@ max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
@@ -34,7 +34,7 @@ max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "test" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ max_inflight_rollouts = 256
|
||||
[[orchestrator.train.env]]
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
|
||||
[orchestrator.eval]
|
||||
@@ -39,7 +39,7 @@ interval = 50
|
||||
[[orchestrator.eval.env]]
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
group_size = 32
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
# v1 port of configs/rlm_swe/qwen35_4b.toml — identical except the env blocks, which load
|
||||
# the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime instead of the
|
||||
# v0 `rlm_swe` composable env. Same model / trainer / inference / orchestrator knobs.
|
||||
# Qwen3.5-4B SWE RL on the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime.
|
||||
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
|
||||
@@ -27,7 +27,7 @@ max_completion_tokens = 128
|
||||
taskset = { id = "reverse-text-v1" }
|
||||
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
|
||||
# directly) and use the subprocess runtime (no docker).
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
|
||||
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
|
||||
|
||||
@@ -16,7 +16,8 @@ rollouts_per_example = 4
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ rollouts_per_example = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
min_tier = 1
|
||||
|
||||
@@ -32,7 +32,8 @@ rollouts_per_example = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "general-agent-solver-rlm"
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 SEARCH-domain envs — bring-your-own-search QA, run
|
||||
# through the rlm harness (its built-in `search` skill) on a prime sandbox. GRPO + linear length
|
||||
# penalty. 2 train + 4 infer nodes. Single run label (glm45air-search) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-search"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-search" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.env]]
|
||||
name = "openseeker"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
|
||||
[[orchestrator.train.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "redsearcher"
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: BrowseComp held-out test, every 20 steps (incl. step 0) ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -0,0 +1,133 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
|
||||
# CPU offload, and skip-gather / skip-optimizer checkpointing. Derived from
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
taskset = { id = "scaleswe-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -0,0 +1,181 @@
|
||||
# exp: GLM-4.5-Air (100B MoE) RL across our v1 TERMINAL-domain envs — agentic shell/sandbox tasks
|
||||
# run through the rlm harness (ipython-only) on a prime sandbox. Each task ships its own Docker image
|
||||
# (NEEDS_CONTAINER) injected into the sandbox; grading is host-side inside the container. GRPO +
|
||||
# linear length penalty. 2 train + 4 infer nodes. Single run label (glm45air-terminal) for all envs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-terminal"
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-terminal" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 4
|
||||
|
||||
[wandb]
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_gather_master_weights = true
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "tmax"
|
||||
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
|
||||
[orchestrator.train.env.taskset]
|
||||
id = "tmax-v1"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Eval: swebench-verified (avg@1) + terminal-bench-2 (full, avg@4) every 20 steps, incl. step 0 ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
use_prime_registry = true
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp.
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 131072
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -1,4 +1,4 @@
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.23.
|
||||
# GLM-5.2-FP8 16-node P/D, FULL STACK: mooncake + llm-d router, vLLM 0.24.
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
@@ -31,9 +31,9 @@ num_bytes = 1_000_000_000_000
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
|
||||
|
||||
[deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 2
|
||||
gpus_per_node = 8
|
||||
|
||||
[slurm]
|
||||
|
||||
@@ -16,9 +16,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[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 }
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
|
||||
@@ -16,9 +16,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[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 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -5,7 +5,7 @@ seq_len = 2048
|
||||
|
||||
[slurm]
|
||||
job_name = "nemotron-4node"
|
||||
pre_run_command = "uv sync --all-extras --group mamba-ssm"
|
||||
pre_run_command = "uv sync --all-extras --all-packages --group mamba-ssm"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -51,9 +51,9 @@ group_size = 8
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[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 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -50,9 +50,9 @@ group_size = 16
|
||||
max_completion_tokens = 4096
|
||||
|
||||
[[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 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 10
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "rlm-swe-qwen35-4b"
|
||||
project_dir = "."
|
||||
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 2
|
||||
|
||||
[wandb]
|
||||
project = "rlm-swe-debug"
|
||||
name = "qwen35-4b"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 8
|
||||
max_inflight_rollouts = 512
|
||||
max_off_policy_steps = 16
|
||||
|
||||
# Thinking enabled for the Qwen3.5 renderer.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-r2e"
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-swebench-verified-quick"
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.args]
|
||||
task_type = "swebench"
|
||||
dataset_name = "PrimeIntellect/SWE-Bench-Verified-Quick"
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
dp = 8
|
||||
|
||||
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
|
||||
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
|
||||
[inference.vllm_extra]
|
||||
language_model_only = true
|
||||
@@ -23,7 +23,7 @@ batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
id = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: a5efbb97e4...5904fa24aa
Vendored
+1
-1
Submodule deps/research-environments updated: 99ebd2e133...06232831fd
Vendored
+1
-1
Submodule deps/verifiers updated: aa95826d4e...31415cd32a
+1
-1
@@ -106,7 +106,7 @@ dropout = 0.0
|
||||
|
||||
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
|
||||
|
||||
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
|
||||
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
|
||||
|
||||
```toml
|
||||
[ckpt.weights]
|
||||
|
||||
+4
-4
@@ -157,7 +157,7 @@ At step $n = 1, 2, 3, \dots$:
|
||||
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
|
||||
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
|
||||
|
||||
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
|
||||
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
|
||||
|
||||
## Loss
|
||||
|
||||
@@ -282,14 +282,14 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Write a named algorithm class when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …) — see [Authoring an Algorithm](#authoring-an-algorithm).
|
||||
|
||||
Two built-in **length penalties** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling: `tokens` penalizes long completions by weighted token cost, `turns` penalizes long multi-turn rollouts by turn count.
|
||||
A **length penalty** (`length_penalty` on the `grpo`-family algorithms) can be layered on top to discourage rambling. The `linear` penalty subtracts a single `pass_rate`-scaled penalty from each reward before the GRPO baseline, combining output tokens (`num_output_tokens_weight`), input / context tokens (`num_input_tokens_weight`), and turns (`num_turns_weight`) — each normalized by the group's own max for that quantity, with `num_input_tokens_weight` and `num_turns_weight` defaulting to `0.1`.
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "tokens"
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
|
||||
@@ -312,7 +312,7 @@ class MyAlgorithm(Algorithm):
|
||||
rollout.assign_advantages(advantage)
|
||||
```
|
||||
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask). Shared math like `efficiency_shaping` lives in `prime_rl.orchestrator.algo.advantage`.
|
||||
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
|
||||
|
||||
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
|
||||
|
||||
|
||||
@@ -151,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
|
||||
id = "math-env"
|
||||
name = "gsm8k"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "math-env"
|
||||
@@ -162,6 +163,8 @@ name = "gsm8k-eval"
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
|
||||
|
||||
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
|
||||
@@ -215,7 +218,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
|
||||
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
|
||||
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
|
||||
|
||||
|
||||
+9
-11
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
|
||||
|
||||
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
|
||||
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
|
||||
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
prefill_nodes_per_replica = 2
|
||||
decode_nodes_per_replica = 2
|
||||
```
|
||||
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
|
||||
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 2
|
||||
num_decode_nodes = 2
|
||||
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 2
|
||||
decode_nodes_per_replica = 2
|
||||
num_decode_replicas = 1
|
||||
```
|
||||
|
||||
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
|
||||
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
|
||||
|
||||
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
|
||||
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
|
||||
|
||||
```toml
|
||||
[deployment] # this is a top-level RL deployment, not inference.deployment!!
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
num_infer_nodes = 6 # this is per-replica
|
||||
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
+2
-2
@@ -179,7 +179,7 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
|
||||
|
||||
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
|
||||
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
|
||||
|
||||
### Activation
|
||||
|
||||
@@ -208,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
|
||||
gpus_per_node = 8 # default
|
||||
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
|
||||
```
|
||||
|
||||
+3
-1
@@ -226,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
|
||||
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
|
||||
|
||||
```bash
|
||||
# First run: steps 0–10
|
||||
# First run: steps 1–10
|
||||
uv run rl @ rl.toml --max-steps 10 --ckpt
|
||||
|
||||
# Resume: continue to step 20
|
||||
@@ -307,6 +307,8 @@ uv run rl @ rl.toml --wandb \
|
||||
--no-trainer.wandb.log-extras.distributions
|
||||
```
|
||||
|
||||
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
|
||||
|
||||
### Platform Monitoring
|
||||
|
||||
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
|
||||
|
||||
@@ -32,7 +32,7 @@ group_size = 8
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ You also need prime-rl cloned on your cluster into the shared filesystem.
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
### Install llm-d
|
||||
|
||||
@@ -19,15 +19,14 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
prefill_nodes_per_replica = 2
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
decode_nodes_per_replica = 8
|
||||
num_decode_replicas = 1
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
@@ -96,17 +95,9 @@ extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "r2e"
|
||||
num_workers = 16
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
max_turns = 300
|
||||
timeout_seconds = 21600
|
||||
summarize_at_tokens = [35000, 80000]
|
||||
poll_interval = 5
|
||||
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
|
||||
labels = ["glm5-llmd"]
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -15,14 +15,13 @@ quantize_in_weight_transfer = true
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 8
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 2
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 4
|
||||
num_decode_nodes = 4
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
@@ -73,9 +72,9 @@ name = "zai-org/GLM-5-FP8"
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", 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}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
|
||||
@@ -17,16 +17,17 @@ group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[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"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "primeintellect/aime2024"
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
|
||||
@@ -15,7 +15,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
@@ -48,34 +48,34 @@ batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[[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}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
|
||||
|
||||
[[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" }
|
||||
taskset = { id = "deepdive-v1" }
|
||||
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
|
||||
taskset = { id = "i3_math_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "logic-env"
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
|
||||
taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "code-env"
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
args = { pool_size = 512 }
|
||||
taskset = { id = "i3_code_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
@@ -85,12 +85,14 @@ enforce = true
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", 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}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
name = "aime2025"
|
||||
taskset = { id = "aime25-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -50,17 +50,17 @@ max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[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}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", 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}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -42,9 +42,9 @@ group_size = 16
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[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 }
|
||||
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -49,14 +49,17 @@ max_off_policy_steps = 8
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "math-env"
|
||||
name = "math"
|
||||
taskset = { id = "i3_math_v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "aime2025"
|
||||
name = "aime2025"
|
||||
taskset = { id = "aime25-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
@@ -47,17 +47,17 @@ oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[[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}
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "mini-swe-agent-plus"
|
||||
name = "swe-bench-verified-quick"
|
||||
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", 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}
|
||||
name = "swe-bench-verified"
|
||||
taskset = { id = "swebench-verified-v1" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
@@ -45,7 +45,7 @@ type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wiki-search"
|
||||
id = "wiki-search"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ batch_size = 1024
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
id = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.1.15.dev390",
|
||||
"verifiers>=0.2.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -91,24 +91,22 @@ class SamplingConfig(BaseConfig):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
"""Linear ``pass_rate``-scaled penalty subtracted from each reward before the GRPO baseline — the sum of three terms (completion tokens, input tokens, turns), each normalized by the group's own max for that quantity and disabled by setting its coefficient to 0."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
type: Literal["linear"] = "linear"
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
num_output_tokens_weight: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the output-token term. Each reward is reduced by ``num_output_tokens_weight * pass_rate * (rollout num_output_tokens / group's max num_output_tokens)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative; 0 disables the term."""
|
||||
|
||||
num_input_tokens_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the input-token term — tokens the model conditioned on but did not generate (``num_total_tokens - num_output_tokens``: prompts, tool responses), as a fraction of the group's max input tokens. 0 disables the term."""
|
||||
|
||||
num_turns_weight: float = Field(0.1, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the turns term (``pass_rate * (rollout num_turns / group's max num_turns)``). 0 disables the term."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
LengthPenaltyConfig: TypeAlias = LinearLengthPenaltyConfig
|
||||
|
||||
|
||||
class EchoRoleConfig(BaseConfig):
|
||||
@@ -199,7 +197,7 @@ class GRPOAlgoConfig(BaseAlgoConfig):
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
"""Linear length penalty subtracted from each reward before the GRPO baseline (see ``LinearLengthPenaltyConfig``): a ``pass_rate``-scaled sum of output-token, input-token, and turns terms, each normalized by the group's own max for that quantity. None disables it."""
|
||||
|
||||
|
||||
class EchoAlgoConfig(GRPOAlgoConfig):
|
||||
|
||||
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
|
||||
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
|
||||
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
|
||||
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
|
||||
# request routing.
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: int = Field(1, ge=1)
|
||||
"""Total prefill nodes."""
|
||||
prefill_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each prefill vLLM instance."""
|
||||
|
||||
num_decode_nodes: int = Field(1, ge=1)
|
||||
"""Total decode nodes."""
|
||||
decode_nodes_per_replica: int = Field(1, ge=1)
|
||||
"""Nodes in each decode vLLM instance."""
|
||||
|
||||
num_prefill_replicas: int = Field(1, ge=1)
|
||||
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
|
||||
"""Independent prefill vLLM instances."""
|
||||
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
"""Independent decode vLLM instances."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
@@ -312,24 +309,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_prefill_nodes(self) -> int:
|
||||
return self.prefill_nodes_per_replica * self.num_prefill_replicas
|
||||
|
||||
@property
|
||||
def num_decode_nodes(self) -> int:
|
||||
return self.decode_nodes_per_replica * self.num_decode_replicas
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_replicas_divide_nodes(self):
|
||||
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
|
||||
f"num_prefill_nodes ({self.num_prefill_nodes})"
|
||||
)
|
||||
if self.num_decode_nodes % self.num_decode_replicas != 0:
|
||||
raise ValueError(
|
||||
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
|
||||
f"num_decode_nodes ({self.num_decode_nodes})"
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
|
||||
@@ -337,10 +328,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
@@ -420,6 +407,9 @@ class InferenceConfig(BaseConfig):
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
@@ -436,8 +426,6 @@ class InferenceConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
|
||||
@@ -614,6 +602,10 @@ class InferenceConfig(BaseConfig):
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_lm_head"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
if self.enable_fp32_router_logits:
|
||||
existing = getattr(namespace, "additional_config", None) or {}
|
||||
existing["fp32_router_logits"] = True
|
||||
rsetattr(namespace, "additional_config", existing)
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
|
||||
@@ -50,7 +50,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0)
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
@@ -92,7 +92,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0)
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
"""Sampling temperature. None defers to the inference server default."""
|
||||
|
||||
top_p: float | None = None
|
||||
@@ -157,11 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -193,9 +190,9 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
def validate_env(self):
|
||||
if not self.taskset.id and not self.id:
|
||||
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
|
||||
if self.resolved_name == "all":
|
||||
if self.resolved_name == "agg":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -248,13 +245,10 @@ class TrainConfig(BaseConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
|
||||
worker ``pool`` is configured per env, defaulting to elastic)."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -262,8 +256,6 @@ class TrainConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -276,15 +268,6 @@ class TrainConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_ratios(self):
|
||||
ratios = [env.ratio for env in self.env]
|
||||
if all(r is None for r in ratios):
|
||||
return self
|
||||
if any(r is None for r in ratios):
|
||||
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
@@ -299,9 +282,6 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
@@ -311,7 +291,7 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
@@ -326,8 +306,6 @@ class EvalConfig(BaseConfig):
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -443,10 +421,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -563,8 +537,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
|
||||
@@ -46,10 +46,6 @@ from prime_rl.utils.validation import (
|
||||
)
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
level: str | None = None
|
||||
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
@@ -115,7 +111,7 @@ class SharedModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem"] = "nccl"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
port: int = 29501
|
||||
@@ -159,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
num_infer_nodes: int = Field(ge=0)
|
||||
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
num_infer_nodes: int | None = Field(None, ge=0)
|
||||
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
@@ -171,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def infer_nodes_per_replica(self) -> int:
|
||||
return self.num_infer_nodes or 0
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
return self.infer_nodes_per_replica * self.num_infer_replicas
|
||||
|
||||
|
||||
DeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -234,23 +234,49 @@ class RLConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: RLExperimentalConfig = RLExperimentalConfig()
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_infer_nodes(self):
|
||||
if self.deployment.type != "multi_node":
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
inferred_nodes = 0
|
||||
elif self.inference.deployment.type == "multi_node":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
elif self.inference.deployment.type == "disaggregated":
|
||||
inferred_nodes = self.inference.deployment.num_nodes
|
||||
else:
|
||||
inferred_nodes = 1
|
||||
|
||||
if self.deployment.num_infer_nodes is None:
|
||||
self.deployment.num_infer_nodes = inferred_nodes
|
||||
elif (
|
||||
self.inference is not None
|
||||
and self.inference.deployment.type == "multi_node"
|
||||
and self.deployment.num_infer_nodes != inferred_nodes
|
||||
):
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
num_infer_nodes = self.deployment.infer_nodes_per_replica
|
||||
if num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
if num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
@@ -310,29 +336,46 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
|
||||
|
||||
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
|
||||
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
|
||||
server is configured (NCCL requires a running inference pool).
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
|
||||
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
|
||||
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
|
||||
# an adapter and would hang/fail on the startup weight sync.
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with NCCL weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
@@ -537,7 +580,7 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
|
||||
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
|
||||
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
|
||||
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
|
||||
expected_global_world_size = self.inference.parallel.dp * inference_tp
|
||||
if expected_global_world_size != total_infer_gpus:
|
||||
raise ValueError(
|
||||
@@ -599,12 +642,11 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
infer_deploy = self.inference.deployment
|
||||
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
|
||||
if self.deployment.num_infer_nodes != expected_infer_nodes:
|
||||
expected_infer_nodes = infer_deploy.num_nodes
|
||||
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
|
||||
raise ValueError(
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
|
||||
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
|
||||
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
|
||||
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
|
||||
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
|
||||
)
|
||||
|
||||
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
|
||||
@@ -167,10 +167,6 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class SFTExperimentalConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -226,7 +222,7 @@ class SFTConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 600
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
|
||||
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
|
||||
@@ -243,8 +239,6 @@ class SFTConfig(BaseConfig):
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
|
||||
@@ -58,6 +58,9 @@ class SlurmConfig(BaseConfig):
|
||||
cleanup_grace_period: int = Field(3600, ge=0)
|
||||
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
|
||||
|
||||
shared_fs: bool = True
|
||||
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
"""Common template variables for all SLURM templates."""
|
||||
@@ -71,6 +74,7 @@ class SlurmConfig(BaseConfig):
|
||||
"time": self.time,
|
||||
"pre_run_command": self.pre_run_command,
|
||||
"cleanup_grace_period": self.cleanup_grace_period,
|
||||
"shared_fs": self.shared_fs,
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -117,6 +117,9 @@ class DebugModelConfig(BaseConfig):
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
conversion_dir: Path | None = None
|
||||
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
|
||||
|
||||
seq_len: int = 2048
|
||||
"""Sequence length the model is trained on."""
|
||||
|
||||
@@ -171,6 +174,9 @@ class ModelConfig(BaseModelConfig):
|
||||
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""dtype for gradient/parameter reductions."""
|
||||
|
||||
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
|
||||
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
|
||||
|
||||
moe_use_grouped_mm: bool = True
|
||||
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
|
||||
|
||||
@@ -554,7 +560,7 @@ class TrainerConfig(BaseConfig):
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: int = 600
|
||||
dist_timeout_seconds: int = 3600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
@@ -649,7 +655,7 @@ class TrainerConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support this
|
||||
# TODO: Support NCCL broadcast with LoRA
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
|
||||
@@ -6,6 +6,40 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
|
||||
from pydantic_config import cli # noqa: F401
|
||||
|
||||
|
||||
def to_toml_dict(config: BaseModel, exclude: set[str] | None = None) -> dict:
|
||||
"""Dump a config to a TOML-serializable dict.
|
||||
|
||||
TOML cannot represent null, so None fields left at their default are dropped
|
||||
(they re-resolve identically on re-parse) while explicitly-set None fields
|
||||
are encoded as the string ``"None"``, which ``BaseConfig`` converts back to
|
||||
``None``. Dropping those too would silently revert explicit None overrides
|
||||
(e.g. ``--trainer.model.compile None``) to their non-None defaults when the
|
||||
written config is re-parsed.
|
||||
"""
|
||||
return _encode_model(config, config.model_dump(exclude=exclude, mode="json"))
|
||||
|
||||
|
||||
def _encode_model(model: BaseModel, dumped: dict) -> dict:
|
||||
encoded = {}
|
||||
for name, value in dumped.items():
|
||||
if value is None:
|
||||
if name in model.model_fields_set:
|
||||
encoded[name] = "None"
|
||||
continue
|
||||
encoded[name] = _encode_value(getattr(model, name), value)
|
||||
return encoded
|
||||
|
||||
|
||||
def _encode_value(attr: Any, value: Any) -> Any:
|
||||
if isinstance(attr, BaseModel) and isinstance(value, dict):
|
||||
return _encode_model(attr, value)
|
||||
if isinstance(value, list) and isinstance(attr, (list, tuple)):
|
||||
return [_encode_value(a, v) for a, v in zip(attr, value)]
|
||||
if isinstance(value, dict) and isinstance(attr, dict):
|
||||
return {k: _encode_value(a, v) for (k, v), a in zip(value.items(), attr.values())}
|
||||
return "None" if value is None else value
|
||||
|
||||
|
||||
def find_package_resource(subdir: str) -> Path | None:
|
||||
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
|
||||
|
||||
@@ -38,19 +72,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
|
||||
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
|
||||
|
||||
@@ -317,14 +317,11 @@ def validate_shared_weight_broadcast(
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
if (
|
||||
inference
|
||||
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
|
||||
):
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
|
||||
)
|
||||
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
|
||||
raise ValueError(
|
||||
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
|
||||
)
|
||||
|
||||
+33
-97
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -19,9 +19,10 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers==5.6.2",
|
||||
"vllm>=0.23.0",
|
||||
"vllm>=0.24.0",
|
||||
"mooncake-transfer-engine>=0.3.10.post2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
"pyzmq>=27.1.0",
|
||||
@@ -33,7 +34,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers>=0.1.15.dev400",
|
||||
"verifiers[harbor]>=0.2.0",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
@@ -54,7 +55,7 @@ orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
@@ -65,55 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"alphabet-sort",
|
||||
"general-agent",
|
||||
"logic-env",
|
||||
"math-env",
|
||||
"math-python",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"uuid-ctf-v1",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
"reverse-text-v1",
|
||||
"gsm8k-v1",
|
||||
"math-env-v1",
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort-v1",
|
||||
"scaleswe-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"gpqa-v1",
|
||||
"livecodebench-v1",
|
||||
"r2e-gym-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"code-golf-v1",
|
||||
"deepwiki-v1",
|
||||
"glossary-v1",
|
||||
"swelego-v1",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle-v1",
|
||||
"general-agent-v1",
|
||||
"swebench-verified-v1",
|
||||
"tau2-bench-v1",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"ifeval-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"i3-code-v1",
|
||||
"i3-science-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
"deep-gemm ; platform_machine == 'x86_64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router ; platform_machine == 'x86_64'",
|
||||
"vllm-router",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
@@ -152,7 +110,6 @@ dev = [
|
||||
# *without* the cooldown — bypassing this security policy.
|
||||
required-version = ">=0.11.1"
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
"sys_platform == 'linux' and platform_machine == 'x86_64'",
|
||||
@@ -166,7 +123,21 @@ override-dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers>=0.1.15.dev400",
|
||||
]
|
||||
|
||||
# Environment packages (research-environments + verifiers) are auto-discovered as
|
||||
# workspace members, so new envs need no per-package registration. Install them
|
||||
# with `uv sync --all-packages`.
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"deps/research-environments/environments/*/*",
|
||||
"deps/verifiers/environments/*",
|
||||
]
|
||||
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
|
||||
exclude = [
|
||||
"deps/research-environments/environments/tool_use/tau2_synth_v1",
|
||||
"deps/research-environments/environments/tool_use/tau3_bench_v1",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -218,60 +189,25 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
|
||||
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
|
||||
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
|
||||
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
|
||||
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
math500-v1 = { path = "deps/research-environments/environments/math500_v1", editable = true }
|
||||
mmlu-pro-v1 = { path = "deps/research-environments/environments/mmlu_pro_v1", editable = true }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
i3-code-v1 = { path = "deps/research-environments/environments/i3_code_v1", editable = true }
|
||||
i3-science-v1 = { path = "deps/research-environments/environments/i3_science_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
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" }
|
||||
|
||||
@@ -59,9 +59,9 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
|
||||
|
||||
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
|
||||
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
|
||||
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
|
||||
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
|
||||
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
|
||||
(one training sample is built per branch).
|
||||
|
||||
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
|
||||
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
|
||||
condition and a complete conversation, so it stays; its reward may be partial/zero, which
|
||||
`--min-reward` handles.
|
||||
|
||||
Usage (from the prime-rl repo):
|
||||
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
|
||||
[-o OUT_DIR] [--push HF_REPO_ID]
|
||||
|
||||
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
|
||||
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
|
||||
(PrimeIntellect-ai/verifiers#1963).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from datasets import Dataset
|
||||
from verifiers.v1 import Trace, WireTrace
|
||||
from verifiers.v1.dialects.chat import message_to_wire
|
||||
|
||||
|
||||
def sft_rows(trace: Trace) -> list[dict]:
|
||||
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
|
||||
dicts plus the trace's advertised tools, JSON-encoded."""
|
||||
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
|
||||
return [
|
||||
{
|
||||
"messages": [message_to_wire(m) for m in branch.messages],
|
||||
"tools": tools,
|
||||
}
|
||||
for branch in trace.branches
|
||||
if branch.messages
|
||||
]
|
||||
|
||||
|
||||
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
|
||||
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
|
||||
if trace.stop_condition == "error":
|
||||
return False
|
||||
if drop_truncated and trace.is_truncated:
|
||||
return False
|
||||
return min_reward is None or trace.reward >= min_reward
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
|
||||
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
|
||||
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
|
||||
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
|
||||
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
|
||||
args = parser.parse_args()
|
||||
|
||||
traces_path = args.run_dir / "traces.jsonl"
|
||||
if not traces_path.exists():
|
||||
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
|
||||
|
||||
total, rows = 0, []
|
||||
with traces_path.open(encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if not line.strip():
|
||||
continue
|
||||
total += 1
|
||||
trace = WireTrace.model_validate(json.loads(line))
|
||||
if keep(trace, args.min_reward, args.drop_truncated):
|
||||
rows.extend(sft_rows(trace))
|
||||
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
|
||||
if not rows:
|
||||
raise SystemExit("export-sft: no rows to export after selection")
|
||||
|
||||
dataset = Dataset.from_list(rows)
|
||||
if args.push:
|
||||
dataset.push_to_hub(args.push)
|
||||
print(f"export-sft: pushed to {args.push}")
|
||||
return
|
||||
out = args.output_dir or args.run_dir / "sft"
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
dataset.to_parquet(str(out / "train.parquet"))
|
||||
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+6
-10
@@ -22,12 +22,14 @@ git submodule update --init --recursive
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
uv sync # core only
|
||||
uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
|
||||
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
|
||||
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
|
||||
```
|
||||
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -41,12 +43,6 @@ CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
|
||||
|
||||
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
|
||||
|
||||
### FP8 inference (GLM-5-FP8, etc.)
|
||||
|
||||
```bash
|
||||
uv sync --group fp8-inference # installs the prebuilt deep-gemm wheel
|
||||
```
|
||||
|
||||
### Trainer DeepEP backend
|
||||
|
||||
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
|
||||
|
||||
@@ -34,6 +34,8 @@ Default cadence: **1 hour** (researcher can override). At each check-in:
|
||||
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
|
||||
```
|
||||
|
||||
In W&B, each project auto-gets an **"overview" saved view** (train / eval / stability / performance sections) on its first run — use it for a quick check instead of the auto-generated default workspace.
|
||||
|
||||
### Restarting a run
|
||||
|
||||
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
|
||||
@@ -56,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
|
||||
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
|
||||
- `{output_dir}/logs/` — see below.
|
||||
- `{output_dir}/rollouts/step_N/` — saved rollouts.
|
||||
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
|
||||
|
||||
### Logs
|
||||
|
||||
@@ -128,21 +130,28 @@ curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
### Rollouts
|
||||
### Traces
|
||||
|
||||
```
|
||||
{output_dir}/rollouts/step_N/
|
||||
├── train_rollouts.jsonl # all train rollouts (vf.RolloutOutput, trajectory excluded)
|
||||
├── eval_rollouts.jsonl # only present when eval ran
|
||||
└── train_rollouts.bin # binary batch consumed by the trainer
|
||||
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
|
||||
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
|
||||
```
|
||||
|
||||
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
|
||||
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
|
||||
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
|
||||
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
|
||||
`kind`, `env_name`, `group_id`, `policy_version`, and `eval_step`, plus `runtime` (config +
|
||||
provisioned resource id, e.g. the sandbox id).
|
||||
|
||||
```bash
|
||||
wc -l {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
head -1 {output_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
|
||||
jq '.reward' {output_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
|
||||
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.errors != []) | {id, env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
|
||||
|
||||
@@ -36,10 +36,11 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- SLURM: single- and multi-node
|
||||
- Environment packages: before launching a config with a non-core verifier env id,
|
||||
verify the package imports under `uv run` (for example
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('rlm_swe'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` but does not
|
||||
import, add it to the root `pyproject.toml` env extra, workspace members, and
|
||||
`[tool.uv.sources]`, then run `uv sync --all-extras`.
|
||||
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
|
||||
If a local env exists under `deps/research-environments/environments/` or
|
||||
`deps/verifiers/environments/` but does not import, install the env workspace
|
||||
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
|
||||
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
|
||||
|
||||
## `sft` — SFT training
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
|
||||
@@ -33,7 +33,7 @@ def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] |
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = output_dir / INFERENCE_TOML
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude=exclude, exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
return config_path
|
||||
|
||||
|
||||
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars.update(
|
||||
num_prefill_nodes=config.deployment.num_prefill_nodes,
|
||||
num_decode_nodes=config.deployment.num_decode_nodes,
|
||||
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
|
||||
num_prefill_replicas=config.deployment.num_prefill_replicas,
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
@@ -56,9 +56,8 @@ def get_physical_gpu_ids() -> list[int]:
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(output_dir / RL_TOML, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
@@ -66,16 +65,16 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / TRAINER_TOML, "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.trainer), f)
|
||||
|
||||
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.orchestrator), f)
|
||||
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -410,6 +409,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
num_prefill_nodes=infer_deploy.num_prefill_nodes,
|
||||
num_decode_nodes=infer_deploy.num_decode_nodes,
|
||||
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
|
||||
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
@@ -441,11 +442,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
@@ -496,7 +497,7 @@ def rl_slurm(config: RLConfig):
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
|
||||
has_infer = config.deployment.num_infer_nodes > 0
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
|
||||
@@ -9,7 +9,7 @@ from threading import Event, Thread
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
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
|
||||
from prime_rl.utils.process import (
|
||||
@@ -28,9 +28,8 @@ SFT_SBATCH = "sft.sbatch"
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
"""Write resolved config to disk, excluding launcher-only fields."""
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(config_dict, f)
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
|
||||
|
||||
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
|
||||
|
||||
+173
-226
@@ -3,20 +3,19 @@ import torch
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
in every vLLM process, including spawned workers. Note vLLM swallows plugin
|
||||
load failures (``load_plugins_by_group`` logs and continues), so a broken
|
||||
entry-point target silently skips ALL of these patches.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
@@ -100,6 +99,91 @@ def monkey_patch_nano_v3_reasoning_parser():
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_qwen3_coder_param_newline_trim():
|
||||
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
|
||||
|
||||
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
|
||||
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
|
||||
exactly one leading and one trailing newline. A full strip corrupts
|
||||
whitespace-significant string parameters (str_replace-style
|
||||
``old_str``/``new_str``, file content with an indented first line, values
|
||||
with intentional trailing newlines), silently changing tool execution and
|
||||
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
|
||||
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
|
||||
"""
|
||||
import json
|
||||
|
||||
from vllm.parser import qwen3
|
||||
|
||||
def _trim_one_newline(value: str) -> str:
|
||||
if value.startswith("\n"):
|
||||
value = value[1:]
|
||||
if value.endswith("\n"):
|
||||
value = value[:-1]
|
||||
return value
|
||||
|
||||
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
params: dict[str, object] = {}
|
||||
|
||||
for match in qwen3._PARAM_RE.finditer(raw_args):
|
||||
name = match.group(1)
|
||||
value = match.group(2)
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
if partial:
|
||||
remaining = qwen3._PARAM_RE.sub("", raw_args)
|
||||
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
value = m.group(2)
|
||||
if name:
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
return json.dumps(params, ensure_ascii=False)
|
||||
|
||||
qwen3._qwen3_arg_converter = _patched_arg_converter
|
||||
# qwen3_config captures the converter when first built; drop any cached configs.
|
||||
qwen3.qwen3_config.cache_clear()
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
|
||||
|
||||
prime-rl serves MiniMax-M2 with ``reasoning=minimax_m2_append_think``, which
|
||||
returns content as ``<think>`` + the full completion so think tags round-trip
|
||||
through multi-turn re-serialization. vLLM 0.24's minimax_m2 parser engine
|
||||
added a ``(CONTENT, THINK_END) -> no-events`` transition that silently
|
||||
swallows the ``</think>`` (0.23's regex tool parser passed it through
|
||||
untouched), and it also ``.strip()``s content whenever tool calls are
|
||||
present. Drop the transition — the engine emits unmatched terminals as plain
|
||||
state content — and disable the content strip.
|
||||
"""
|
||||
import dataclasses
|
||||
import functools
|
||||
|
||||
from vllm.parser import minimax_m2
|
||||
from vllm.parser.engine.parser_engine_config import ParserState
|
||||
|
||||
original_config = minimax_m2.minimax_m2_config
|
||||
|
||||
@functools.cache
|
||||
def _patched_config():
|
||||
config = original_config()
|
||||
transitions = dict(config.transitions)
|
||||
del transitions[(ParserState.CONTENT, "THINK_END")]
|
||||
return dataclasses.replace(
|
||||
config,
|
||||
transitions=transitions,
|
||||
strip_content_whitespace_with_tools=False,
|
||||
)
|
||||
|
||||
minimax_m2.minimax_m2_config = _patched_config
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -185,7 +269,7 @@ def monkey_patch_strip_routed_experts_from_chat():
|
||||
def _patch_qwen35_moe_lora_format():
|
||||
"""Force Qwen3.5-MoE onto vLLM's 2D per-expert LoRA format.
|
||||
|
||||
vLLM 0.23.0 defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
vLLM 0.24.0 still defaults ``Qwen3_5MoeForConditionalGeneration.is_3d_moe_weight = True``,
|
||||
which makes the LoRA loader expect 3D stacked-expert adapters
|
||||
(``base_layer.lora_{A,B}.weight`` / ``lora_{A,B}.weight``, experts folded into the
|
||||
rank dim; see ``_stack_moe_lora_weights``). Our trainer instead emits the 2D
|
||||
@@ -206,16 +290,23 @@ def _patch_qwen35_moe_lora_format():
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
"""Accept both bare-suffix and fully-qualified expert module names in LoRA adapters.
|
||||
|
||||
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
|
||||
We can remove this patch once that PR makes it into a release.
|
||||
Copy of vLLM 0.24.0's ``LoRAModel.from_local_checkpoint`` with one change: the
|
||||
``.experts`` branch of ``check_unexpected_modules`` accepts either the bare suffix
|
||||
(``down_proj``) or the qualified per-expert name (``experts.N.down_proj``), where
|
||||
upstream only accepts the qualified form. Our trainer's 2D per-expert adapters
|
||||
(Qwen3.5-MoE) carry names whose qualified form is not in the expected set while
|
||||
the bare suffix is; Qwen3-30B-A3B adapters go the other way. Upstream fix
|
||||
vllm-project/vllm#38522 was closed unmerged, so this stays.
|
||||
"""
|
||||
from vllm.lora.lora_model import (
|
||||
LoRAModel,
|
||||
MoEEPLoadSpec,
|
||||
PEFTHelper,
|
||||
TensorizerConfig,
|
||||
WeightsMapper,
|
||||
_is_remote_expert_key,
|
||||
get_lora_id,
|
||||
is_base_embedding_weights,
|
||||
os,
|
||||
@@ -236,6 +327,7 @@ def _patch_lora_key_prefix():
|
||||
weights_mapper: WeightsMapper | None = None,
|
||||
tensorizer_config_dict: dict | None = None,
|
||||
skip_prefixes: list[str] | None = None,
|
||||
moe_ep_spec: MoEEPLoadSpec | None = None,
|
||||
) -> "LoRAModel":
|
||||
"""Create a LoRAModel from a local checkpoint.
|
||||
|
||||
@@ -251,6 +343,11 @@ def _patch_lora_key_prefix():
|
||||
skip_prefixes: List of module name prefixes to skip during loading.
|
||||
Models can define this to skip modules not used in inference
|
||||
(e.g., MTP layers). Format: ["mtp."]
|
||||
moe_ep_spec: When 2D FusedMoE LoRA modules are present with
|
||||
expert parallelism enabled, the (ep_rank, local, global)
|
||||
slicing metadata shared across all MoE layers. Non-local
|
||||
expert weights are skipped at read time instead of being
|
||||
loaded and discarded later.
|
||||
|
||||
Returns:
|
||||
Loaded LoRA Model.
|
||||
@@ -275,22 +372,13 @@ def _patch_lora_key_prefix():
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
# Case for expert lora weights.
|
||||
# For standard MoE models the name ends in "...experts",
|
||||
# so expert_idx+1 yields "experts" which is in
|
||||
# expected_lora_modules.
|
||||
# For Qwen 3.5 MoE (and similar models) the expert index
|
||||
# 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.
|
||||
# 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.
|
||||
## START PATCHED CODE (upstream only accepts the qualified form)
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
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)
|
||||
## END PATCHED CODE
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
@@ -307,11 +395,15 @@ def _patch_lora_key_prefix():
|
||||
from tensorizer import TensorDeserializer
|
||||
|
||||
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
|
||||
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_dir = tensorizer_config.tensorizer_dir
|
||||
if tensorizer_dir is None:
|
||||
raise ValueError("tensorizer_dir must be set in tensorizer config.")
|
||||
lora_tensor_path = os.path.join(tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_args = tensorizer_config._construct_tensorizer_args()
|
||||
tensors = TensorDeserializer(
|
||||
lora_tensor_path,
|
||||
dtype=tensorizer_config.dtype,
|
||||
device=device,
|
||||
**tensorizer_args.deserialization_kwargs,
|
||||
)
|
||||
check_unexpected_modules(tensors)
|
||||
@@ -328,11 +420,18 @@ def _patch_lora_key_prefix():
|
||||
# Load tensors if there are only expected modules.
|
||||
check_unexpected_modules(f)
|
||||
for module in f.keys(): # noqa
|
||||
if moe_ep_spec is not None and _is_remote_expert_key(module, moe_ep_spec):
|
||||
continue
|
||||
tensors[module] = f.get_tensor(module)
|
||||
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
|
||||
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
|
||||
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
|
||||
check_unexpected_modules(tensors)
|
||||
if moe_ep_spec is not None:
|
||||
# `.bin`/`.pt` adapters can't be lazy-loaded, but pruning
|
||||
# the dict here still frees the non-local expert tensors
|
||||
# before the dtype cast / pin_memory work that follows.
|
||||
tensors = {k: v for k, v in tensors.items() if not _is_remote_expert_key(k, moe_ep_spec)}
|
||||
else:
|
||||
raise ValueError(f"{lora_dir} doesn't contain tensors")
|
||||
|
||||
@@ -350,177 +449,6 @@ def _patch_lora_key_prefix():
|
||||
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
|
||||
|
||||
|
||||
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_load_lora_adapter():
|
||||
from http import HTTPStatus
|
||||
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.models.serving import (
|
||||
OpenAIServingModels,
|
||||
create_error_response,
|
||||
)
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
async def _patched_load_lora_adapter(
|
||||
self: OpenAIServingModels, request: LoadLoRAAdapterRequest, base_model_name: str | None = None
|
||||
) -> ErrorResponse | str:
|
||||
lora_name = request.lora_name
|
||||
|
||||
# Ensure atomicity based on the lora name
|
||||
async with self.lora_resolver_lock[lora_name]:
|
||||
lora_path = request.lora_path
|
||||
## START PATCHED CODE
|
||||
if lora_name in self.lora_requests:
|
||||
lora_request = self.lora_requests[lora_name]
|
||||
lora_request.lora_path = lora_path
|
||||
else:
|
||||
unique_id = self.lora_id_counter.inc(1)
|
||||
lora_request = LoRARequest(lora_name=lora_name, lora_int_id=unique_id, lora_path=lora_path)
|
||||
## END PATCHED CODE
|
||||
if base_model_name is not None and self.is_base_model(base_model_name):
|
||||
lora_request.base_model_name = base_model_name
|
||||
|
||||
# Validate that the adapter can be loaded into the engine
|
||||
# This will also preload it for incoming requests
|
||||
try:
|
||||
await self.engine_client.add_lora(lora_request)
|
||||
except Exception as e:
|
||||
error_type = "BadRequestError"
|
||||
status_code = HTTPStatus.BAD_REQUEST
|
||||
if "No adapter found" in str(e):
|
||||
error_type = "NotFoundError"
|
||||
status_code = HTTPStatus.NOT_FOUND
|
||||
|
||||
return create_error_response(message=str(e), err_type=error_type, status_code=status_code)
|
||||
|
||||
self.lora_requests[lora_name] = lora_request
|
||||
logger.info("Loaded new LoRA adapter: name '%s', path '%s'", lora_name, lora_path)
|
||||
return f"Success: LoRA adapter '{lora_name}' added successfully."
|
||||
|
||||
OpenAIServingModels.load_lora_adapter = _patched_load_lora_adapter
|
||||
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_LRUCacheWorkerLoRAManager():
|
||||
from vllm.lora.worker_manager import LoRARequest, LRUCacheLoRAModelManager, LRUCacheWorkerLoRAManager
|
||||
|
||||
# The dunder is intended. It's a private method that we're patching.
|
||||
def _patched__apply_adapters(self: LRUCacheWorkerLoRAManager, lora_requests: set[LoRARequest]) -> None:
|
||||
loras_map = {lora_request.lora_int_id: lora_request for lora_request in lora_requests if lora_request}
|
||||
if len(loras_map) > self._adapter_manager.lora_slots:
|
||||
raise RuntimeError(
|
||||
f"Number of requested LoRAs ({len(loras_map)}) is greater "
|
||||
"than the number of GPU LoRA slots "
|
||||
f"({self._adapter_manager.lora_slots})."
|
||||
)
|
||||
for lora in loras_map.values():
|
||||
## START PATCHED CODE
|
||||
self.add_adapter(lora, force_load=False)
|
||||
## END PATCHED CODE
|
||||
|
||||
def _patched_add_adapter(
|
||||
self: LRUCacheWorkerLoRAManager, lora_request: LoRARequest, force_load: bool = True
|
||||
) -> bool:
|
||||
# Note that this method is not thread-safe. It may be invoked multiple
|
||||
# times for the same adapter when using multiple API servers.
|
||||
# This is ok because it's currently only called from
|
||||
# the single-threaded core engine loop.
|
||||
|
||||
## START PATCHED CODE
|
||||
if lora_request.lora_int_id not in self.list_adapters() or force_load:
|
||||
## END PATCHED CODE
|
||||
# Load the new adapter first to ensure it is actually valid, before
|
||||
# evicting any existing adapters.
|
||||
# This may cause the # of loaded lora adapters to very temporarily
|
||||
# exceed `--max-cpu-loras`.
|
||||
lora = self._load_adapter(lora_request)
|
||||
## START PATCHED CODE
|
||||
self._adapter_manager.remove_adapter(lora.id)
|
||||
## END PATCHED CODE
|
||||
|
||||
# Loading succeeded, now check if we will exceed cache capacity and
|
||||
# evict if the oldest adapter if so
|
||||
if len(self._adapter_manager) + 1 > self._adapter_manager.capacity:
|
||||
assert isinstance(self._adapter_manager, LRUCacheLoRAModelManager)
|
||||
self._adapter_manager.remove_oldest_adapter()
|
||||
# Then add the new adapter to the cache
|
||||
loaded = self._adapter_manager.add_adapter(lora)
|
||||
else:
|
||||
# If the lora is already loaded, just touch it to
|
||||
# update its position in the caches
|
||||
loaded = self._adapter_manager.get_adapter(lora_request.lora_int_id) is not None
|
||||
self._adapter_manager.activate_adapter(lora_request.lora_int_id)
|
||||
return loaded
|
||||
|
||||
LRUCacheWorkerLoRAManager._apply_adapters = _patched__apply_adapters
|
||||
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():
|
||||
"""
|
||||
@@ -608,7 +536,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: rebuild the gate as GateLinear with a bf16 weight (out_dtype=float32
|
||||
keeps fp32 router logits). vLLM 0.23.0's own forward already drops the
|
||||
keeps fp32 router logits). vLLM 0.24.0's own forward already drops the
|
||||
float32 input cast. FusedMoE also has router_logits_dtype=float32, so
|
||||
routing precision is preserved inside the expert dispatch.
|
||||
|
||||
@@ -634,7 +562,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
|
||||
# vLLM 0.23.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# vLLM 0.24.0 builds the gate as GateLinear with a float32 weight; rebuild it
|
||||
# with a bf16 weight (model dtype) so the LoRA Triton kernel's float16/bfloat16
|
||||
# assertion passes, keeping out_dtype=float32 so router logits stay fp32 (the
|
||||
# GateLinear bf16xbf16->fp32 path).
|
||||
@@ -646,19 +574,7 @@ def monkey_patch_minimax_m2_for_lora():
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
@@ -703,23 +619,15 @@ def monkey_patch_no_moe_lora():
|
||||
Otherwise, the oracle will always try to pick TritonExperts.
|
||||
For blackwells, we want TRTLLMFlashInfer.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig, logger
|
||||
from vllm.model_executor.layers.fused_moe.config import FusedMoEConfig
|
||||
|
||||
original_post_init = FusedMoEConfig.__post_init__
|
||||
|
||||
def _patched__post_init__(self: FusedMoEConfig):
|
||||
if self.dp_size > 1:
|
||||
logger.debug_once("Using FusedMoEConfig::max_num_tokens=%d", self.max_num_tokens)
|
||||
|
||||
assert self.max_num_tokens > 0
|
||||
|
||||
if self.router_logits_dtype is None:
|
||||
self.router_logits_dtype = self.in_dtype
|
||||
|
||||
if self.hidden_dim_unpadded is None:
|
||||
self.hidden_dim_unpadded = self.hidden_dim
|
||||
if self.intermediate_size_per_partition_unpadded is None:
|
||||
self.intermediate_size_per_partition_unpadded = self.intermediate_size_per_partition
|
||||
|
||||
# Disable LoRA for MoE layers
|
||||
original_post_init(self)
|
||||
# Disable LoRA for MoE layers. `is_lora_enabled` is only read later during
|
||||
# kernel selection (modular_kernel / unquantized oracle), never inside
|
||||
# `__post_init__`, so flipping it after the original runs is sufficient.
|
||||
self.is_lora_enabled = False
|
||||
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
@@ -787,12 +695,51 @@ def monkey_patch_fp32_lm_head():
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_fp32_router_logits():
|
||||
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
|
||||
|
||||
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
|
||||
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
|
||||
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
|
||||
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
|
||||
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
|
||||
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
|
||||
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
|
||||
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
|
||||
|
||||
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
|
||||
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
|
||||
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
|
||||
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
|
||||
branch, whose kernel wants matching dtypes).
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = DeepseekV2MoE.__init__
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
additional_config = get_current_vllm_config().additional_config or {}
|
||||
if not additional_config.get("fp32_router_logits", False):
|
||||
return
|
||||
if self.gate.out_dtype is None:
|
||||
self.gate.set_out_dtype(torch.float32)
|
||||
|
||||
DeepseekV2MoE.__init__ = _patched_init
|
||||
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
own spawn-time re-import can exceed the hard-coded timeout under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
|
||||
@@ -2,7 +2,6 @@ import logging.config
|
||||
import os
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli
|
||||
|
||||
|
||||
def setup_vllm_env(config: InferenceConfig):
|
||||
@@ -11,7 +10,8 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.23.0 routes dense Llama/Mistral/Qwen3 to the
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
@@ -20,6 +20,12 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
# grammar-constrains generation (xgrammar structural tags) for tool_choice
|
||||
# "required"/named and strict tools — a sampling distribution the trainer never
|
||||
# sees. Keep it off so rollout logprobs stay faithful for importance ratios.
|
||||
os.environ.setdefault("VLLM_ENFORCE_STRICT_TOOL_CALLING", "0")
|
||||
|
||||
deep_gemm_enabled = "1" if config.use_deep_gemm else "0"
|
||||
os.environ["VLLM_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
os.environ["VLLM_MOE_USE_DEEP_GEMM"] = deep_gemm_enabled
|
||||
@@ -41,17 +47,3 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
|
||||
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
|
||||
logging.config.dictConfig(build_dict_config(config.log.level))
|
||||
|
||||
|
||||
def main():
|
||||
config = cli(InferenceConfig)
|
||||
setup_vllm_env(config)
|
||||
|
||||
# We import here to be able to set environment variables before importing vLLM
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -22,7 +22,6 @@ logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -32,9 +31,6 @@ from prime_rl.inference.patches import (
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
|
||||
monkey_patch_harmony_stop_token_propagation()
|
||||
# NOTE: Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# 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.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
@@ -50,7 +46,7 @@ monkey_patch_vllm_padded_input_scrub()
|
||||
# routed_experts from chat responses since the server-wide enable flag has no
|
||||
# per-request toggle.
|
||||
monkey_patch_strip_routed_experts_from_chat()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# NOTE: vLLM hard-codes a 120s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
@@ -97,9 +93,29 @@ async def update_weights(request: Request):
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter."""
|
||||
"""Wrapper around vLLM's /v1/load_lora_adapter.
|
||||
|
||||
prime-rl reloads a fixed-name adapter with fresh weights every step (the path
|
||||
changes per policy version; the name is constant, see orchestrator.lora_name).
|
||||
vLLM's native loader rejects a same-name reload unless ``load_inplace=True``,
|
||||
so we force it here — that makes the worker re-read the new weights during
|
||||
``add_lora``, reusing the existing ``lora_int_id``.
|
||||
|
||||
We then reset the stored request's flag back to ``False``. ``load_inplace`` is
|
||||
a sticky field on the ``LoRARequest`` that ``_maybe_get_adapters`` hands to
|
||||
every generation request; left ``True`` it would force a disk reload on each
|
||||
scheduler step. The orchestrator awaits this endpoint before dispatching
|
||||
rollouts for the new version, so the reset always lands before generation.
|
||||
The reset runs regardless of success/error: vLLM only stores the adapter on
|
||||
success today, but resetting whatever is stored keeps us correct even if a
|
||||
future version were to leave a ``load_inplace=True`` request behind on error.
|
||||
"""
|
||||
handler = models(raw_request)
|
||||
lora_request.load_inplace = True
|
||||
response = await handler.load_lora_adapter(lora_request)
|
||||
stored = handler.lora_requests.get(lora_request.lora_name)
|
||||
if stored is not None:
|
||||
stored.load_inplace = False
|
||||
if isinstance(response, ErrorResponse):
|
||||
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
|
||||
return {"status": "ok"}
|
||||
@@ -150,7 +166,6 @@ async def custom_init_app_state(
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
state.liveness_timeout_seconds = args.liveness_timeout_seconds
|
||||
|
||||
# Swap in our ServingTokens subclass for /inference/v1/generate so the
|
||||
|
||||
@@ -3,19 +3,13 @@ import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_LRUCacheWorkerLoRAManager,
|
||||
monkey_patch_fp32_router_logits,
|
||||
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)
|
||||
@@ -27,3 +21,6 @@ else:
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
|
||||
monkey_patch_fp32_router_logits()
|
||||
|
||||
@@ -24,42 +24,6 @@ else:
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nccl")
|
||||
|
||||
# NemotronH mixer.D is dropped by vLLM's layerwise online-reload path (left uninitialized).
|
||||
_RELOAD_CORRUPTED_SUFFIXES = (".mixer.D",)
|
||||
|
||||
|
||||
def _restore_reload_corrupted_params(model: Module, received: dict[str, torch.Tensor]) -> None:
|
||||
"""Work around a vLLM layerwise-reload bug for NemotronH (present through vLLM 0.23.0).
|
||||
|
||||
The online reload drops the weight load for every Mamba layer's ``mixer.D`` (the SSD skip
|
||||
connection), leaving it as uninitialized ``empty_strided`` memory -- it reads back as garbage
|
||||
(NaN/inf) and the logits go NaN after a weight update. Root cause: ``mixer.A`` is loaded with
|
||||
``composed_weight_loader`` (an extra in-place transform copy), so the reload element counter
|
||||
double-counts ``A`` and finalizes the layer before ``D`` (loaded last) is loaded. The received
|
||||
broadcast value is correct, so restore D from it via the param's own ``weight_loader``.
|
||||
|
||||
Fixed upstream by vllm-project/vllm#44814 (merged 2026-06-10) but NOT in the pinned 0.23.0
|
||||
release; remove this shim once we bump to a vLLM release that includes it.
|
||||
"""
|
||||
|
||||
def _layer_key(name: str) -> str:
|
||||
index = name.find("layers.")
|
||||
return name[index:] if index >= 0 else name
|
||||
|
||||
received_by_key = {_layer_key(name): tensor for name, tensor in received.items()}
|
||||
for name, param in model.named_parameters():
|
||||
if not name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
continue
|
||||
tensor = received_by_key.get(_layer_key(name))
|
||||
if tensor is None:
|
||||
continue
|
||||
tensor = tensor.to(device=param.device)
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
weight_loader(param, tensor)
|
||||
elif tensor.shape == param.shape:
|
||||
param.data.copy_(tensor.to(param.dtype))
|
||||
|
||||
|
||||
def receive_integer(communicator: PyNcclCommunicator) -> int:
|
||||
"""Receive an integer from the trainer master rank using NCCL communicator."""
|
||||
@@ -184,20 +148,9 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
# vLLM's layerwise reload drops NemotronH mixer.D's weight load (see
|
||||
# _restore_reload_corrupted_params). Capture the correct received value to restore after.
|
||||
received_reload_fix: dict[str, torch.Tensor] = {}
|
||||
|
||||
def _capture_reload_fix(weights):
|
||||
for name, tensor in weights:
|
||||
if name.endswith(_RELOAD_CORRUPTED_SUFFIXES):
|
||||
received_reload_fix[name] = tensor.detach().to("cpu", copy=True)
|
||||
yield name, tensor
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
_capture_reload_fix(state_iter),
|
||||
state_iter,
|
||||
self.model_runner.model_config,
|
||||
self.vllm_config,
|
||||
)
|
||||
_restore_reload_corrupted_params(model, received_reload_fix)
|
||||
|
||||
@@ -5,6 +5,7 @@ from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -47,20 +48,20 @@ def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_p
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
if module._expert_map is None:
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(module._expert_map >= 0)[0]
|
||||
local_indices = module._expert_map[physical_indices]
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(module, "eplb_state", None)
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, module.global_num_experts)
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
@@ -70,14 +71,23 @@ def _build_expert_source_indices(module) -> torch.Tensor | None:
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map FusedMoE module names to source expert indices local to this worker."""
|
||||
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, FusedMoE):
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module)
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
@@ -94,7 +104,10 @@ def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Te
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
for name, tensor in state_iter:
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
@@ -14,10 +14,9 @@ turns the signal half into runtime objects (the sampling half is the env's
|
||||
and register it below.
|
||||
- ``base`` — the :class:`Algorithm` base class, whose non-virtual
|
||||
``finalize_rollout`` / ``finalize_group`` methods the pipeline drives.
|
||||
- ``advantage`` — shared advantage math (``efficiency_shaping``). Advantages
|
||||
are per-token everywhere they are stored or shipped — there is no scalar
|
||||
advantage in the pipeline. An algorithm assigns credit in its scoring hook
|
||||
via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
|
||||
Advantages are per-token everywhere they are stored or shipped — there is no
|
||||
scalar advantage in the pipeline. An algorithm assigns credit in its scoring
|
||||
hook via ``Rollout.assign_advantages``: a scalar that is *broadcast* over the
|
||||
rollout's completion tokens (uniform credit, the common case), or an explicit
|
||||
full-length-N per-token list aligned to the concatenated sample token_ids
|
||||
(0.0 off-mask).
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the 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 efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
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)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from prime_rl.configs.algorithm import EchoAlgoConfig
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -55,7 +56,9 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
(role tags, separators, tool-response wraps) is excluded. Nodes without
|
||||
attribution (the default renderer, or relay turns with no token ids)
|
||||
fall back to weighting the whole non-sampled span."""
|
||||
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
|
||||
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
|
||||
# stays aligned when fork dedup drops a branch.
|
||||
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
|
||||
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
|
||||
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
|
||||
weights = [0.0] * len(sample.token_ids)
|
||||
|
||||
@@ -4,10 +4,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig, TokensLengthPenaltyConfig
|
||||
from prime_rl.orchestrator.algo.advantage import efficiency_shaping
|
||||
from prime_rl.configs.algorithm import GRPOAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
from prime_rl.orchestrator.utils import get_tool_response_len
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -25,21 +23,21 @@ class GRPOAlgorithm(Algorithm):
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
|
||||
lp = self.length_penalty
|
||||
if lp is None:
|
||||
length_penalty = self.length_penalty
|
||||
if length_penalty is None:
|
||||
advantages = rewards - rewards.mean()
|
||||
elif isinstance(lp, TokensLengthPenaltyConfig):
|
||||
costs = torch.tensor(
|
||||
[
|
||||
lp.completion_weight * rollout.completion_len
|
||||
+ lp.tool_response_weight * get_tool_response_len(rollout)
|
||||
for rollout in group
|
||||
],
|
||||
dtype=rewards.dtype,
|
||||
else:
|
||||
output = torch.tensor([rollout.num_output_tokens for rollout in group], dtype=rewards.dtype)
|
||||
total = torch.tensor([rollout.num_total_tokens for rollout in group], dtype=rewards.dtype)
|
||||
turns = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
|
||||
input = total - output
|
||||
penalty_frac = (
|
||||
length_penalty.num_output_tokens_weight * (output / output.max().clamp(min=1))
|
||||
+ length_penalty.num_input_tokens_weight * (input / input.max().clamp(min=1))
|
||||
+ length_penalty.num_turns_weight * (turns / turns.max().clamp(min=1))
|
||||
)
|
||||
advantages = efficiency_shaping(rewards, costs)
|
||||
else: # TurnsLengthPenaltyConfig
|
||||
costs = torch.tensor([rollout.num_turns for rollout in group], dtype=rewards.dtype)
|
||||
advantages = efficiency_shaping(rewards, costs)
|
||||
penalty = rewards.mean() * penalty_frac
|
||||
shaped_rewards = rewards - penalty
|
||||
advantages = shaped_rewards - shaped_rewards.mean()
|
||||
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
|
||||
rollout.assign_advantages(advantage)
|
||||
|
||||
@@ -53,11 +53,11 @@ class OPSDAlgorithm(Algorithm):
|
||||
def _demonstration(self, rollout: Rollout) -> str:
|
||||
demonstration = rollout.info.get(self.demo_key)
|
||||
if demonstration is None:
|
||||
demonstration = getattr(rollout.task, self.demo_key, None)
|
||||
demonstration = getattr(rollout.task.data, self.demo_key, None)
|
||||
if demonstration is None:
|
||||
raise ValueError(
|
||||
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
|
||||
f"(env '{rollout.env_name}', task {rollout.task.idx})."
|
||||
f"(env '{rollout.env_name}', task {rollout.task.data.idx})."
|
||||
)
|
||||
return demonstration
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
@@ -27,8 +30,17 @@ class CheckpointManager:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
with open(ckpt_path / "progress.pt", "wb") as f:
|
||||
torch.save({"progress": progress}, f)
|
||||
# Save to a temporary file and do an atomic rename, to avoid corrupting the last
|
||||
# file if the process gets killed while writing
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
torch.save({"progress": progress}, f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
get_logger().debug(
|
||||
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
@@ -201,12 +201,21 @@ class RolloutDispatcher:
|
||||
def queued_eval_examples(self) -> int:
|
||||
return len(self.eval_source) if self.eval_source is not None else 0
|
||||
|
||||
@property
|
||||
def eval_has_work(self) -> bool:
|
||||
"""Eval has work while its source queue is non-empty OR any opened eval group still has
|
||||
rollouts to schedule. An example leaves ``eval_source`` when its group opens
|
||||
(``next_fresh_group``), but its ``group_size`` rollouts dispatch one at a time across
|
||||
``fill_inflight`` passes — so the queue can be empty while a group is still mid-schedule."""
|
||||
return bool(self.eval_source) or any(
|
||||
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
|
||||
)
|
||||
|
||||
@property
|
||||
def is_idle(self) -> bool:
|
||||
"""True once nothing is in flight, no eval queued, and ``out_q`` is
|
||||
empty — the pipeline has fully drained."""
|
||||
eval_drained = self.eval_source is None or not self.eval_source
|
||||
return not self.inflight and eval_drained and self.out_q.empty()
|
||||
"""True once nothing is in flight, no eval work remains (queued *or* a partly-scheduled eval
|
||||
group), and ``out_q`` is empty — the pipeline has fully drained."""
|
||||
return not self.inflight and not self.eval_has_work and self.out_q.empty()
|
||||
|
||||
def disable_train_scheduling(self) -> None:
|
||||
"""Stop scheduling new train rollouts; in-flight train + any
|
||||
@@ -307,10 +316,7 @@ class RolloutDispatcher:
|
||||
# PREFER_EVAL is only entered when the orchestrator triggers
|
||||
# eval, which requires ``eval_source`` to be configured
|
||||
assert self.eval_source is not None
|
||||
eval_has_work = bool(self.eval_source) or any(
|
||||
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
|
||||
)
|
||||
if not eval_has_work:
|
||||
if not self.eval_has_work:
|
||||
# Eval source + all eval groups fully dispatched. Flip
|
||||
# to PREFER_TRAIN so any remaining permits go to train
|
||||
# while the in-flight eval tail completes naturally
|
||||
@@ -500,7 +506,10 @@ class RolloutDispatcher:
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
|
||||
rollouts = [
|
||||
Rollout(task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)))
|
||||
for _ in range(meta.rollout_count)
|
||||
]
|
||||
for r in rollouts:
|
||||
r.capture_error(exc)
|
||||
is_synth_exception = True
|
||||
@@ -568,7 +577,7 @@ class RolloutDispatcher:
|
||||
for _, meta in claimed:
|
||||
for _ in range(meta.rollout_count):
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
@@ -594,7 +603,7 @@ class RolloutDispatcher:
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
|
||||
@@ -5,12 +5,12 @@ external one given by ``config.address``) and an ``EnvClient`` to drive it. The
|
||||
orchestrator never *runs* an environment: it asks the server for ``info``
|
||||
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
|
||||
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
|
||||
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
|
||||
properties, not serialized) which we validate into a ``Trace[WireTaskData]`` — a real ``vf.Trace``
|
||||
(never a loose dict) whose task keeps the env's
|
||||
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
|
||||
task-specific fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
|
||||
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
|
||||
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
|
||||
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
|
||||
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,10 +35,10 @@ from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
|
||||
# Every wire trace validates into this type. WireTaskData (extra="allow") keeps the env's task
|
||||
# fields without importing the env package — the orchestrator never reads them typed (only
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTask]
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. The child
|
||||
# loads the taskset (possibly downloading a dataset) before reporting, so this
|
||||
@@ -83,7 +83,8 @@ class Env:
|
||||
def __init__(self, config: EnvConfig):
|
||||
self.config = config
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int = 0
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count reported by the server; ``None`` means the taskset is infinite."""
|
||||
self.requires_group_scoring: bool = False
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
@@ -112,9 +113,8 @@ class Env:
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
get_logger().info(
|
||||
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
|
||||
)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
|
||||
@@ -220,7 +220,12 @@ class EvalEnv(Env):
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
if self.num_tasks is None:
|
||||
if self.config.num_examples < 0:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
n = self.config.num_examples
|
||||
else:
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(n)]
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ Same shape as ``TrainSink``, but no tokenization / advantages / filters:
|
||||
1. ``process_rollout`` — no-op.
|
||||
2. ``process_group`` — at ``group_size`` arrivals, move the rollouts
|
||||
(errored ones included) into the ``(env, eval_step)`` bucket.
|
||||
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, build
|
||||
the ``EvalBatchMetrics`` and return an ``EvalBatch``.
|
||||
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, return an
|
||||
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
|
||||
|
||||
``add()`` returns ``EvalBatch | None``.
|
||||
"""
|
||||
@@ -17,8 +17,8 @@ import uuid
|
||||
from collections import defaultdict
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts
|
||||
from prime_rl.orchestrator.types import EvalBatch, Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -96,7 +96,7 @@ class EvalSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.idx
|
||||
task_idx = group[0].task.data.idx
|
||||
eval_step = group[0].eval_step
|
||||
bucket = self.pending_batches[(env_name, eval_step)]
|
||||
bucket.extend(group)
|
||||
@@ -111,50 +111,10 @@ class EvalSink:
|
||||
)
|
||||
|
||||
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
|
||||
"""Build ``EvalBatchMetrics`` and return the finalized ``EvalBatch``.
|
||||
Errored rollouts (env failures, cancellations, task exceptions) are
|
||||
excluded from reward / pass@k / seq_len aggregation (including them
|
||||
at reward=0 would bias the score down) and surfaced separately as
|
||||
``n_cancelled`` / ``n_errored``."""
|
||||
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
|
||||
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
|
||||
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
|
||||
does no aggregation."""
|
||||
env_name, step = key
|
||||
rollouts = self.pending_batches.pop(key, [])
|
||||
|
||||
n_total = len(rollouts)
|
||||
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
|
||||
valid = [r for r in rollouts if not r.has_error]
|
||||
metrics = EvalBatchMetrics(
|
||||
n_rollouts=n_total,
|
||||
n_cancelled=n_cancelled,
|
||||
n_errored=n_errored,
|
||||
)
|
||||
|
||||
if valid:
|
||||
rewards = [r.reward for r in valid]
|
||||
lens = [sum(b.output_len for b in r.branches) for r in valid]
|
||||
metrics.group_size = self.group_size_for(env_name)
|
||||
metrics.reward_mean = float(sum(rewards) / len(rewards))
|
||||
metrics.completion_len_mean = float(sum(lens) / len(lens))
|
||||
metrics.completion_len_max = float(max(lens))
|
||||
metrics.completion_len_min = float(min(lens))
|
||||
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
|
||||
num_turns = [r.num_turns for r in valid]
|
||||
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
|
||||
metrics.num_turns_min = float(min(num_turns))
|
||||
metrics.num_turns_max = float(max(num_turns))
|
||||
|
||||
# pass@k: errored attempts don't count toward k tries
|
||||
by_example: dict[int, list[float]] = {}
|
||||
for r in valid:
|
||||
by_example.setdefault(r.task.idx, []).append(r.reward)
|
||||
metrics.n_examples = len(by_example)
|
||||
unique_rewards = {float(r) for r in rewards}
|
||||
if unique_rewards.issubset({0.0, 1.0}) and by_example:
|
||||
pass_at_k_per_example = [compute_pass_at_k(rs) for rs in by_example.values()]
|
||||
keys = set().union(*(d.keys() for d in pass_at_k_per_example))
|
||||
for k in keys:
|
||||
values = [d[k] for d in pass_at_k_per_example if k in d]
|
||||
metrics.pass_at_k[k] = float(sum(values) / len(values))
|
||||
|
||||
return EvalBatch(env_name=env_name, step=step, rollouts=rollouts, metrics=metrics)
|
||||
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
||||
"""Unbiased estimator of pass@k (Chen et al., 2021).
|
||||
|
||||
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
|
||||
"""
|
||||
if n - c < k:
|
||||
return 1.0
|
||||
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
|
||||
n = len(rewards)
|
||||
c = sum(r == 1.0 for r in rewards)
|
||||
ks = [2**i for i in range(n.bit_length())]
|
||||
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user