Compare commits
55
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 |
@@ -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,8 @@
|
||||
|
||||
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.
|
||||
|
||||
+1
-1
@@ -111,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
|
||||
|
||||
@@ -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,7 +22,7 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
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,7 +41,7 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "color-codeword"
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
|
||||
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
|
||||
|
||||
@@ -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 }
|
||||
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,7 +41,7 @@ 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 } }
|
||||
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
|
||||
harness = { id = "null", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -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
|
||||
@@ -1,7 +1,11 @@
|
||||
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, default (bash+edit) 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.
|
||||
# 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
|
||||
@@ -10,19 +14,18 @@
|
||||
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 65536
|
||||
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-$USER-$SLURM_JOB_ID"
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
# 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"
|
||||
@@ -82,43 +85,49 @@ 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" }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
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, default (bash+edit) harness on prime ---
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
skip_first_step = false
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
|
||||
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
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
|
||||
|
||||
@@ -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: de32ad4af2...06232831fd
Vendored
+1
-1
Submodule deps/verifiers updated: 22d6333a00...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]
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
@@ -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
-141
@@ -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[harbor]>=0.1.15.dev411",
|
||||
"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,78 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
|
||||
flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
envs = [
|
||||
"aime24-v1",
|
||||
"aime25-v1",
|
||||
"aime26-v1",
|
||||
"alphabet-sort",
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"browsecomp-v1",
|
||||
"code-golf-v1",
|
||||
"color-codeword-v1",
|
||||
"deepdive-v1",
|
||||
"deepwiki-v1",
|
||||
"forth-lang-v1",
|
||||
"general-agent",
|
||||
"general-agent-v1",
|
||||
"glossary-v1",
|
||||
"gpqa-v1",
|
||||
"graphwalks-v1",
|
||||
"gsm8k-v1",
|
||||
"i3-code-v1",
|
||||
"i3-science-v1",
|
||||
"ifbench-v1",
|
||||
"ifeval-v1",
|
||||
"lean-v1",
|
||||
"livecodebench-v1",
|
||||
"logic-env",
|
||||
"longcot-mini-v1",
|
||||
"longcot-v1",
|
||||
"longpdfs-v1",
|
||||
"math-env",
|
||||
"math-env-v1",
|
||||
"math-python",
|
||||
"math500-v1",
|
||||
"mmlu-pro-v1",
|
||||
"mrcr-v2-v1",
|
||||
"oolong-pairs-v1",
|
||||
"oolong-real-v1",
|
||||
"oolong-synth-v1",
|
||||
"openseeker-v1",
|
||||
"openthoughts-tblite-v1",
|
||||
"papersearchqa-v1",
|
||||
"patterned-needle-in-haystack-v1",
|
||||
"prolog-v1",
|
||||
"r2e-gym-v1",
|
||||
"redsearcher-v1",
|
||||
"reverse-text",
|
||||
"reverse-text-v1",
|
||||
"rlm-search",
|
||||
"scaleswe-v1",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
"swebench-pro-v1",
|
||||
"swebench-verified-v1",
|
||||
"swelego-v1",
|
||||
"tau2-bench-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"unscramble-v1",
|
||||
"uuid-ctf-v1",
|
||||
"verbatim-copy-v1",
|
||||
"wideseek-v1",
|
||||
"wiki-search",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle",
|
||||
"wordle-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",
|
||||
@@ -190,6 +125,21 @@ override-dependencies = [
|
||||
"openenv-core",
|
||||
]
|
||||
|
||||
# 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
|
||||
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
|
||||
# this capped to the validated protobuf major.
|
||||
@@ -239,83 +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 }
|
||||
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 = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
|
||||
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_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 }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
|
||||
graphwalks-v1 = { path = "deps/research-environments/environments/graphwalks_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_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 }
|
||||
ifbench-v1 = { path = "deps/research-environments/environments/ifbench_v1", editable = true }
|
||||
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
|
||||
lean-v1 = { path = "deps/research-environments/environments/lean_v1", editable = true }
|
||||
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
|
||||
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
|
||||
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
|
||||
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
|
||||
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
|
||||
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
|
||||
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
|
||||
math-python = { path = "deps/verifiers/environments/math_python", 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 }
|
||||
mrcr-v2-v1 = { path = "deps/research-environments/environments/mrcr_v2_v1", editable = true }
|
||||
oolong-pairs-v1 = { path = "deps/research-environments/environments/oolong_pairs_v1", editable = true }
|
||||
oolong-real-v1 = { path = "deps/research-environments/environments/oolong_real_v1", editable = true }
|
||||
oolong-synth-v1 = { path = "deps/research-environments/environments/oolong_synth_v1", editable = true }
|
||||
openseeker-v1 = { path = "deps/research-environments/environments/openseeker_v1", editable = true }
|
||||
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/openthoughts_tblite_v1", editable = true }
|
||||
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
|
||||
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
|
||||
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
|
||||
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
|
||||
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
|
||||
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
|
||||
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
|
||||
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
|
||||
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
|
||||
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
|
||||
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
|
||||
wideseek-v1 = { path = "deps/research-environments/environments/wideseek_v1", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", 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 = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_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.
|
||||
|
||||
@@ -37,9 +37,10 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
|
||||
- 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('r2e_gym_v1'))"`).
|
||||
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`.
|
||||
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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)}"
|
||||
)
|
||||
|
||||
@@ -506,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
|
||||
@@ -574,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",
|
||||
)
|
||||
@@ -600,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)]
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -72,10 +72,11 @@ from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -100,6 +101,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# Default wait for the trainer's startup weight broadcast when no ckpt block
|
||||
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
|
||||
# broadcast is always coming, so wait rather than fail immediately.
|
||||
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -165,6 +171,8 @@ class Orchestrator:
|
||||
# Trigger timestamps so eval success logs can report epoch duration
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.component_tasks = []
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
@@ -193,7 +201,7 @@ class Orchestrator:
|
||||
config_dir = config.output_dir / "control"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
|
||||
tomli_w.dump(to_toml_dict(config), f)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
@@ -222,6 +230,8 @@ class Orchestrator:
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
train_env_names=[env.resolved_name for env in config.train.env],
|
||||
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
|
||||
)
|
||||
|
||||
if config.heartbeat is not None:
|
||||
@@ -305,20 +315,34 @@ class Orchestrator:
|
||||
|
||||
if self.resume_step is not None and self.ckpt_manager is not None:
|
||||
self.ckpt_manager.load(self.progress, step=self.resume_step)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = self.progress.step
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, whether fresh (v0 = base) or
|
||||
# resumed (v{resume_step}). This pauses inference and rendezvouses with the trainer's
|
||||
# first-step broadcast (train.py), so inference serves the correct policy from step 1. Keeping
|
||||
# it unconditional makes trainer/orchestrator startup symmetric and avoids the resume deadlock
|
||||
# where inference waited for weights the trainer only sent at the end of a step.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Wait for the trainer's startup broadcast to land. On a fresh start there is no ckpt block,
|
||||
# so fall back to a default timeout instead of not waiting at all (which would raise before
|
||||
# broadcasts/step_0/STABLE is written when using filesystem weight broadcast).
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -361,7 +385,7 @@ class Orchestrator:
|
||||
inference=self.policy_inference,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.progress.step,
|
||||
ckpt_step=self.policy.version,
|
||||
)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
@@ -407,11 +431,11 @@ class Orchestrator:
|
||||
asyncio.create_task(self.watcher.start(), name="watcher"),
|
||||
]
|
||||
|
||||
# Default step-0 base-model eval — fires before any train rollouts
|
||||
# unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so step 0 measures startup → first batch
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
self.last_batch_at = time.perf_counter()
|
||||
|
||||
# ``clean_exit`` stays False if ``main_loop`` raises (signal-driven
|
||||
@@ -428,7 +452,11 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
|
||||
self.monitor.save_final_summary()
|
||||
if self.ckpt_manager is not None:
|
||||
# ``progress.step`` points at the next (unshipped) step; the last finished step is
|
||||
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
|
||||
# first ship).
|
||||
if self.ckpt_manager is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
self.ckpt_manager.save(self.progress, step=self.progress.step)
|
||||
await self.stop()
|
||||
@@ -453,6 +481,18 @@ class Orchestrator:
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
# Every completed rollout — errored, filtered, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
# eval rollouts to the step whose eval triggered them.
|
||||
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
|
||||
assert step is not None
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
[rollout.to_record()],
|
||||
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
|
||||
)
|
||||
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
@@ -481,9 +521,7 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
|
||||
@@ -514,20 +552,23 @@ class Orchestrator:
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
|
||||
# drops the per-node training tensors — they're for training, not the rollout record, and
|
||||
# can't round-trip json (raw numpy bytes).
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
effective = batch.rollouts.effective
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.progress.step += 1
|
||||
self.update_dispatch_gate()
|
||||
# Checkpoint the step we just shipped (resume point: continue at step + 1).
|
||||
save_ckpt_time = await self.maybe_save_ckpt(step)
|
||||
trim_process_memory()
|
||||
|
||||
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
|
||||
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
|
||||
effective = batch.rollouts.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
|
||||
@@ -554,6 +595,7 @@ class Orchestrator:
|
||||
"progress/total_tasks": self.progress.total_problems,
|
||||
"time/step": step_time,
|
||||
"time/save_ckpt": save_ckpt_time,
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
for env_name, env_pool in batch.rollouts.by_env().items():
|
||||
@@ -565,6 +607,7 @@ class Orchestrator:
|
||||
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
|
||||
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.monitor.log_samples(effective.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
@@ -592,7 +635,6 @@ class Orchestrator:
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.progress.step += 1
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
@@ -726,12 +768,13 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_record() for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
|
||||
# completion (multiple eval envs share the step file — each epoch appends its cohort
|
||||
# once, and every record carries ``env_name``); the full returned cohort already
|
||||
# streamed into ``all`` on arrival.
|
||||
records = [r.to_record() for r in batch.rollouts.effective]
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
|
||||
)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
@@ -764,19 +807,13 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
async def maybe_save_ckpt(self, step: int) -> float:
|
||||
"""Save the checkpoint if we're at an interval boundary. Returns
|
||||
"""Checkpoint the step just shipped if it's an interval boundary. Returns
|
||||
elapsed time (0.0 when no save happened)."""
|
||||
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
|
||||
return 0.0
|
||||
if step <= 0:
|
||||
return 0.0
|
||||
# Skip only the drain-entry step (step == max_steps, which never ships):
|
||||
# it would double-save with the final checkpoint in ``start()`` (also at
|
||||
# progress.step == max_steps). The last *shipped* step (max_steps - 1) is
|
||||
# NOT skipped — the trainer saves there (its is_last_step is max_steps),
|
||||
# so the orchestrator must too or resume from that interval ckpt breaks.
|
||||
near_end = self.config.max_steps is not None and step >= self.config.max_steps
|
||||
if near_end:
|
||||
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
|
||||
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
|
||||
if self.config.max_steps is not None and step >= self.config.max_steps:
|
||||
return 0.0
|
||||
if step % self.config.ckpt.interval != 0:
|
||||
return 0.0
|
||||
@@ -786,22 +823,37 @@ class Orchestrator:
|
||||
return time.perf_counter() - t
|
||||
|
||||
def update_dispatch_gate(self) -> None:
|
||||
"""Pause/resume the dispatcher based on how far the orchestrator's
|
||||
next batch would run ahead of ``policy.version``. Called from two
|
||||
sites: after shipping a batch (step advances) and from
|
||||
``on_new_version`` (policy advances)."""
|
||||
lead = (self.progress.step + 1) - self.policy.version
|
||||
"""Pause/resume the dispatcher based on how far the in-flight batch runs
|
||||
ahead of ``policy.version``. ``progress.step`` is always the batch being
|
||||
collected — advanced right after shipping — so both call sites (ship time
|
||||
here, policy update in ``on_new_version``) share one lead formula. Steps
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final NCCL weight broadcast (inference group is
|
||||
# torn down), so policy.version never reaches the last step. Without this
|
||||
# the gate deadlocks waiting for a version that will never be published.
|
||||
# The last batch uses the penultimate policy anyway, so let it through.
|
||||
building_final_batch_nccl = (
|
||||
self.config.weight_broadcast.type == "nccl"
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG:
|
||||
if lead > TARGET_LAG and not building_final_batch_nccl:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
|
||||
@@ -30,6 +30,19 @@ from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def payload_tokens(rollout: Rollout) -> int:
|
||||
"""Token cost of the rollout's trainer-bound payload — the samples built by
|
||||
``process_rollout``. This is what actually ships: forked traces can drop
|
||||
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
|
||||
over all branches) may overcount. For linear traces the two agree.
|
||||
|
||||
Zero-payload rollouts (no trainable samples at all) fall back to the trace
|
||||
total so they still advance token batching — a degenerate all-zero-payload
|
||||
stream then ships empty batches and trips the orchestrator's
|
||||
consecutive-empty-batch abort instead of stalling the readiness check."""
|
||||
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
|
||||
|
||||
|
||||
class TrainSink:
|
||||
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
|
||||
|
||||
@@ -57,15 +70,18 @@ class TrainSink:
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
# Observation window for the next shipped batch: rollouts of groups
|
||||
# finalized since the last ship (errored + filtered + survivors).
|
||||
# In-progress groups stay out until they finalize.
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_rollouts: TrainRollouts = TrainRollouts()
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running token total of ``pending_batch`` (token-batched runs), kept in
|
||||
# sync on append/pop so the readiness check never re-walks the uncached
|
||||
# ``Trace.num_total_tokens`` graph property per arrival.
|
||||
# Running payload-token total of ``pending_batch`` (token-batched
|
||||
# runs), kept in sync on append/pop so the readiness check never
|
||||
# re-sums per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
@@ -117,13 +133,18 @@ class TrainSink:
|
||||
|
||||
async def add(self, rollout: Rollout) -> TrainBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
|
||||
the batch over its threshold. Arrivals into still-incomplete groups
|
||||
never ship a batch."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.pending_rollouts.append(rollout)
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
await self.process_group(rollout.group_id)
|
||||
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
|
||||
return None
|
||||
await self.process_group(rollout.group_id)
|
||||
# ``pending_batch`` only grows on group finalization, so readiness is
|
||||
# only re-checked here — the window of a shipped batch then always
|
||||
# contains at least the group that finalized it.
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
@@ -159,8 +180,14 @@ class TrainSink:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
return
|
||||
# Window membership follows group finalization, not arrival: a rollout
|
||||
# only becomes observable (metrics / persistence) once its whole group
|
||||
# is finalized, so a batch's window never claims rollouts of a group
|
||||
# that ships later. Dropped groups still land here — they were observed.
|
||||
for r in group:
|
||||
self.pending_rollouts.append(r)
|
||||
env_name = group[0].env_name
|
||||
task_idx = group[0].task.idx
|
||||
task_idx = group[0].task.data.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
|
||||
@@ -211,7 +238,7 @@ class TrainSink:
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += r.num_total_tokens
|
||||
self.pending_tokens += payload_tokens(r)
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
@@ -238,7 +265,7 @@ class TrainSink:
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += r.num_total_tokens
|
||||
running += payload_tokens(r)
|
||||
cut = i + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
@@ -253,11 +280,12 @@ class TrainSink:
|
||||
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
|
||||
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
|
||||
|
||||
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
|
||||
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
|
||||
# the clean subset + metric views on demand. Reset the window only when the batch actually
|
||||
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
|
||||
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
|
||||
# ``rollouts`` is the observation window — every rollout of every group finalized since the
|
||||
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
|
||||
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
|
||||
# metric views on demand. Reset the window only when the batch actually ships (non-empty
|
||||
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
|
||||
# finalized groups (and any overflow) into the next shipped batch's window.
|
||||
rollouts = self.pending_rollouts
|
||||
if samples:
|
||||
self.pending_rollouts = TrainRollouts()
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights default to configured ``ratio`` (when every env sets one) or to
|
||||
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). A finite env serves a shuffled task-index table, reshuffled on
|
||||
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
|
||||
monotonic ``task_idx`` — the server generates tasks on demand, so every
|
||||
pull is a fresh task and there are no epochs to shuffle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,26 +25,27 @@ class TrainSource:
|
||||
if not self.envs:
|
||||
raise ValueError("TrainSource needs at least one train env")
|
||||
|
||||
self.examples: dict[str, list[dict]] = {}
|
||||
# A finite env's shuffled index table; ``None`` for an infinite env,
|
||||
# whose cursor alone is the (monotonic) task_idx stream.
|
||||
self.examples: dict[str, list[dict] | None] = {}
|
||||
self.cursors: dict[str, int] = {}
|
||||
# Group-scoring envs reserve ``group_size`` permits up front;
|
||||
# per-rollout envs need 1
|
||||
self.env_costs: dict[str, int] = {}
|
||||
for env in self.envs:
|
||||
# The orchestrator never loads the env: sample over the task-index
|
||||
# range the server reported via info() (num_tasks).
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
# range the server reported via info() (num_tasks; None = infinite).
|
||||
if env.num_tasks is None:
|
||||
self.examples[env.name] = None
|
||||
else:
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
self.cursors[env.name] = 0
|
||||
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
|
||||
|
||||
self.env_names = [e.name for e in self.envs]
|
||||
configured_ratios = [e.config.ratio for e in self.envs]
|
||||
if all(r is not None for r in configured_ratios):
|
||||
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
|
||||
else:
|
||||
self.weights = [float(len(self.examples[name])) for name in self.env_names]
|
||||
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
|
||||
|
||||
def next_example(self, available_permits: int) -> dict | None:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
@@ -49,6 +53,9 @@ class TrainSource:
|
||||
return None
|
||||
rows = self.examples[env_name]
|
||||
cursor = self.cursors[env_name]
|
||||
if rows is None: # infinite env: the cursor is the task_idx
|
||||
self.cursors[env_name] = cursor + 1
|
||||
return {"task_idx": cursor, "env_name": env_name}
|
||||
if cursor >= len(rows):
|
||||
self.rng.shuffle(rows)
|
||||
cursor = 0
|
||||
|
||||
@@ -15,6 +15,8 @@ the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -64,6 +66,29 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
|
||||
"""Yield each branch that yields a training sample, with its trainable-token mask.
|
||||
|
||||
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
|
||||
(a mid-trajectory fork) is trainable only in the first branch containing it; later
|
||||
branches carry its tokens as context (mask False). Branches left with no trainable
|
||||
tokens are skipped, so consumers pairing branches with `trace_to_samples` output
|
||||
(e.g. echo's observation weighting) must filter through here to stay aligned.
|
||||
"""
|
||||
trained_nodes: set[int] = set()
|
||||
for branch in trace.branches:
|
||||
mask: list[bool] = []
|
||||
for node in branch.nodes:
|
||||
if node.sampled and any(node.mask) and id(node) in trained_nodes:
|
||||
mask.extend([False] * len(node.mask))
|
||||
else:
|
||||
if node.sampled and any(node.mask):
|
||||
trained_nodes.add(id(node))
|
||||
mask.extend(node.mask)
|
||||
if any(mask):
|
||||
yield branch, mask
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
@@ -75,17 +100,14 @@ def trace_to_samples(
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. On a rollout error the whole completion is masked out. A branch carrying images also
|
||||
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
|
||||
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
|
||||
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
|
||||
yield nothing.
|
||||
"""
|
||||
has_error = trace.has_error
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
@@ -97,7 +119,7 @@ def trace_to_samples(
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
mask=[m and not has_error for m in mask],
|
||||
mask=mask,
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
env_name=env_name,
|
||||
@@ -108,6 +130,6 @@ def trace_to_samples(
|
||||
)
|
||||
if not samples:
|
||||
get_logger().warning(
|
||||
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
f"No trainable samples (error={trace.has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
)
|
||||
return samples
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Generic, Literal, Protocol
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
from verifiers.v1.task import TaskT
|
||||
from verifiers.v1.task import DataT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
@@ -27,9 +27,9 @@ class Policy:
|
||||
|
||||
@dataclass
|
||||
class Progress:
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step."""
|
||||
"""Persistent counters; ``step`` is the trainer-aligned step (1-indexed)."""
|
||||
|
||||
step: int = 0
|
||||
step: int = 1
|
||||
total_tokens: int = 0
|
||||
total_samples: int = 0
|
||||
total_problems: int = 0
|
||||
@@ -69,12 +69,12 @@ class GroupState:
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
class Rollout(vf.Trace[DataT], Generic[DataT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged.
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire;
|
||||
:meth:`to_record` adds the small metadata fields back for the on-disk trace files.
|
||||
|
||||
It is also the single currency the scoring hooks receive: a hook reads the trace
|
||||
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
|
||||
@@ -98,6 +98,19 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
def to_record(self) -> dict:
|
||||
"""The plain trace record plus the orchestration metadata (excluded from the pydantic
|
||||
dump), so a record stays fully placeable — kind, env, policy — even when trace files
|
||||
are merged or read away from their paths. ``eval_step`` is the eval trigger step (None
|
||||
for train rollouts)."""
|
||||
return super().to_record() | {
|
||||
"kind": self.kind,
|
||||
"env_name": self.env_name,
|
||||
"group_id": str(self.group_id),
|
||||
"policy_version": self.policy_version,
|
||||
"eval_step": self.eval_step,
|
||||
}
|
||||
|
||||
def assign_advantages(self, values: float | list[float]) -> None:
|
||||
"""Write the rl advantage stream: a scalar broadcast over the
|
||||
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
|
||||
@@ -134,11 +147,12 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
|
||||
@dataclass
|
||||
class TrainBatch:
|
||||
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
|
||||
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
|
||||
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
|
||||
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
|
||||
``samples``, so neither is carried as a field."""
|
||||
"""``rollouts`` is the observation window since the last ship — every rollout of every group
|
||||
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
|
||||
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
|
||||
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
|
||||
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
|
||||
|
||||
rollouts: TrainRollouts
|
||||
samples: list[TrainingSample]
|
||||
|
||||
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
@@ -51,14 +50,15 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
def save_rollouts(rollouts: list[dict], path: Path) -> None:
|
||||
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
|
||||
The trace streams are append-only: ``all`` grows one rollout at a time as they
|
||||
complete, ``effective`` one batch at a time on finalize."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
with open(path, "ab") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
f.write(orjson.dumps(row, default=str, option=opts))
|
||||
f.write(orjson.dumps(rollout, default=str, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -94,16 +94,6 @@ def trim_process_memory() -> None:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
def get_tool_response_len(trace: vf.Trace) -> int:
|
||||
"""Total tool-response tokens consumed across the whole rollout, read from a
|
||||
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
|
||||
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
|
||||
for key, value in (trace.metrics or {}).items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
|
||||
"""Get the weight directory for a given checkpoint step.
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_REPLICA=$((NUM_PREFILL_NODES + NUM_DECODE_NODES))
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
@@ -61,7 +61,17 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
|
||||
@@ -41,8 +41,8 @@ export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
|
||||
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
@@ -144,7 +144,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
@@ -48,9 +48,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
{% if not shared_fs %}
|
||||
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
|
||||
# build the batch node, so srun runs it on every node (one task each) and blocks until
|
||||
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
|
||||
# inside the task because unexported vars in .env don't cross srun even with normal
|
||||
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
|
||||
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
|
||||
{% else %}
|
||||
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
|
||||
cd $PROJECT_DIR && uv sync --all-extras --all-packages
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if pre_run_command %}
|
||||
|
||||
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
|
||||
cd $PROJECT_DIR
|
||||
[ -f .env ] && source .env
|
||||
source .venv/bin/activate
|
||||
uv sync --all-extras
|
||||
uv sync --all-extras --all-packages
|
||||
|
||||
{% if pre_run_command %}
|
||||
# Pre-run command
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user