Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
944163ac68 | ||
|
|
1e7561668d | ||
|
|
fd78f21f79 | ||
|
|
7eade4f7e1 | ||
|
|
bf0f903b86 | ||
|
|
8ffa00c648 | ||
|
|
bc740de6dc | ||
|
|
c8fdcbb39c | ||
|
|
f87be6ba76 | ||
|
|
192035e52c | ||
|
|
30a14c1702 | ||
|
|
a646ad6050 | ||
|
|
10135d4814 | ||
|
|
29cc7b24ef |
@@ -59,5 +59,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
|
||||
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
|
||||
|
||||
|
||||
+18
-4
@@ -1,6 +1,8 @@
|
||||
# SLURM
|
||||
|
||||
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
## RL
|
||||
|
||||
For RL on SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
|
||||
@@ -118,9 +120,9 @@ tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
## Custom SLURM Templates
|
||||
### Custom SLURM Templates
|
||||
|
||||
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
The default RL template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl_slurm \
|
||||
@@ -130,7 +132,7 @@ uv run rl_slurm \
|
||||
|
||||
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
|
||||
|
||||
## Monitoring
|
||||
### Monitoring
|
||||
|
||||
After submission, the logs are available at:
|
||||
|
||||
@@ -152,3 +154,15 @@ This creates a tmux session `slurm-my-rl-job` with two windows:
|
||||
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
|
||||
|
||||
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
|
||||
|
||||
---
|
||||
|
||||
## SFT
|
||||
|
||||
For SFT on SLURM, use the `sft_slurm` entrypoint. It works the same way as `rl_slurm` but only needs a trainer config — no inference or orchestrator nodes.
|
||||
|
||||
```bash
|
||||
uv run sft_slurm @ examples/slurm/sft_moe.toml
|
||||
```
|
||||
|
||||
See [`examples/slurm/sft_moe.toml`](../examples/slurm/sft_moe.toml) for a MoE example with activation checkpointing, CPU offload, and compilation. Use `--dry-run` to generate the script without submitting.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
job_name = "sft-moe-math"
|
||||
output_dir = "/shared/outputs/sft-moe-math"
|
||||
num_nodes = 1
|
||||
gpus_per_node = 8
|
||||
|
||||
max_steps = 500
|
||||
|
||||
[wandb]
|
||||
project = "sft-moe-intellect"
|
||||
name = "sft-moe-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.compile]
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
subsets = ["default"]
|
||||
splits = ["math"]
|
||||
batch_size = 128
|
||||
seq_len = 8192
|
||||
+2
-1
@@ -44,6 +44,7 @@ orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
sft_slurm = "prime_rl.slurm.sft:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
@@ -83,7 +84,7 @@ override-dependencies = [
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
math-env = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "013d4da" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "9052ecf" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
|
||||
@@ -3,9 +3,90 @@ from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
|
||||
from prime_rl.utils.utils import rgetattr, rsetattr
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-4.5
|
||||
"zai-org/GLM-4.5": "glm45",
|
||||
"zai-org/GLM-4.5-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Base": "glm45",
|
||||
"zai-org/GLM-4.5-Air": "glm45",
|
||||
"zai-org/GLM-4.5-Air-FP8": "glm45",
|
||||
"zai-org/GLM-4.5-Air-Base": "glm45",
|
||||
"zai-org/GLM-4.5V": "glm45",
|
||||
"zai-org/GLM-4.5V-FP8": "glm45",
|
||||
# GLM-4.7
|
||||
"zai-org/GLM-4.7": "glm47",
|
||||
"zai-org/GLM-4.7-FP8": "glm47",
|
||||
"zai-org/GLM-4.7-Flash": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
|
||||
# INTELLECT-3
|
||||
"PrimeIntellect/INTELLECT-3": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
|
||||
"PrimeIntellect/INTELLECT-3.1": "hermes",
|
||||
# Qwen3 dense
|
||||
"Qwen/Qwen3-0.6B": "hermes",
|
||||
"Qwen/Qwen3-0.6B-Base": "hermes",
|
||||
"Qwen/Qwen3-0.6B-FP8": "hermes",
|
||||
"Qwen/Qwen3-1.7B": "hermes",
|
||||
"Qwen/Qwen3-1.7B-Base": "hermes",
|
||||
"Qwen/Qwen3-1.7B-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B": "hermes",
|
||||
"Qwen/Qwen3-4B-Base": "hermes",
|
||||
"Qwen/Qwen3-4B-FP8": "hermes",
|
||||
"Qwen/Qwen3-8B": "hermes",
|
||||
"Qwen/Qwen3-8B-Base": "hermes",
|
||||
"Qwen/Qwen3-8B-FP8": "hermes",
|
||||
"Qwen/Qwen3-14B": "hermes",
|
||||
"Qwen/Qwen3-14B-Base": "hermes",
|
||||
"Qwen/Qwen3-14B-FP8": "hermes",
|
||||
"Qwen/Qwen3-32B": "hermes",
|
||||
"Qwen/Qwen3-32B-FP8": "hermes",
|
||||
# Qwen3 MoE
|
||||
"Qwen/Qwen3-30B-A3B": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Base": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
|
||||
# Qwen3 2507
|
||||
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
|
||||
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
|
||||
# Qwen3-Next
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
|
||||
# Qwen3-Coder
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
|
||||
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
|
||||
# Qwen3-Coder-Next
|
||||
"Qwen/Qwen3-Coder-Next": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-Base": "hermes",
|
||||
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
|
||||
# Qwen3.5
|
||||
"Qwen/Qwen3.5-397B-A17B": "hermes",
|
||||
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
|
||||
}
|
||||
|
||||
# TODO: Set thinking/ solution budget
|
||||
|
||||
|
||||
@@ -79,16 +160,18 @@ class ModelConfig(BaseConfig):
|
||||
enable_auto_tool_choice: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
|
||||
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
|
||||
"Automatically set to True when tool_call_parser is configured.",
|
||||
),
|
||||
] = False
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str,
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
"If not set, automatically inferred from the model name.",
|
||||
),
|
||||
] = "hermes"
|
||||
] = None
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
@@ -104,6 +187,19 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_tool_call_parser(self):
|
||||
if self.tool_call_parser is None:
|
||||
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
|
||||
if parser is not None:
|
||||
logger.info(f"Auto-detected tool_call_parser='{parser}' for model '{self.name}'")
|
||||
self.tool_call_parser = parser
|
||||
|
||||
if self.tool_call_parser is not None:
|
||||
self.enable_auto_tool_choice = True
|
||||
|
||||
return self
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseSettings):
|
||||
"""Configures weight broadcast settings."""
|
||||
|
||||
@@ -205,6 +205,73 @@ def monkey_patch_tokenize_params_validation():
|
||||
TokenizeParams._text_len_check = _patched_text_len_check
|
||||
|
||||
|
||||
def monkey_patch_hermes_tool_parser_thread_safety():
|
||||
"""Patch Hermes2ProToolParser to cache tokenizer encode/decode results.
|
||||
|
||||
The original __init__ calls tokenizer.encode() and tokenizer.decode() on
|
||||
every instantiation. Under concurrent load, the shared HuggingFace tokenizer's
|
||||
Rust backend panics with ``RuntimeError: Already borrowed`` because multiple
|
||||
threads mutably borrow the same internal state simultaneously.
|
||||
|
||||
Fix: run the first __init__ (which calls encode/decode) under a lock, cache
|
||||
the results, and reuse them for all subsequent instantiations without ever
|
||||
touching the tokenizer again.
|
||||
"""
|
||||
import threading
|
||||
|
||||
import regex as re
|
||||
from vllm.tool_parsers.abstract_tool_parser import ToolParser
|
||||
from vllm.tool_parsers.hermes_tool_parser import Hermes2ProToolParser
|
||||
|
||||
_original_init = Hermes2ProToolParser.__init__
|
||||
_cache: dict[int, dict] = {}
|
||||
_lock = threading.Lock()
|
||||
|
||||
def _patched_init(self, tokenizer):
|
||||
from vllm.tokenizers.mistral import MistralTokenizer
|
||||
|
||||
# Resolve the actual tokenizer that __init__ will use for encode/decode
|
||||
actual_tokenizer = tokenizer.tokenizer if isinstance(tokenizer, MistralTokenizer) else tokenizer
|
||||
key = id(actual_tokenizer)
|
||||
|
||||
if key in _cache:
|
||||
# Fast path: skip encode/decode entirely, set up instance from cache
|
||||
ToolParser.__init__(self, tokenizer)
|
||||
if isinstance(tokenizer, MistralTokenizer):
|
||||
self.model_tokenizer = tokenizer.tokenizer
|
||||
self.current_tool_name_sent = False
|
||||
self.prev_tool_call_arr = []
|
||||
self.current_tool_id = -1
|
||||
self.streamed_args_for_tool = []
|
||||
self.tool_call_start_token = "<tool_call>"
|
||||
self.tool_call_end_token = "</tool_call>"
|
||||
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>|<tool_call>(.*)", re.DOTALL)
|
||||
self.scratch_pad_regex = re.compile(r"<scratch_pad>(.*?)</scratch_pad>", re.DOTALL)
|
||||
cached = _cache[key]
|
||||
self.tool_call_start_token_ids = cached["start_ids"]
|
||||
self.tool_call_end_token_ids = cached["end_ids"]
|
||||
self.tool_call_start_token_array = cached["start_array"]
|
||||
self.tool_call_end_token_array = cached["end_array"]
|
||||
self.buffered_delta_text = ""
|
||||
return
|
||||
|
||||
# Slow path: first instantiation for this tokenizer, run under lock
|
||||
with _lock:
|
||||
if key in _cache:
|
||||
# Another thread populated it while we waited
|
||||
_patched_init(self, tokenizer)
|
||||
return
|
||||
_original_init(self, tokenizer)
|
||||
_cache[key] = {
|
||||
"start_ids": self.tool_call_start_token_ids,
|
||||
"end_ids": self.tool_call_end_token_ids,
|
||||
"start_array": self.tool_call_start_token_array,
|
||||
"end_array": self.tool_call_end_token_array,
|
||||
}
|
||||
|
||||
Hermes2ProToolParser.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_hermes_tool_parser_thread_safety,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
@@ -38,6 +39,8 @@ monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode()
|
||||
monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Monkeypatch Hermes tool parser to fix "Already borrowed" RuntimeError under concurrent load
|
||||
monkey_patch_hermes_tool_parser_thread_safety()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ class CheckpointManager:
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "orchestrator"
|
||||
|
||||
def _save_to_path(
|
||||
def save_to_path(
|
||||
self,
|
||||
ckpt_path: Path,
|
||||
progress: Progress,
|
||||
@@ -47,7 +47,7 @@ class CheckpointManager:
|
||||
|
||||
self.logger.debug(f"Orchestrator checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
def _load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
|
||||
def load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
|
||||
"""Loads a checkpoint from a given path in-place."""
|
||||
self.logger.debug(f"Loading checkpoint from {ckpt_path}")
|
||||
start_time = time.perf_counter()
|
||||
@@ -76,7 +76,7 @@ class CheckpointManager:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self._load_from_path(ckpt_path, progress, buffer)
|
||||
self.load_from_path(ckpt_path, progress, buffer)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -87,7 +87,7 @@ class CheckpointManager:
|
||||
"""Saves the full checkpoint state for a specified step."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
self._save_to_path(ckpt_path, progress, buffer)
|
||||
self.save_to_path(ckpt_path, progress, buffer)
|
||||
|
||||
|
||||
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
|
||||
|
||||
@@ -825,6 +825,13 @@ class OrchestratorConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
),
|
||||
] = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
|
||||
@@ -45,22 +45,21 @@ def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any
|
||||
return sampling_args
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
|
||||
total_attempts = len(rewards)
|
||||
k = total_attempts // 2
|
||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
||||
"""Unbiased estimator of pass@k (Chen et al., 2021).
|
||||
|
||||
if k == 0:
|
||||
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
|
||||
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
|
||||
"""
|
||||
if n - c < k:
|
||||
return 1.0
|
||||
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
|
||||
|
||||
num_trials = 100
|
||||
pass_rates = []
|
||||
|
||||
for _ in range(num_trials):
|
||||
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
|
||||
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
|
||||
pass_rates.append(pass_rate)
|
||||
|
||||
return {f"pass@{k}": float(np.mean(pass_rates))}
|
||||
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
|
||||
n = len(rewards)
|
||||
c = sum(r == 1.0 for r in rewards)
|
||||
ks = [2**i for i in range(n.bit_length())]
|
||||
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
|
||||
|
||||
|
||||
async def evaluate_env(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import multiprocessing as mp
|
||||
import random
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
@@ -102,7 +103,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
install_env(env_id)
|
||||
|
||||
# Setup inference pool (handles both static and elastic modes)
|
||||
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
|
||||
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
|
||||
"history and the chat template has the extension property."
|
||||
)
|
||||
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
@@ -164,9 +171,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
|
||||
train_env_addresses = []
|
||||
env_processes: list[mp.Process] = []
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
@@ -175,6 +183,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
env_processes.append(process)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting train environment {env_name} to server at {address}")
|
||||
@@ -201,7 +210,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
for env_id, env, eval_env_name in zip(env_ids, config.eval.env, eval_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
address, process = spawn_env_server(
|
||||
env_id=env_id,
|
||||
env_args=env.args,
|
||||
extra_env_kwargs=env.extra_env_kwargs,
|
||||
@@ -210,6 +219,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
env_processes.append(process)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
|
||||
@@ -487,12 +497,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
train_examples: list[TrainingSample] = []
|
||||
rollout_prefill_lens: list[int] = []
|
||||
rollout_decode_lens: list[int] = []
|
||||
rollout_samples_per_rollout: list[int] = []
|
||||
num_prefill_tokens = 0
|
||||
num_decode_tokens = 0
|
||||
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
|
||||
rollout_prefill_tokens = 0
|
||||
rollout_decode_tokens = 0
|
||||
if samples is not None:
|
||||
rollout_samples_per_rollout.append(len(samples))
|
||||
for sample in samples:
|
||||
sample.advantage = advantage
|
||||
sample.reward = rollout["reward"]
|
||||
@@ -501,6 +513,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
train_examples.append(sample)
|
||||
else:
|
||||
rollout_samples_per_rollout.append(0)
|
||||
rollout_prefill_lens.append(rollout_prefill_tokens)
|
||||
rollout_decode_lens.append(rollout_decode_tokens)
|
||||
num_prefill_tokens += rollout_prefill_tokens
|
||||
@@ -568,6 +582,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
"decode_len": rollout_decode_lens,
|
||||
"samples_per_rollout": rollout_samples_per_rollout,
|
||||
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
|
||||
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
|
||||
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
|
||||
@@ -630,6 +645,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
|
||||
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
|
||||
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
|
||||
# Seqs per rollout metrics
|
||||
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
|
||||
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
|
||||
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
|
||||
# Turn metrics
|
||||
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
|
||||
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
|
||||
@@ -775,6 +794,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Cancel event loop lag monitor task
|
||||
event_loop_lag_monitor_task.cancel()
|
||||
|
||||
# Shutdown env processes
|
||||
for process in env_processes:
|
||||
process.terminate()
|
||||
process.join(timeout=5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join(timeout=5)
|
||||
|
||||
logger.success("Orchestrator finished.")
|
||||
|
||||
# Optionally, print benchmark table
|
||||
|
||||
@@ -27,8 +27,7 @@ def spawn_env_server(
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
daemon: bool = True,
|
||||
) -> str:
|
||||
) -> tuple[str, mp.Process]:
|
||||
"""
|
||||
Starts a ZMQEnvServer process in a subprocess.
|
||||
|
||||
@@ -38,7 +37,7 @@ def spawn_env_server(
|
||||
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
|
||||
# the parent process, which has caused hangs when multiple env server
|
||||
# subprocesses share the same fds.
|
||||
mp.get_context("spawn").Process(
|
||||
process = mp.get_context("spawn").Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
env_id,
|
||||
@@ -49,17 +48,18 @@ def spawn_env_server(
|
||||
log_file_level,
|
||||
),
|
||||
kwargs=dict(address=address, json_logging=json_logging),
|
||||
daemon=daemon,
|
||||
).start()
|
||||
daemon=False, # cannot run daemon because env server uses subprocesses
|
||||
)
|
||||
process.start()
|
||||
|
||||
return address
|
||||
return address, process
|
||||
|
||||
|
||||
def setup_env_client(
|
||||
address: str,
|
||||
name: str | None = None,
|
||||
# health check configs
|
||||
health_check_interval: float = 1.0, # 1s
|
||||
health_check_interval: float = 5.0, # 5s (we detect an env server as unhealth after 3 * 5s = 15s of unsuccessful health checks)
|
||||
startup_timeout: float = 600.0, # 10m
|
||||
recovery_timeout: float = 600.0, # 10m
|
||||
) -> EnvClient:
|
||||
|
||||
@@ -91,9 +91,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--enable-auto-tool-choice \
|
||||
--enable-log-requests \
|
||||
--no-disable-log-requests \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent
|
||||
TEMPLATE_NAME = "sft_slurm.sh.j2"
|
||||
|
||||
|
||||
class SFTSLURMConfig(SFTTrainerConfig):
|
||||
job_name: str
|
||||
num_nodes: int = Field(default=1, description="Number of training nodes.")
|
||||
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
|
||||
nodes_per_fsdp_group: int | None = Field(
|
||||
default=None,
|
||||
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group.",
|
||||
)
|
||||
|
||||
project_dir: Path = Field(
|
||||
default_factory=lambda: Path.cwd(),
|
||||
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
|
||||
)
|
||||
hf_hub_offline: bool = Field(
|
||||
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
|
||||
)
|
||||
|
||||
slurm_template: Path | None = Field(
|
||||
default=None, description="The path to the SLURM template file. If none, will use the default template."
|
||||
)
|
||||
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_replicate(self):
|
||||
if self.nodes_per_fsdp_group is not None:
|
||||
if self.num_nodes % self.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"num_nodes ({self.num_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.model.dp_replicate = self.num_nodes // self.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
|
||||
def write_trainer_config(config: SFTSLURMConfig, output_dir: Path) -> None:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
slurm_only_fields = set(SFTSLURMConfig.model_fields) - set(SFTTrainerConfig.model_fields)
|
||||
trainer_data = config.model_dump(exclude_none=True, mode="json", exclude=slurm_only_fields)
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(trainer_data, f)
|
||||
|
||||
|
||||
def render_slurm_script(config: SFTSLURMConfig, config_dir: Path) -> str:
|
||||
if config.slurm_template is not None:
|
||||
template_dir = config.slurm_template.parent
|
||||
template_name = config.slurm_template.name
|
||||
else:
|
||||
template_dir = TEMPLATE_DIR
|
||||
template_name = TEMPLATE_NAME
|
||||
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
|
||||
template = env.get_template(template_name)
|
||||
return template.render(
|
||||
job_name=config.job_name,
|
||||
output_dir=config.output_dir,
|
||||
config_dir=config_dir,
|
||||
num_nodes=config.num_nodes,
|
||||
project_dir=config.project_dir,
|
||||
gpus_per_node=config.gpus_per_node,
|
||||
hf_hub_offline=config.hf_hub_offline,
|
||||
)
|
||||
|
||||
|
||||
def sft_slurm(config: SFTSLURMConfig):
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_trainer_config(config, config_dir)
|
||||
|
||||
logger.info(f"Wrote trainer config to {config_dir}")
|
||||
|
||||
script = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "sft.sh"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
log_message = f"Logs:\n Trainer: tail -f {config.output_dir}/slurm/latest_train_node_rank_0.log"
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def main():
|
||||
sft_slurm(parse_argv(SFTSLURMConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition=cluster
|
||||
#SBATCH --exclusive # Get the ENTIRE node exclusively
|
||||
#SBATCH --output=/shared/logs/job_%j.log
|
||||
#SBATCH --error=/shared/logs/job_%j.log
|
||||
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/slurm
|
||||
|
||||
# General
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[0]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
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
|
||||
|
||||
|
||||
# Run SFT
|
||||
srun bash -c '
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
export GIT_LFS_SKIP_SMUDGE=1
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
|
||||
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
|
||||
|
||||
# This is required for compilation to work correctly
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
|
||||
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--nnodes=$NUM_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$OUTPUT_DIR/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
|
||||
-m prime_rl.trainer.sft.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
'
|
||||
@@ -298,6 +298,12 @@ class WeightCheckpointManager:
|
||||
"""Get the path to write the weight checkpoint for a given step."""
|
||||
return get_step_path(self.weights_dir, step)
|
||||
|
||||
def mark_stable(self, step: int) -> None:
|
||||
"""Write STABLE file to indicate weight checkpoint is complete."""
|
||||
if self.world.is_master:
|
||||
step_path = self.get_step_path(step)
|
||||
(step_path / "STABLE").touch()
|
||||
|
||||
def save_to_path(
|
||||
self,
|
||||
path: Path,
|
||||
@@ -307,44 +313,45 @@ class WeightCheckpointManager:
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
):
|
||||
"""Save HF-compatible weight checkpoint to a given path."""
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
start_time = time.perf_counter()
|
||||
if self.world.is_master:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
start_time = time.perf_counter()
|
||||
|
||||
self.logger.debug(f"Saving weight checkpoint to {path}")
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
self.logger.debug(f"Saving weight checkpoint to {path}")
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
# Save weights
|
||||
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
|
||||
# Save weights
|
||||
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
|
||||
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(path)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with
|
||||
# cache_implementation — save with use_cache=True without
|
||||
# mutating the model's config
|
||||
from copy import deepcopy
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(path)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with
|
||||
# cache_implementation — save with use_cache=True without
|
||||
# mutating the model's config
|
||||
from copy import deepcopy
|
||||
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(path)
|
||||
tokenizer.save_pretrained(path)
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(path)
|
||||
tokenizer.save_pretrained(path)
|
||||
|
||||
if self.config.save_adapter_separately and lora_state_dict is not None:
|
||||
adapter_path = path / "lora_adapters"
|
||||
adapter_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
|
||||
if self.lora_config:
|
||||
save_lora_config(
|
||||
model,
|
||||
adapter_path,
|
||||
rank=self.lora_config.rank,
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
|
||||
if self.config.save_adapter_separately and lora_state_dict is not None:
|
||||
adapter_path = path / "lora_adapters"
|
||||
adapter_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
|
||||
if self.lora_config:
|
||||
save_lora_config(
|
||||
model,
|
||||
adapter_path,
|
||||
rank=self.lora_config.rank,
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -393,10 +400,8 @@ class WeightCheckpointManager:
|
||||
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
# Save weight checkpoint on master rank
|
||||
if self.world.is_master:
|
||||
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
|
||||
# Write STABLE file to indicate checkpoint is complete (for eval to safely read)
|
||||
(step_path / "STABLE").touch()
|
||||
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
|
||||
self.mark_stable(step)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
|
||||
def maybe_clean(self) -> None:
|
||||
|
||||
@@ -13,11 +13,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
|
||||
# to attempt installing a kernel from hub.
|
||||
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
|
||||
|
||||
MOE_MODEL_MAPS = {
|
||||
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
|
||||
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
|
||||
}
|
||||
|
||||
|
||||
class ActivationCheckpointConfig(BaseConfig):
|
||||
"""Configures activation checkpointing."""
|
||||
@@ -255,6 +250,13 @@ class ModelConfig(BaseConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to freeze the MoE router parameters during training.",
|
||||
),
|
||||
] = False
|
||||
|
||||
lora: Annotated[
|
||||
LoRAConfig | None,
|
||||
Field(
|
||||
@@ -291,13 +293,6 @@ class ModelConfig(BaseConfig):
|
||||
data["attn"] = _ATTN_ALIASES[data["attn"]]
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _map_model_name_for_moe(self):
|
||||
"""Map model name if it exists in MOE_MODEL_MAPS."""
|
||||
if self.name in MOE_MODEL_MAPS:
|
||||
self.name = MOE_MODEL_MAPS[self.name]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
"""Trust remote code only if the model is from HF."""
|
||||
|
||||
@@ -85,6 +85,34 @@ def freeze_vision_encoder(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} parameters in vision encoder")
|
||||
|
||||
|
||||
def freeze_moe_router(model: nn.Module) -> None:
|
||||
"""Freeze MoE router parameters to maintain stable routing during training."""
|
||||
logger = get_logger()
|
||||
language_model = get_language_model(model)
|
||||
num_frozen = 0
|
||||
|
||||
for layer in language_model.layers:
|
||||
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
|
||||
if mlp is None:
|
||||
continue
|
||||
|
||||
# Custom implementation: MoE class with router attribute
|
||||
if isinstance(mlp, MoE):
|
||||
for param in mlp.router.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
# HuggingFace implementation: gate attribute (nn.Linear)
|
||||
elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear):
|
||||
for param in mlp.gate.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen == 0:
|
||||
raise ValueError("No MoE router parameters found to freeze. Is this a MoE model?")
|
||||
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def is_tt_moe_model(model: nn.Module) -> bool:
|
||||
return hasattr(model.config, "num_experts") or hasattr(model.config, "n_routed_experts")
|
||||
|
||||
@@ -641,6 +669,9 @@ def setup_model(
|
||||
if config.lora is not None:
|
||||
apply_lora_to_model(model, config.lora)
|
||||
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, parallel_dims)
|
||||
|
||||
|
||||
@@ -505,6 +505,12 @@ def train(config: RLTrainerConfig):
|
||||
}
|
||||
monitor.log(optim_metrics, step=progress.step)
|
||||
|
||||
# Compute derived metrics
|
||||
entropy_mean = tensor_stats.get("entropy/mean", 0.0)
|
||||
mismatch_kl_mean = tensor_stats.get("mismatch_kl/mean")
|
||||
if mismatch_kl_mean is not None and entropy_mean > 0:
|
||||
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
|
||||
|
||||
# Log tensor stats
|
||||
tensor_stats["step"] = progress.step
|
||||
monitor.log(tensor_stats, step=progress.step)
|
||||
|
||||
@@ -11,7 +11,7 @@ import torch.distributed.distributed_c10d as c10d
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_stable_ckpt_steps
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_stable_ckpt_steps
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
@@ -264,8 +264,11 @@ class MultiRunManager:
|
||||
if config.ckpt is None or config.ckpt.resume_step is None:
|
||||
self.progress[new_id].step = 0
|
||||
elif config.ckpt.resume_step == -1:
|
||||
stable_steps = get_stable_ckpt_steps(self.get_run_dir(new_id) / "checkpoints")
|
||||
self.progress[new_id].step = max(stable_steps) if stable_steps else 0
|
||||
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
|
||||
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
|
||||
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
|
||||
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
|
||||
self.progress[new_id].step = max(steps) if steps else 0
|
||||
else:
|
||||
self.progress[new_id].step = config.ckpt.resume_step
|
||||
|
||||
|
||||
@@ -96,31 +96,33 @@ class StaticInferencePool:
|
||||
pass
|
||||
|
||||
|
||||
async def setup_inference_pool(client_config: ClientConfig, model_name: str) -> InferencePool:
|
||||
async def setup_inference_pool(
|
||||
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
|
||||
|
||||
logger.info(
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
clients=setup_clients(client_config),
|
||||
clients=setup_clients(client_config, client_type=client_type),
|
||||
admin_clients=setup_admin_clients(client_config),
|
||||
skip_model_check=client_config.skip_model_check,
|
||||
)
|
||||
|
||||
|
||||
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
|
||||
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
|
||||
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
|
||||
return vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type="openai_chat_completions_token",
|
||||
client_type=client_type,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
|
||||
@@ -107,6 +107,7 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
port: int = 8000,
|
||||
sync_interval: float = 5.0,
|
||||
client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
@@ -115,6 +116,7 @@ class ElasticInferencePool:
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.port = port
|
||||
self.sync_interval = sync_interval
|
||||
self.client_type = client_type
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
self._admin_clients: dict[str, AsyncClient] = {}
|
||||
@@ -129,7 +131,9 @@ class ElasticInferencePool:
|
||||
self._started = False
|
||||
|
||||
@classmethod
|
||||
async def from_config(cls, config: ClientConfig, model_name: str) -> ElasticInferencePool:
|
||||
async def from_config(
|
||||
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
) -> ElasticInferencePool:
|
||||
if config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
@@ -138,6 +142,7 @@ class ElasticInferencePool:
|
||||
model_name=model_name,
|
||||
port=config.elastic.port,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
client_type=client_type,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -168,7 +173,8 @@ class ElasticInferencePool:
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
)
|
||||
),
|
||||
client_type=self.client_type,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
|
||||
@@ -114,6 +114,7 @@ class MetricsServer(HealthServer):
|
||||
self._mismatch_kl = Gauge(
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
# Aggregate run metrics
|
||||
self._runs_discovered = Gauge(
|
||||
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
|
||||
@@ -206,6 +207,8 @@ class MetricsServer(HealthServer):
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
|
||||
def update_runs(
|
||||
|
||||
@@ -8,6 +8,7 @@ from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.rl import RLConfig
|
||||
from prime_rl.slurm.rl import RLSLURMConfig
|
||||
from prime_rl.slurm.sft import SFTSLURMConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
@@ -20,6 +21,7 @@ CONFIG_CLASSES = [
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
RLSLURMConfig,
|
||||
SFTSLURMConfig,
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
from prime_rl.inference.config import ModelConfig
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_name,expected_parser",
|
||||
[
|
||||
# GLM-4.5
|
||||
("zai-org/GLM-4.5", "glm45"),
|
||||
("zai-org/GLM-4.5-Air", "glm45"),
|
||||
("zai-org/GLM-4.5V", "glm45"),
|
||||
# GLM-4.7
|
||||
("zai-org/GLM-4.7", "glm47"),
|
||||
("zai-org/GLM-4.7-Flash", "glm47"),
|
||||
# MiniMax
|
||||
("MiniMaxAI/MiniMax-M2", "minimax_m2"),
|
||||
("MiniMaxAI/MiniMax-M2.1", "minimax_m2"),
|
||||
("MiniMaxAI/MiniMax-M2.5", "minimax_m2"),
|
||||
# INTELLECT
|
||||
("PrimeIntellect/INTELLECT-3", "hermes"),
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "hermes"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "hermes"),
|
||||
# Qwen3
|
||||
("Qwen/Qwen3-0.6B", "hermes"),
|
||||
("Qwen/Qwen3-32B", "hermes"),
|
||||
("Qwen/Qwen3-235B-A22B", "hermes"),
|
||||
("Qwen/Qwen3-4B-Instruct-2507", "hermes"),
|
||||
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "hermes"),
|
||||
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes"),
|
||||
("Qwen/Qwen3.5-397B-A17B", "hermes"),
|
||||
],
|
||||
)
|
||||
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
|
||||
config = ModelConfig(name=model_name)
|
||||
assert config.tool_call_parser == expected_parser
|
||||
|
||||
|
||||
def test_explicit_parser_overrides_auto_detect():
|
||||
config = ModelConfig(name="Qwen/Qwen3-4B-Instruct-2507", tool_call_parser="qwen3_xml")
|
||||
assert config.tool_call_parser == "qwen3_xml"
|
||||
@@ -92,6 +92,7 @@ def test_server_update_metrics():
|
||||
assert "trainer_loss" in content
|
||||
assert "trainer_last_step_timestamp_seconds" in content
|
||||
assert "trainer_mismatch_kl" in content
|
||||
assert "trainer_kl_ent_ratio" in content
|
||||
|
||||
server.stop()
|
||||
|
||||
@@ -102,6 +103,8 @@ def test_server_metrics_values_are_correct():
|
||||
server.start()
|
||||
time.sleep(0.1)
|
||||
|
||||
entropy = 1.5
|
||||
mismatch_kl = 0.045
|
||||
server.update(
|
||||
step=100,
|
||||
loss=0.123,
|
||||
@@ -109,7 +112,8 @@ def test_server_metrics_values_are_correct():
|
||||
grad_norm=2.5,
|
||||
peak_memory_gib=16.0,
|
||||
learning_rate=3e-5,
|
||||
mismatch_kl=0.045,
|
||||
entropy=entropy,
|
||||
mismatch_kl=mismatch_kl,
|
||||
)
|
||||
|
||||
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
|
||||
@@ -118,6 +122,7 @@ def test_server_metrics_values_are_correct():
|
||||
assert "trainer_step 100.0" in content
|
||||
assert "trainer_loss 0.123" in content
|
||||
assert "trainer_mismatch_kl 0.045" in content
|
||||
assert f"trainer_kl_ent_ratio {mismatch_kl / entropy}" in content
|
||||
|
||||
server.stop()
|
||||
|
||||
|
||||
@@ -2373,7 +2373,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=9052ecf" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
@@ -3702,7 +3702,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11.dev0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da#013d4da8a906bef2e1cbb6b4bc4347214c1fd534" }
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=9052ecf#9052ecf0c794cd539b5555ae620c3d8935b347cd" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
|
||||
Reference in New Issue
Block a user