feat(monitor): add local file monitor (#3111)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
208ea64308
commit
cd00986f71
@@ -14,6 +14,7 @@ from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
@@ -493,6 +494,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
prime_monitor: PrimeMonitorConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ from prime_rl.configs.orchestrator import (
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
SlurmConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
@@ -242,6 +243,9 @@ class RLConfig(BaseConfig):
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
|
||||
|
||||
model: SharedModelConfig | None = None
|
||||
"""Shared model config. If None, falls back to the sub-config model settings."""
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
@@ -191,6 +192,9 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
|
||||
@@ -221,6 +221,18 @@ class WandbWithExtrasConfig(WandbConfig):
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
|
||||
|
||||
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
|
||||
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
|
||||
is disabled.
|
||||
"""
|
||||
|
||||
filename: str = "metrics.jsonl"
|
||||
"""Name of the JSONL file written under the component's ``output_dir``."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
|
||||
"""Base URL for the Prime Intellect monitoring API."""
|
||||
|
||||
@@ -7,6 +7,7 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
@@ -582,6 +583,9 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
|
||||
@@ -106,6 +106,9 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
|
||||
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
|
||||
|
||||
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
|
||||
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
# differ between sub-configs (auto-derived from model names, which may
|
||||
@@ -172,7 +175,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
|
||||
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
|
||||
# parent-class validator converts it, which happens after this one.
|
||||
for key in ("ckpt", "wandb"):
|
||||
for key in ("ckpt", "wandb", "file_monitor"):
|
||||
if isinstance(get(key), dict):
|
||||
fill(f"trainer.{key}", {})
|
||||
fill(f"orchestrator.{key}", {})
|
||||
|
||||
@@ -231,6 +231,7 @@ class Orchestrator:
|
||||
self.monitor = setup_monitor(
|
||||
wandb_config=config.wandb,
|
||||
prime_config=config.prime_monitor,
|
||||
file_config=config.file_monitor,
|
||||
output_dir=config.output_dir,
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
|
||||
@@ -86,7 +86,9 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
|
||||
monitor = setup_monitor(
|
||||
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
|
||||
)
|
||||
|
||||
# Setup heartbeat (only on rank 0)
|
||||
heart = None
|
||||
|
||||
@@ -73,7 +73,9 @@ def train(config: SFTConfig):
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
|
||||
monitor = setup_monitor(
|
||||
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
|
||||
)
|
||||
|
||||
# Setup heartbeat (only on rank 0)
|
||||
heart = None
|
||||
|
||||
@@ -2,9 +2,10 @@ from pathlib import Path
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.configs.shared import FileMonitorConfig, PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.monitor.base import Monitor, NoOpMonitor
|
||||
from prime_rl.utils.monitor.file import FileMonitor
|
||||
from prime_rl.utils.monitor.multi import MultiMonitor
|
||||
from prime_rl.utils.monitor.prime import PrimeMonitor
|
||||
from prime_rl.utils.monitor.wandb import WandbMonitor
|
||||
@@ -13,6 +14,7 @@ __all__ = [
|
||||
"Monitor",
|
||||
"WandbMonitor",
|
||||
"PrimeMonitor",
|
||||
"FileMonitor",
|
||||
"MultiMonitor",
|
||||
"NoOpMonitor",
|
||||
"setup_monitor",
|
||||
@@ -37,6 +39,7 @@ def setup_monitor(
|
||||
run_config: BaseConfig | None = None,
|
||||
*,
|
||||
prime_config: PrimeMonitorConfig | None = None,
|
||||
file_config: FileMonitorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
@@ -83,6 +86,16 @@ def setup_monitor(
|
||||
)
|
||||
)
|
||||
|
||||
if file_config is not None:
|
||||
monitors.append(
|
||||
FileMonitor(
|
||||
config=file_config,
|
||||
output_dir=output_dir,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
if len(monitors) == 0:
|
||||
_MONITOR = NoOpMonitor(keep_full_history=keep_full_history)
|
||||
elif len(monitors) == 1:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -8,6 +9,45 @@ if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
_DROPPED_JSON_VALUE = object()
|
||||
|
||||
|
||||
def drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
|
||||
"""Recursively drop non-finite floats (NaN/inf) from a JSON-serializable value.
|
||||
|
||||
Appends the dotted path of each dropped value to `dropped_paths`. Used before
|
||||
serializing metric payloads that must be strict JSON (the public Prime API and
|
||||
the local `metrics.jsonl` sink), since NaN/Infinity are not valid JSON.
|
||||
"""
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
dropped_paths.append(path)
|
||||
return _DROPPED_JSON_VALUE
|
||||
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: sanitized_item
|
||||
for key, item in value.items()
|
||||
if (
|
||||
sanitized_item := drop_non_finite_json_values(
|
||||
item,
|
||||
dropped_paths,
|
||||
f"{path}.{key}" if path else str(key),
|
||||
)
|
||||
)
|
||||
is not _DROPPED_JSON_VALUE
|
||||
}
|
||||
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
sanitized_item
|
||||
for idx, item in enumerate(value)
|
||||
if (sanitized_item := drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
|
||||
is not _DROPPED_JSON_VALUE
|
||||
]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
|
||||
"""Apply monitor sample_ratio semantics to a batch of items.
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from prime_rl.configs.shared import FileMonitorConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class FileMonitor(Monitor):
|
||||
"""Appends logged metrics to a local ``metrics.jsonl`` file.
|
||||
|
||||
A self-hosted, dependency-free mirror of what ``WandbMonitor.log`` sees: one
|
||||
JSON object per line, ``{"step": step, "time": <wall>, **metrics}``. The file is
|
||||
flushed after every write so an in-progress run can be read (e.g. to build a
|
||||
static dashboard snapshot mid-run). Only rank 0 writes. Samples and
|
||||
distributions are not persisted here (scalars only).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: FileMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self.output_dir = output_dir
|
||||
self._file = None
|
||||
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
self.enabled = self.config is not None
|
||||
self.is_master = rank == 0
|
||||
if not self.enabled or not self.is_master:
|
||||
if not self.is_master:
|
||||
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
|
||||
return
|
||||
|
||||
if output_dir is None:
|
||||
self.logger.warning("FileMonitor requires an output_dir; disabling.")
|
||||
self.enabled = False
|
||||
return
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._path = output_dir / config.filename
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self._file = open(self._path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics to {self._path}")
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
if not self.is_master or not self.enabled or self._file is None:
|
||||
return
|
||||
|
||||
dropped_paths: list[str] = []
|
||||
sanitized = drop_non_finite_json_values(metrics, dropped_paths)
|
||||
if dropped_paths:
|
||||
preview = ", ".join(dropped_paths[:5])
|
||||
suffix = " ..." if len(dropped_paths) > 5 else ""
|
||||
self.logger.debug(
|
||||
f"Dropping {len(dropped_paths)} non-finite value(s) from metrics.jsonl: {preview}{suffix}"
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
self._file.write(json.dumps(row))
|
||||
self._file.write("\n")
|
||||
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
if not self.is_master or not self.enabled or self.output_dir is None:
|
||||
return
|
||||
summary = self.history[-1] if self.history else {}
|
||||
dropped_paths: list[str] = []
|
||||
sanitized = drop_non_finite_json_values(summary, dropped_paths)
|
||||
with open(self.output_dir / filename, "w") as f:
|
||||
json.dump(sanitized, f)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
@@ -3,7 +3,6 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
@@ -21,7 +20,7 @@ from verifiers.v1.push import trace_to_sample
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values, sample_items_for_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -52,46 +51,13 @@ _SAMPLE_SCHEMA = pa.schema(
|
||||
)
|
||||
|
||||
|
||||
_DROPPED_JSON_VALUE = object()
|
||||
|
||||
|
||||
def _drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
dropped_paths.append(path)
|
||||
return _DROPPED_JSON_VALUE
|
||||
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: sanitized_item
|
||||
for key, item in value.items()
|
||||
if (
|
||||
sanitized_item := _drop_non_finite_json_values(
|
||||
item,
|
||||
dropped_paths,
|
||||
f"{path}.{key}" if path else str(key),
|
||||
)
|
||||
)
|
||||
is not _DROPPED_JSON_VALUE
|
||||
}
|
||||
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
sanitized_item
|
||||
for idx, item in enumerate(value)
|
||||
if (sanitized_item := _drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
|
||||
is not _DROPPED_JSON_VALUE
|
||||
]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs to Prime Intellect API."""
|
||||
|
||||
def _sanitize_json_payload(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Drop non-finite floats before sending JSON payloads to the public API."""
|
||||
dropped_paths: list[str] = []
|
||||
sanitized_payload = _drop_non_finite_json_values(payload, dropped_paths)
|
||||
sanitized_payload = drop_non_finite_json_values(payload, dropped_paths)
|
||||
if not dropped_paths:
|
||||
return payload
|
||||
|
||||
|
||||
Reference in New Issue
Block a user