Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ffa00c648 | ||
|
|
bc740de6dc | ||
|
|
c8fdcbb39c | ||
|
|
f87be6ba76 | ||
|
|
192035e52c | ||
|
|
30a14c1702 | ||
|
|
a646ad6050 | ||
|
|
10135d4814 | ||
|
|
29cc7b24ef | ||
|
|
deb1aa92bc | ||
|
|
5c3008b3a5 | ||
|
|
54b3e4cd24 |
+1
-1
@@ -37,7 +37,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
|
||||
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
|
||||
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
|
||||
- **`orchestrator.reload_weights_on_start`**: Added flag to control resetting inference weights to the base model when starting from scratch (default: True) (2026-01-21)
|
||||
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
|
||||
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
|
||||
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
|
||||
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ The trainer is responsible for producing an updated policy model given rollouts
|
||||
|
||||
### Inference
|
||||
|
||||
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with two custom endpoints to enable updating the server with the latest policy: `update_weights` is used to reload model weights from a HF-compatible checkpoint on disk, and `reload_weights` is used to reset the weights to the base model in between experiments. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
|
||||
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
|
||||
|
||||
### RL
|
||||
|
||||
|
||||
+1
-1
@@ -83,7 +83,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" }
|
||||
|
||||
@@ -203,3 +203,145 @@ def monkey_patch_tokenize_params_validation():
|
||||
|
||||
TokenizeParams._token_len_check = _patched_token_len_check
|
||||
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.
|
||||
|
||||
These patches are only needed when using LoRA with MiniMax M2 but are safe
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them at
|
||||
import time because the worker __init__ runs before the vLLM config is
|
||||
available, so we can't check if LoRA is enabled.
|
||||
|
||||
Problem 1 — Gate dtype mismatch:
|
||||
vLLM's MiniMaxM2MoE creates the gate (router) with params_dtype=float32
|
||||
and casts inputs to float32. When LoRA is enabled, vLLM wraps ALL
|
||||
ReplicatedLinear layers (including the gate) with LoRA support. Even
|
||||
though our adapter has no gate LoRA weights, the LoRA Triton kernel
|
||||
still runs for all wrapped layers when any adapter is active — and it
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: recreate the gate in model dtype and remove the float32 cast.
|
||||
FusedMoE already has router_logits_dtype=float32, so routing precision
|
||||
is preserved inside the expert dispatch.
|
||||
|
||||
Problem 2 — Adapter key naming mismatch:
|
||||
PrimeRL saves adapter keys using its internal naming convention
|
||||
(mlp.experts.{j}.gate_proj/down_proj/up_proj), which matches Qwen3 MoE
|
||||
but not MiniMax M2. vLLM's MiniMax M2 model expects HF-style keys
|
||||
(block_sparse_moe.experts.{j}.w1/w2/w3). For full model weights this
|
||||
is handled by vLLM's load_weights(), but LoRA adapters are loaded
|
||||
through a separate path (LoRAModel.from_local_checkpoint) that doesn't
|
||||
have model-specific key translation.
|
||||
Fix: set hf_to_vllm_mapper on the model class so vLLM remaps adapter
|
||||
keys during LoRA loading. This attribute is only read by _load_adapter
|
||||
in the LoRA worker manager — it has no effect without LoRA.
|
||||
"""
|
||||
from vllm.model_executor.models.minimax_m2 import MiniMaxM2ForCausalLM, MiniMaxM2MoE
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
|
||||
# --- Gate dtype fix (only matters with LoRA, safe without) ---
|
||||
_original_init = MiniMaxM2MoE.__init__
|
||||
|
||||
def _patched_init(self, config, quant_config=None, prefix=""):
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
|
||||
self.gate = ReplicatedLinear(
|
||||
config.hidden_size,
|
||||
config.num_local_experts,
|
||||
bias=False,
|
||||
quant_config=None,
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_substr={
|
||||
".mlp.experts.": ".block_sparse_moe.experts.",
|
||||
".gate_proj.": ".w1.",
|
||||
".down_proj.": ".w2.",
|
||||
".up_proj.": ".w3.",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -76,14 +79,6 @@ async def update_weights(request: Request):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/reload_weights")
|
||||
async def reload_weights(request: Request):
|
||||
await engine_client(request).collective_rpc("reload_weights")
|
||||
# Reset prefix cache to invalidate KV states computed with old weights
|
||||
await engine_client(request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Load a LoRA adapter and reset the prefix cache.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager
|
||||
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -720,12 +720,6 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
# Whether to reset inference weights to base model when starting from scratch
|
||||
reload_weights_on_start: Annotated[
|
||||
bool,
|
||||
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
|
||||
] = True
|
||||
|
||||
# The validation configuration
|
||||
val: ValConfig | None = None
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -50,7 +51,6 @@ from prime_rl.orchestrator.vf_utils import (
|
||||
)
|
||||
from prime_rl.utils.client import (
|
||||
init_nccl_broadcast,
|
||||
reload_weights,
|
||||
setup_inference_pool,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
@@ -165,9 +165,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,
|
||||
@@ -176,6 +177,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}")
|
||||
@@ -202,7 +204,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,
|
||||
@@ -211,6 +213,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}")
|
||||
@@ -321,14 +324,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
lora_name = config.model.lora.name if config.model.lora else None
|
||||
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
|
||||
else:
|
||||
if config.reload_weights_on_start:
|
||||
if config.model.lora is None:
|
||||
logger.info("Training from scratch. Resetting weights to base model")
|
||||
await reload_weights(inference_pool.admin_clients)
|
||||
else:
|
||||
logger.info("Training from scratch. Skipping base weight reload because LoRA is enabled")
|
||||
else:
|
||||
logger.info("Training from scratch. Skipping base weight reload")
|
||||
logger.info("Training from scratch")
|
||||
|
||||
# Iterate over dataset in batches
|
||||
max_steps = config.max_steps or int(1e9)
|
||||
@@ -783,6 +779,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:
|
||||
|
||||
@@ -30,7 +30,6 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.tensor_hashing import get_module_signature, get_optimizer_signature
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
|
||||
|
||||
|
||||
@@ -214,9 +213,6 @@ class CheckpointManager:
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self.load_from_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
self.logger.debug(
|
||||
f"Signatures after loading training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
|
||||
)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -230,9 +226,6 @@ class CheckpointManager:
|
||||
"""Save the full checkpoint state for a specified step."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.logger.debug(
|
||||
f"Signatures before saving training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
|
||||
)
|
||||
|
||||
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
@@ -305,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,
|
||||
@@ -314,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,
|
||||
@@ -400,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."""
|
||||
|
||||
@@ -40,7 +40,6 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.tensor_hashing import get_module_signature
|
||||
from prime_rl.utils.vlm import is_vlm_model
|
||||
|
||||
# Add filter to the standard logging module for transformers.modeling_utils to supress the
|
||||
@@ -86,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")
|
||||
|
||||
@@ -642,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)
|
||||
|
||||
@@ -679,7 +709,6 @@ def setup_model(
|
||||
else:
|
||||
load_dcp_from_hf(model, config, parallel_dims)
|
||||
|
||||
logger.debug(f"Model signature: {get_module_signature(model, compress=True)}")
|
||||
return model
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -249,24 +249,6 @@ async def update_weights(
|
||||
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
|
||||
|
||||
|
||||
async def reload_weights(admin_clients: list[AsyncClient]) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to reload weights (reset to base model)."""
|
||||
logger = get_logger()
|
||||
|
||||
async def _reload_weights(admin_client: AsyncClient) -> None:
|
||||
logger.debug("Sending request to reload weights (reset to base model)")
|
||||
try:
|
||||
response = await admin_client.post("/reload_weights", json={})
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning("The route /reload_weights does not exist. Skipping weight reload.")
|
||||
return
|
||||
raise
|
||||
|
||||
await asyncio.gather(*[_reload_weights(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
def _is_retryable_lora_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for LoRA loading."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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