Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0a026c0d4 | ||
|
|
7c9c1308dc | ||
|
|
941019f2e3 | ||
|
|
9e1f0521e3 | ||
|
|
e466d233e9 | ||
|
|
9ea9fb193e | ||
|
|
91c86b7383 | ||
|
|
d4b30bf3ae | ||
|
|
d5ce4ce84d | ||
|
|
04d067145f | ||
|
|
632ef2b318 | ||
|
|
c8759c370a | ||
|
|
0695f9caa5 |
@@ -7,9 +7,6 @@
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
|
||||
@@ -55,10 +55,10 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
|
||||
| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#vision-language-models) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
|
||||
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
|
||||
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
|
||||
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
|
||||
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
|
||||
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ❌ | ✅ |
|
||||
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
|
||||
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
enable_token_export = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
Submodule configs/private deleted from 70c3503e1d
Vendored
+1
-1
Submodule deps/research-environments updated: c752781984...4c08260f07
Vendored
+1
-1
Submodule deps/verifiers updated: 05c66c2358...0ad8b4d523
+1
-1
@@ -115,7 +115,7 @@ LoRA pairs naturally with [multi-tenant training](#multi-tenant-training) — ea
|
||||
|
||||
## Multi-Tenant Training
|
||||
|
||||
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/src/prime_rl/trainer/runs).
|
||||
Multi-tenant training lets a single trainer + inference deployment serve many concurrent LoRA "tenants" — each a fully isolated run with its own orchestrator, LoRA adapter, optimizer, scheduler, checkpoints, and progress tracking — sharing the same backbone weights and the same vLLM server. This is the topology behind hosted training on the [Prime Intellect platform (Lab)](https://app.primeintellect.ai). The trainer-side implementation is the `MultiRunManager` singleton, enabled by setting `trainer.max_concurrent_runs > 1`. For the full API surface, see [`src/prime_rl/trainer/runs.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/src/prime_rl/trainer/runs.py).
|
||||
|
||||
## Disaggregated Prefill/Decode Inference
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
+1
-1
@@ -252,7 +252,7 @@ headless = true
|
||||
|
||||
### Router Replay
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer<->inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.enable_return_routed_experts = true`.
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
|
||||
- **Inference** — vLLM-backed server (or fleet) holding the current policy. The orchestrator drives rollouts through the token-in `/v1/generate` route via the [`renderers`](https://github.com/PrimeIntellect-ai/renderers) package (OpenAI-compatible chat/completions routes are also exposed for external clients). We are trying to stay up-to-date with the latest vLLM features, you can read more about the supported features and deployment options in the dedicated [inference documentation](inference.md).
|
||||
- **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 [trainer documentation](trainer.md).
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -522,7 +522,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
|
||||
opts into MITO (``openai_chat_completions``); SFT mode forces this."""
|
||||
opts into MITO (``openai_chat_completions``)."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump
|
||||
@@ -759,11 +759,10 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
|
||||
renderer client doesn't apply. Force ``renderer=None`` so the user
|
||||
doesn't have to remember to set it. Declared before the renderer
|
||||
validators below so they see the corrected value."""
|
||||
if self.training_mode == "sft":
|
||||
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
|
||||
endpoint; the renderer client doesn't apply. When no teacher is
|
||||
configured, SFT uses the student rollout path and keeps the renderer."""
|
||||
if self.training_mode == "sft" and self.teacher is not None:
|
||||
self.renderer = None
|
||||
return self
|
||||
|
||||
@@ -773,8 +772,8 @@ class OrchestratorConfig(BaseConfig):
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
if self.training_mode == "opd" and not has_teacher:
|
||||
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -490,15 +490,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -562,7 +553,8 @@ class TrainerConfig(BaseConfig):
|
||||
max_concurrent_runs: int = Field(1, ge=1)
|
||||
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
|
||||
|
||||
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
|
||||
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
|
||||
+3
-2
@@ -79,7 +79,6 @@ envs = [
|
||||
"math-python",
|
||||
"math500",
|
||||
"mini-swe-agent-plus",
|
||||
"mini-swe-agent-plus-rlm",
|
||||
"mmlu-pro",
|
||||
"opencode-cp",
|
||||
"opencode-deepdive",
|
||||
@@ -152,6 +151,7 @@ override-dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -209,6 +209,7 @@ color-codeword = { path = "deps/research-environments/environments/color_codewor
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
@@ -217,7 +218,6 @@ math-env = { path = "deps/research-environments/environments/math_env", editable
|
||||
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
|
||||
math500 = { path = "deps/research-environments/environments/math500", editable = true }
|
||||
mini-swe-agent-plus = { path = "deps/research-environments/environments/mini_swe_agent_plus", editable = true }
|
||||
mini-swe-agent-plus-rlm = { path = "deps/research-environments/environments/mini_swe_agent_plus_rlm", editable = true }
|
||||
mmlu-pro = { path = "deps/research-environments/environments/mmlu_pro", editable = true }
|
||||
opencode-cp = { path = "deps/research-environments/environments/opencode_cp", editable = true }
|
||||
opencode-deepdive = { path = "deps/research-environments/environments/opencode_deepdive", editable = true }
|
||||
@@ -229,6 +229,7 @@ rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable =
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
|
||||
+1
-17
@@ -74,27 +74,11 @@ ensure_known_hosts() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Initialize each submodule independently so that a missing private repo
|
||||
# (e.g. configs/private when the user lacks access) does not abort the install.
|
||||
init_submodules() {
|
||||
if [ ! -f .gitmodules ]; then
|
||||
return 0
|
||||
fi
|
||||
local paths failures
|
||||
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
|
||||
failures=()
|
||||
for path in $paths; do
|
||||
log_info "Initializing submodule: ${path}"
|
||||
if git submodule update --init --recursive -- "$path"; then
|
||||
:
|
||||
else
|
||||
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
|
||||
failures+=("$path")
|
||||
fi
|
||||
done
|
||||
if [ "${#failures[@]}" -gt 0 ]; then
|
||||
log_warn "Skipped submodules: ${failures[*]}"
|
||||
fi
|
||||
git submodule update --init --recursive
|
||||
}
|
||||
|
||||
main() {
|
||||
|
||||
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
|
||||
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
|
||||
# with RDMA devices, require the headers up front instead of failing at runtime.
|
||||
HAVE_RDMA=0
|
||||
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
|
||||
HAVE_RDMA=1
|
||||
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
|
||||
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
|
||||
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-rdmacm \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
|
||||
# Fail loudly if the IB transports didn't make it into the build.
|
||||
if [ "$HAVE_RDMA" = 1 ]; then
|
||||
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
|
||||
"$UCX_INSTALL/bin/ucx_info" -d)
|
||||
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
|
||||
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
|
||||
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
@@ -74,5 +74,4 @@ Leave it unset for normal training. When enabled, it exports every sequence from
|
||||
|
||||
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
|
||||
- `configs/debug/` — minimal debug configs
|
||||
- `configs/private/` — private configs submodule (internal)
|
||||
- `examples/` — full example configs
|
||||
|
||||
@@ -16,11 +16,9 @@ bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync
|
||||
For an existing clone, init submodules explicitly:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
|
||||
|
||||
## Sync
|
||||
|
||||
```bash
|
||||
|
||||
@@ -17,11 +17,29 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
|
||||
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
|
||||
def extract_reasoning(self, model_output, request):
|
||||
reasoning_content, final_content = super().extract_reasoning(model_output, request)
|
||||
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
|
||||
|
||||
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
|
||||
reasoning_content, final_content = final_content, reasoning_content
|
||||
|
||||
return reasoning_content, final_content
|
||||
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
|
||||
@@ -22,6 +22,7 @@ logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
@@ -35,6 +36,9 @@ 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()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
|
||||
@@ -133,6 +133,7 @@ class RolloutDispatcher:
|
||||
tasks_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
training_mode: Literal["rl", "opd", "sft"],
|
||||
use_cache_salt: bool = True,
|
||||
) -> None:
|
||||
self.policy = policy
|
||||
self.train_envs = train_envs
|
||||
@@ -144,6 +145,7 @@ class RolloutDispatcher:
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.training_mode = training_mode
|
||||
self.use_cache_salt = use_cache_salt
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
|
||||
self.max_inflight = max_inflight_rollouts
|
||||
@@ -413,13 +415,10 @@ class RolloutDispatcher:
|
||||
if env_collection is None:
|
||||
return False
|
||||
env = env_collection.get(group.env_name)
|
||||
# SFT-mode train rollouts hit the frozen teacher pool; salting per
|
||||
# policy version would invalidate the teacher's prefix cache every
|
||||
# weight update for no reason.
|
||||
if self.training_mode == "sft" and group.kind == "train":
|
||||
cache_salt = None
|
||||
else:
|
||||
if group.kind == "eval" or self.use_cache_salt:
|
||||
cache_salt = str(group.policy_version_at_start)
|
||||
else:
|
||||
cache_salt = None
|
||||
|
||||
if env.requires_group_scoring:
|
||||
permits = group.rollouts_to_schedule
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +12,16 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -179,8 +188,29 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
|
||||
@@ -108,6 +108,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -345,13 +350,14 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# SFT generates rollouts via the teacher (the student is trained on
|
||||
# the teacher's outputs); RL / OPD generate via the student
|
||||
if config.training_mode == "sft":
|
||||
assert self.teacher_inference is not None, "sft mode requires teacher inference"
|
||||
# SFT train rollouts come from the teacher when configured; otherwise
|
||||
# they use the existing student rollout pool.
|
||||
if config.training_mode == "sft" and self.teacher_inference is not None:
|
||||
rollout_inference = self.teacher_inference
|
||||
use_cache_salt = False
|
||||
else:
|
||||
rollout_inference = self.student_inference
|
||||
use_cache_salt = True
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
@@ -379,8 +385,9 @@ class Orchestrator:
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -458,6 +465,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -508,6 +516,35 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -194,10 +194,28 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
|
||||
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
|
||||
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
|
||||
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
|
||||
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
|
||||
export VLLM_ENGINE_READY_TIMEOUT_S=4200
|
||||
export UCX_TLS=all
|
||||
export UCX_NET_DEVICES=all
|
||||
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
|
||||
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
|
||||
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
|
||||
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
|
||||
rdma_ports() {
|
||||
for port in /sys/class/infiniband/*/ports/*; do
|
||||
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
|
||||
grep -q ACTIVE "$port/state" 2>/dev/null || continue
|
||||
dev=${port%/ports/*}
|
||||
echo "$(basename "$dev"):$(basename "$port")"
|
||||
done | paste -sd,
|
||||
}
|
||||
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
|
||||
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
|
||||
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
|
||||
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
|
||||
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
|
||||
|
||||
@@ -239,10 +239,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_MOE_USE_DEEP_GEMM=1
|
||||
{%- endif %}
|
||||
|
||||
export GLOO_SOCKET_IFNAME=bond0
|
||||
# Bind gloo to the interface that owns LOCAL_IP (the rendezvous IP) — NIC
|
||||
# names vary across clusters (bond0, eth0, ...). If the lookup fails, leave
|
||||
# GLOO_SOCKET_IFNAME unset so gloo falls back to its own detection.
|
||||
GLOO_IFNAME=$(ip -o -4 addr show to "$LOCAL_IP" 2>/dev/null | awk "{print \$2; exit}")
|
||||
if [ -n "$GLOO_IFNAME" ]; then export GLOO_SOCKET_IFNAME=$GLOO_IFNAME; fi
|
||||
export VLLM_ENGINE_READY_TIMEOUT_S=4200
|
||||
export UCX_TLS=all
|
||||
export UCX_NET_DEVICES=all
|
||||
# Enumerate RDMA NICs for UCX/NIXL from sysfs (ibv_devices is not on the job
|
||||
# PATH). Prefer InfiniBand ports and fall back to RoCE: "all" would also pick
|
||||
# up non-functional devices (e.g. an Ethernet bond UCX cannot open), which
|
||||
# fails NIXL backend creation. Hosts without RDMA devices keep "all" (TCP).
|
||||
rdma_ports() {
|
||||
for port in /sys/class/infiniband/*/ports/*; do
|
||||
[ "$(cat "$port/link_layer" 2>/dev/null)" = "$1" ] || continue
|
||||
grep -q ACTIVE "$port/state" 2>/dev/null || continue
|
||||
dev=${port%/ports/*}
|
||||
echo "$(basename "$dev"):$(basename "$port")"
|
||||
done | paste -sd,
|
||||
}
|
||||
UCX_NET_DEVICES=$(rdma_ports InfiniBand)
|
||||
[ -n "$UCX_NET_DEVICES" ] || UCX_NET_DEVICES=$(rdma_ports Ethernet)
|
||||
export UCX_NET_DEVICES=${UCX_NET_DEVICES:-all}
|
||||
export LD_LIBRARY_PATH="$PROJECT_DIR/third_party/ucx/lib:$PROJECT_DIR/third_party/ucx/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
export VLLM_NIXL_SIDE_CHANNEL_HOST=$LOCAL_IP
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
@@ -955,32 +955,44 @@ class NemotronHRouter(nn.Module):
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
expert_bias: torch.Tensor | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
scores = F.linear(x.float(), self.gate.float()).sigmoid()
|
||||
scores_for_choice = scores + self.e_score_correction_bias
|
||||
|
||||
if expert_bias is not None:
|
||||
scores_for_choice = scores_for_choice + expert_bias
|
||||
if routed_experts is not None:
|
||||
# Router replay: reuse the inference engine's expert selection and
|
||||
# only recompute the gating weights from the trainer's scores. The
|
||||
# correction/load-balancing biases only affect selection, so they
|
||||
# are intentionally skipped here.
|
||||
selected_experts_indices = routed_experts
|
||||
else:
|
||||
scores_for_choice = scores + self.e_score_correction_bias
|
||||
|
||||
# Group-based routing
|
||||
if self.n_group > 1:
|
||||
group_scores = (
|
||||
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.topk(2, dim=-1)[0]
|
||||
.sum(dim=-1)
|
||||
)
|
||||
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
||||
group_mask = torch.zeros_like(group_scores)
|
||||
group_mask.scatter_(1, group_idx, 1)
|
||||
score_mask = (
|
||||
group_mask.unsqueeze(-1)
|
||||
.expand(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.reshape(-1, self.num_experts)
|
||||
)
|
||||
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
||||
if expert_bias is not None:
|
||||
scores_for_choice = scores_for_choice + expert_bias
|
||||
|
||||
# Group-based routing
|
||||
if self.n_group > 1:
|
||||
group_scores = (
|
||||
scores_for_choice.view(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.topk(2, dim=-1)[0]
|
||||
.sum(dim=-1)
|
||||
)
|
||||
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
||||
group_mask = torch.zeros_like(group_scores)
|
||||
group_mask.scatter_(1, group_idx, 1)
|
||||
score_mask = (
|
||||
group_mask.unsqueeze(-1)
|
||||
.expand(-1, self.n_group, self.num_experts // self.n_group)
|
||||
.reshape(-1, self.num_experts)
|
||||
)
|
||||
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
||||
|
||||
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
||||
|
||||
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
||||
top_scores = scores.gather(1, selected_experts_indices)
|
||||
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
|
||||
|
||||
@@ -1181,8 +1193,13 @@ class LatentMoE(nn.Module):
|
||||
bs, slen, dim = x.shape
|
||||
x_flat = x.view(-1, dim)
|
||||
|
||||
if routed_experts is not None:
|
||||
# Flatten to (bs * slen, top_k); reshape (not view) since the slice is non-contiguous.
|
||||
_, _, top_k = routed_experts.shape
|
||||
routed_experts = routed_experts.reshape(-1, top_k)
|
||||
|
||||
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
|
||||
x_flat, self.expert_bias
|
||||
x_flat, self.expert_bias, routed_experts=routed_experts
|
||||
)
|
||||
|
||||
with torch.no_grad():
|
||||
|
||||
@@ -223,6 +223,7 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -266,10 +267,11 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
@@ -298,6 +300,7 @@ class NemotronHAttentionLayer(GradientCheckpointingLayer):
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -498,7 +501,13 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token, indexed by global layer index. Only used for router replay; slots
|
||||
for non-MoE (Mamba/attention) layers are ignored.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
@@ -516,12 +525,15 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids) if self.rotary_emb is not None else None
|
||||
|
||||
for decoder_layer in self.layers:
|
||||
for layer_idx, decoder_layer in enumerate(self.layers):
|
||||
# routed_experts is indexed by global layer index; non-MoE layers ignore it.
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
routed_experts=routed_experts_layer,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -550,6 +562,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: int = 0,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
if position_ids is None:
|
||||
@@ -562,6 +575,7 @@ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
|
||||
@@ -10,7 +10,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
|
||||
from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
MicroBatchReceiver,
|
||||
TransportConfig,
|
||||
setup_micro_batch_receiver,
|
||||
)
|
||||
|
||||
|
||||
class TensorMicroBatch(TypedDict):
|
||||
@@ -46,6 +51,10 @@ class TensorMicroBatch(TypedDict):
|
||||
# sft → sft loss). All samples in a micro batch share the same mode.
|
||||
training_mode: str
|
||||
|
||||
# Packer-derived metadata used for run-local debug exports.
|
||||
run_id: str | None
|
||||
run_step: int | None
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
|
||||
@@ -120,6 +129,8 @@ class FakeDataLoader:
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -148,6 +159,8 @@ class FakeDataLoader:
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +256,8 @@ class DataLoader:
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
training_mode=micro_batch.training_mode,
|
||||
run_id=micro_batch.run_id,
|
||||
run_step=micro_batch.run_step,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -111,6 +111,12 @@ class SinglePacker(BasePacker):
|
||||
idxs=[0] * len(batch.examples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
)
|
||||
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
|
||||
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
|
||||
for worker_batches in micro_batch_grid:
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = batch.step
|
||||
|
||||
self.sender.send(micro_batch_grid)
|
||||
|
||||
@@ -300,10 +306,14 @@ class MultiPacker(BasePacker):
|
||||
# Group samples by run_idx - each microbatch must contain samples from only ONE run
|
||||
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
|
||||
samples_by_run: dict[int, list[TrainingSample]] = {}
|
||||
steps_by_run: dict[int, int] = {}
|
||||
per_run_stats: dict[int, tuple[int, int]] = {}
|
||||
for run_idx, sample, step in selected_samples:
|
||||
if run_idx not in samples_by_run:
|
||||
samples_by_run[run_idx] = []
|
||||
steps_by_run[run_idx] = step
|
||||
else:
|
||||
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
|
||||
samples_by_run[run_idx].append(sample)
|
||||
|
||||
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
@@ -328,8 +338,13 @@ class MultiPacker(BasePacker):
|
||||
idxs=[run_idx] * len(run_samples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
)
|
||||
run_id = self.multi_run_manager.idx_2_id[run_idx]
|
||||
run_step = steps_by_run[run_idx]
|
||||
# Merge into combined grid
|
||||
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = run_step
|
||||
all_micro_batches[worker_idx].extend(worker_batches)
|
||||
|
||||
self.sender.send(all_micro_batches)
|
||||
|
||||
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
@@ -30,10 +33,10 @@ class TokenExporter:
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._file: Any | None = None
|
||||
self._closed = False
|
||||
self._current_step: int | None = None
|
||||
self._sequences_this_step = 0
|
||||
self._initialized_files: set[tuple[str | None, int, int]] = set()
|
||||
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
|
||||
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
@@ -45,11 +48,11 @@ class TokenExporter:
|
||||
response_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
if self._current_step != step:
|
||||
self._start_step(step)
|
||||
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
run_id = micro_batch.get("run_id")
|
||||
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(response_lengths):
|
||||
@@ -60,54 +63,73 @@ class TokenExporter:
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"export_step": export_step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_this_step,
|
||||
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
|
||||
"run_id": run_id,
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
"training_mode": str(micro_batch["training_mode"]),
|
||||
**_slice_columns(columns, start, end),
|
||||
}
|
||||
},
|
||||
run_id,
|
||||
export_step,
|
||||
)
|
||||
self._sequences_this_step += 1
|
||||
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _start_step(self, step: int) -> None:
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
# A single run step's sequences can span multiple trainer steps (the packer
|
||||
# splits a run step across packs when it exceeds the token budget). Only
|
||||
# finalize a run's export dir once that run step is fully consumed — the same
|
||||
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
|
||||
# is single-run export, where a step never spans trainer steps, so mark it now.
|
||||
# The caller barriers first so a STABLE only lands after every rank flushed.
|
||||
ready_run_ids = ready_run_ids or set()
|
||||
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
|
||||
for stable_dir in self._pending_stable_dirs.pop(run_id):
|
||||
(stable_dir / "STABLE").touch()
|
||||
|
||||
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
|
||||
if run_id is not None:
|
||||
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
|
||||
return self.output_dir / f"step_{export_step}"
|
||||
|
||||
def _export_file(self, export_step: int, run_id: str | None) -> Path:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._current_step = step
|
||||
self._sequences_this_step = 0
|
||||
step_dir = self.output_dir / f"step_{step}"
|
||||
|
||||
step_dir = self._export_dir(export_step, run_id)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
return step_dir / f"rank_{self.rank}.jsonl"
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is None:
|
||||
raise RuntimeError("Token exporter has no active step file")
|
||||
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
mode = "a" if file_key in self._initialized_files else "w"
|
||||
export_file = self._export_file(export_step, run_id)
|
||||
with export_file.open(mode, encoding="utf-8") as file:
|
||||
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
self._initialized_files.add(file_key)
|
||||
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
token_export_config = config.experimental.token_export
|
||||
if token_export_config is None:
|
||||
if not config.enable_token_export:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
@@ -512,7 +512,14 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
|
||||
token_exporter.export(
|
||||
progress.step,
|
||||
micro_step,
|
||||
micro_batch,
|
||||
out,
|
||||
response_lengths,
|
||||
config.loss,
|
||||
)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
@@ -534,6 +541,15 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
if config.enable_token_export:
|
||||
dist.barrier()
|
||||
ready_run_ids = {
|
||||
multi_run_manager.idx_2_id[idx]
|
||||
for idx in multi_run_manager.ready_to_update_idxs
|
||||
if idx in multi_run_manager.idx_2_id
|
||||
}
|
||||
token_exporter.mark_stable(ready_run_ids)
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
# across dp_cp so the final gradient is the true per-token mean over the global batch.
|
||||
for param in model.parameters():
|
||||
|
||||
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
|
||||
FileSystemTrainingBatchReceiver,
|
||||
FileSystemTrainingBatchSender,
|
||||
)
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
|
||||
from prime_rl.transport.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
TrainingBatch,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transport.zmq import (
|
||||
ZMQMicroBatchReceiver,
|
||||
ZMQMicroBatchSender,
|
||||
|
||||
@@ -89,3 +89,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
# sft → sft loss). All samples packed into a micro batch share the same mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
rewards: list[float] | None = None
|
||||
|
||||
# Packer-derived metadata used for run-local token exports.
|
||||
run_id: str | None = None
|
||||
run_step: int | None = None
|
||||
|
||||
@@ -12,7 +12,7 @@ import verifiers as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import NotFoundError
|
||||
from renderers import RendererConfig
|
||||
from tenacity import retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
@@ -303,8 +303,8 @@ async def check_health(
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def _is_retryable_pause_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for pausing engines."""
|
||||
def _is_retryable_admin_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
|
||||
# client errors (4xx) won't fix themselves on retry.
|
||||
@@ -317,47 +317,55 @@ def _is_retryable_pause_error(exception: BaseException) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
|
||||
# (mode="keep"), so a single attempt can legitimately take a while, but the global
|
||||
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
|
||||
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
|
||||
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
|
||||
PAUSE_READ_TIMEOUT_S = 120.0
|
||||
PAUSE_TOTAL_TIMEOUT_S = 300.0
|
||||
# Per-attempt read timeout for admin ops, overridable per call. The admin
|
||||
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
|
||||
# weight update forever: the read timeout converts a hang into a TimeoutException
|
||||
# that tenacity retries. Sized for `/pause`, which drains in-flight requests
|
||||
# (mode="keep") and so can legitimately take a while.
|
||||
ADMIN_TIMEOUT_S = 300.0
|
||||
# `/update_weights` runs a collective NCCL receive across all DP workers, which
|
||||
# can take longer than the other admin ops.
|
||||
UPDATE_WEIGHTS_TIMEOUT_S = 720.0
|
||||
|
||||
|
||||
async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMIN_TIMEOUT_S, **kwargs) -> None:
|
||||
"""POST an admin op with a bounded per-attempt timeout, retrying transient errors.
|
||||
|
||||
The total wall-clock budget across all retries is twice the per-attempt timeout.
|
||||
"""
|
||||
async for attempt in AsyncRetrying(
|
||||
retry=retry_if_exception(_is_retryable_admin_error),
|
||||
stop=stop_after_delay(2 * timeout_s) | stop_after_attempt(10),
|
||||
wait=wait_exponential(multiplier=1, min=1, max=10),
|
||||
reraise=True,
|
||||
):
|
||||
with attempt:
|
||||
response = await client.post(
|
||||
path,
|
||||
timeout=httpx.Timeout(connect=10.0, read=timeout_s, write=60.0, pool=10.0),
|
||||
**kwargs,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
|
||||
"""Pause all inference engines, waiting for in-flight requests to drain."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Updating policy in-flight to v{step}")
|
||||
|
||||
@retry(
|
||||
retry=retry_if_exception(_is_retryable_pause_error),
|
||||
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
|
||||
wait=wait_exponential(multiplier=1, min=1, max=10),
|
||||
reraise=True,
|
||||
await asyncio.gather(
|
||||
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
|
||||
)
|
||||
async def _pause(client: AsyncClient) -> None:
|
||||
response = await client.post(
|
||||
"/pause",
|
||||
params={"mode": "keep", "clear_cache": "false"},
|
||||
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_pause(client) for client in admin_clients])
|
||||
logger.debug("All inference engines paused")
|
||||
|
||||
|
||||
async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
|
||||
"""Resume all inference engines after weight update."""
|
||||
"""Resume all inference engines after weight update.
|
||||
|
||||
Resuming is idempotent (it just clears the paused flag), so retrying transient
|
||||
failures is safe; a dropped /resume would leave engines paused indefinitely.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
async def _resume(client: AsyncClient) -> None:
|
||||
response = await client.post("/resume")
|
||||
response.raise_for_status()
|
||||
|
||||
await asyncio.gather(*[_resume(client) for client in admin_clients])
|
||||
await asyncio.gather(*[_admin_post(client, "/resume") for client in admin_clients])
|
||||
logger.debug("All inference engines resumed")
|
||||
|
||||
|
||||
@@ -383,11 +391,6 @@ async def update_weights(
|
||||
if lora_name is not None and weight_dir is not None:
|
||||
await load_lora_adapter(admin_clients, lora_name, weight_dir)
|
||||
else:
|
||||
|
||||
async def _update_weights(admin_client: AsyncClient, weight_dir: str | None) -> None:
|
||||
response = await admin_client.post("/update_weights", json={"weight_dir": weight_dir})
|
||||
response.raise_for_status()
|
||||
|
||||
# Pause engines so all DP workers drain in-flight work and can join the NCCL broadcast
|
||||
await _pause_engines(admin_clients, step=step)
|
||||
|
||||
@@ -399,7 +402,17 @@ async def update_weights(
|
||||
nccl_ready_file.touch()
|
||||
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
|
||||
|
||||
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
|
||||
await asyncio.gather(
|
||||
*[
|
||||
_admin_post(
|
||||
admin_client,
|
||||
"/update_weights",
|
||||
json={"weight_dir": weight_dir_posix},
|
||||
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
|
||||
)
|
||||
for admin_client in admin_clients
|
||||
]
|
||||
)
|
||||
finally:
|
||||
await _resume_engines(admin_clients)
|
||||
|
||||
|
||||
@@ -16,8 +16,8 @@ import verifiers as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
|
||||
@@ -112,7 +112,7 @@ class PrimeMonitor(Monitor):
|
||||
config: PrimeMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
run_config: OrchestratorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
@@ -185,7 +185,7 @@ class PrimeMonitor(Monitor):
|
||||
if config.log_extras.distributions:
|
||||
self.last_log_distributions_step = -1
|
||||
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
|
||||
"""Register an external run with the platform. Returns run_id on success, None on failure."""
|
||||
prime_config = None
|
||||
team_id = config.team_id
|
||||
@@ -197,22 +197,23 @@ class PrimeMonitor(Monitor):
|
||||
if frontend_url is None:
|
||||
frontend_url = prime_config.frontend_url
|
||||
|
||||
model = getattr(run_config, "model", None) if run_config else None
|
||||
environments = getattr(run_config, "env", None) if run_config else None
|
||||
wandb = getattr(run_config, "wandb", None) if run_config else None
|
||||
|
||||
payload: dict = {
|
||||
"base_model": model.name if model else "unknown",
|
||||
"max_steps": getattr(run_config, "max_steps", None) or 0,
|
||||
payload: dict[str, Any] = {
|
||||
"base_model": run_config.student.model.name if run_config else "unknown",
|
||||
"max_steps": (run_config.max_steps if run_config else None) or 0,
|
||||
}
|
||||
if run_config:
|
||||
if run_config.batch_size is not None:
|
||||
payload["batch_size"] = run_config.batch_size
|
||||
payload["rollouts_per_example"] = run_config.group_size
|
||||
payload["seq_len"] = run_config.seq_len
|
||||
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
|
||||
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
|
||||
if run_config.wandb:
|
||||
payload["wandb_project"] = run_config.wandb.project
|
||||
if config.run_name:
|
||||
payload["name"] = config.run_name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
if environments:
|
||||
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
|
||||
if wandb and getattr(wandb, "project", None):
|
||||
payload["wandb_project"] = wandb.project
|
||||
|
||||
try:
|
||||
response = httpx.post(
|
||||
|
||||
@@ -26,9 +26,8 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
|
||||
private = Path("configs/private")
|
||||
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
|
||||
"""Any TOML file inside `configs/` or `examples/`."""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files
|
||||
@@ -168,6 +167,11 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
assert not cli(TrainerConfig, args=[]).enable_token_export
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
|
||||
OrchestratorConfig.model_validate(
|
||||
|
||||
@@ -38,8 +38,8 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
|
||||
# NemotronH
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", "nemotron_v3"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", "nano_v3"),
|
||||
# StepFun
|
||||
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
|
||||
# Qwen3 dense
|
||||
|
||||
@@ -110,3 +110,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
sender = sender_holder["sender"]
|
||||
assert len(sender.sent) == 1
|
||||
assert len(sender.sent[0][0]) == 1
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 0
|
||||
|
||||
Reference in New Issue
Block a user