Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ffa00c648 | ||
|
|
bc740de6dc | ||
|
|
c8fdcbb39c | ||
|
|
f87be6ba76 | ||
|
|
192035e52c | ||
|
|
30a14c1702 | ||
|
|
a646ad6050 | ||
|
|
10135d4814 |
+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" }
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -164,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,
|
||||
@@ -175,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}")
|
||||
@@ -201,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,
|
||||
@@ -210,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}")
|
||||
@@ -775,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,10 +48,11 @@ 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(
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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