From 58b9fc3d81b5767d4fe0062f135b376051c7b675 Mon Sep 17 00:00:00 2001 From: zilch <147668916@qq.com> Date: Wed, 2 Dec 2026 14:38:12 +0800 Subject: [PATCH 1/2] refactor(rl): unify training metrics, console phases and worker lifecycle Centralize metric sinks, independent aggregation and output cadence under motrix_rl.log. Share collector episode statistics, device-side metrics and native profiler timing trees across APPO and FastSAC. Unify worker startup and error reporting, dynamically group console metrics, route summary/system/timing views without duplicate displays, and include APPO reward breakdowns. Validation: repository pre-commit hooks; 640 fast regression tests; 19 targeted tests including CPU spawn/resume integration. --- bench/bench_live_metrics.py | 22 +- motrix_rl/src/motrix_rl/console/__init__.py | 9 +- motrix_rl/src/motrix_rl/console/boot.py | 156 +++ motrix_rl/src/motrix_rl/console/data.py | 41 +- .../src/motrix_rl/console/metric_panel.py | 242 ++++ motrix_rl/src/motrix_rl/console/panel.py | 637 +++++----- motrix_rl/src/motrix_rl/console/timing.py | 89 ++ motrix_rl/src/motrix_rl/contracts.py | 6 +- motrix_rl/src/motrix_rl/frameworks.py | 6 +- motrix_rl/src/motrix_rl/log/__init__.py | 4 + motrix_rl/src/motrix_rl/log/accumulator.py | 58 + .../src/motrix_rl/log/collector_stats.py | 189 +++ .../src/motrix_rl/{metrics.py => log/live.py} | 8 +- .../src/motrix_rl/log/process_logging.py | 83 ++ motrix_rl/src/motrix_rl/log/python_logging.py | 35 + motrix_rl/src/motrix_rl/log/schedule.py | 22 + motrix_rl/src/motrix_rl/log/sink.py | 26 + .../metrics.py => log/system_metrics.py} | 9 +- motrix_rl/src/motrix_rl/log/tensor_window.py | 64 ++ .../src/motrix_rl/log/training_logger.py | 155 +++ .../src/motrix_rl/log/training_metrics.py | 143 +++ motrix_rl/src/motrix_rl/runner.py | 6 +- motrix_rl/src/motrix_rl/system_metrics.py | 29 + motrix_rl/src/motrix_rl/training_logger.py | 91 -- motrix_rl/src/motrix_rl/worker.py | 104 +- .../tests/test_boot_panel.py | 97 +- motrix_rl/tests/test_collector_stats.py | 110 ++ motrix_rl/tests/test_console.py | 375 +++++- motrix_rl/tests/test_log_schedule.py | 25 + motrix_rl/tests/test_log_system_metrics.py | 35 + motrix_rl/tests/test_metric_panel.py | 440 +++++++ motrix_rl/tests/test_metrics.py | 34 +- motrix_rl/tests/test_python_logging.py | 59 + motrix_rl/tests/test_rl_contracts.py | 6 +- motrix_rl/tests/test_runner.py | 2 +- motrix_rl/tests/test_tensor_window.py | 46 + motrix_rl/tests/test_timing.py | 105 ++ motrix_rl/tests/test_training_logger.py | 213 +++- motrix_rl/tests/test_training_metrics.py | 221 ++++ motrix_rl/tests/test_worker.py | 104 +- motrix_rl_appo/README.md | 14 + .../src/motrix_rl_appo/collector.py | 46 +- motrix_rl_appo/src/motrix_rl_appo/metrics.py | 60 + motrix_rl_appo/src/motrix_rl_appo/trainer.py | 326 +++--- motrix_rl_appo/tests/test_appo_collector.py | 52 +- motrix_rl_appo/tests/test_appo_metrics_log.py | 61 + motrix_rl_appo/tests/test_appo_trainer.py | 115 +- .../src/motrix_rl_builtin/fastsac/agent.py | 42 +- .../fastsac/async_impl/collector.py | 163 +-- .../fastsac/async_impl/learner.py | 2 +- .../fastsac/async_impl/panels.py | 186 --- .../fastsac/async_impl/stats.py | 349 ++---- .../fastsac/async_impl/train.py | 692 +++++------ .../fastsac/async_impl/worker.py | 1023 ++++++++--------- .../motrix_rl_builtin/fastsac/sync/train.py | 204 ++-- .../fastsac/window_metrics.py | 65 -- .../src/motrix_rl_builtin/fastsac/wrap.py | 7 +- .../tests/fastsac_async_mocks.py | 17 +- .../tests/test_builtin_sim_backend.py | 71 +- .../tests/test_fastsac_async_multi.py | 44 +- .../tests/test_fastsac_collector.py | 101 +- .../tests/test_fastsac_final_obs.py | 2 +- .../tests/test_fastsac_learner.py | 84 +- .../tests/test_fastsac_live_metrics.py | 438 ++++--- .../tests/test_fastsac_multi_final_obs.py | 2 +- .../tests/test_fastsac_sync_trainer.py | 4 +- .../tests/test_fastsac_worker_logging.py | 163 +++ motrix_rl_supermimic/tests/test_trainer.py | 12 +- wiki/design/appo.md | 4 + .../fastsac-async-heterogeneous-trainer.md | 10 +- wiki/design/index.md | 4 +- wiki/design/live-metrics.md | 18 +- wiki/design/training-console.md | 214 ++++ 73 files changed, 5961 insertions(+), 2740 deletions(-) create mode 100644 motrix_rl/src/motrix_rl/console/boot.py create mode 100644 motrix_rl/src/motrix_rl/console/metric_panel.py create mode 100644 motrix_rl/src/motrix_rl/console/timing.py create mode 100644 motrix_rl/src/motrix_rl/log/__init__.py create mode 100644 motrix_rl/src/motrix_rl/log/accumulator.py create mode 100644 motrix_rl/src/motrix_rl/log/collector_stats.py rename motrix_rl/src/motrix_rl/{metrics.py => log/live.py} (99%) create mode 100644 motrix_rl/src/motrix_rl/log/process_logging.py create mode 100644 motrix_rl/src/motrix_rl/log/python_logging.py create mode 100644 motrix_rl/src/motrix_rl/log/schedule.py create mode 100644 motrix_rl/src/motrix_rl/log/sink.py rename motrix_rl/src/motrix_rl/{console/metrics.py => log/system_metrics.py} (74%) create mode 100644 motrix_rl/src/motrix_rl/log/tensor_window.py create mode 100644 motrix_rl/src/motrix_rl/log/training_logger.py create mode 100644 motrix_rl/src/motrix_rl/log/training_metrics.py delete mode 100644 motrix_rl/src/motrix_rl/training_logger.py rename motrix_rl_builtin/tests/test_fastsac_boot_panel.py => motrix_rl/tests/test_boot_panel.py (62%) create mode 100644 motrix_rl/tests/test_collector_stats.py create mode 100644 motrix_rl/tests/test_log_schedule.py create mode 100644 motrix_rl/tests/test_log_system_metrics.py create mode 100644 motrix_rl/tests/test_metric_panel.py create mode 100644 motrix_rl/tests/test_python_logging.py create mode 100644 motrix_rl/tests/test_tensor_window.py create mode 100644 motrix_rl/tests/test_timing.py create mode 100644 motrix_rl/tests/test_training_metrics.py create mode 100644 motrix_rl_appo/src/motrix_rl_appo/metrics.py create mode 100644 motrix_rl_appo/tests/test_appo_metrics_log.py delete mode 100644 motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/panels.py delete mode 100644 motrix_rl_builtin/src/motrix_rl_builtin/fastsac/window_metrics.py create mode 100644 motrix_rl_builtin/tests/test_fastsac_worker_logging.py create mode 100644 wiki/design/training-console.md diff --git a/bench/bench_live_metrics.py b/bench/bench_live_metrics.py index aa887a6ae..ff0de2e6d 100644 --- a/bench/bench_live_metrics.py +++ b/bench/bench_live_metrics.py @@ -10,7 +10,7 @@ failing) or the ingest service (slow, never answering, refusing connections), and one breaks both at once. -The report gives the wall time of each ``scalars`` call on the training +The report gives the wall time of each ``record/advance/flush`` dispatch on the training thread, the loop's throughput against ``off`` (``off, control`` repeats ``off`` and shows the noise floor), and what reached the disk and the service. Only the training loop is measured: closing is not timed, and a faulty scenario closes @@ -42,8 +42,8 @@ import numpy as np from motrix_bench import BenchmarkConfig, PreparedCase, run_case -from motrix_rl.metrics import JSONL_FILENAME, HttpSink, JsonlSink, MetricsLogger -from motrix_rl.training_logger import TrainingLogger +from motrix_rl.log.live import JSONL_FILENAME, HttpSink, JsonlSink, MotrixLiveLogger +from motrix_rl.log.training_logger import TrainingLogger _HEADERS = [ "scenario", @@ -243,7 +243,7 @@ def step(): return step -def _live(scenario: _Scenario, run_dir: Path, args, services: dict[str, _Service], down_url: str) -> MetricsLogger: +def _live(scenario: _Scenario, run_dir: Path, args, services: dict[str, _Service], down_url: str) -> MotrixLiveLogger: jsonl = None path = run_dir / JSONL_FILENAME if scenario.jsonl == _OK: @@ -258,17 +258,17 @@ def _live(scenario: _Scenario, run_dir: Path, args, services: dict[str, _Service http = None if scenario.http is not None: http = HttpSink(down_url if scenario.http == _DOWN else services[scenario.http].url) - return MetricsLogger("bench", jsonl=jsonl, http=http) if jsonl or http else MetricsLogger.disabled() + return MotrixLiveLogger("bench", jsonl=jsonl, http=http) if jsonl or http else MotrixLiveLogger.disabled() def _run(scenario: _Scenario, args, workload, services: dict[str, _Service], down_url: str) -> _Result: with tempfile.TemporaryDirectory() as tmp: run_dir = Path(tmp) live = _live(scenario, run_dir, args, services, down_url) - log = TrainingLogger(run_dir, live) + log = TrainingLogger(run_dir, live, live_only_prefixes=("sys/",)) values = {f"train/key_{index}": float(index) for index in range(args.keys)} sys_samples = {"sys/cpu_percent": 50.0, "sys/mem_used_gb": 8.0} - log.scalars({}, 0, env_steps=0) # opens TensorBoard (a one-off startup cost) before timing; sends nothing + log._open_tensorboard() # Exclude backend startup from timed dispatch; emit no warmup records. emit_ns = [] iteration = 0 @@ -279,7 +279,9 @@ def step() -> None: if iteration % args.log_every == 0: values["train/key_0"] = float(iteration) emit_started = time.perf_counter_ns() - log.scalars(values, iteration, env_steps=iteration * 4096, live_extra=lambda: sys_samples) + log.record(values | sys_samples) + log.advance(iterations=iteration - log.iteration, env_steps=iteration * 4096 - log.env_steps) + log.flush(force=True) emit_ns.append(time.perf_counter_ns() - emit_started) iteration += 1 @@ -318,7 +320,9 @@ def main() -> None: parser.add_argument("--step-ms", type=float, default=2.0, help="Target duration of one workload step.") parser.add_argument("--workload", choices=["numpy", "python"], default="numpy", help="What a step spends time on.") parser.add_argument("--matrix", type=int, default=256, help="Side of the square matmul in the numpy workload.") - parser.add_argument("--log-every", type=int, default=1, help="Iterations between scalars() calls (1 = worst case).") + parser.add_argument( + "--log-every", type=int, default=1, help="Iterations between record/flush dispatches (1 = worst case)." + ) parser.add_argument("--keys", type=int, default=40, help="Scalars per record.") parser.add_argument("--repeats", type=int, default=5, help="Runs per scenario; throughput is the median.") parser.add_argument("--disk-delay", type=float, default=0.5, help="Stall per batch for the slow-disk scenario.") diff --git a/motrix_rl/src/motrix_rl/console/__init__.py b/motrix_rl/src/motrix_rl/console/__init__.py index ec1ba3b65..dcbb4e44b 100644 --- a/motrix_rl/src/motrix_rl/console/__init__.py +++ b/motrix_rl/src/motrix_rl/console/__init__.py @@ -3,17 +3,17 @@ """Shared RL training console and panel data utilities.""" +from .boot import BootPanel, BootWorker from .data import ( EpisodeWindow, EpisodeWindowStats, PanelClock, - PanelSystemSampler, - PanelSystemStats, RateTracker, ScalarWindow, TimingWindow, ) from .panel import ( + TimingNode, TrainingPanelSession, TrainingPanelStats, emit_training_panel, @@ -23,14 +23,15 @@ ) __all__ = [ + "BootPanel", + "BootWorker", "EpisodeWindow", "EpisodeWindowStats", "PanelClock", - "PanelSystemSampler", - "PanelSystemStats", "RateTracker", "ScalarWindow", "TimingWindow", + "TimingNode", "TrainingPanelSession", "TrainingPanelStats", "emit_training_panel", diff --git a/motrix_rl/src/motrix_rl/console/boot.py b/motrix_rl/src/motrix_rl/console/boot.py new file mode 100644 index 000000000..4de8b2ec7 --- /dev/null +++ b/motrix_rl/src/motrix_rl/console/boot.py @@ -0,0 +1,156 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Shared worker-startup rendering, independent of terminal session ownership.""" + +from __future__ import annotations + +import math +import os +from collections.abc import Collection, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from rich.console import Console + from rich.panel import Panel + from rich.text import Text + +_LOG_TAIL_PLACEHOLDER = "(waiting for worker logs…)" + + +@dataclass(frozen=True, slots=True) +class BootWorker: + """One worker's display identity: a table row and its log tail source. + + Spawn fixes both facts for the whole startup phase, so callers build the + worker list once. Readiness is a per-refresh fact passed to ``render``. + """ + + name: str + log_path: Path | None = None + + +def boot_worker_status(worker: BootWorker, ready: Collection[str], started: bool) -> str: + """Derive one worker's row status from the caller's startup facts.""" + if started: + return "starting" + return "ready" if worker.name in ready else "booting" + + +def worker_log_tail( + log_dir: Path, + log_names: Sequence[str], + max_lines: int = 4, + line_width: int = 120, + per_file: int = 2, + wrap: bool = False, +) -> Text: + """Read bounded log tails in the supplied order, capped in display lines. + + Missing logs are expected while workers start. Wrapped continuation lines + count towards the same cap, keeping terminal frame geometry stable. + """ + from rich.text import Text + + display: list[str] = [] + for name in log_names: + path = Path(log_dir) / name + try: + with path.open("rb") as stream: + stream.seek(0, os.SEEK_END) + size = stream.tell() + stream.seek(max(0, size - 8192)) + chunk = stream.read().decode(errors="replace") + except OSError: + continue + tail = [line for line in chunk.splitlines() if line.strip()][-per_file:] + for line in tail: + if wrap: + display.extend(line[start : start + line_width] for start in range(0, len(line), line_width)) + else: + display.append(line[:line_width]) + return Text("\n".join(display[-max_lines:]) or _LOG_TAIL_PLACEHOLDER, style="dim") + + +class BootPanel: + """Render fixed-height boot/handoff frames using a borrowed console. + + The caller owns worker readiness and the Console/Live lifecycle. A reserved + message row keeps boot and handoff frames identical in height; workers + without logs still appear in the status table but need no log cell. + """ + + def __init__(self, title: str, console: Console) -> None: + self._title = title + self.console = console + + def _worker_panel(self, name: str, path: Path, lines: int, width: int) -> Panel: + from rich.panel import Panel + from rich.text import Text + + text = worker_log_tail(path.parent, [path.name], lines, width, per_file=lines, wrap=True) + body = text.plain.splitlines() + body += [""] * (lines - len(body)) + return Panel( + Text("\n".join(body), style="dim"), + title=Text(name), + border_style="dim", + expand=True, + height=lines + 2, + ) + + def render( + self, workers: Sequence[BootWorker], *, ready: Collection[str] = (), started: bool = False, message: str = "" + ) -> Panel: + """Render one terminal-height frame without creating or updating a Live. + + Row status derives from the caller's facts: ``started`` flips everyone + past the barrier, otherwise membership in ``ready`` marks readiness. + """ + from rich.console import Group + from rich.layout import Layout + from rich.panel import Panel + from rich.table import Table + from rich.text import Text + + inner_width = max(1, self.console.width - 4) + table_lines = len(workers) + 5 + table = Table(expand=True, width=inner_width) + table.add_column("worker") + table.add_column("status") + for worker in workers: + status = boot_worker_status(worker, ready, started) + label, style = { + "booting": ("booting…", "dim"), + "ready": ("ready", "green"), + "starting": ("starting", "yellow"), + }[status] + table.add_row(Text(worker.name), Text(label, style=style)) + + log_workers = [(worker.name, worker.log_path) for worker in workers if worker.log_path is not None] + logs = Layout(Text(""), name="logs") + if log_workers: + columns = math.ceil(math.sqrt(len(log_workers))) + rows_count = math.ceil(len(log_workers) / columns) + region_lines = max(rows_count * 3, self.console.height - 2 - table_lines) + lines = max(1, region_lines // rows_count - 2) + width = max(1, inner_width // columns - 4) + rows = [] + for start in range(0, len(log_workers), columns): + row = Layout() + row.split_row( + *( + Layout(self._worker_panel(name, path, lines, width)) + for name, path in log_workers[start : start + columns] + ) + ) + rows.append(row) + logs.split_column(*rows) + layout = Layout() + layout.split_column( + logs, + Layout(Group(table, Text(message, style="dim", no_wrap=True, overflow="ellipsis")), size=table_lines), + ) + return Panel(layout, title=self._title, border_style="cyan", padding=(0, 1), height=self.console.height) diff --git a/motrix_rl/src/motrix_rl/console/data.py b/motrix_rl/src/motrix_rl/console/data.py index 3419560e5..fd96eadad 100644 --- a/motrix_rl/src/motrix_rl/console/data.py +++ b/motrix_rl/src/motrix_rl/console/data.py @@ -12,21 +12,10 @@ import time from collections import deque -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Iterable, Mapping from dataclasses import dataclass from typing import Any -from motrix_rl.system_metrics import ( - CpuLoad, - CpuLoadSampler, - GpuDeviceUsage, - GpuMemoryUsageSampler, - GpuUtilizationSampler, - MemoryUsage, - MemoryUsageSampler, - sample_gpu_devices, -) - @dataclass(frozen=True) class EpisodeWindowStats: @@ -153,31 +142,3 @@ def drain(self, *, include_range: bool = True) -> dict[str, float]: self._minimums.clear() self._maximums.clear() return result - - -@dataclass(frozen=True) -class PanelSystemStats: - cpu_load: CpuLoad | None - gpu_utilization_percent: float | None - memory_usage: MemoryUsage | None - gpu_memory_usage: MemoryUsage | None - gpu_devices: Sequence[GpuDeviceUsage] | None - - -class PanelSystemSampler: - """Sample host resources once for a panel frame.""" - - def __init__(self) -> None: - self._cpu = CpuLoadSampler() - self._gpu = GpuUtilizationSampler() - self._memory = MemoryUsageSampler() - self._gpu_memory = GpuMemoryUsageSampler() - - def sample(self) -> PanelSystemStats: - return PanelSystemStats( - cpu_load=self._cpu.sample(), - gpu_utilization_percent=self._gpu.sample(), - memory_usage=self._memory.sample(), - gpu_memory_usage=self._gpu_memory.sample(), - gpu_devices=sample_gpu_devices(self._gpu, self._gpu_memory), - ) diff --git a/motrix_rl/src/motrix_rl/console/metric_panel.py b/motrix_rl/src/motrix_rl/console/metric_panel.py new file mode 100644 index 000000000..420426d0f --- /dev/null +++ b/motrix_rl/src/motrix_rl/console/metric_panel.py @@ -0,0 +1,242 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Metric aggregation and sampling owned by one console consumer.""" + +from __future__ import annotations + +import math +import re +import time +from collections.abc import Iterable, Mapping +from dataclasses import replace +from typing import TYPE_CHECKING, Any, Literal + +from motrix_rl.console.data import PanelClock +from motrix_rl.console.panel import EpisodeSummary, ThroughputSummary, TimingNode, TimingView, TrainingPanelStats +from motrix_rl.log.accumulator import MetricAccumulator +from motrix_rl.system_metrics import SystemSampler + +if TYPE_CHECKING: + from motrix_rl.console.panel import TrainingPanelSession + + +def _timing_tree(values: Mapping[str, float]) -> tuple[TimingNode, ...]: + durations: dict[tuple[str, ...], float] = {} + paths: dict[tuple[str, ...], None] = {} + for key, value in values.items(): + parts = key.split("/")[1:] + if not parts or not parts[-1].endswith("_s"): + continue + if parts[-1] == "total_s": + parts.pop() + else: + parts[-1] = parts[-1][:-2] + path = tuple(parts) + if not path: + continue + durations[path] = value * 1000.0 + for length in range(1, len(path) + 1): + paths[path[:length]] = None + + def node(path: tuple[str, ...]) -> TimingNode: + children = tuple(node(child) for child in paths if len(child) == len(path) + 1 and child[:-1] == path) + return TimingNode(path[-1], durations.get(path), children) + + return tuple(node(path) for path in paths if len(path) == 1) + + +def _project_summary( + values: Mapping[str, float], keys: tuple[str, str] | None, hidden: set[str] +) -> tuple[float | None, float | None]: + """Project observations and hide only exact keys present in the mapping.""" + if keys is None: + return None, None + hidden.update(key for key in keys if key in values) + return values.get(keys[0]), values.get(keys[1]) + + +class MetricsPanel: + """Independent panel window, progress counters and host sampler. + + Missing metrics remain visible unless a complete timing report replaces + their root. Shared timing keys retain all samples in the current window. + """ + + def __init__( + self, + session: TrainingPanelSession, + *, + total_iterations: int, + initial_iteration: int = 0, + initial_env_steps: int = 0, + reductions: Mapping[str, Literal["mean", "last"]] | None = None, + default_reduction: Literal["mean", "last"] = "last", + throughput_summary: ThroughputSummary | None = ThroughputSummary(), + episode_summary: EpisodeSummary | None = EpisodeSummary(), + timing_view: TimingView = TimingView(), + ) -> None: + self._timing_view = timing_view + self._session = session + self._throughput_summary = throughput_summary + self._episode_summary = episode_summary + self._latest: TrainingPanelStats | None = None + self._last_refresh = 0.0 + self._last_checkpoint: str | None = None + self._window = MetricAccumulator(reductions=reductions, default_reduction=default_reduction) + self._values: dict[str, float] = {} + self._timing_keys: dict[str, set[str]] = {} + self._total_iterations = total_iterations + self._initial_iteration = initial_iteration + self._iteration = initial_iteration + self._env_steps = initial_env_steps + now = time.monotonic() + self._clock = PanelClock(start=now) + self._system = SystemSampler() + + def start(self, *, now: float) -> None: + """Anchor elapsed time to the current invocation.""" + if not self._session._is_active(self): + return + self._clock.restart(now=now) + + def record(self, values: Mapping[str, float | Iterable[float]]) -> None: + if not self._session._is_active(self): + return + reported: dict[str, set[str]] = {} + for key in values: + if key.startswith(self._timing_view.prefix): + relative = key[len(self._timing_view.prefix) :].split("/") + if len(relative) >= 2: + reported.setdefault(relative[0], set()).add(key) + for root, keys in reported.items(): + previous = self._timing_keys.setdefault(root, set()) + if f"{self._timing_view.prefix}{root}/total_s" in keys: + # The newest complete report defines this root's key set, but + # shared keys keep their pending samples for mean reductions. + removed = previous - keys + for key in removed: + self._values.pop(key, None) + self._window.discard(removed) + previous.clear() + previous.update(keys) + self._window.record(values) + + def advance(self, *, iterations: int = 1, env_steps: int) -> None: + """Advance invocation-owned counters by increments, including on resume.""" + if not self._session._is_active(self): + return + self._iteration += iterations + self._env_steps += env_steps + + @property + def iteration(self) -> int: + return self._iteration + + @property + def env_steps(self) -> int: + return self._env_steps + + def due(self) -> bool: + """Whether aggregation and hardware sampling can produce a frame now.""" + return self._session._is_active(self) and ( + self._last_refresh == 0.0 or time.monotonic() - self._last_refresh >= self._session.interval_seconds + ) + + def flush(self, *, force: bool = False) -> None: + """Aggregate pending observations and render only at display cadence.""" + if not self._session._is_active(self) or (not force and not self.due()): + return + stats = self.snapshot() + if stats is not None: + self._emit(stats, force=True) + + def _emit(self, stats: TrainingPanelStats, *, force: bool = False) -> None: + if not self._session._is_active(self): + return + if self._last_checkpoint is not None and stats.checkpoint_path != self._last_checkpoint: + stats = replace(stats, checkpoint_path=self._last_checkpoint) + self._latest = stats + if force or self.due(): + self._session._draw(stats) + self._last_refresh = time.monotonic() + + def event(self, name: str, *, iteration: int, data: Mapping[str, Any]) -> None: + """Display checkpoint events; other event types do not alter this phase.""" + if not self._session._is_active(self) or name != "checkpoint_saved": + return + path = str(data["path"]) + self._last_checkpoint = path + if self._latest is not None: + self._emit(replace(self._latest, checkpoint_path=path), force=True) + else: + print(f"saved checkpoint {path}") + + def snapshot(self) -> TrainingPanelStats | None: + """Build a snapshot, consuming this phase's pending aggregation window.""" + if not self._session._is_active(self): + return self._latest + self._values.update(self._window.snapshot()) + self._window.clear() + routed_timing = {key: value for key, value in self._values.items() if key.startswith(self._timing_view.prefix)} + timing = {"timing/" + key[len(self._timing_view.prefix) :]: value for key, value in routed_timing.items()} + extras = { + key: value + for key, value in routed_timing.items() + if not key.endswith("_s") + or "/" not in key[len(self._timing_view.prefix) :] + or key == self._timing_view.prefix + "total_s" + } + system = self._system.sample() + now = time.monotonic() + collect_ms = timing.get("timing/collector/total_s", 0.0) * 1000.0 + if "timing/learner/total_s" in timing: + learn_ms = timing["timing/learner/total_s"] * 1000.0 + else: + learner_seconds = [ + value + for key, value in timing.items() + if re.fullmatch(r"timing/learner\[\d+\]/total_s", key) and math.isfinite(value) and value >= 0.0 + ] + learn_ms = 1000.0 * sum(learner_seconds) / len(learner_seconds) if learner_seconds else 0.0 + summary = self._throughput_summary + episode = self._episode_summary + hidden: set[str] = set() if self._timing_view.overview else set(routed_timing) + steps_per_second, iterations_per_second = _project_summary( + self._values, + (summary.env_steps_key, summary.iterations_key) if summary is not None else None, + hidden, + ) + mean_return, mean_episode_length = _project_summary( + self._values, + (episode.return_key, episode.length_key) if episode is not None else None, + hidden, + ) + return TrainingPanelStats( + checkpoint_path=self._last_checkpoint, + iteration=self._iteration, + total_iterations=self._total_iterations, + initial_iteration=self._initial_iteration, + steps_per_second=steps_per_second, + iterations_per_second=iterations_per_second, + overview_hidden_metrics=frozenset(hidden), + show_throughput=summary is not None, + show_episode_summary=episode is not None, + elapsed_seconds=self._clock.elapsed(now=now), + mean_return=mean_return, + mean_episode_length=mean_episode_length, + collect_ms=collect_ms, + learn_ms=learn_ms, + learn_percent=self._values.get("learner/learn_percent", 0.0), + warming=bool(self._values.get("learner/replay_warming", 0.0)), + buffer_size=self._values.get("learner/buffer_size"), + buffer_capacity=self._values.get("learner/buffer_capacity"), + metrics=dict(self._values), + timings=_timing_tree(timing), + timing_extras=extras, + cpu_load=system.cpu_load, + gpu_utilization_percent=system.gpu_utilization_percent, + memory_usage=system.memory_usage, + gpu_memory_usage=system.gpu_memory_usage, + gpu_devices=system.gpu_devices, + ) diff --git a/motrix_rl/src/motrix_rl/console/panel.py b/motrix_rl/src/motrix_rl/console/panel.py index 61a9bf013..1823bcabd 100644 --- a/motrix_rl/src/motrix_rl/console/panel.py +++ b/motrix_rl/src/motrix_rl/console/panel.py @@ -12,9 +12,13 @@ import sys import time from collections.abc import Mapping, Sequence -from dataclasses import dataclass, field, replace -from typing import Any +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Literal +if TYPE_CHECKING: + from motrix_rl.console.metric_panel import MetricsPanel + +from motrix_rl.console.boot import BootPanel, BootWorker from motrix_rl.system_metrics import CpuLoad, GpuDeviceUsage, MemoryUsage try: # cbreak keyboard input needs a POSIX terminal; other platforms keep a plain Live @@ -37,38 +41,83 @@ _RICH = False +@dataclass(frozen=True, slots=True) +class TimingNode: + """One timing scope; children divide by this scope's explicit duration. + + Durations are milliseconds from the same sampling window. None denotes an + organizational node, not an aggregate inferred from its children. + """ + + name: str + duration_ms: float | None + children: tuple[TimingNode, ...] = () + + +@dataclass(frozen=True) +class ThroughputSummary: + """Canonical metric keys projected into the optional throughput summary.""" + + env_steps_key: str = "throughput/env_steps_per_s" + iterations_key: str = "throughput/iterations_per_s" + + +@dataclass(frozen=True) +class EpisodeSummary: + """Canonical metric keys projected into the optional episode summary.""" + + return_key: str = "episode/recent_return_mean" + length_key: str = "episode/recent_length_mean" + + +@dataclass(frozen=True) +class TimingView: + """Route one metric namespace to the timing tab without changing stored keys.""" + + prefix: str = "timing/" + overview: bool = False + + def __post_init__(self) -> None: + if not self.prefix or not self.prefix.endswith("/"): + raise ValueError("TimingView.prefix must be nonempty and end with '/' ") + + @dataclass(frozen=True) class TrainingPanelStats: """Structured stats consumed by the shared RL training panel. Fields required by the panel layout are explicit dataclass attributes. - Backend-specific values belong in the extension dictionaries. + Canonical metric keys retain their identity until the rendering boundary. """ iteration: int total_iterations: int steps_per_second: float | None elapsed_seconds: float - mean_return: float - mean_episode_length: float - episodes: int - buffer_size: float - buffer_capacity: float + mean_return: float | None + mean_episode_length: float | None collect_ms: float learn_ms: float learn_percent: float warming: bool = False + # Replay/rollout storage occupancy in transitions; None hides the + # plain-text buffer row for backends without meaningful storage counts. + buffer_size: float | None = None + buffer_capacity: float | None = None # Rolling-window iteration rate; None = same unavailable-rate semantics as # steps_per_second. Falls back to the cumulative average when absent. iterations_per_second: float | None = None - training_metrics: Mapping[str, Any] | None = None - reward_terms: Mapping[str, Any] = field(default_factory=dict) - env_metrics: Mapping[str, Any] = field(default_factory=dict) - timing_metrics: Mapping[str, Any] = field(default_factory=dict) - diagnostics: Mapping[str, Any] = field(default_factory=dict) - # Group name -> items. Item values are scalars, or a nested mapping rendered - # as an indented sub-tree (e.g. per-process timing with stage breakdowns). - timing_groups: Mapping[str, Mapping[str, Any]] = field(default_factory=dict) + # Iteration already reached before this invocation (resume baseline); rate + # and ETA averages must count only progress made during this invocation. + initial_iteration: int = 0 + metrics: Mapping[str, float] = field(default_factory=dict) + # Summary projection changes overview presentation, never canonical metrics. + overview_hidden_metrics: frozenset[str] = frozenset() + show_throughput: bool = True + show_episode_summary: bool = True + # Independent roots represent concurrent timing scopes, never a serial sum. + timings: tuple[TimingNode, ...] = () + timing_extras: Mapping[str, float] = field(default_factory=dict) cpu_load: CpuLoad | None = None gpu_utilization_percent: float | None = None memory_usage: MemoryUsage | None = None @@ -127,37 +176,103 @@ def _restore_stdin(self): self._owns_input_fd = False -def open_training_live(): +def open_training_live(*, screen: bool = False): """Start a rich live panel on TTYs, otherwise return ``(None, None)``.""" if not _RICH or not sys.stdout.isatty(): return None, None console = Console() - live = (_InputLive if _POSIX_TTY else Live)(console=console, auto_refresh=False, vertical_overflow="visible") + live = (_InputLive if _POSIX_TTY else Live)( + console=console, auto_refresh=False, vertical_overflow="visible", screen=screen + ) live.start() return console, live -class TrainingPanelSession: - """Own one training panel's terminal lifecycle and latest snapshot. +class BootPanelView: + """Phase handle that records startup facts and draws through the session. - Providers only submit already-aggregated :class:`TrainingPanelStats` values; - this object owns Rich/TTY resources, refresh cadence, view input and cleanup. + Inputs split by kind: ``boot_panel(workers)`` binds the spawn-fixed + structure (identities, log paths) once; ``mark_ready`` and ``start`` + advance monotonic state; ``message`` overwrites the single phase line; + ``refresh`` redraws at the session cadence so log tails keep scrolling. + Creating another phase retires this handle; closing the session also makes + further events no-ops. """ + def __init__(self, session: TrainingPanelSession, workers: Sequence[BootWorker]) -> None: + self._session = session + self._workers = tuple(workers) + self._ready: set[str] = set() + self._started = False + self._message = "" + self._last_refresh = 0.0 + + def mark_ready(self, *names: str) -> None: + """State: these workers finished booting; the event redraws once.""" + session = self._session + if not session._is_active(self) or not names: + return + self._ready.update(names) + if session.live is not None: + self._redraw() + else: + print(" | ".join(f"{name}: ready" for name in names)) + + def start(self) -> None: + """State: the barrier released; every worker row shows ``starting``.""" + session = self._session + if not session._is_active(self): + return + self._started = True + if session.live is not None: + self._redraw() + + def message(self, text: str) -> None: + """Message: overwrite the phase line; changes redraw immediately.""" + session = self._session + if not session._is_active(self) or text == self._message: + return + self._message = text + if session.live is not None: + self._redraw() + else: + print(text) + + def refresh(self) -> None: + """Cadence: redraw at the session interval so log tails advance.""" + session = self._session + if not session._is_active(self): + return + now = time.monotonic() + if now - self._last_refresh < session.interval_seconds: + return + if session.live is not None: + self._redraw() + + def _redraw(self) -> None: + session = self._session + self._last_refresh = time.monotonic() + frame = BootPanel(session.title, session.console).render( + self._workers, ready=self._ready, started=self._started, message=self._message + ) + session.live.update(frame, refresh=True) + + +class TrainingPanelSession: + """Own terminal resources and the identity of the current display phase.""" + def __init__(self, *, title: str = "rl", interval_seconds: float = 1.0) -> None: self.title = title self.interval_seconds = interval_seconds self.console = None self.live = None - self._latest: TrainingPanelStats | None = None - self._last_refresh = 0.0 - self._last_checkpoint: str | None = None self._closed = False + self._active: BootPanelView | MetricsPanel | None = None @classmethod - def open(cls, *, title: str = "rl", interval_seconds: float = 1.0) -> TrainingPanelSession: + def open(cls, *, title: str = "rl", interval_seconds: float = 1.0, screen: bool = False) -> TrainingPanelSession: session = cls(title=title, interval_seconds=interval_seconds) - session.console, session.live = open_training_live() + session.console, session.live = open_training_live(screen=True) if screen else open_training_live() return session def __enter__(self) -> TrainingPanelSession: @@ -166,40 +281,58 @@ def __enter__(self) -> TrainingPanelSession: def __exit__(self, exc_type, exc, tb) -> None: self.close() - def submit(self, stats: TrainingPanelStats, *, force: bool = False) -> None: - """Store the latest stats and refresh when the session cadence allows.""" - if self._closed: - return - if self._last_checkpoint is not None and stats.checkpoint_path != self._last_checkpoint: - stats = replace(stats, checkpoint_path=self._last_checkpoint) - self._latest = stats - now = time.monotonic() - if force or self._last_refresh == 0.0 or now - self._last_refresh >= self.interval_seconds: - self.refresh(force=True) - - def checkpoint(self, path: str) -> None: - """Show a successfully saved checkpoint on the next panel frame.""" - self._last_checkpoint = path - if self._latest is not None: - self._latest = replace(self._latest, checkpoint_path=path) - self.refresh(force=True) - elif self.console is None: - print(f"saved checkpoint {path}") - - def refresh(self, *, force: bool = False) -> None: - if self._closed or self._latest is None: - return - now = time.monotonic() - if not force and self._last_refresh and now - self._last_refresh < self.interval_seconds: - return - emit_training_panel(self.live, self._latest, title=self.title) - self._last_refresh = now + def _is_active(self, phase: BootPanelView | MetricsPanel) -> bool: + return not self._closed and self._active is phase + + def _activate(self, phase: BootPanelView | MetricsPanel) -> None: + self._active = phase + + def boot_panel(self, workers: Sequence[BootWorker]) -> BootPanelView: + """Replace the current phase with a startup display handle.""" + phase = BootPanelView(self, workers) + self._activate(phase) + return phase + + def metrics_panel( + self, + *, + total_iterations: int, + initial_iteration: int = 0, + initial_env_steps: int = 0, + reductions: Mapping[str, Literal["mean", "last"]] | None = None, + default_reduction: Literal["mean", "last"] = "last", + throughput_summary: ThroughputSummary | None = ThroughputSummary(), + episode_summary: EpisodeSummary | None = EpisodeSummary(), + timing_view: TimingView = TimingView(), + ) -> MetricsPanel: + """Replace the current phase with an independent metrics consumer.""" + from motrix_rl.console.metric_panel import MetricsPanel + + phase = MetricsPanel( + self, + total_iterations=total_iterations, + initial_iteration=initial_iteration, + initial_env_steps=initial_env_steps, + reductions=reductions, + default_reduction=default_reduction, + throughput_summary=throughput_summary, + episode_summary=episode_summary, + timing_view=timing_view, + ) + self._activate(phase) + return phase + + def _draw(self, stats: TrainingPanelStats) -> None: + emit_training_panel(self.live, stats, title=self.title) def close(self) -> None: if self._closed: return + from motrix_rl.console.metric_panel import MetricsPanel + try: - self.refresh(force=True) + if isinstance(self._active, MetricsPanel): + self._active.flush(force=True) finally: self._closed = True if self.live is not None: @@ -228,6 +361,11 @@ def emit_training_panel(live, stats: TrainingPanelStats, *, title: str = "rl") - print(format_training_panel(stats, title=title)) +def _available(value: float | None) -> bool: + """A metric is renderable only when it is a finite observation.""" + return value is not None and math.isfinite(value) + + def _format_value(value: Any, precision: int = 3, signed: bool = False) -> str: if isinstance(value, float): sign = "+" if signed else "" @@ -240,8 +378,23 @@ def _format_value(value: Any, precision: int = 3, signed: bool = False) -> str: return str(value) -def _format_metric_items(items: Mapping[str, Any], *, precision: int = 3, signed: bool = False) -> list[str]: - return [f"{k} {_format_value(v, precision=precision, signed=signed)}" for k, v in items.items()] +def _group_metrics( + metrics: Mapping[str, float], *, hidden: frozenset[str] = frozenset() +) -> dict[str, list[tuple[str, float]]]: + """Derive display groups without changing the canonical metric mapping.""" + groups: dict[str, list[tuple[str, float]]] = {} + for key, value in metrics.items(): + if key in hidden: + continue + group, separator, label = key.partition("/") + if not separator: + group, label = "ungrouped", key + groups.setdefault(group, []).append((label, value)) + return groups + + +def _format_metric_items(items: Sequence[tuple[str, float]]) -> list[str]: + return [f"{key} {_format_value(value)}" for key, value in items] def _format_duration(seconds: float) -> str: @@ -252,10 +405,23 @@ def _format_duration(seconds: float) -> str: def _eta_seconds(stats: TrainingPanelStats) -> float | None: - """Remaining-time estimate from the cumulative iteration rate.""" - if stats.iteration <= 0 or stats.elapsed_seconds <= 0.0: - return None - rate = stats.iteration / stats.elapsed_seconds + """Remaining-time estimate from this invocation's iteration rate. + + The rolling ``iterations_per_second`` is preferred because backends that + provide it already exclude pre-resume progress. Otherwise the cumulative + average anchors to ``initial_iteration`` so a resumed run does not divide + previously accumulated iterations by this invocation's elapsed time; a + completed run has no remaining time. + """ + if stats.iteration >= stats.total_iterations: + return 0.0 + if stats.iterations_per_second is not None: + rate = stats.iterations_per_second + else: + done = stats.iteration - stats.initial_iteration + if done <= 0 or stats.elapsed_seconds <= 0.0: + return None + rate = done / stats.elapsed_seconds if rate <= 0.0: return None return (stats.total_iterations - stats.iteration) / rate @@ -264,9 +430,10 @@ def _eta_seconds(stats: TrainingPanelStats) -> float | None: def _iter_rate_text(stats: TrainingPanelStats) -> str: if stats.iterations_per_second is not None: return f"{stats.iterations_per_second:,.0f} iter/s" - if stats.steps_per_second is None: + done = stats.iteration - stats.initial_iteration + if stats.steps_per_second is None or done <= 0: return "warming up" if stats.warming else "measuring…" - return f"{stats.iteration / max(stats.elapsed_seconds, 1e-9):,.0f} iter/s" + return f"{done / max(stats.elapsed_seconds, 1e-9):,.0f} iter/s" def format_training_panel(stats: TrainingPanelStats, *, title: str = "rl") -> str: @@ -290,17 +457,20 @@ def si(n: float) -> str: if stats.steps_per_second is not None else ("warming up" if stats.warming else "measuring…") ) + throughput_text = f"{sps_text} - " if stats.show_throughput else "" header = ( f" {title} - iter {stats.iteration}/{stats.total_iterations} ({pct:.1f}%) - " - f"{sps_text} - {hms(stats.elapsed_seconds)}{eta_text}" + f"{throughput_text}{hms(stats.elapsed_seconds)}{eta_text}" ) + return_text = f"{stats.mean_return:>9.3f}" if _available(stats.mean_return) else " n/a" + length_text = f"{stats.mean_episode_length:>7.1f}" if _available(stats.mean_episode_length) else " n/a" lines = [ "-" * width, header, "-" * width, - f" rollout return {stats.mean_return:>9.3f} " - f"ep_len {stats.mean_episode_length:>7.1f} episodes {stats.episodes:>6d}", ] + if stats.show_episode_summary: + lines.append(f" rollout return {return_text} ep_len {length_text}") if stats.cpu_load is not None: load = stats.cpu_load cores = f", {load.physical_core_count}C" if load.physical_core_count is not None else "" @@ -319,47 +489,26 @@ def si(n: float) -> str: if gpu_util is not None or gpu_mem is not None: parts = [f"{gpu_util:.0f}%" if gpu_util is not None else "n/a", _format_memory(gpu_mem)] lines.append(" system gpu " + " ".join(parts)) - metrics = stats.training_metrics - buf = f"{si(stats.buffer_size)}/{si(stats.buffer_capacity)}" - if metrics is None: - message = "warmup - filling replay buffer" if stats.warming else "training metrics unavailable" - lines.append(f" train {message} ({buf})") - else: - toks = _format_metric_items(metrics) - colw = max(len(t) for t in toks) + 2 if toks else 1 - per_line = max(1, (width - 13) // colw) + for name, values in _group_metrics(stats.metrics, hidden=stats.overview_hidden_metrics).items(): + toks = _format_metric_items(values) + prefix = f" {name} " + colw = max(len(token) for token in toks) + 2 + per_line = max(1, (width - len(prefix)) // colw) for i in range(0, len(toks), per_line): - prefix = " train " if i == 0 else " " * 13 - row = "".join(t.ljust(colw) for t in toks[i : i + per_line]) - lines.append((prefix + row).rstrip()) + row = "".join(token.ljust(colw) for token in toks[i : i + per_line]) + lines.append(((prefix if i == 0 else " " * len(prefix)) + row).rstrip()) + if stats.buffer_capacity: + buf = f"{si(stats.buffer_size)}/{si(stats.buffer_capacity)}" lines.append(f" buffer {buf}") - terms = stats.reward_terms - if terms: - sorted_terms = dict(sorted(terms.items(), key=lambda kv: -abs(float(kv[1])))) - toks = _format_metric_items(sorted_terms, precision=4, signed=True) - colw = max(len(t) for t in toks) + 2 - per_line = max(1, (width - 13) // colw) - for i in range(0, len(toks), per_line): - prefix = " reward(dt) " if i == 0 else " " * 13 - row = "".join(t.ljust(colw) for t in toks[i : i + per_line]) - lines.append((prefix + row).rstrip()) - - env_metrics = stats.env_metrics - if env_metrics: - toks = _format_metric_items(dict(sorted(env_metrics.items())), signed=True) - lines.append(" metrics " + " ".join(toks)) - # The standalone collect/learn row is for panels without timing groups; # tree panels fold those values into their group titles instead. - if not stats.timing_groups: + if not stats.timings: lines.append(f" timing collect {stats.collect_ms:.1f}ms learn {stats.learn_ms:.1f}ms") - if stats.timing_metrics: - lines.append(" timing(detail) " + " ".join(_format_metric_items(stats.timing_metrics))) - for group, items in stats.timing_groups.items(): - _append_timing_group_lines(lines, group, items, width) - if stats.diagnostics: - lines.append(" diagnostics " + " ".join(_format_metric_items(stats.diagnostics))) + for root in stats.timings: + _append_timing_node_lines(lines, root) + for name, values in _group_metrics(stats.timing_extras).items(): + lines.append(f" {name}(detail) " + " ".join(_format_metric_items(values))) lines.append("-" * width) return "\n".join(lines) @@ -369,66 +518,29 @@ def _strip_markup(text: str) -> str: return re.sub(r"\[[^\]]*\]", "", text) -def _append_timing_group_lines(lines: list[str], group: str, items: Mapping[str, Any], width: int) -> None: - """Append one timing group as a tree of aligned ``key value`` token rows. +def _timing_share(node: TimingNode, parent: TimingNode) -> str | None: + if node.duration_ms is None or parent.duration_ms is None or parent.duration_ms <= 0.0: + return None + return f"{100.0 * node.duration_ms / parent.duration_ms:.0f}%" - Scalar items flow as wrapped tokens on the group's label column. A nested - mapping renders as a tree branch (``├─``/``└─`` by sibling position) whose - children form an indented token block, each wrapped row joined with branch - glyphs so the hierarchy stays visible. A ``total`` key inside a nested - mapping is the node's own aggregate and renders inline after its name. - Group titles may carry rich markup; it is stripped for plain text. - """ - group_name = _strip_markup(group) - group_width = max(18, len(group_name) + 1) - row_prefix = " " * (group_width + 1) - def token(key: str, value: Any) -> str: - return f"{key} {_format_value(value)}" +def _append_timing_node_lines(lines: list[str], root: TimingNode) -> None: + """Render the same timing forest as Rich, with direct-parent shares.""" - def render_block( - toks: list[str], first_prefix: str, cont_prefix: str, last_prefix: str, single_prefix: str | None = None - ) -> None: - if not toks: - return - colw = max(len(t) for t in toks) + 2 - per_line = max(1, (width - len(cont_prefix)) // colw) - chunks = [toks[i : i + per_line] for i in range(0, len(toks), per_line)] - for j, chunk in enumerate(chunks): - if len(chunks) == 1: - prefix = single_prefix if single_prefix is not None else first_prefix - elif j == 0: - prefix = first_prefix - elif j == len(chunks) - 1: - prefix = last_prefix - else: - prefix = cont_prefix - lines.append((prefix + "".join(t.ljust(colw) for t in chunk)).rstrip()) - - pending: list[str] = [] - lead = f" {group_name:<{group_width}}" - entries = list(items.items()) - for idx, (key, value) in enumerate(entries): - if isinstance(value, Mapping): - render_block(pending, lead, row_prefix, row_prefix) - pending = [] - lead = row_prefix - branch, hang = ("└─", " ") if idx == len(entries) - 1 else ("├─", "│ ") - below = row_prefix + hang - children = dict(value) - node_total = children.pop("total", None) - label = f"{key} {_format_value(node_total)}" if node_total is not None else f"{key}:" - lines.append(f"{row_prefix}{branch} {label}") - render_block( - [token(k, v) for k, v in children.items()], - below + "├─ ", - below + "├─ ", - below + "└─ ", - single_prefix=below + "└─ ", - ) - else: - pending.append(token(key, value)) - render_block(pending, lead, row_prefix, row_prefix) + def label(node: TimingNode) -> str: + name = _strip_markup(node.name) + return f"{name} {_format_value(node.duration_ms)} ms" if node.duration_ms is not None else name + + lines.append(" " + label(root)) + + def append(parent: TimingNode, prefix: str) -> None: + for index, child in enumerate(parent.children): + last = index == len(parent.children) - 1 + share = _timing_share(child, parent) + lines.append(prefix + ("└─ " if last else "├─ ") + label(child) + (f" {share}" if share else "")) + append(child, prefix + (" " if last else "│ ")) + + append(root, " ") def _timing_totals(stats: TrainingPanelStats) -> tuple[float, float]: @@ -436,15 +548,6 @@ def _timing_totals(stats: TrainingPanelStats) -> tuple[float, float]: return stats.collect_ms, stats.learn_ms -def _timing_group_total(group: str, stats: TrainingPanelStats, index: int) -> float: - name = _strip_markup(group).lower() - if name.startswith("collector"): - return stats.collect_ms - if name.startswith("learner") and "idle" not in name: - return stats.learn_ms - return stats.collect_ms if index == 0 else stats.learn_ms - - # --------------------------------------------------------------------------- # Prototype layout renderer # @@ -462,11 +565,7 @@ def _prototype_metric_cell( ): from rich.text import Text - name = _strip_markup(str(key)) - # Reward terms commonly have descriptive names, so keep a wider label - # while still bounding unusual keys to preserve the grid layout. - if len(name) > label_width: - name = name[: label_width - 3] + "..." + name = key text = Text(f"{name:<{label_width}} ", style="white") color = "white" if signed and isinstance(value, (float, int)): @@ -488,7 +587,7 @@ def _compact_metric_value(value: Any, *, precision: int = 3, signed: bool = Fals return f"{value:+.2e}" if signed else f"{value:.2e}" -def _rich_compact_metric_grid(items: Mapping[str, Any], *, limit: int | None, precision: int = 3, signed: bool = False): +def _rich_compact_metric_grid(items: Sequence[tuple[str, float]], *, limit: int | None): grid = Table.grid(expand=True, padding=(0, 1)) # A metric cell is roughly 25–30 terminal columns wide. Adapt the number # of columns to the real TTY instead of forcing every group into two. @@ -498,17 +597,15 @@ def _rich_compact_metric_grid(items: Mapping[str, Any], *, limit: int | None, pr grid.add_column(ratio=1) if index < column_count - 1: grid.add_column(width=1, justify="center") - pairs = list(items.items()) + pairs = list(items) visible = pairs if limit is None else pairs[:limit] - # Compact grids render one Panel deep (Training/Rewards/Environment), so + # Compact grids render one Panel deep, so # budget for that panel's border and padding. Each metric cell needs label # + separator + 9-char value; deriving the label width from the exact rich # column arithmetic keeps every cell on one line down to narrow widths. column_width = (terminal_width - 8 - 3 * column_count) // column_count label_width = max(12, min(32, column_width - 11)) - cells = [ - _prototype_metric_cell(k, v, precision=precision, signed=signed, label_width=label_width) for k, v in visible - ] + cells = [_prototype_metric_cell(k, v, label_width=label_width) for k, v in visible] omitted = 0 if limit is None else len(pairs) - len(visible) if omitted: from rich.text import Text @@ -526,32 +623,38 @@ def _rich_compact_metric_grid(items: Mapping[str, Any], *, limit: int | None, pr return grid -def _rich_timing_grid(items: Mapping[str, Any], *, total: float | None = None): +def _rich_timing_grid(root: TimingNode) -> Table: from rich.text import Text grid = Table.grid(expand=True, padding=(0, 1)) grid.add_column(ratio=1) grid.add_column(justify="right", width=11) - grid.add_column(justify="right", width=8) - grid.add_row(Text("STAGE", style="dim"), Text("MEAN", style="dim"), Text("SHARE", style="dim")) - - def append(values: Mapping[str, Any], level: int = 0) -> None: - entries = list(values.items()) - for index, (key, value) in enumerate(entries): - branch = "'- " if index == len(entries) - 1 else "|- " - prefix = " " * level + branch - if isinstance(value, Mapping): - children = dict(value) - node_total = children.pop("total", None) - if node_total is not None: - share = f"{100.0 * float(node_total) / total:.0f}%" if total else "-" - grid.add_row(Text(prefix + str(key), style="white"), f"{_format_value(node_total)} ms", share) - append(children, level + 1) - else: - share = f"{100.0 * float(value) / total:.0f}%" if total else "-" - grid.add_row(Text(prefix + str(key), style="white"), f"{_format_value(value)} ms", share) - append(items) + def has_shares(node: TimingNode) -> bool: + return any(_timing_share(child, node) is not None or has_shares(child) for child in node.children) + + show_shares = has_shares(root) + if show_shares: + grid.add_column(justify="right", width=8) + header = [Text("STAGE", style="dim"), Text("MEAN", style="dim")] + if show_shares: + header.append(Text("SHARE", style="dim")) + grid.add_row(*header) + + def append(parent: TimingNode, prefix: str = "") -> None: + for index, child in enumerate(parent.children): + last = index == len(parent.children) - 1 + branch = "└─ " if last else "├─ " + cells = [ + Text(prefix + branch + _strip_markup(child.name), style="white"), + f"{_format_value(child.duration_ms)} ms" if child.duration_ms is not None else "", + ] + if show_shares: + cells.append(_timing_share(child, parent) or "") + grid.add_row(*cells) + append(child, prefix + (" " if last else "│ ")) + + append(root) return grid @@ -781,14 +884,14 @@ def card(label: str, body: Any, footer: Any = "") -> Panel: parts.append(footer) return Panel(Group(*parts), title=label, border_style="grey37", padding=(0, 1)) - # Overview keeps the five operator-facing cards on one row. Replay-buffer + # Overview keeps the enabled operator-facing cards on one row. Replay-buffer # occupancy remains available in the training/metrics data, but is not a # headline card. summary = Table.grid(expand=True, padding=(0, 1)) # System health contains two side-by-side stacks (CPU/GPU and RAM/VRAM), # so give it 1.5x the width of the other cards instead of forcing each # value into a narrow half-column. - for ratio in (2, 2, 2, 2, 3): + for ratio in (2,) * (2 + stats.show_episode_summary + stats.show_throughput) + (3,): summary.add_column(ratio=ratio) load = stats.cpu_load @@ -835,24 +938,44 @@ def memory_style(memory: MemoryUsage | None) -> str: _run_progress_time_text(stats), ), ), - card( - "Episode stats", - Group( - Text(f"return {stats.mean_return:+.2f}", style="bold green"), - Text(f"length {stats.mean_episode_length:.1f}", style="white"), - ), + *( + [ + card( + "Episode stats", + Group( + Text( + f"return {stats.mean_return:+.2f}" if _available(stats.mean_return) else "return n/a", + style="bold green", + ), + Text( + f"length {stats.mean_episode_length:.1f}" + if _available(stats.mean_episode_length) + else "length n/a", + style="white", + ), + ), + ) + ] + if stats.show_episode_summary + else [] ), - card( - "Throughput", - Group( - Text( - f"{stats.steps_per_second:,.0f} env-steps/s" - if stats.steps_per_second is not None - else ("warming up" if stats.warming else "measuring…"), - style="bold cyan", - ), - Text(_iter_rate_text(stats), style="white"), - ), + *( + [ + card( + "Throughput", + Group( + Text( + f"{stats.steps_per_second:,.0f} env-steps/s" + if stats.steps_per_second is not None + else ("warming up" if stats.warming else "measuring…"), + style="bold cyan", + ), + Text(_iter_rate_text(stats), style="white"), + ), + ) + ] + if stats.show_throughput + else [] ), card( "Timing", @@ -864,46 +987,6 @@ def memory_style(memory: MemoryUsage | None) -> str: card("System health", system_health), ) - # UTD (update-to-data ratio) describes learner/training efficiency, so - # keep it with algorithm metrics rather than environment observations. - utd_items = {k: v for k, v in stats.diagnostics.items() if str(k).strip().lower() == "utd"} - train_items = dict(stats.training_metrics or {}) - train_items.update(utd_items) - train_parts: list[Any] = [] - if train_items: - train_parts.append(_rich_compact_metric_grid(train_items, limit=None)) - else: - train_parts.append( - Text("warmup - filling replay buffer" if stats.warming else "training metrics unavailable", style="grey70") - ) - training = Panel(Group(*train_parts), title=f"Training ({len(train_items)})", border_style="grey37", padding=(0, 1)) - left_blocks: list[Any] = [training] - if stats.reward_terms: - rewards = dict(sorted(stats.reward_terms.items(), key=lambda kv: -abs(float(kv[1])))) - left_blocks.append( - Panel( - _rich_compact_metric_grid(rewards, limit=None, precision=4, signed=True), - title=f"Rewards ({len(rewards)})", - border_style="grey37", - padding=(0, 1), - ) - ) - - env_items = dict(sorted(stats.env_metrics.items())) - env_parts: list[Any] = [] - if env_items: - env_parts.append(_rich_compact_metric_grid(env_items, limit=None, signed=True)) - else: - env_parts.append(Text("no environment metrics reported", style="grey70")) - other_diagnostics = {k: v for k, v in stats.diagnostics.items() if str(k).strip().lower() != "utd"} - if other_diagnostics: - env_parts.append( - Text(" · ".join(f"{k} {_format_value(v)}" for k, v in other_diagnostics.items()), style="cyan") - ) - environment = Panel( - Group(*env_parts), title=f"Environment metrics ({len(env_items)})", border_style="grey37", padding=(0, 1) - ) - if view == "system": lower = Group(_prototype_system_page(stats, load_style, memory_style)) elif view == "timing": @@ -911,47 +994,49 @@ def memory_style(memory: MemoryUsage | None) -> str: columns = Table.grid(expand=True, padding=(0, 1)) columns.add_column(ratio=1) columns.add_column(ratio=1) - groups = list(stats.timing_groups.items()) - for index in range(0, len(groups), 2): + roots = stats.timings + for index in range(0, len(roots), 2): row: list[Any] = [] for offset in (0, 1): - if index + offset >= len(groups): + if index + offset >= len(roots): row.append("") continue - group, items = groups[index + offset] - total = _timing_group_total(group, stats, index + offset) + root = roots[index + offset] row.append( Panel( - _rich_timing_grid(items, total=total), - title=f"{_strip_markup(group)} {total:.1f} ms", + _rich_timing_grid(root), + title=f"{_strip_markup(root.name)} {_format_value(root.duration_ms)} ms" + if root.duration_ms is not None + else _strip_markup(root.name), border_style="grey37", padding=(0, 1), ) ) columns.add_row(*row) - if groups: + if roots: timing_blocks.append(columns) - if stats.timing_metrics: + for name, values in _group_metrics(stats.timing_extras).items(): timing_blocks.append( Panel( - _rich_compact_metric_grid(stats.timing_metrics, limit=None), - title="Timing detail", + _rich_compact_metric_grid(values, limit=None), + title=Text(f"{name} ({len(values)})"), border_style="grey37", padding=(0, 1), ) ) - if stats.diagnostics: - timing_blocks.append( + lower = Group(*timing_blocks) if timing_blocks else Text("timing details unavailable", style="grey70") + else: + lower = Group( + *( Panel( - _rich_compact_metric_grid(stats.diagnostics, limit=None, signed=True), - title="Diagnostics", + _rich_compact_metric_grid(values, limit=None), + title=Text(f"{name} ({len(values)})"), border_style="grey37", padding=(0, 1), ) + for name, values in _group_metrics(stats.metrics, hidden=stats.overview_hidden_metrics).items() ) - lower = Group(*timing_blocks) if timing_blocks else Text("timing details unavailable", style="grey70") - else: - lower = Group(*left_blocks, environment) + ) blocks = [summary, lower, _prototype_tabs(stats, view)] if stats.checkpoint_path: blocks.insert(-1, Text(f"✓ saved checkpoint {stats.checkpoint_path}", style="green")) diff --git a/motrix_rl/src/motrix_rl/console/timing.py b/motrix_rl/src/motrix_rl/console/timing.py new file mode 100644 index 000000000..3c2c74a3b --- /dev/null +++ b/motrix_rl/src/motrix_rl/console/timing.py @@ -0,0 +1,89 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Build console timing scopes from dotted paths.""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field + +from motrix_env_core.perf import Perf, PerfNode +from motrix_rl.console.panel import TimingNode + + +@dataclass +class _TimingBranch: + duration_ms: float | None = None + children: dict[str, _TimingBranch] = field(default_factory=dict) + + def to_node(self, name: str) -> TimingNode: + return TimingNode( + name, + self.duration_ms, + tuple(child.to_node(child_name) for child_name, child in self.children.items()), + ) + + +def timing_nodes_from_paths(values: Mapping[str, float]) -> tuple[TimingNode, ...]: + """Build scopes in first-seen path-segment order from millisecond values. + + Only an explicit path supplies its node's duration; implicit parent scopes + have duration None, never a sum inferred from their children. + """ + root = _TimingBranch() + for path, duration_ms in values.items(): + branch = root + for name in path.split("."): + if name not in branch.children: + branch.children[name] = _TimingBranch() + branch = branch.children[name] + branch.duration_ms = duration_ms + return tuple(child.to_node(name) for name, child in root.children.items()) + + +def timing_node_from_perf(node: PerfNode) -> TimingNode: + """Preserve every profiler scope and its own per-call mean, converting ns to ms.""" + return TimingNode(node.name, node.mean_ns / 1e6, tuple(timing_node_from_perf(child) for child in node.children)) + + +class PerfTimingWindow: + """Exclusive consumer of a borrowed Perf's reporting window. + + start clears pre-window samples and enables profiling; snapshot consumes + completed scopes and resets the profiler. close restores the original + enabled state, never closes the environment. No other consumer may reset + this profiler while the window owns it. Operations require inactive scopes. + """ + + def __init__(self, perf: Perf, *, root: str = "step", parent: str = "env_step") -> None: + self._perf = perf + self._root = root + self.parent = parent + self._was_enabled = perf.enabled + self._started = False + + def start(self) -> None: + if self._started: + return + self._perf.reset() + self._perf.enable() + self._started = True + + def snapshot(self) -> tuple[TimingNode, ...]: + if not self._started: + return () + roots = self._perf.snapshot() + children = next((node.children for node in roots if node.name == self._root), ()) + result = tuple(timing_node_from_perf(child) for child in children) + self._perf.reset() + return result + + def close(self) -> None: + if not self._started: + return + if self._was_enabled: + self._perf.enable() + else: + self._perf.disable() + self._started = False diff --git a/motrix_rl/src/motrix_rl/contracts.py b/motrix_rl/src/motrix_rl/contracts.py index 444a945e0..2297c7dda 100644 --- a/motrix_rl/src/motrix_rl/contracts.py +++ b/motrix_rl/src/motrix_rl/contracts.py @@ -11,7 +11,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Generic, TypeVar -from motrix_rl.metrics import MetricsLogger +from motrix_rl.log.live import MotrixLiveLogger if TYPE_CHECKING: from motrix_env_core.renderer import RenderConfig @@ -52,7 +52,7 @@ class TrainerContext(Generic[CfgT]): render: RenderConfig | None = None resume_from: str | None = None # Live metrics for this run; disabled unless the control plane enabled it for training. - metrics: MetricsLogger = field(default_factory=MetricsLogger.disabled) + metrics: MotrixLiveLogger = field(default_factory=MotrixLiveLogger.disabled) @dataclass(frozen=True) @@ -62,7 +62,7 @@ class TrainerHandle: run: Any trainer: TrainerBase result_factory: Any = None - metrics: MetricsLogger = field(default_factory=MetricsLogger.disabled) + metrics: MotrixLiveLogger = field(default_factory=MotrixLiveLogger.disabled) # Extra fields of the ``running`` record (see wiki/design/live-metrics.md). run_info: Mapping[str, Any] = field(default_factory=dict) diff --git a/motrix_rl/src/motrix_rl/frameworks.py b/motrix_rl/src/motrix_rl/frameworks.py index 6d9ad144a..9ff3db36c 100644 --- a/motrix_rl/src/motrix_rl/frameworks.py +++ b/motrix_rl/src/motrix_rl/frameworks.py @@ -24,7 +24,7 @@ TrainerContext, TrainerHandle, ) -from motrix_rl.metrics import MetricsLogger +from motrix_rl.log.live import MotrixLiveLogger if TYPE_CHECKING: from motrix_env_core.renderer import RenderConfig @@ -175,7 +175,7 @@ def create_trainer_context( checkpoint: CheckpointConfig, render: RenderConfig | None = None, resume_from: str | None = None, - metrics: MetricsLogger | None = None, + metrics: MotrixLiveLogger | None = None, ) -> TrainerContext[Any]: _validate_runtime_config(logging, checkpoint) metadata = run.metadata @@ -194,7 +194,7 @@ def create_trainer_context( checkpoint=checkpoint, render=render, resume_from=resume_from, - metrics=metrics or MetricsLogger.disabled(), + metrics=metrics or MotrixLiveLogger.disabled(), ) diff --git a/motrix_rl/src/motrix_rl/log/__init__.py b/motrix_rl/src/motrix_rl/log/__init__.py new file mode 100644 index 000000000..fc399a40b --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/__init__.py @@ -0,0 +1,4 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Log aggregation and process-output utilities.""" diff --git a/motrix_rl/src/motrix_rl/log/accumulator.py b/motrix_rl/src/motrix_rl/log/accumulator.py new file mode 100644 index 000000000..3ca93db37 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/accumulator.py @@ -0,0 +1,58 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Host metric accumulation shared by independently drained output windows.""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from typing import Literal + +Reduction = Literal["mean", "last"] + + +@dataclass +class _Metric: + value: float = 0.0 + count: int = 0 + + +class MetricAccumulator: + def __init__( + self, reductions: Mapping[str, Reduction] | None = None, default_reduction: Reduction = "last" + ) -> None: + self._reductions = dict(reductions or {}) + self._default_reduction = default_reduction + for reduction in (default_reduction, *self._reductions.values()): + if reduction not in ("mean", "last"): + raise ValueError(f"Unsupported metric reduction: {reduction!r}") + self._metrics: dict[str, _Metric] = {} + + def record(self, metrics: Mapping[str, float | Iterable[float]]) -> None: + for key, value in metrics.items(): + reduction = self._reductions.get(key, self._default_reduction) + metric = self._metrics.get(key) + samples = (value,) if isinstance(value, (int, float)) else value + for sample in samples: + if metric is None: + metric = _Metric() + self._metrics[key] = metric + if reduction == "mean": + metric.value += sample + metric.count += 1 + else: + metric.value = sample + metric.count = 1 + + def snapshot(self) -> dict[str, float]: + return {key: metric.value / metric.count for key, metric in self._metrics.items()} + + def discard(self, keys: Iterable[str]) -> None: + """Drop selected pending metrics without draining other observations.""" + for key in keys: + self._metrics.pop(key, None) + + def clear(self) -> None: + self._metrics.clear() + + def __bool__(self) -> bool: + return bool(self._metrics) diff --git a/motrix_rl/src/motrix_rl/log/collector_stats.py b/motrix_rl/src/motrix_rl/log/collector_stats.py new file mode 100644 index 000000000..e3a1accc9 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/collector_stats.py @@ -0,0 +1,189 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Repeatable collector observation snapshots, not incremental sample records.""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass + +import numpy as np +import torch + +from motrix_rl.console.data import EpisodeWindow +from motrix_rl.console.panel import TimingNode +from motrix_rl.console.timing import PerfTimingWindow, timing_nodes_from_paths + + +@dataclass(frozen=True) +class CollectorStats: + """Latest observations from one collector; reading again adds no samples. + + ``episodes`` is cumulative for this collector invocation. Episode means + describe the producer's recent completed-episode window, not necessarily + those cumulative episodes: never use the count as their averaging weight. + None means no completed episode has supplied a mean yet; nonfinite values + after episodes exist remain observations (e.g. divergence), not missing data. + + Reward terms/timings describe the producer's reporting window; env metrics + and diagnostics are latest observations. The producer defines these windows + and metric names. Consumers must not feed repeated snapshots into an + incremental mean accumulator. These mappings are owned snapshot copies. + """ + + collector_id: int + episodes: int + mean_return: float | None + mean_episode_length: float | None + reward_terms: Mapping[str, float] + env_metrics: Mapping[str, float] + diagnostics: Mapping[str, float] + timings: tuple[TimingNode, ...] + + +@dataclass(frozen=True) +class CompletedEpisodes: + """Completed-episode samples consumed once, independent of repeatable snapshots.""" + + returns: tuple[float, ...] + lengths: tuple[int, ...] + + +class CollectorStatsTracker: + """Own collector observation windows without depending on an environment. + + Completed episodes remain in a bounded recent window with a cumulative + count. Reward/timing report windows reset at snapshot; latest observations + persist. Per-environment raw returns/lengths are retained across snapshots; + reset only discards unfinished trajectories, never resets the environment. + Inputs to record_step are original rewards, before algorithm bootstrap, + and explicit episode boundaries; input tensors are never modified. + Each timing record is one successful batch, including explicit + zeros for stages skipped in that batch (e.g. infrequent weight polling). + """ + + def __init__( + self, + collector_id: int, + *, + num_envs: int, + device: torch.device, + recent_episodes: int = 100, + collect_episode_deltas: bool = False, + perf_window: PerfTimingWindow | None = None, + ) -> None: + self._perf_window = perf_window + self._returns = torch.zeros(num_envs, device=device) + self._lengths = torch.zeros(num_envs, device=device, dtype=torch.long) + self._collect_episode_deltas = collect_episode_deltas + self._completed_returns: list[float] = [] + self._completed_lengths: list[int] = [] + self._collector_id = collector_id + self._episodes = EpisodeWindow(max_episodes=recent_episodes) + self._reward_sums: dict[str, float] = {} + self._reward_count = 0 + self._timing_sums: dict[str, float] = {} + self._timing_count = 0 + self._env_metrics: dict[str, float] = {} + self._diagnostics: dict[str, float] = {} + + @torch.no_grad() + def record_step( + self, + rewards: torch.Tensor, + episode_done: torch.Tensor, + *, + reward_terms: Mapping[str, torch.Tensor | np.ndarray], + metrics: Mapping[str, float], + ) -> None: + """Consume raw rewards and batch reward terms; metrics are already reduced scalars.""" + self._returns.add_(rewards) + self._lengths.add_(1) + ids = torch.nonzero(episode_done, as_tuple=False).flatten() + if ids.numel(): + self.add_episodes(self._returns[ids].tolist(), self._lengths[ids].tolist()) + self.reset(ids) + self.record_reward_terms( + {key: float(torch.as_tensor(value).float().mean()) for key, value in reward_terms.items()} + ) + self.set_env_metrics(metrics) + + @torch.no_grad() + def reset(self, env_ids: torch.Tensor | None = None) -> None: + """Discard unfinished statistics on explicit reopen, without recording an episode.""" + if env_ids is None: + self._returns.zero_() + self._lengths.zero_() + else: + self._returns[env_ids] = 0.0 + self._lengths[env_ids] = 0 + + def add_episodes(self, returns: Iterable[float], lengths: Iterable[float]) -> None: + return_values, length_values = list(returns), list(lengths) + self._episodes.add(return_values, length_values) + if self._collect_episode_deltas: + self._completed_returns.extend(return_values) + self._completed_lengths.extend(int(value) for value in length_values) + + def take_episodes(self) -> CompletedEpisodes: + """Consume delta samples; snapshot/reset never consume completed episodes.""" + result = CompletedEpisodes(tuple(self._completed_returns), tuple(self._completed_lengths)) + self._completed_returns.clear() + self._completed_lengths.clear() + return result + + def record_reward_terms(self, values: Mapping[str, float]) -> None: + """Record one reward-term observation; absent terms contribute zero.""" + if not values: + return + for key, value in values.items(): + self._reward_sums[key] = self._reward_sums.get(key, 0.0) + value + self._reward_count += 1 + + def set_env_metrics(self, values: Mapping[str, float]) -> None: + self._env_metrics = dict(values) + + def set_diagnostics(self, values: Mapping[str, float]) -> None: + self._diagnostics = dict(values) + + def record_timings(self, seconds: Mapping[str, float]) -> None: + """Add one successful batch's host-wall durations, in seconds.""" + for key, value in seconds.items(): + self._timing_sums[key] = self._timing_sums.get(key, 0.0) + value + self._timing_count += 1 + + def snapshot(self) -> CollectorStats: + """Copy observations and reset report windows, retaining recent episodes. + + Profiler sub-scopes are consumed as a tree, not averaged again. Their + parent duration remains the collector's own inclusive wall measurement. + """ + episodes = self._episodes.snapshot() + timing_ms = {key: seconds * 1000.0 / max(self._timing_count, 1) for key, seconds in self._timing_sums.items()} + timings = timing_nodes_from_paths(timing_ms) + if self._perf_window is not None: + children = self._perf_window.snapshot() + if children: + parent = self._perf_window.parent + timings = ( + tuple( + TimingNode(node.name, node.duration_ms, children) if node.name == parent else node + for node in timings + ) + if any(node.name == parent for node in timings) + else (*timings, TimingNode(parent, None, children)) + ) + result = CollectorStats( + collector_id=self._collector_id, + episodes=episodes.episodes, + mean_return=episodes.mean_return, + mean_episode_length=episodes.mean_length, + reward_terms={key: value / self._reward_count for key, value in self._reward_sums.items()}, + env_metrics=dict(self._env_metrics), + diagnostics=dict(self._diagnostics), + timings=timings, + ) + self._reward_sums.clear() + self._reward_count = 0 + self._timing_sums = dict.fromkeys(self._timing_sums, 0.0) + self._timing_count = 0 + return result diff --git a/motrix_rl/src/motrix_rl/metrics.py b/motrix_rl/src/motrix_rl/log/live.py similarity index 99% rename from motrix_rl/src/motrix_rl/metrics.py rename to motrix_rl/src/motrix_rl/log/live.py index e633835b7..fdc615418 100644 --- a/motrix_rl/src/motrix_rl/metrics.py +++ b/motrix_rl/src/motrix_rl/log/live.py @@ -44,10 +44,10 @@ # How long the interpreter waits at exit for sinks still writing or sending (see _join_at_exit). EXIT_TIMEOUT = 5.0 -_OPEN: weakref.WeakSet[MetricsLogger] = weakref.WeakSet() +_OPEN: weakref.WeakSet[MotrixLiveLogger] = weakref.WeakSet() -class MetricsLogger: +class MotrixLiveLogger: """Emits ``motrix.metrics/v1`` records to a jsonl file and an ingest service. Every record gets one ``seq`` and goes to every sink, so a jsonl written @@ -85,12 +85,12 @@ def __init__( _OPEN.add(self) @classmethod - def disabled(cls) -> MetricsLogger: + def disabled(cls) -> MotrixLiveLogger: """A logger whose methods do nothing.""" return cls("disabled") @classmethod - def from_env(cls, run_dir: str | Path, *, role: str = "trainer") -> MetricsLogger: + def from_env(cls, run_dir: str | Path, *, role: str = "trainer") -> MotrixLiveLogger: """Build the logger the ``MOTRIX_METRICS_*`` environment asks for.""" url = os.environ.get("MOTRIX_METRICS_URL", "") jsonl = os.environ.get("MOTRIX_METRICS_JSONL", "").strip().lower() in _TRUTHY diff --git a/motrix_rl/src/motrix_rl/log/process_logging.py b/motrix_rl/src/motrix_rl/log/process_logging.py new file mode 100644 index 000000000..771d88480 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/process_logging.py @@ -0,0 +1,83 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""File-backed stdio/logging isolation for spawned worker processes. + +A parent that owns a live console cannot let worker output reach the shared +terminal: spawn children re-import heavy modules and may print (banners, +warnings, native output) before their entry function runs, and C-level writes +bypass Python logging entirely. The helpers here route both phases to a +per-worker log file while keeping the file append-open for restarts. +""" + +from __future__ import annotations + +import logging +import os +from contextlib import contextmanager +from pathlib import Path + + +@contextmanager +def inherit_log_stdio(log_file: Path): + """Parent-side spawn guard: point fd 1/2 at the worker's log file while starting it. + + Spawn children inherit the parent's terminal fds and re-import modules + BEFORE their entry function runs, so import-time output would land raw on + the shared terminal. Holding the log file on fd 1/2 across + ``Process.start()`` makes the child inherit it from its first instruction; + the parent's own fds are restored immediately afterwards. + + fd 1/2 are process-global: keep the guarded region short, do not render + console output from the parent inside it, and do not start workers from + multiple threads concurrently. + """ + import sys + + sys.stdout.flush() + sys.stderr.flush() + log_fd = os.open(str(log_file), os.O_WRONLY | os.O_CREAT | os.O_APPEND) + saved_stdout, saved_stderr = os.dup(1), os.dup(2) + try: + os.dup2(log_fd, 1) + os.dup2(log_fd, 2) + yield + finally: + sys.stdout.flush() + sys.stderr.flush() + os.dup2(saved_stdout, 1) + os.dup2(saved_stderr, 2) + os.close(saved_stdout) + os.close(saved_stderr) + os.close(log_fd) + + +def configure_process_logging(log_file: Path) -> None: + """Child-side: route logging and fd 1/2 to the worker's log file. + + Call this before any heavy initialization in the child entry function so + later stdout/stderr output, warnings, tracebacks and native writes stay out + of the parent's console and remain inspectable under the run's ``logs/`` + directory. Immediate failure reporting keeps its own channel (error queue + or pipe); the log file is the full-output record. + """ + import sys + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + filename=str(log_file), + filemode="a", + force=True, + ) + sys.stdout.flush() + sys.stderr.flush() + log_fd = os.open(str(log_file), os.O_WRONLY | os.O_CREAT | os.O_APPEND) + os.dup2(log_fd, 1) + os.dup2(log_fd, 2) + os.close(log_fd) + # Rebind the Python stream objects: a replaced sys.stdout (capture tools, + # embedding hosts) may hold a different fd, and stale buffering would + # otherwise send Python-level output to the pre-redirect destination. + sys.stdout = os.fdopen(os.dup(1), "w", buffering=1) + sys.stderr = os.fdopen(os.dup(2), "w", buffering=1) diff --git a/motrix_rl/src/motrix_rl/log/python_logging.py b/motrix_rl/src/motrix_rl/log/python_logging.py new file mode 100644 index 000000000..d884158f5 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/python_logging.py @@ -0,0 +1,35 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Temporary file routing for an explicit Python logging namespace.""" + +import logging +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + + +@contextmanager +def scoped_file_logging(scope: logging.Logger | str, path: Path) -> Iterator[None]: + """Route a logger and its propagating descendants exclusively to a file. + + The scope's handlers, level and propagation are restored even on failure; + borrowed handlers are never closed. This changes Python logging only, not + stdout, stderr or native output. Descendants retain their own configuration. + Like other logging configuration, this is process-global, not thread-local. + """ + logger = logging.getLogger(scope) if isinstance(scope, str) else scope + path.parent.mkdir(parents=True, exist_ok=True) + handler = logging.FileHandler(path, encoding="utf-8") + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) + handlers, level, propagate = logger.handlers[:], logger.level, logger.propagate + try: + logger.handlers = [handler] + logger.setLevel(logging.INFO) + logger.propagate = False + yield + finally: + logger.handlers = handlers + logger.setLevel(level) + logger.propagate = propagate + handler.close() diff --git a/motrix_rl/src/motrix_rl/log/schedule.py b/motrix_rl/src/motrix_rl/log/schedule.py new file mode 100644 index 000000000..0308e2887 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/schedule.py @@ -0,0 +1,22 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Iteration-aligned logging cadence for sequential and asynchronously observed counters.""" + + +class IterationLogSchedule: + """Emit once when crossing a boundary; never replay skipped intervals. + + ``initial_iteration`` is the resume baseline. Nonpositive intervals mean one + boundary per iteration. Check with ``due`` and advance only after output succeeds. + """ + + def __init__(self, interval: int, *, initial_iteration: int = 0) -> None: + self._interval = max(interval, 1) + self._next_iteration = (initial_iteration // self._interval + 1) * self._interval + + def due(self, iteration: int) -> bool: + return iteration >= self._next_iteration + + def mark_logged(self, iteration: int) -> None: + self._next_iteration = (iteration // self._interval + 1) * self._interval diff --git a/motrix_rl/src/motrix_rl/log/sink.py b/motrix_rl/src/motrix_rl/log/sink.py new file mode 100644 index 000000000..8020a59eb --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/sink.py @@ -0,0 +1,26 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Structural contract for independently scheduled training metric outputs.""" + +from collections.abc import Iterable, Mapping +from typing import Any, Protocol + + +class MetricsSink(Protocol): + """A borrowed output with its own aggregation/cadence and no implicit ownership transfer. + + Construct sinks with the same resume baseline as TrainingMetrics. Implement + event/start explicitly (a no-op is valid); output-specific close is owned by + the creator, not the dispatcher. record inputs may be retained read-only. + """ + + def record(self, metrics: Mapping[str, float | Iterable[float]]) -> None: ... + + def advance(self, *, iterations: int = 1, env_steps: int) -> None: ... + + def flush(self, *, force: bool = False) -> None: ... + + def event(self, name: str, *, iteration: int, data: Mapping[str, Any]) -> None: ... + + def start(self, *, now: float) -> None: ... diff --git a/motrix_rl/src/motrix_rl/console/metrics.py b/motrix_rl/src/motrix_rl/log/system_metrics.py similarity index 74% rename from motrix_rl/src/motrix_rl/console/metrics.py rename to motrix_rl/src/motrix_rl/log/system_metrics.py index 61b1f90c0..5d76c0429 100644 --- a/motrix_rl/src/motrix_rl/console/metrics.py +++ b/motrix_rl/src/motrix_rl/log/system_metrics.py @@ -5,16 +5,13 @@ from __future__ import annotations -from motrix_rl.console.panel import TrainingPanelStats +from motrix_rl.system_metrics import SystemStats _GIB = 1024**3 -# Rollout means that are a NaN placeholder until the first episode ends. -ROLLOUT_MEANS = ("rollout/mean_return", "rollout/mean_ep_len") - -def system_scalars(stats: TrainingPanelStats) -> dict[str, float]: - """The fixed ``sys/*`` keys from the samples a panel frame already holds. +def system_scalars(stats: SystemStats) -> dict[str, float]: + """The fixed ``sys/*`` keys from a UI-independent host observation. Memory is reported in GiB, like the panel. Per-core CPU load is left out on purpose: it would spend the service's per-run key budget on large hosts. diff --git a/motrix_rl/src/motrix_rl/log/tensor_window.py b/motrix_rl/src/motrix_rl/log/tensor_window.py new file mode 100644 index 000000000..656177dac --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/tensor_window.py @@ -0,0 +1,64 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Device-resident scalar diagnostics with host conversion only at logging boundaries.""" + +from collections.abc import Mapping +from typing import Literal + +import torch + +TensorReduction = Literal["mean", "range"] + + +class TensorMetricWindow: + """Accumulate detached scalars using a fixed per-key reduction policy. + + Every key produces a mean; ``range`` additionally produces ``_min`` and + ``_max``. Each key counts its own samples (e.g. infrequent actor updates). + Recording never converts tensors to host scalars. Draining owns that sync. + """ + + def __init__( + self, reductions: Mapping[str, TensorReduction], *, default_reduction: TensorReduction | None = None + ) -> None: + self._default_reduction = default_reduction + self._reductions = dict(reductions) + for reduction in self._reductions.values(): + if reduction not in ("mean", "range"): + raise ValueError(f"Unsupported tensor metric reduction: {reduction!r}") + if default_reduction is not None and default_reduction not in ("mean", "range"): + raise ValueError(f"Unsupported tensor metric reduction: {default_reduction!r}") + self._sums: dict[str, torch.Tensor] = {} + self._counts: dict[str, int] = {} + self._minimums: dict[str, torch.Tensor] = {} + self._maximums: dict[str, torch.Tensor] = {} + + def record(self, key: str, value: torch.Tensor) -> None: + reduction = self._reductions[key] if key in self._reductions else self._default_reduction + if reduction is None: + raise KeyError(key) + sample = value.detach().float() + if key not in self._sums: + self._sums[key] = sample.clone() + self._counts[key] = 1 + if reduction == "range": + self._minimums[key] = sample.clone() + self._maximums[key] = sample.clone() + else: + self._sums[key] = self._sums[key] + sample + self._counts[key] += 1 + if reduction == "range": + self._minimums[key] = torch.minimum(self._minimums[key], sample) + self._maximums[key] = torch.maximum(self._maximums[key], sample) + + def stats_and_reset(self) -> dict[str, float]: + """Return window means/extremes as host scalars, then clear all samples.""" + result = {key: (total / self._counts[key]).item() for key, total in self._sums.items()} + result.update({f"{key}_min": value.item() for key, value in self._minimums.items()}) + result.update({f"{key}_max": value.item() for key, value in self._maximums.items()}) + self._sums.clear() + self._counts.clear() + self._minimums.clear() + self._maximums.clear() + return result diff --git a/motrix_rl/src/motrix_rl/log/training_logger.py b/motrix_rl/src/motrix_rl/log/training_logger.py new file mode 100644 index 000000000..4e1da08b5 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/training_logger.py @@ -0,0 +1,155 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""The one interface a trainer logs its training metrics through. + +``TrainingLogger`` puts TensorBoard and live metrics (``motrix.metrics/v1``, +see :mod:`motrix_rl.log.live`) behind one call per logging window, so a trainer +builds its scalars once and never talks to either output directly. See +``wiki/design/live-metrics.md``. +""" + +from __future__ import annotations + +import logging +from collections.abc import Iterable, Mapping +from pathlib import Path +from types import MappingProxyType +from typing import Any + +from motrix_rl.log.accumulator import MetricAccumulator, Reduction +from motrix_rl.log.live import MotrixLiveLogger +from motrix_rl.log.schedule import IterationLogSchedule + +logger = logging.getLogger(__name__) + + +class TrainingLogger: + """Writes a trainer's scalars to TensorBoard and sends them, with its events, to live metrics. + + The TensorBoard writer under ``log_dir`` is opened on the first + :meth:`flush` call, so a run that fails before logging anything leaves no + event file. TensorBoard is optional: when it cannot be opened, scalars still + go live. The live :class:`MotrixLiveLogger` belongs to the control plane, which + reports the run state and closes it; :meth:`close` closes only TensorBoard. + """ + + def __init__( + self, + log_dir: str | Path, + live: MotrixLiveLogger, + *, + interval: int = 1, + initial_iteration: int = 0, + initial_env_steps: int = 0, + reductions: Mapping[str, Reduction] | None = None, + default_reduction: Reduction = "last", + live_only_prefixes: tuple[str, ...] = (), + ) -> None: + self._reductions = MappingProxyType(dict(reductions or {})) + self._default_reduction = default_reduction + self._live_only_prefixes = live_only_prefixes + self._iteration = initial_iteration + self._env_steps = initial_env_steps + self._log_dir = Path(log_dir) + self.live = live + self._tensorboard: Any = None + self._tensorboard_opened = False + self._schedule = IterationLogSchedule(interval, initial_iteration=initial_iteration) + self._metrics = MetricAccumulator(reductions, default_reduction) + + @property + def reductions(self) -> Mapping[str, Reduction]: + return self._reductions + + @property + def default_reduction(self) -> Reduction: + return self._default_reduction + + @property + def iteration(self) -> int: + return self._iteration + + @property + def env_steps(self) -> int: + return self._env_steps + + def advance(self, *, iterations: int = 1, env_steps: int) -> None: + """Add completed progress, not absolute counters; zero deltas are valid. + + Async observers pass differences from their current logger context. + This never writes metrics or advances the logging interval by itself. + """ + if iterations < 0 or env_steps < 0: + raise ValueError("Logger progress increments must be nonnegative") + self._iteration += iterations + self._env_steps += env_steps + + def record(self, metrics: Mapping[str, float | Iterable[float]]) -> None: + """Accumulate host samples with construction-time mean/last policy. + + Mean weights individual samples, not per-call means. Empty iterables + add nothing; keys absent from reductions use default_reduction. + """ + self._metrics.record(metrics) + + def due(self) -> bool: + """Query cadence without consuming it or requiring recorded metrics. + + Use before expensive device-to-host conversion; repeated queries are + harmless. A flush without samples does not advance this boundary. + """ + return self._schedule.due(self._iteration) + + def flush(self, *, force: bool = False) -> None: + """Write recorded metrics if due, or force the final report. + + Only a successful dispatch clears samples and advances cadence. Partial + backend output is not transactional: retry can duplicate earlier writes. + """ + if not self._metrics or (not force and not self.due()): + return + values = self._metrics.snapshot() + self._emit(values) + self._metrics.clear() + self._schedule.mark_logged(self._iteration) + + def _emit(self, values: Mapping[str, float]) -> None: + tensorboard_values = { + key: value for key, value in values.items() if not key.startswith(self._live_only_prefixes) + } + if tensorboard_values: + tensorboard = self._open_tensorboard() + if tensorboard is not None: + for tag, value in tensorboard_values.items(): + tensorboard.add_scalar(tag, value, self._iteration) + if self.live.enabled: + self.live.scalars(values, self._iteration, env_steps=self._env_steps) + + def start(self, *, now: float) -> None: + """Start notification; iteration cadence does not depend on wall time.""" + + def event(self, name: str, *, iteration: int, data: Mapping[str, Any]) -> None: + """Report an explicit event position; events go live only.""" + self.live.event(name, iteration, **data) + + def close(self) -> None: + """Close TensorBoard safely; never implicitly emit pending host metrics.""" + if self._tensorboard is None: + return + try: + self._tensorboard.close() + except Exception as exc: # noqa: BLE001 - closing must not mask the run's outcome + logger.warning("closing TensorBoard failed: %s", exc) + self._tensorboard = None + + def _open_tensorboard(self) -> Any: + if not self._tensorboard_opened: + self._tensorboard_opened = True + try: + from torch.utils.tensorboard import SummaryWriter + + self._tensorboard = SummaryWriter(log_dir=str(self._log_dir)) + except Exception as exc: # noqa: BLE001 - TensorBoard is optional + logger.warning("TensorBoard is unavailable, logging live metrics only: %s", exc) + return self._tensorboard diff --git a/motrix_rl/src/motrix_rl/log/training_metrics.py b/motrix_rl/src/motrix_rl/log/training_metrics.py new file mode 100644 index 000000000..5408301f3 --- /dev/null +++ b/motrix_rl/src/motrix_rl/log/training_metrics.py @@ -0,0 +1,143 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""One recording entry point for independently scheduled logs and terminal output.""" + +import time +from collections.abc import Iterable, Mapping, Sequence +from typing import Any + +from motrix_rl.console.data import EpisodeWindow, RateTracker +from motrix_rl.log.sink import MetricsSink +from motrix_rl.log.system_metrics import system_scalars +from motrix_rl.system_metrics import SystemSampler + + +class TrainingMetrics: + """Fan observations out to structural MetricsSink implementations. + + Caller owns closing outputs and initializing their progress/reductions. + The dispatcher owns authoritative progress; no sink is a privileged logger + or panel. A generator is materialized once so all outputs see the same samples. + """ + + def __init__( + self, + sinks: Sequence[MetricsSink], + *, + initial_iteration: int = 0, + initial_env_steps: int = 0, + system_sink: MetricsSink | None = None, + system_interval_seconds: float = 1.0, + recent_episodes: int = 100, + ) -> None: + self._episodes = EpisodeWindow(max_episodes=recent_episodes) + self._env_rate = RateTracker() + self._iteration_rate = RateTracker() + now = time.monotonic() + self._env_rate.update(initial_env_steps, now=now) + self._iteration_rate.update(initial_iteration, now=now) + self._last_rate_observation = now + self._pending = False + self._sinks = tuple(sinks) + if len({id(sink) for sink in self._sinks}) != len(self._sinks): + raise ValueError("Metrics sinks must be distinct objects") + if system_sink is not None and not any(sink is system_sink for sink in self._sinks): + raise ValueError("system_sink must be one of the connected sinks") + self._system_sink = system_sink + self._iteration = initial_iteration + self._env_steps = initial_env_steps + if system_interval_seconds <= 0.0: + raise ValueError("system_interval_seconds must be positive") + self._system_interval_seconds = system_interval_seconds + self._last_system_sample: float | None = None + self._system = SystemSampler() if system_sink is not None else None + + def start(self) -> None: + """Anchor training time after boot; retain counters and buffered observations.""" + now = time.monotonic() + self._env_rate.reset() + self._iteration_rate.reset() + self._env_rate.update(self.env_steps, now=now) + self._iteration_rate.update(self.iteration, now=now) + self._last_rate_observation = now + for sink in self._sinks: + sink.start(now=now) + + @property + def iteration(self) -> int: + return self._iteration + + @property + def env_steps(self) -> int: + return self._env_steps + + def record(self, metrics: Mapping[str, float | Iterable[float]]) -> None: + values = {key: value if isinstance(value, (float, int)) else tuple(value) for key, value in metrics.items()} + if any(isinstance(value, (int, float)) or value for value in values.values()): + self._pending = True + for sink in self._sinks: + sink.record(values) + + def record_episodes(self, returns: Iterable[float], lengths: Iterable[float]) -> None: + """Consume newly completed episodes once and publish a shared recent mean. + + This window survives both output flushes. Empty increments preserve the + last recent mean; no episode history is inferred from resumed counters. + """ + self._episodes.add(returns, lengths) + snapshot = self._episodes.snapshot() + values: dict[str, float] = {} + if snapshot.mean_return is not None: + values["episode/recent_return_mean"] = snapshot.mean_return + values["episode/recent_length_mean"] = snapshot.mean_length + self.record(values) + + def advance(self, *, iterations: int = 1, env_steps: int) -> None: + if iterations < 0 or env_steps < 0: + raise ValueError("Metrics progress increments must be nonnegative") + self._iteration += iterations + self._env_steps += env_steps + for sink in self._sinks: + sink.advance(iterations=iterations, env_steps=env_steps) + self._observe_rates(time.monotonic()) + + def _observe_rates(self, now: float) -> None: + self._last_rate_observation = now + rates = {} + for key, value in ( + ("throughput/env_steps_per_s", self._env_rate.update(self.env_steps, now=now)), + ("throughput/iterations_per_s", self._iteration_rate.update(self.iteration, now=now)), + ): + if value is not None: + rates[key] = value + if rates: + self.record(rates) + + def flush(self, *, force: bool = False) -> None: + """Offer each sink an independent output opportunity. + + System observations have their own wall-clock cadence, never borrowed + from an output. Device-to-host sampling remains the producer's policy. + """ + now = time.monotonic() + # Waiting for data is still a shared progress observation. Refreshing + # the console must not independently compute a conflicting rate. + if now - self._last_rate_observation >= 1.0: + self._observe_rates(now) + sample_due = self._last_system_sample is None or now - self._last_system_sample >= self._system_interval_seconds + if self._pending and self._system is not None and (sample_due or force): + values = system_scalars(self._system.sample()) + self._system_sink.record(values) + self._last_system_sample = now + self._pending = False + for sink in self._sinks: + sink.flush(force=force) + + def event(self, name: str, iteration: int | None = None, **data: Any) -> None: + event_iteration = self.iteration if iteration is None else iteration + for sink in self._sinks: + sink.event(name, iteration=event_iteration, data=data) + + def checkpoint(self, path: str, *, iteration: int | None = None) -> None: + self.event("checkpoint_saved", iteration=iteration, path=path) diff --git a/motrix_rl/src/motrix_rl/runner.py b/motrix_rl/src/motrix_rl/runner.py index 65254072a..9adaabf50 100644 --- a/motrix_rl/src/motrix_rl/runner.py +++ b/motrix_rl/src/motrix_rl/runner.py @@ -11,8 +11,8 @@ from motrix_env_core.renderer import RenderConfig from motrix_rl import backend_runtime, checkpoints, frameworks, runs, utils from motrix_rl.config import TaskConfig, TrainConfig +from motrix_rl.log.live import MotrixLiveLogger from motrix_rl.method import RlMethod -from motrix_rl.metrics import MetricsLogger from motrix_rl.result import TrainResult logger = logging.getLogger(__name__) @@ -85,7 +85,7 @@ def create_training_handle(request: TrainRequest) -> frameworks.TrainerHandle: resume_from = None if config.resume is not None: resume_from = str(checkpoints.resolve_resume_checkpoint_path(config.resume)) - metrics = MetricsLogger.from_env(run.run_dir) + metrics = MotrixLiveLogger.from_env(run.run_dir) try: handle = _create_handle( run, @@ -153,7 +153,7 @@ def _create_handle( randomize_seed: bool = False, render: RenderConfig | None = None, resume_from: str | None = None, - metrics: MetricsLogger | None = None, + metrics: MotrixLiveLogger | None = None, ) -> frameworks.TrainerHandle: metadata = run.metadata if ( diff --git a/motrix_rl/src/motrix_rl/system_metrics.py b/motrix_rl/src/motrix_rl/system_metrics.py index a122ef27d..a142a45ed 100644 --- a/motrix_rl/src/motrix_rl/system_metrics.py +++ b/motrix_rl/src/motrix_rl/system_metrics.py @@ -18,6 +18,7 @@ import platform import re import sys +from collections.abc import Sequence from dataclasses import dataclass from importlib import metadata as importlib_metadata from pathlib import Path @@ -550,3 +551,31 @@ def _pkg(name: str) -> str | None: def _slugify(text: str) -> str: slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") return re.sub(r"-+", "-", slug)[:48] or "unknown" + + +@dataclass(frozen=True) +class SystemStats: + cpu_load: CpuLoad | None + gpu_utilization_percent: float | None + memory_usage: MemoryUsage | None + gpu_memory_usage: MemoryUsage | None + gpu_devices: Sequence[GpuDeviceUsage] | None + + +class SystemSampler: + """Sample host observations for independent logging and display consumers.""" + + def __init__(self) -> None: + self._cpu = CpuLoadSampler() + self._gpu = GpuUtilizationSampler() + self._memory = MemoryUsageSampler() + self._gpu_memory = GpuMemoryUsageSampler() + + def sample(self) -> SystemStats: + return SystemStats( + cpu_load=self._cpu.sample(), + gpu_utilization_percent=self._gpu.sample(), + memory_usage=self._memory.sample(), + gpu_memory_usage=self._gpu_memory.sample(), + gpu_devices=sample_gpu_devices(self._gpu, self._gpu_memory), + ) diff --git a/motrix_rl/src/motrix_rl/training_logger.py b/motrix_rl/src/motrix_rl/training_logger.py deleted file mode 100644 index 3f5c31475..000000000 --- a/motrix_rl/src/motrix_rl/training_logger.py +++ /dev/null @@ -1,91 +0,0 @@ -# Copyright Motphys Technology Co., Ltd. 2025, 2026 -# SPDX-License-Identifier: Apache-2.0 - -"""The one interface a trainer logs its training metrics through. - -``TrainingLogger`` puts TensorBoard and live metrics (``motrix.metrics/v1``, -see :mod:`motrix_rl.metrics`) behind one call per logging window, so a trainer -builds its scalars once and never talks to either output directly. See -``wiki/design/live-metrics.md``. -""" - -from __future__ import annotations - -import logging -from collections.abc import Callable, Collection, Mapping -from pathlib import Path -from typing import Any - -from motrix_rl.metrics import MetricsLogger - -logger = logging.getLogger(__name__) - - -class TrainingLogger: - """Writes a trainer's scalars to TensorBoard and sends them, with its events, to live metrics. - - The TensorBoard writer under ``log_dir`` is opened on the first - :meth:`scalars` call, so a run that fails before logging anything leaves no - event file. TensorBoard is optional: when it cannot be opened, scalars still - go live. The live :class:`MetricsLogger` belongs to the control plane, which - reports the run state and closes it; :meth:`close` closes only TensorBoard. - """ - - def __init__(self, log_dir: str | Path, live: MetricsLogger) -> None: - self._log_dir = Path(log_dir) - self.live = live - self._tensorboard: Any = None - self._tensorboard_opened = False - - def scalars( - self, - values: Mapping[str, float], - step: int, - *, - env_steps: int, - live_extra: Callable[[], Mapping[str, float]] | None = None, - placeholders: Collection[str] = (), - ) -> None: - """Log one window: *values* to TensorBoard under their keys as tags, and live. - - *live_extra* returns scalars sent live only (host samples TensorBoard - never had); it is called only when live metrics are on. - *placeholders* names keys whose value is not defined yet, such as a NaN - mean before the first episode ends: TensorBoard still gets them, live - leaves them out so its once-per-key ``nonfinite`` event stays free for a - real divergence. - """ - tensorboard = self._open_tensorboard() - if tensorboard is not None: - for tag, value in values.items(): - tensorboard.add_scalar(tag, value, step) - if self.live.enabled: - live = {key: value for key, value in values.items() if key not in placeholders} - if live_extra is not None: - live.update(live_extra()) - self.live.scalars(live, step, env_steps=env_steps) - - def event(self, name: str, step: int | None = None, **data: Any) -> None: - """Report a named event such as ``checkpoint_saved``; events go live only.""" - self.live.event(name, step, **data) - - def close(self) -> None: - """Flush and close TensorBoard; never raises, so it is safe in a ``finally``.""" - if self._tensorboard is None: - return - try: - self._tensorboard.close() - except Exception as exc: # noqa: BLE001 - closing must not mask the run's outcome - logger.warning("closing TensorBoard failed: %s", exc) - self._tensorboard = None - - def _open_tensorboard(self) -> Any: - if not self._tensorboard_opened: - self._tensorboard_opened = True - try: - from torch.utils.tensorboard import SummaryWriter - - self._tensorboard = SummaryWriter(log_dir=str(self._log_dir)) - except Exception as exc: # noqa: BLE001 - TensorBoard is optional - logger.warning("TensorBoard is unavailable, logging live metrics only: %s", exc) - return self._tensorboard diff --git a/motrix_rl/src/motrix_rl/worker.py b/motrix_rl/src/motrix_rl/worker.py index 64129fb38..8cdd096f9 100644 --- a/motrix_rl/src/motrix_rl/worker.py +++ b/motrix_rl/src/motrix_rl/worker.py @@ -11,10 +11,15 @@ from __future__ import annotations import multiprocessing as mp +import traceback from abc import ABC, abstractmethod +from contextlib import nullcontext from dataclasses import dataclass +from multiprocessing.connection import Connection from multiprocessing.context import BaseContext +from pathlib import Path +from motrix_rl.log.process_logging import configure_process_logging, inherit_log_stdio from motrix_rl.numa import apply_binding, spawn_placement @@ -24,11 +29,15 @@ class WorkerRuntime: The caller owns seed derivation and thread budgets. ``seed`` initializes Python, NumPy and Torch default RNGs; NumPy uses its low 32 bits. - Unset values leave process defaults untouched. + ``log_path`` routes the child's logging and fd 1/2 to a file so its output + cannot corrupt a parent-owned console; the parent also holds the file on + fd 1/2 across spawn so import-time output is captured too. Unset values + leave process defaults untouched. """ torch_num_threads: int | None = None seed: int | None = None + log_path: Path | None = None def __post_init__(self) -> None: if self.torch_num_threads is not None and self.torch_num_threads < 1: @@ -43,14 +52,47 @@ class WorkerPlacement: cpus: tuple[int, ...] = () +class WorkerError(RuntimeError): + """A child reported an exception or exited unsuccessfully.""" + + class WorkerHandle: """Parent-side lifecycle handle for a started worker.""" - def __init__(self, process: mp.Process, *, name: str, placement: WorkerPlacement) -> None: + def __init__(self, process: mp.Process, *, name: str, placement: WorkerPlacement, errors: Connection) -> None: + self._errors = errors + self._failure: str | None = None + self._closed = False self._process = process self.name = name self.placement = placement + def check(self) -> None: + """Nonblocking health check; normal exit is not an error. + + Error summaries are cached, so repeated checks preserve the failure. + Bootstrap/import/native failures without a report fall back to exitcode. + """ + if self._closed: + raise RuntimeError(f"Worker {self.name!r} handle is closed") + if self._failure is None and self._errors.poll(): + try: + self._failure = self._errors.recv_bytes().decode("utf-8", errors="replace") + except EOFError: + pass + if self._failure is not None: + raise WorkerError(f"Worker {self.name!r} failed:\n{self._failure}") + if self.exitcode not in (None, 0): + raise WorkerError(f"Worker {self.name!r} exited with code {self.exitcode}") + + def close(self) -> None: + """Release process/error resources after exit; does not stop a live task.""" + if self._closed: + return + self._process.close() + self._errors.close() + self._closed = True + def join(self, timeout: float | None = None) -> None: """Wait for the child process to exit.""" self._process.join(timeout) @@ -108,18 +150,62 @@ def start( """Start this task and return its parent-side lifecycle handle.""" worker_name = name or type(self).__name__ worker_placement = placement or WorkerPlacement() + worker_runtime = runtime or WorkerRuntime() + error_rx, error_tx = ctx.Pipe(duplex=False) process = ctx.Process( target=_worker_bootstrap, - args=(self, worker_placement, worker_name, runtime or WorkerRuntime()), + args=(self, worker_placement, worker_name, worker_runtime, error_rx, error_tx), name=worker_name, ) - with spawn_placement(worker_placement.numa_node, worker_name): - process.start() - return WorkerHandle(process, name=worker_name, placement=worker_placement) - - -def _worker_bootstrap(worker: Worker, placement: WorkerPlacement, worker_name: str, runtime: WorkerRuntime) -> None: + # Spawn children inherit fd 1/2 across Process.start(); the guard makes + # import-time output land in the worker log instead of the terminal. + guard = inherit_log_stdio(worker_runtime.log_path) if worker_runtime.log_path is not None else nullcontext() + try: + with guard: + with spawn_placement(worker_placement.numa_node, worker_name): + process.start() + except BaseException: + error_rx.close() + process.close() + raise + finally: + error_tx.close() + return WorkerHandle(process, name=worker_name, placement=worker_placement, errors=error_rx) + + +def _worker_bootstrap( + worker: Worker, + placement: WorkerPlacement, + worker_name: str, + runtime: WorkerRuntime, + error_rx: Connection, + error_tx: Connection, +) -> None: + error_rx.close() + try: + _run_worker(worker, placement, worker_name, runtime) + except BaseException as exc: + if not isinstance(exc, (KeyboardInterrupt, SystemExit)) or ( + isinstance(exc, SystemExit) and exc.code not in (None, 0) + ): + # A single bounded packet stays below the pipe capacity even when + # the parent is not polling. Full traceback is printed by Process. + report = traceback.format_exc().encode("utf-8") + if len(report) > 2048: + report = b"[traceback truncated; see worker log]\n" + report[-2000:] + try: + error_tx.send_bytes(report) + except (BrokenPipeError, EOFError, OSError): + pass + raise + finally: + error_tx.close() + + +def _run_worker(worker: Worker, placement: WorkerPlacement, worker_name: str, runtime: WorkerRuntime) -> None: """Apply placement, runtime settings and seeds, then invoke the worker task.""" + if runtime.log_path is not None: + configure_process_logging(runtime.log_path) apply_binding(worker_name, placement.numa_node, list(placement.cpus)) if runtime.torch_num_threads is not None or runtime.seed is not None: import torch diff --git a/motrix_rl_builtin/tests/test_fastsac_boot_panel.py b/motrix_rl/tests/test_boot_panel.py similarity index 62% rename from motrix_rl_builtin/tests/test_fastsac_boot_panel.py rename to motrix_rl/tests/test_boot_panel.py index 5d90e2155..0e1ac8408 100644 --- a/motrix_rl_builtin/tests/test_fastsac_boot_panel.py +++ b/motrix_rl/tests/test_boot_panel.py @@ -7,9 +7,12 @@ wrapping) and tolerate workers that have not created their log file yet. """ +from io import StringIO from pathlib import Path -from motrix_rl_builtin.fastsac.async_impl.panels import BootPanel, worker_log_tail +from rich.console import Console + +from motrix_rl.console.boot import BootPanel, BootWorker, worker_log_tail def test_tail_shows_placeholder_before_any_log_exists(tmp_path: Path) -> None: @@ -114,50 +117,60 @@ def test_tail_wrap_keeps_display_line_count_capped_at_max_lines(tmp_path: Path) assert lines[-1].endswith("short") -def test_boot_panel_render_fits_terminal_height(tmp_path: Path, monkeypatch) -> None: - from rich.console import Console +def render_frame( + panel: BootPanel, + workers: list[BootWorker], + *, + ready: set[str] = set(), + started: bool = False, + message: str = "", +) -> list[str]: + return [ + "".join(segment.text for segment in row) + for row in panel.console.render_lines(panel.render(workers, ready=ready, started=started, message=message)) + ] + + +def test_boot_panel_render_fits_terminal_height(tmp_path: Path) -> None: + log = tmp_path / "unrelated-filename.log" + log.write_text("c-line\n") + panel = BootPanel("env/framework", Console(width=100, height=20, file=StringIO())) + rendered = render_frame(panel, [BootWorker("collector[0]", log), BootWorker("learner[0]")], ready={"collector[0]"}) + + assert len(rendered) == 20 + text = "\n".join(rendered) + assert "ready" in text and "booting" in text and "c-line" in text + assert "collector[0]" in text + assert "unrelated-filename" not in text + + +def test_boot_panel_handoff_preserves_geometry(tmp_path: Path) -> None: + log = tmp_path / "worker.log" + log.write_text("c-line\n") + panel = BootPanel("env/framework", Console(width=100, height=20, file=StringIO())) + boot = render_frame(panel, [BootWorker("worker", log)], ready={"worker"}) + log.write_text("x" * 5000 + "\n") + handoff = render_frame(panel, [BootWorker("worker", log)], started=True, message="panel data — waiting") - (tmp_path / "collector0.log").write_text("c-line\n") - monkeypatch.setattr("motrix_rl_builtin.fastsac.async_impl.panels.Console", lambda: Console(width=100, height=20)) - panel = BootPanel( - title="env/motrix.fastsac — worker startup", - log_dir=tmp_path, - log_names=["collector0.log", "learner.log"], - workers=[("collector", 0), ("learner", 0)], - ) + assert len(handoff) == len(boot) == 20 + assert all(len(line) == 100 for line in boot + handoff) + assert "starting" in "\n".join(handoff) + assert "panel data — waiting" in "\n".join(handoff) - probe = Console(width=100, height=20, force_terminal=True, file=open("/dev/null", "w")) - rendered = ["".join(seg.text for seg in row) for row in probe.render_lines(panel.render({("collector", 0)}))] - assert len(rendered) == 20 # full-height frame, never taller - assert any("ready" in ln for ln in rendered) - assert any("booting" in ln for ln in rendered) - assert any("c-line" in ln for ln in rendered) +def test_boot_panel_supports_workers_without_logs() -> None: + panel = BootPanel("env/framework", Console(width=80, height=20, file=StringIO())) + rendered = render_frame(panel, [BootWorker("local worker")], ready={"local worker"}, message="initializing") + assert len(rendered) == 20 + text = "\n".join(rendered) + assert "local worker" in text and "ready" in text and "initializing" in text + assert "waiting for worker logs" not in text -def test_boot_panel_handoff_mode_renders_progress_and_gate(tmp_path: Path, monkeypatch) -> None: - from rich.console import Console - (tmp_path / "collector0.log").write_text("c-line\n") - import motrix_rl_builtin.fastsac.async_impl.panels as panels - - devnull = open("/dev/null", "w") - monkeypatch.setattr(panels, "Console", lambda: Console(width=100, height=20, force_terminal=True, file=devnull)) - panel = panels.BootPanel( - "env/motrix.fastsac", - tmp_path, - ["collector0.log", "learner.log"], - [("collector", 0), ("learner", 0)], - ) - probe = Console(width=100, height=20, force_terminal=True, file=devnull) - boot = ["".join(s.text for s in row) for row in probe.render_lines(panel.render({("collector", 0)}))] - handoff = ["".join(s.text for s in row) for row in probe.render_lines(panel.render(set(), gate="g", starting=True))] - - # Boot phase: ready/booting statuses; the reserved gate line is blank. - boot_text = "\n".join(boot) - assert "ready" in boot_text and "booting" in boot_text and "c-line" in boot_text - # Handoff phase: same frame height, every worker "starting", gate line filled. - handoff_text = "\n".join(handoff) - assert len(handoff) == len(boot) == 20 - assert handoff_text.count("starting") == 2 - assert "│ g" in handoff_text # gate line filled inside the outer frame +def test_boot_panel_supports_empty_worker_list() -> None: + panel = BootPanel("env/framework", Console(width=80, height=20, file=StringIO())) + rendered = render_frame(panel, [], message="preparing workers") + + assert len(rendered) == 20 + assert "preparing workers" in "\n".join(rendered) diff --git a/motrix_rl/tests/test_collector_stats.py b/motrix_rl/tests/test_collector_stats.py new file mode 100644 index 000000000..398331f5c --- /dev/null +++ b/motrix_rl/tests/test_collector_stats.py @@ -0,0 +1,110 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import pickle + +import pytest +import torch + +from motrix_rl.console.panel import TimingNode +from motrix_rl.log.collector_stats import CollectorStats, CollectorStatsTracker + + +def test_collector_snapshot_round_trips_across_process_serialization() -> None: + snapshot = CollectorStats( + collector_id=2, + episodes=10, + mean_return=None, + mean_episode_length=None, + reward_terms={"alive": 0.5}, + env_metrics={"height": 0.9}, + diagnostics={"policy_lag": 3.0}, + timings=(TimingNode("env_step", 2.0, (TimingNode("physics", 1.0),)),), + ) + restored = pickle.loads(pickle.dumps(snapshot)) + assert restored == snapshot + assert restored.env_metrics is not snapshot.env_metrics + + +def test_tracker_retains_recent_episodes_but_resets_report_windows() -> None: + tracker = CollectorStatsTracker(3, num_envs=2, device=torch.device("cpu"), recent_episodes=2) + assert tracker.snapshot().mean_return is None + tracker.add_episodes([1.0, 3.0, 5.0], [10, 30, 50]) + tracker.record_reward_terms({"a": 2.0, "b": 4.0}) + tracker.record_reward_terms({"a": 4.0}) + env = {"height": 0.5} + tracker.set_env_metrics(env) + tracker.set_diagnostics({"lag": 2.0}) + env["height"] = 9.0 + tracker.record_timings({"collect": 0.010, "sync": 0.004}) + tracker.record_timings({"collect": 0.020, "sync": 0.0}) + first = tracker.snapshot() + assert first.collector_id == 3 and first.episodes == 3 + assert first.mean_return == 4.0 and first.mean_episode_length == 40.0 + assert first.reward_terms == {"a": 3.0, "b": 2.0} + durations = {node.name: node.duration_ms for node in first.timings} + assert durations["collect"] == pytest.approx(15.0) + assert durations["sync"] == pytest.approx(2.0) # denominator includes skipped polls + second = tracker.snapshot() + assert second.episodes == first.episodes and second.mean_return == first.mean_return + assert second.reward_terms == {} + assert second.env_metrics == {"height": 0.5} and second.diagnostics == {"lag": 2.0} + assert all(node.duration_ms == 0.0 for node in second.timings) + tracker.set_env_metrics({"height": 1.0}) + assert first.env_metrics == {"height": 0.5} + assert first.reward_terms == {"a": 3.0, "b": 2.0} + + +def test_episode_boundaries_metrics_and_borrowed_rewards() -> None: + stats = CollectorStatsTracker(0, num_envs=2, device=torch.device("cpu")) + rewards = torch.tensor([1.0, 10.0], requires_grad=True) + stats.record_step( + rewards, + torch.tensor([False, True]), + reward_terms={"alive": torch.tensor([1.0, 3.0])}, + metrics={"error": 3.0}, + ) + torch.testing.assert_close(rewards, torch.tensor([1.0, 10.0])) + first = stats.snapshot() + assert first.episodes == 1 and first.mean_return == 10.0 and first.mean_episode_length == 1.0 + assert first.reward_terms == {"alive": 2.0} and first.env_metrics == {"error": 3.0} + # Snapshot does not reset unfinished env 0; done env 1 starts a fresh episode. + stats.record_step(torch.tensor([2.0, 20.0]), torch.tensor([True, True]), reward_terms={}, metrics={}) + second = stats.snapshot() + assert second.episodes == 3 and second.mean_return == 11.0 + assert second.mean_episode_length == 4.0 / 3.0 + assert second.reward_terms == {} and second.env_metrics == {} + + +def test_explicit_partial_and_full_reset_discard_unfinished_returns() -> None: + stats = CollectorStatsTracker(0, num_envs=2, device=torch.device("cpu")) + stats.record_step(torch.tensor([100.0, 200.0]), torch.tensor([False, False]), reward_terms={}, metrics={}) + stats.reset(torch.tensor([0])) + stats.record_step(torch.tensor([1.0, 2.0]), torch.tensor([True, True]), reward_terms={}, metrics={}) + snapshot = stats.snapshot() + assert snapshot.mean_return == 101.5 and snapshot.mean_episode_length == 1.5 + stats.record_step(torch.tensor([9.0, 9.0]), torch.tensor([False, False]), reward_terms={}, metrics={}) + stats.reset() + stats.record_step(torch.tensor([1.0, 1.0]), torch.tensor([True, True]), reward_terms={}, metrics={}) + snapshot = stats.snapshot() + assert snapshot.episodes == 4 and snapshot.mean_return == 51.25 + + +def test_episode_delta_drain_is_independent_of_snapshot_and_reset() -> None: + stats = CollectorStatsTracker(0, num_envs=1, device=torch.device("cpu"), collect_episode_deltas=True) + stats.record_step( + torch.tensor([2.0]), torch.tensor([True]), reward_terms={"bool": torch.tensor([True])}, metrics={"height": 0.9} + ) + assert stats.snapshot().env_metrics == {"height": 0.9} + stats.reset() + delta = stats.take_episodes() + assert delta.returns == (2.0,) and delta.lengths == (1,) + assert stats.take_episodes().returns == () + assert stats.snapshot().episodes == 1 + + +def test_snapshot_only_tracker_does_not_accumulate_delta_history() -> None: + stats = CollectorStatsTracker(0, num_envs=1, device=torch.device("cpu")) + stats.add_episodes([2.0], [3]) + assert stats.snapshot().episodes == 1 + assert stats.take_episodes().returns == () diff --git a/motrix_rl/tests/test_console.py b/motrix_rl/tests/test_console.py index 1c288abc7..6f6b85fd4 100644 --- a/motrix_rl/tests/test_console.py +++ b/motrix_rl/tests/test_console.py @@ -11,7 +11,8 @@ import motrix_rl.console.panel as console_module from motrix_rl.console import TrainingPanelSession, TrainingPanelStats, format_training_panel, render_training_panel -from motrix_rl.console.panel import _compact_metric_value, _format_memory, _format_value +from motrix_rl.console.boot import BootWorker +from motrix_rl.console.panel import TimingNode, _compact_metric_value, _format_memory, _format_value from motrix_rl.system_metrics import CpuLoad, MemoryUsage @@ -20,11 +21,13 @@ def test_training_panel_session_submits_and_closes(monkeypatch) -> None: monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) monkeypatch.setattr(console_module, "emit_training_panel", lambda live, stats, **kwargs: rendered.append(stats)) session = TrainingPanelSession.open(title="test", interval_seconds=60.0) + phase = session.metrics_panel(total_iterations=100) stats = _panel_stats() - session.submit(stats) + phase._emit(stats) session.close() session.close() - assert rendered == [stats, stats] + assert rendered[0] is stats + assert rendered[-1].iteration == 0 # close flushes the active metric counters def test_format_value_uses_fixed_notation_for_regular_floats() -> None: @@ -70,24 +73,24 @@ def test_format_training_panel_groups_timing_metrics() -> None: elapsed_seconds=1.0, mean_return=0.0, mean_episode_length=0.0, - episodes=0, buffer_size=0, buffer_capacity=1, collect_ms=2.0, learn_ms=3.0, learn_percent=0.0, - timing_groups={"collector": {"wait_ms": 4.0, "env_step_ms": 1.5}}, + timings=(TimingNode("collector", None, (TimingNode("wait_ms", 4.0), TimingNode("env_step_ms", 1.5))),), ) panel = format_training_panel(stats) - assert "collector wait_ms 4.000" in panel + assert "collector" in panel + assert "wait_ms 4.000" in panel assert "env_step_ms 1.500" in panel assert "collector_wait_ms" not in panel assert "collect 2.0ms" not in panel # standalone timing row suppressed for tree panels -def test_format_training_panel_renders_nested_timing_groups_as_tree() -> None: +def test_format_training_panel_renders_nested_timing_nodes_as_tree() -> None: stats = TrainingPanelStats( iteration=1, total_iterations=10, @@ -95,28 +98,29 @@ def test_format_training_panel_renders_nested_timing_groups_as_tree() -> None: elapsed_seconds=1.0, mean_return=0.0, mean_episode_length=0.0, - episodes=0, buffer_size=0, buffer_capacity=1, collect_ms=2.0, learn_ms=3.0, learn_percent=0.0, - timing_groups={ - "learner(ms)": { - "drain": 0.5, - "update": {"total": 3.0, "critic_alpha": 2.0, "actor": 1.0}, - }, - }, + timings=( + TimingNode( + "learner(ms)", + None, + ( + TimingNode("drain", 0.5), + TimingNode("update", 3.0, (TimingNode("critic_alpha", 2.0), TimingNode("actor", 1.0))), + ), + ), + ), ) panel = format_training_panel(stats) assert "drain 0.500" in panel - assert sum(1 for line in panel.splitlines() if line.strip() == "└─ update 3.000") == 1 - child_lines = [line for line in panel.splitlines() if line.lstrip().startswith("└─ critic_alpha 2.000")] - assert len(child_lines) == 1 - assert child_lines[0].startswith(" " * 22) - assert "actor 1.000" in child_lines[0] + assert "└─ update 3.000 ms" in panel + assert " ├─ critic_alpha 2.000 ms 67%" in panel + assert " └─ actor 1.000 ms 33%" in panel def test_format_training_panel_strips_markup_from_group_titles() -> None: @@ -127,13 +131,12 @@ def test_format_training_panel_strips_markup_from_group_titles() -> None: elapsed_seconds=1.0, mean_return=0.0, mean_episode_length=0.0, - episodes=0, buffer_size=0, buffer_capacity=1, collect_ms=2.0, learn_ms=3.0, learn_percent=0.0, - timing_groups={"learner [magenta]3.0[/]ms": {"drain": 0.5}}, + timings=(TimingNode("learner [magenta]3.0[/]ms", None, (TimingNode("drain", 0.5),)),), ) panel = format_training_panel(stats) @@ -151,7 +154,6 @@ def test_format_training_panel_shows_cpu_load_with_explicit_topology() -> None: elapsed_seconds=1.0, mean_return=0.0, mean_episode_length=0.0, - episodes=0, buffer_size=0, buffer_capacity=1, collect_ms=2.0, @@ -182,7 +184,6 @@ def _panel_stats(**overrides: Any) -> TrainingPanelStats: elapsed_seconds=1.0, mean_return=1.5, mean_episode_length=8.0, - episodes=4, buffer_size=512, buffer_capacity=100_000, collect_ms=2.0, @@ -202,10 +203,17 @@ def _render_panel(stats: TrainingPanelStats, *, view: str = "overview", width: i def test_render_training_panel_overview_keeps_timing_tree_hidden() -> None: stats = _panel_stats( - timing_groups={ - "collector": {"env_step": 1.0, "sync": {"total": 0.5, "weights": 0.25}}, - "learner": {"update": {"total": 3.0, "critic": 2.0}}, - }, + timings=( + TimingNode( + "collector", + 2.0, + ( + TimingNode("env_step", 1.0), + TimingNode("sync", 0.5, (TimingNode("weights", 0.25),)), + ), + ), + TimingNode("learner", 3.0, (TimingNode("update", 3.0, (TimingNode("critic", 2.0),)),)), + ), ) panel = _render_panel(stats) @@ -217,8 +225,6 @@ def test_render_training_panel_overview_keeps_timing_tree_hidden() -> None: assert "elapsed" in panel assert "left" in panel assert "System health" in panel - assert "Training (" in panel - assert "Environment metrics (" in panel # per-stage timing belongs to the detail view only assert "STAGE" not in panel assert "env_step" not in panel @@ -226,20 +232,26 @@ def test_render_training_panel_overview_keeps_timing_tree_hidden() -> None: def test_render_training_panel_detail_view_shows_timing_tree_with_shares() -> None: stats = _panel_stats( - timing_groups={ - "collector": { - "env_step": { - "total": 18.0, - "apply_action": 1.0, - "physics": {"total": 15.0, "read": 12.0}, - "reset": 2.0, - }, - "sync": {"total": 0.5, "weights": 0.25}, - }, - "learner": {"update": {"total": 3.0, "critic": 2.0}}, - }, - timing_metrics={"queue_depth": 1.0}, - diagnostics={"UTD": 0.5}, + timings=( + TimingNode( + "collector", + 20.0, + ( + TimingNode( + "env_step", + 18.0, + ( + TimingNode("apply_action", 1.0), + TimingNode("physics", 15.0, (TimingNode("read", 12.0),)), + TimingNode("reset", 2.0), + ), + ), + TimingNode("sync", 0.5, (TimingNode("weights", 0.25),)), + ), + ), + TimingNode("learner", 3.0, (TimingNode("update", 3.0, (TimingNode("critic", 2.0),)),)), + ), + metrics={"timing/queue_depth": 1.0, "diagnostics/UTD": 0.5}, ) overview = _render_panel(stats) @@ -250,8 +262,10 @@ def test_render_training_panel_detail_view_shows_timing_tree_with_shares() -> No assert "collector" in detail assert "learner" in detail assert "env_step" in detail - assert "Timing detail" in detail - assert "Diagnostics" in detail + assert "queue_depth" in overview + assert "queue_depth" not in detail + assert "diagnostics (1)" in overview + assert "diagnostics (1)" not in detail # env_step sub-stages render as an indented subtree under their total, # with second-level stages (physics -> read) nested one level deeper assert "apply_action" in detail @@ -262,6 +276,47 @@ def test_render_training_panel_detail_view_shows_timing_tree_with_shares() -> No assert "%" in detail +@pytest.mark.parametrize("rich", [False, True]) +def test_metrics_group_by_first_slash_with_literal_relative_labels(rich: bool) -> None: + metrics = { + "custom/optimizer/loss": 0.25, + "custom/return": -0.5, + "standalone": 2.0, + "ungrouped/standalone": 3.0, + "[red]literal/value": 4.0, + "episode/return": 5.0, + "runtime/env_steps": 6.0, + "timing/update_ms": 7.0, + "sys/cpu_percent": 8.0, + } + stats = _panel_stats(metrics=metrics) + text = _render_panel(stats) if rich else format_training_panel(stats) + + assert "optimizer/loss" in text + assert "custom/optimizer/loss" not in text + assert "[red]literal" in text + assert "standalone" in text + assert "2.000" in text and "3.000" in text + assert "-0.500" in text + assert "+0.250" not in text + for group, label in ( + ("episode", "return"), + ("runtime", "env_steps"), + ("timing", "update_ms"), + ("sys", "cpu_percent"), + ): + assert group in text and label in text + assert text.index("optimizer/loss") < text.index("-0.500") # insertion order, not magnitude + assert stats.metrics == metrics # rendering never rewrites canonical identities + + +def test_metric_relative_labels_preserve_full_paths() -> None: + label = "optimizer/nested/long_metric_label" + stats = _panel_stats(metrics={f"custom/{label}": 0.125}) + assert label in _render_panel(stats, width=240) + assert label in format_training_panel(stats) + + def test_render_training_panel_shows_saved_checkpoint_path() -> None: panel = _render_panel(_panel_stats(checkpoint_path="/runs/cartpole/model_0000002.pt")) @@ -402,15 +457,14 @@ def test_compact_metric_value_fits_the_nine_char_value_cell() -> None: def test_render_training_panel_keeps_metric_values_on_their_label_line(monkeypatch) -> None: stats = _panel_stats( - reward_terms={"torque": -3.62e-05, "action_rate": -0.0123}, - training_metrics={"alpha_loss": 1.235e-04}, + metrics={"reward/torque": -3.62e-05, "reward/action_rate": -0.0123, "train/alpha_loss": 1.235e-04}, ) for width in (120, 150, 190): monkeypatch.setenv("COLUMNS", str(width)) lines = _render_panel(stats, width=width).splitlines() assert any("torque" in line and "e-05" in line for line in lines), f"wrapped at width {width}" - assert any("action_rate" in line and "-0.0123" in line for line in lines), f"wrapped at width {width}" + assert any("action_rate" in line and "-0.012" in line for line in lines), f"wrapped at width {width}" assert any("alpha_loss" in line and "e-04" in line for line in lines), f"wrapped at width {width}" @@ -444,3 +498,228 @@ def test_console_module_degrades_without_posix_tty_support(_reload_console_modul stats = _panel_stats() assert "Run progress" in _render_panel(stats) assert "iter" in reloaded.format_training_panel(stats) + + +def test_resume_eta_uses_invocation_progress_not_absolute_iteration() -> None: + from motrix_rl.console.panel import _eta_seconds, _iter_rate_text + + resumed = _panel_stats(iteration=1000, initial_iteration=990, total_iterations=1010, elapsed_seconds=10.0) + assert _eta_seconds(resumed) == 10.0 + assert "1 iter/s" in _iter_rate_text(resumed) + rolling = _panel_stats(iteration=1000, total_iterations=1010, elapsed_seconds=10.0, iterations_per_second=0.5) + assert _eta_seconds(rolling) == 20.0 # rolling rate wins over cumulative delta + fresh_done = _panel_stats(iteration=10, total_iterations=10, elapsed_seconds=5.0) + assert _eta_seconds(fresh_done) == 0.0 + no_progress = _panel_stats(iteration=1000, initial_iteration=1000, total_iterations=1010, elapsed_seconds=5.0) + assert _eta_seconds(no_progress) is None + + +@pytest.mark.parametrize("rich", [False, True]) +def test_unavailable_episode_values_render_as_na_not_zero(rich) -> None: + stats = _panel_stats(mean_return=None, mean_episode_length=None) + text = format_training_panel(stats) if not rich else _render_panel(stats) + assert "n/a" in text + assert "nan" not in text + + +def test_format_training_panel_hides_buffer_row_without_storage() -> None: + stats = _panel_stats(buffer_size=None, buffer_capacity=None) + assert "buffer" not in format_training_panel(stats) + assert " buffer 3/8" in format_training_panel(_panel_stats(buffer_size=3, buffer_capacity=8)) + + +def test_plain_text_fallback_shows_checkpoint_path() -> None: + rendered = [] + monkeypatch = pytest.MonkeyPatch() + monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) + monkeypatch.setattr(console_module, "emit_training_panel", lambda live, stats, **k: rendered.append(stats)) + try: + session = TrainingPanelSession.open(title="test", interval_seconds=60.0) + phase = session.metrics_panel(total_iterations=100) + phase.event("checkpoint_saved", iteration=0, data={"path": "/tmp/ckpt.pt"}) + stats = _panel_stats(checkpoint_path="/tmp/ckpt.pt") + phase._emit(stats) + finally: + monkeypatch.undo() + assert phase._last_checkpoint == "/tmp/ckpt.pt" + + +def test_due_gates_refresh_until_first_submitted_frame(monkeypatch) -> None: + monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) + monkeypatch.setattr(console_module, "emit_training_panel", lambda live, stats, **k: None) + session = TrainingPanelSession.open(title="test", interval_seconds=60.0) + phase = session.metrics_panel(total_iterations=100) + assert phase.due() + stats = _panel_stats() + phase._emit(stats) + assert not phase.due() # submit refreshed immediately on first frame + session.close() + assert session._closed + + +@pytest.mark.parametrize("duration", [None, 0.0]) +def test_timing_share_requires_positive_parent_duration(duration: float | None) -> None: + stats = _panel_stats(timings=(TimingNode("collector", duration, (TimingNode("collect", 5.0),)),)) + assert "SHARE" not in _render_panel(stats, view="timing") + assert all("%" not in line for line in format_training_panel(stats).splitlines() if "collect 5.000" in line) + + +@pytest.mark.parametrize("rich", [False, True]) +def test_timing_shares_use_direct_parent_not_sibling_sum_or_other_roots(rich: bool) -> None: + stats = _panel_stats( + timings=( + TimingNode( + "collector", + 20.0, + ( + TimingNode("env_step", 10.0, (TimingNode("physics", 8.0),)), + TimingNode("organization", None, (TimingNode("unscoped", 7.0),)), + ), + ), + TimingNode("learner", 100.0, (TimingNode("optimize", 25.0),)), + ) + ) + rendered = _render_panel(stats, view="timing") if rich else format_training_panel(stats) + for name, share in (("env_step", "50%"), ("physics", "80%"), ("optimize", "25%")): + assert any(name in line and share in line for line in rendered.splitlines()) + for name in ("organization", "unscoped"): + assert all("%" not in line for line in rendered.splitlines() if name in line) + + +def test_boot_plain_output_reports_changes_without_log_frames(monkeypatch, capsys) -> None: + monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) + session = console_module.TrainingPanelSession.open() + boot = session.boot_panel((BootWorker("collector"),)) + boot.message("waiting") + boot.refresh() # plain mode has no frame to redraw; events carry the output + boot.mark_ready("collector") + boot.message("building learner") + session.close() + assert capsys.readouterr().out.splitlines() == [ + "waiting", + "collector: ready", + "building learner", + ] + + +def test_boot_and_training_share_live_and_close_once(monkeypatch) -> None: + updates = [] + stopped = [] + + class RecordingLive: + def update(self, frame, *, refresh: bool) -> None: + updates.append(frame) + + def stop(self) -> None: + stopped.append(True) + + live = RecordingLive() + console = Console(width=100, height=24) + monkeypatch.setattr(console_module, "open_training_live", lambda **kwargs: (console, live)) + monkeypatch.setattr( + console_module, "emit_training_panel", lambda target, stats, **kwargs: target.update(stats, refresh=True) + ) + session = console_module.TrainingPanelSession.open(screen=True, interval_seconds=60.0) + boot = session.boot_panel((BootWorker("collector"),)) + boot.message("waiting") + boot.refresh() + boot.refresh() # throttled: no event within the interval + assert len(updates) == 1 + boot.mark_ready("collector") + assert len(updates) == 2 # readiness events redraw immediately + phase = session.metrics_panel(total_iterations=100) + stats = _panel_stats() + phase._emit(stats) + assert updates[-1] is stats + session.close() + session.close() + assert updates[-1].iteration == phase.iteration # closing flushes active metrics, then stops + assert stopped == [True] + + +def test_replaced_boot_handles_do_not_update_or_print(monkeypatch, capsys) -> None: + monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) + session = TrainingPanelSession.open() + old = session.boot_panel((BootWorker("old"),)) + current = session.boot_panel((BootWorker("new"),)) + old.message("retired") + old.mark_ready("old") + old.start() + old.refresh() + assert old._ready == set() + assert not old._started + current.message("active") + phase = session.metrics_panel(total_iterations=10) + current.message("retired after metrics") + current.mark_ready("new") + phase.record({"train/loss": 1.0}) + # A boot phase after training must not reconstruct a final training frame. + final = session.boot_panel((BootWorker("final"),)) + final.message("last boot") + session.close() + final.message("closed") + assert capsys.readouterr().out.splitlines() == ["active", "last boot"] + + +def test_boot_exception_stops_same_live(monkeypatch) -> None: + stopped = [] + + class RecordingLive: + def update(self, frame, *, refresh: bool) -> None: + pass + + def stop(self) -> None: + stopped.append(True) + + monkeypatch.setattr(console_module, "open_training_live", lambda **kwargs: (Console(), RecordingLive())) + with pytest.raises(RuntimeError, match="startup failed"): + with console_module.TrainingPanelSession.open(screen=True) as session: + session.boot_panel((BootWorker("collector"),)).message("waiting") + raise RuntimeError("startup failed") + assert stopped == [True] + + +@pytest.mark.parametrize("rich", [False, True]) +def test_overview_hides_exact_projected_keys_not_groups(rich: bool) -> None: + metrics = { + "throughput/env_steps_per_s": 100.0, + "throughput/iterations_per_s": 2.0, + "throughput/extra": 3.0, + "custom/projected": 4.0, + "custom/projected/nested": 5.0, + } + stats = _panel_stats( + metrics=metrics, + overview_hidden_metrics=frozenset( + ("throughput/env_steps_per_s", "throughput/iterations_per_s", "custom/projected") + ), + ) + text = _render_panel(stats) if rich else format_training_panel(stats) + assert "env_steps_per_s" not in text + assert "iterations_per_s" not in text + assert "extra" in text + assert "projected/nested" in text + assert "throughput" in text + assert "custom" in text + assert stats.metrics == metrics + + +@pytest.mark.parametrize("view", ["overview", "timing", "system"]) +@pytest.mark.parametrize("show_throughput", [False, True]) +@pytest.mark.parametrize("show_episode_summary", [False, True]) +def test_optional_summary_cards_leave_only_filled_columns( + view: str, show_throughput: bool, show_episode_summary: bool +) -> None: + stats = _panel_stats(show_throughput=show_throughput, show_episode_summary=show_episode_summary) + frame = render_training_panel(stats, view=view) + summary = frame.renderable.renderables[0] + assert len(summary.columns) == 3 + show_throughput + show_episode_summary + assert all(len(column._cells) == 1 for column in summary.columns) + text = _render_panel(stats, view=view) + assert ("Throughput" in text) is show_throughput + assert ("Episode stats" in text) is show_episode_summary + for label in ("Run progress", "Timing", "System health"): + assert label in text + plain = format_training_panel(stats) + assert ("env-steps/s" in plain) is show_throughput + assert ("rollout" in plain) is show_episode_summary diff --git a/motrix_rl/tests/test_log_schedule.py b/motrix_rl/tests/test_log_schedule.py new file mode 100644 index 000000000..c79458fed --- /dev/null +++ b/motrix_rl/tests/test_log_schedule.py @@ -0,0 +1,25 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +from motrix_rl.log.schedule import IterationLogSchedule + + +def test_skipped_boundaries_emit_current_window_once() -> None: + schedule = IterationLogSchedule(20) + assert not schedule.due(19) + assert schedule.due(23) + schedule.mark_logged(23) + assert not schedule.due(23) + assert not schedule.due(39) + assert schedule.due(81) + schedule.mark_logged(81) + assert not schedule.due(81) + assert not schedule.due(99) + assert schedule.due(100) + + +def test_resume_starts_after_baseline() -> None: + schedule = IterationLogSchedule(20, initial_iteration=45) + assert not schedule.due(45) + assert not schedule.due(59) + assert schedule.due(60) diff --git a/motrix_rl/tests/test_log_system_metrics.py b/motrix_rl/tests/test_log_system_metrics.py new file mode 100644 index 000000000..dcbcfefbf --- /dev/null +++ b/motrix_rl/tests/test_log_system_metrics.py @@ -0,0 +1,35 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +from motrix_rl.log.system_metrics import system_scalars +from motrix_rl.system_metrics import CpuLoad, GpuDeviceUsage, MemoryUsage, SystemStats + + +def test_system_scalars_use_the_fixed_key_list(): + gib = 1024**3 + stats = SystemStats( + gpu_utilization_percent=None, + gpu_memory_usage=None, + cpu_load=CpuLoad( + utilization_percent=37.5, + used_logical_cpus=3.0, + logical_cpu_count=8, + physical_core_count=4, + iowait_percent=0.0, + steal_percent=0.0, + per_core_percent=(37.5,) * 8, + ), + memory_usage=MemoryUsage(used_bytes=3 * gib, total_bytes=16 * gib), + gpu_devices=[ + GpuDeviceUsage(index=0, utilization_percent=55.0, memory=MemoryUsage(used_bytes=2 * gib, total_bytes=gib)), + GpuDeviceUsage(index=1, utilization_percent=None, memory=None), + ], + ) + + assert system_scalars(stats) == { + "sys/cpu_percent": 37.5, + "sys/mem_used_gb": 3.0, + "sys/gpu0/util_percent": 55.0, + "sys/gpu0/mem_used_gb": 2.0, + } + assert system_scalars(SystemStats(None, None, None, None, None)) == {} diff --git a/motrix_rl/tests/test_metric_panel.py b/motrix_rl/tests/test_metric_panel.py new file mode 100644 index 000000000..7039dcbb3 --- /dev/null +++ b/motrix_rl/tests/test_metric_panel.py @@ -0,0 +1,440 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +from collections.abc import Iterator +from typing import Literal + +import pytest +from rich.console import Console + +from motrix_rl.console.metric_panel import MetricsPanel +from motrix_rl.console.panel import ( + EpisodeSummary, + ThroughputSummary, + TimingView, + TrainingPanelSession, + format_training_panel, + render_training_panel, +) +from motrix_rl.log.accumulator import MetricAccumulator +from motrix_rl.system_metrics import SystemStats + + +@pytest.fixture +def panel(monkeypatch: pytest.MonkeyPatch) -> Iterator[MetricsPanel]: + class Sampler: + def sample(self) -> SystemStats: + return SystemStats(None, None, None, None, None) + + monkeypatch.setattr("motrix_rl.console.metric_panel.SystemSampler", Sampler) + session = TrainingPanelSession(interval_seconds=100.0) + phase = session.metrics_panel( + total_iterations=100, + initial_iteration=0, + initial_env_steps=0, + reductions={"train/loss": "mean"}, + ) + yield phase + session.close() + + +def test_metric_prefixes_and_unknown_groups_remain_visible(panel: MetricsPanel) -> None: + panel.record( + { + "train/loss": 2.0, + "env/speed": 3.0, + "reward/alive": 1.0, + "collector/lag": 4.0, + "learner/updates": 5.0, + "learner/buffer_size": 50.0, + "learner/buffer_capacity": 100.0, + "learner/learn_percent": 40.0, + "async/ratio": 6.0, + "episode/recent_return_mean": 10.0, + "episode/recent_length_mean": 20.0, + "learner/replay_warming": 1.0, + "custom/score": 42.0, + "sys/custom": 9.0, + "unprefixed": 8.0, + } + ) + panel.flush() + stats = panel._latest + assert stats is not None + assert stats.metrics["train/loss"] == 2.0 + assert stats.metrics["env/speed"] == 3.0 + assert stats.metrics["reward/alive"] == 1.0 + assert stats.metrics["collector/lag"] == 4.0 + assert stats.buffer_size == 50.0 + assert stats.buffer_capacity == 100.0 + assert stats.learn_percent == 40.0 + assert stats.mean_return == 10.0 + assert stats.mean_episode_length == 20.0 + assert stats.warming + assert stats.metrics["custom/score"] == 42.0 + assert stats.metrics["sys/custom"] == 9.0 + assert stats.metrics["unprefixed"] == 8.0 + assert "custom" in format_training_panel(stats) + assert "score 42" in format_training_panel(stats) + console = Console(record=True, width=160) + console.print(render_training_panel(stats)) + rendered = console.export_text() + assert "custom" in rendered and "score" in rendered + + +def test_panel_mean_window_is_independent_and_keeps_latest_values(panel: MetricsPanel) -> None: + other = MetricAccumulator({"train/loss": "mean"}) + for value in (1.0, 3.0): + panel.record({"train/loss": value}) + other.record({"train/loss": value}) + assert other.snapshot() == {"train/loss": 2.0} + other.clear() + panel.record({"train/loss": [5.0, 7.0], "env/speed": 4.0}) + panel.flush() + assert panel._latest.metrics["train/loss"] == 4.0 + panel.record({"train/loss": [10.0, 14.0]}) + panel.flush() # Not due: the new window must not be drained. + assert panel._latest.metrics["train/loss"] == 4.0 + panel.record({"train/loss": 18.0}) + panel.flush(force=True) + assert panel._latest.metrics["train/loss"] == 14.0 + assert panel._latest.metrics["env/speed"] == 4.0 + assert "env/missing" not in panel._latest.metrics + panel.flush(force=True) + assert panel._latest.metrics["train/loss"] == 14.0 + + +def test_progress_and_rates_start_from_resume_baseline(panel: MetricsPanel, monkeypatch: pytest.MonkeyPatch) -> None: + now = [100.0] + monkeypatch.setattr("time.monotonic", lambda: now[0]) + panel = panel._session.metrics_panel(total_iterations=100, initial_iteration=40, initial_env_steps=10000) + now[0] = 102.0 + panel.advance(iterations=2, env_steps=200) + panel.record({"throughput/env_steps_per_s": 75.0, "throughput/iterations_per_s": 0.75}) + panel.flush(force=True) + stats = panel._latest + assert stats.iteration == 42 + assert stats.initial_iteration == 40 + assert stats.total_iterations == 100 + assert stats.elapsed_seconds == 2.0 + # Summary rates are observations, not a second calculation from progress. + assert stats.steps_per_second == 75.0 + assert stats.iterations_per_second == 0.75 + assert stats.mean_return is None + assert stats.mean_episode_length is None + + +def test_timing_paths_use_explicit_parent_durations(panel: MetricsPanel) -> None: + panel.record( + { + "timing/collector/total_s": 0.5, + "timing/collector/env_step_s": 0.2, + "timing/collector/env_step/physics_s": 0.1, + "timing/learner/total_s": 0.4, + "timing/learner/update/critic_s": 0.3, + } + ) + panel.flush() + collector, learner = panel._latest.timings + assert collector.name == "collector" + assert collector.duration_ms == 500.0 + assert collector.children[0].name == "env_step" + assert collector.children[0].duration_ms == 200.0 + assert collector.children[0].children[0].duration_ms == 100.0 + assert learner.duration_ms == 400.0 + # Concurrent collector/learner roots do not define a serial percentage. + assert panel._latest.learn_percent == 0.0 + assert learner.children[0].duration_ms is None + assert learner.children[0].children[0].duration_ms == 300.0 + + +@pytest.mark.parametrize("flush_between", [False, True], ids=["same-window", "across-frames"]) +@pytest.mark.parametrize("reduction", ["last", "mean"]) +def test_complete_timing_report_replaces_only_its_root( + panel: MetricsPanel, flush_between: bool, reduction: Literal["last", "mean"] +) -> None: + panel = panel._session.metrics_panel( + total_iterations=100, + initial_iteration=0, + initial_env_steps=0, + reductions={ + "timing/learner/total_s": reduction, + "timing/learner/update_s": reduction, + "timing/learner/removed_s": reduction, + }, + ) + panel.record( + { + "timing/collector/total_s": 0.5, + "timing/collector/env_step_s": 0.2, + "timing/learner/total_s": 0.1, + "timing/learner/update_s": 0.04, + "timing/learner/removed_s": 0.02, + "timing/learner/removed_count": 2.0, + } + ) + if flush_between: + panel.flush(force=True) + panel.record({"timing/learner/total_s": 0.3, "timing/learner/update_s": 0.08}) + panel.flush(force=True) + stats = panel._latest + collector, learner = stats.timings + assert collector.duration_ms == 500.0 + assert collector.children[0].duration_ms == 200.0 + assert [child.name for child in learner.children] == ["update"] + assert "timing/learner/removed_count" not in stats.metrics + mean_window = reduction == "mean" and not flush_between + assert learner.duration_ms == pytest.approx(200.0 if mean_window else 300.0) + assert learner.children[0].duration_ms == pytest.approx(60.0 if mean_window else 80.0) + + # Reports without a new total do not invalidate any existing timing root. + panel.record({"train/loss": 4.0}) + panel.flush(force=True) + assert panel._latest.timings == stats.timings + panel.record({"timing/learner/wait_s": 0.01}) + panel.flush(force=True) + retained_learner = panel._latest.timings[1] + assert retained_learner.duration_ms == learner.duration_ms + assert retained_learner.children[0] == learner.children[0] + assert retained_learner.children[1].name == "wait" + assert retained_learner.children[1].duration_ms == 10.0 + panel.record({"timing/collector/total_s": 0.6}) + panel.flush(force=True) + collector, final_learner = panel._latest.timings + assert collector.duration_ms == 600.0 + assert collector.children == () + assert final_learner == retained_learner + + +def test_timing_mean_retains_all_samples_for_surviving_keys(panel: MetricsPanel) -> None: + panel = panel._session.metrics_panel( + total_iterations=100, + initial_iteration=0, + initial_env_steps=0, + reductions={"timing/learner/total_s": "mean", "timing/learner/update_s": "mean"}, + ) + panel.record({"timing/learner/total_s": [0.1, 0.2], "timing/learner/update_s": [0.01, 0.02]}) + panel.record({"timing/learner/total_s": [0.3], "timing/learner/update_s": [0.03]}) + panel.flush(force=True) + learner = panel._latest.timings[0] + assert learner.duration_ms == pytest.approx(200.0) + assert learner.children[0].duration_ms == pytest.approx(20.0) + + +@pytest.mark.parametrize("single_learner", [False, True]) +def test_learner_overview_uses_concurrent_worker_mean(panel: MetricsPanel, single_learner: bool) -> None: + values = { + "timing/learner[0]/total_s": 0.1, + "timing/learner[1]/total_s": 0.2, + "timing/learner[2]/total_s": float("nan"), + "timing/learner[3]/total_s": float("inf"), + "timing/learner[4]/total_s": -0.1, + "timing/learner[0]/update_s": 0.05, + } + if single_learner: + values["timing/learner/total_s"] = 0.4 + panel.record(values) + panel.flush(force=True) + assert panel._latest.learn_ms == pytest.approx(400.0 if single_learner else 150.0) + + +def test_replaced_metrics_phase_ignores_events_and_sampling(panel: MetricsPanel, monkeypatch, capsys) -> None: + panel.record({"train/loss": 2.0}) + panel.flush() + previous = panel._latest + session = panel._session + active = session.metrics_panel(total_iterations=10) + monkeypatch.setattr(panel._system, "sample", lambda: pytest.fail("retired phase sampled hardware")) + capsys.readouterr() + panel.record({"train/loss": 9.0}) + panel.advance(iterations=3, env_steps=12) + panel.start(now=0.0) + panel.event("checkpoint_saved", iteration=0, data={"path": "retired.pt"}) + panel.flush(force=True) + assert not panel.due() + assert panel.snapshot() is previous + assert panel.iteration == 0 + assert panel.env_steps == 0 + assert capsys.readouterr().out == "" + active.record({"train/loss": 4.0}) + active.advance(env_steps=5) + session.close() + assert active._latest.metrics["train/loss"] == 4.0 + assert active._latest.iteration == 1 + assert active.env_steps == 5 + + +def test_close_flushes_pending_window_once(panel: MetricsPanel, monkeypatch) -> None: + rendered = [] + session = panel._session + monkeypatch.setattr(session, "_draw", rendered.append) + panel.record({"train/loss": 2.0}) + panel.flush() + panel.record({"train/loss": [4.0, 8.0]}) + panel.advance(env_steps=20) + panel.event("checkpoint_saved", iteration=0, data={"path": "latest.pt"}) + session.close() + session.close() + assert len(rendered) == 3 # initial, checkpoint annotation, final pending window + assert rendered[-1].metrics == {"train/loss": 6.0} + assert rendered[-1].checkpoint_path == "latest.pt" + assert rendered[-1].iteration == 1 + panel.record({"train/loss": 100.0}) + panel.advance(env_steps=100) + assert panel.iteration == 1 + assert panel.env_steps == 20 + assert not panel.due() + + +def test_phase_default_reduction_is_used(panel: MetricsPanel) -> None: + phase = panel._session.metrics_panel(total_iterations=10, default_reduction="mean") + phase.record({"custom/value": [2.0, 4.0]}) + phase.flush() + assert phase._latest.metrics == {"custom/value": 3.0} + + +@pytest.mark.parametrize( + "summary", + [ThroughputSummary(), ThroughputSummary(env_steps_key="custom/steps", iterations_key="custom/iters"), None], + ids=["canonical", "custom", "disabled"], +) +def test_throughput_summary_projects_only_configured_observations( + panel: MetricsPanel, summary: ThroughputSummary | None +) -> None: + phase = panel._session.metrics_panel(total_iterations=100, throughput_summary=summary) + metrics = { + "throughput/env_steps_per_s": 123.0, + "throughput/iterations_per_s": 4.0, + "throughput/extra": 5.0, + "custom/steps": 456.0, + "custom/iters": 7.0, + "custom/extra": 8.0, + } + phase.record(metrics) + phase.advance(env_steps=999) + stats = phase.snapshot() + assert stats.metrics == metrics + assert stats.show_throughput is (summary is not None) + if summary is None: + assert stats.steps_per_second is None + assert stats.iterations_per_second is None + assert stats.overview_hidden_metrics == frozenset() + else: + assert stats.steps_per_second == metrics[summary.env_steps_key] + assert stats.iterations_per_second == metrics[summary.iterations_key] + assert stats.overview_hidden_metrics == frozenset((summary.env_steps_key, summary.iterations_key)) + + +@pytest.mark.parametrize( + "summary", + [EpisodeSummary(), EpisodeSummary(return_key="custom/return", length_key="custom/length"), None], + ids=["canonical", "custom", "disabled"], +) +@pytest.mark.parametrize("rich", [False, True]) +def test_episode_summary_projects_only_configured_observations( + panel: MetricsPanel, summary: EpisodeSummary | None, rich: bool +) -> None: + phase = panel._session.metrics_panel(total_iterations=100, episode_summary=summary) + metrics = { + "episode/recent_return_mean": 12.0, + "episode/recent_length_mean": 34.0, + "episode/recent_return_mean/nested": 56.0, + "episode/extra": 78.0, + "custom/return": 90.0, + "custom/length": 123.0, + } + phase.record(metrics) + stats = phase.snapshot() + assert stats.metrics == metrics + assert stats.show_episode_summary is (summary is not None) + if summary is None: + assert stats.mean_return is None + assert stats.mean_episode_length is None + assert stats.overview_hidden_metrics == frozenset() + else: + assert stats.mean_return == metrics[summary.return_key] + assert stats.mean_episode_length == metrics[summary.length_key] + assert stats.overview_hidden_metrics == frozenset((summary.return_key, summary.length_key)) + if rich: + console = Console(record=True, width=200) + console.print(render_training_panel(stats)) + text = console.export_text() + assert ("Episode stats" in text) is (summary is not None) + else: + text = format_training_panel(stats) + assert ("rollout" in text) is (summary is not None) + assert "recent_return_mean/nested" in text + assert "extra" in text + for key in metrics: + if key not in stats.overview_hidden_metrics: + assert key.partition("/")[2] in text + # The canonical labels cannot leak from the summary into ordinary rows. + if summary == EpisodeSummary(): + assert "recent_length_mean" not in text + assert stats.metrics == metrics + + +def test_missing_episode_observations_hide_only_present_exact_keys(panel: MetricsPanel) -> None: + panel.record({"episode/extra": 3.0}) + stats = panel.snapshot() + assert stats.mean_return is None + assert stats.mean_episode_length is None + assert stats.show_episode_summary + assert stats.overview_hidden_metrics == frozenset() + panel.record({"episode/recent_return_mean": 0.0}) + stats = panel.snapshot() + assert stats.mean_return == 0.0 + assert stats.mean_episode_length is None + assert stats.overview_hidden_metrics == frozenset(("episode/recent_return_mean",)) + + +def test_missing_throughput_observations_keep_summary_measuring_and_other_metrics(panel: MetricsPanel) -> None: + panel.advance(iterations=10, env_steps=1000) + panel.record({"throughput/extra": 3.0, "custom/score": 4.0}) + stats = panel.snapshot() + assert stats.steps_per_second is None + assert stats.iterations_per_second is None + assert stats.show_throughput + assert stats.overview_hidden_metrics == frozenset() + rendered = format_training_panel(stats) + assert "measuring…" in rendered + assert "extra 3.000" in rendered + assert "score 4.000" in rendered + panel.record({"throughput/iterations_per_s": 0.0}) + stats = panel.snapshot() + assert stats.iterations_per_second == 0.0 + assert stats.overview_hidden_metrics == frozenset(("throughput/iterations_per_s",)) + + +@pytest.mark.parametrize("overview", [False, True]) +def test_explicit_timing_route_preserves_full_data_and_non_duration_values(overview): + session = TrainingPanelSession(interval_seconds=0) + phase = session.metrics_panel(total_iterations=10, timing_view=TimingView(overview=overview)) + phase.record( + {"timing/learner/total_s": 0.5, "timing/learner/update_s": 0.4, "timing/queue_depth": 3.0, "train/loss": 1.0} + ) + stats = phase.snapshot() + assert stats.metrics["timing/learner/update_s"] == 0.4 + assert ("timing/learner/update_s" in stats.overview_hidden_metrics) == (not overview) + assert stats.timing_extras == {"timing/queue_depth": 3.0} + console = Console(record=True, width=160) + console.print(render_training_panel(stats)) + text = console.export_text() + assert ("learner/update_s" in text) == overview + console.print(render_training_panel(stats, view="timing")) + text = console.export_text() + assert "update" in text and "queue_depth" in text + assert "queue_depth" in format_training_panel(stats) + session.close() + + +def test_custom_timing_namespace_is_routed_without_hiding_other_prefixes(): + session = TrainingPanelSession(interval_seconds=0) + phase = session.metrics_panel(total_iterations=2, timing_view=TimingView(prefix="profile/")) + phase.record({"profile/collector/total_s": 0.2, "profile/collector/env_s": 0.1, "timing/custom": 2.0}) + stats = phase.snapshot() + assert stats.collect_ms == 200.0 + assert stats.timings[0].children[0].name == "env" + assert "profile/collector/env_s" in stats.overview_hidden_metrics + assert "timing/custom" not in stats.overview_hidden_metrics + session.close() diff --git a/motrix_rl/tests/test_metrics.py b/motrix_rl/tests/test_metrics.py index d8da1740f..9a1e98cdb 100644 --- a/motrix_rl/tests/test_metrics.py +++ b/motrix_rl/tests/test_metrics.py @@ -18,8 +18,8 @@ import pytest import torch -from motrix_rl import metrics as metrics_module -from motrix_rl.metrics import JSONL_FILENAME, SCHEMA, HttpSink, JsonlSink, MetricsLogger +from motrix_rl.log import live as metrics_module +from motrix_rl.log.live import JSONL_FILENAME, SCHEMA, HttpSink, JsonlSink, MotrixLiveLogger FIXTURES = Path(__file__).parent / "fixtures" / "metrics_v1" RUN_ID_PATTERN = re.compile(r"^[A-Za-z0-9._-]{1,200}$") @@ -106,7 +106,7 @@ def _clean_env(monkeypatch): def _logger(tmp_path, url=None, token="", **http_kwargs): http = HttpSink(url, token, **http_kwargs) if url else None - return MetricsLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME), http=http) + return MotrixLiveLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME), http=http) def _wait_until(predicate, timeout=5.0): @@ -140,7 +140,7 @@ def _metrics_threads(): def test_without_url_or_jsonl_logger_is_disabled_and_inert(tmp_path): threads_before = _metrics_threads() - logger = MetricsLogger.from_env(tmp_path) + logger = MotrixLiveLogger.from_env(tmp_path) logger.run("running", total_steps=1) logger.scalars({"a": 1.0}, step=0) @@ -258,7 +258,7 @@ def join(self, timeout): calls.append(("join", self.name, timeout)) time.sleep(timeout) - logger = MetricsLogger("run-1", jsonl=Stuck("jsonl"), http=Stuck("http")) + logger = MotrixLiveLogger("run-1", jsonl=Stuck("jsonl"), http=Stuck("http")) logger.close() assert calls == [("close", "jsonl"), ("close", "http")] # told, not waited for @@ -270,7 +270,7 @@ def join(self, timeout): def test_exit_writes_what_a_logger_still_holds(monkeypatch, tmp_path): monkeypatch.setattr(metrics_module, "_OPEN", weakref.WeakSet()) - logger = MetricsLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME, flush_interval=60)) + logger = MotrixLiveLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME, flush_interval=60)) logger.run("finished") metrics_module._join_at_exit() # never closed: the exit hook closes it and waits @@ -282,13 +282,13 @@ def test_run_id_prefers_environment_and_is_sanitized(monkeypatch, tmp_path): monkeypatch.setenv("MOTRIX_METRICS_JSONL", "1") run_dir = tmp_path / "runs" / "cartpole" / "skrl" / "torch" / "ppo" / "26-10-12_10-00-00-000000" - derived = MetricsLogger.from_env(run_dir) + derived = MotrixLiveLogger.from_env(run_dir) derived.close() derived.join(5) assert derived.run_id == "cartpole__skrl__torch__ppo__26-10-12_10-00-00-000000" monkeypatch.setenv("MOTRIX_METRICS_RUN_ID", "a b/c:" + "x" * 300 + "-tail") - explicit = MetricsLogger.from_env(run_dir) + explicit = MotrixLiveLogger.from_env(run_dir) explicit.close() explicit.join(5) assert RUN_ID_PATTERN.match(explicit.run_id) @@ -296,7 +296,7 @@ def test_run_id_prefers_environment_and_is_sanitized(monkeypatch, tmp_path): assert explicit.run_id.endswith("x-tail") monkeypatch.setenv("MOTRIX_METRICS_RUN_ID", "ok.run_1-2") - kept = MetricsLogger.from_env(run_dir) + kept = MotrixLiveLogger.from_env(run_dir) kept.close() kept.join(5) assert kept.run_id == "ok.run_1-2" @@ -305,7 +305,7 @@ def test_run_id_prefers_environment_and_is_sanitized(monkeypatch, tmp_path): @pytest.mark.integration def test_url_alone_pushes_without_writing_a_local_file(monkeypatch, tmp_path, ingest): monkeypatch.setenv("MOTRIX_METRICS_URL", ingest.url) - logger = MetricsLogger.from_env(tmp_path) + logger = MotrixLiveLogger.from_env(tmp_path) logger.run("running") logger.close() @@ -319,7 +319,7 @@ def test_url_alone_pushes_without_writing_a_local_file(monkeypatch, tmp_path, in def test_jsonl_flag_alone_writes_locally_without_http(monkeypatch, tmp_path, flag): monkeypatch.setenv("MOTRIX_METRICS_JSONL", flag) before = set(threading.enumerate()) # other tests' senders may still be finishing in the background - logger = MetricsLogger.from_env(tmp_path) + logger = MotrixLiveLogger.from_env(tmp_path) assert logger.enabled assert [thread.name for thread in set(threading.enumerate()) - before] == ["motrix-metrics-jsonl"] @@ -333,7 +333,7 @@ def test_jsonl_flag_alone_writes_locally_without_http(monkeypatch, tmp_path, fla def test_jsonl_flag_off_values_keep_the_logger_disabled(monkeypatch, tmp_path): monkeypatch.setenv("MOTRIX_METRICS_JSONL", "0") - assert not MetricsLogger.from_env(tmp_path).enabled + assert not MotrixLiveLogger.from_env(tmp_path).enabled def test_stuck_disk_does_not_block_emit_and_loses_nothing(tmp_path): @@ -351,7 +351,7 @@ def _write_batch(self, batch): super()._write_batch(batch) sink = StuckSink(tmp_path / JSONL_FILENAME) - logger = MetricsLogger("run-1", jsonl=sink) + logger = MotrixLiveLogger("run-1", jsonl=sink) logger.scalars({"a": 0.0}, step=0) writing.wait(5) # the writer took the first record and is stuck on it @@ -375,7 +375,7 @@ def test_from_env_pushes_gzip_batches_with_bearer_token(monkeypatch, tmp_path, i monkeypatch.setenv("MOTRIX_METRICS_PROJECT", "proj") monkeypatch.setenv("MOTRIX_METRICS_GROUP", "grp") monkeypatch.setenv("MOTRIX_METRICS_META", '{"flow_run_id": "7"}') - logger = MetricsLogger.from_env(tmp_path) + logger = MotrixLiveLogger.from_env(tmp_path) logger.run("running", total_steps=10) logger.scalars({"rollout/mean_return": 1.0}, step=1, env_steps=8) @@ -588,7 +588,7 @@ def test_unreachable_service_keeps_the_jsonl_and_gives_up_within_its_flush_budge endpoint.bind(("127.0.0.1", 0)) url = f"http://127.0.0.1:{endpoint.getsockname()[1]}" http = HttpSink(url, flush_interval=0.01, backoff=0.01, flush_budget=0.2) - logger = MetricsLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME), http=http) + logger = MotrixLiveLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME), http=http) for step in range(1000): logger.scalars({"a": float(step)}, step=step) @@ -635,7 +635,7 @@ def test_idle_sink_sends_heartbeats_only_over_http(tmp_path, ingest): @pytest.mark.parametrize("name", ["pipeline_pending.json", "pipeline_failed.json"]) def test_orchestrator_fixtures_share_the_record_format(name, captured_http): fixture = json.loads((FIXTURES / name).read_text()) - logger = MetricsLogger("run-1", http=HttpSink("http://metrics.invalid", "fixture-token")) + logger = MotrixLiveLogger("run-1", http=HttpSink("http://metrics.invalid", "fixture-token")) logger.run("running") logger.close() logger.join(5) @@ -651,7 +651,7 @@ def test_orchestrator_fixtures_share_the_record_format(name, captured_http): def test_logger_reproduces_motrixlab_fixtures(name, captured_http): fixture = json.loads((FIXTURES / name).read_text()) expected = fixture["body"]["records"] - logger = MetricsLogger( + logger = MotrixLiveLogger( expected[0]["run_id"], http=HttpSink("http://metrics.invalid", "fixture-token", flush_interval=60) ) diff --git a/motrix_rl/tests/test_python_logging.py b/motrix_rl/tests/test_python_logging.py new file mode 100644 index 000000000..e919881f6 --- /dev/null +++ b/motrix_rl/tests/test_python_logging.py @@ -0,0 +1,59 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import io +import logging + +import pytest + +from motrix_rl.log.python_logging import scoped_file_logging + + +def test_scope_routes_descendants_only_and_restores_on_exception(tmp_path) -> None: + scope = logging.getLogger("test_scoped_logging") + sibling = logging.getLogger("test_scoped_logging_other") + output = io.StringIO() + handler = logging.StreamHandler(output) + original_handlers, original_level, original_propagate = scope.handlers[:], scope.level, scope.propagate + scope.handlers = [handler] + scope.setLevel(logging.WARNING) + scope.propagate = True + path = tmp_path / "logs" / "learner.log" + try: + with pytest.raises(ValueError, match="learner failure"): + with scoped_file_logging(scope, path): + logging.getLogger("test_scoped_logging.learner").info("learner ready") + sibling.warning("unrelated") + try: + raise ValueError("learner failure") + except ValueError: + scope.exception("update failed") + raise + text = path.read_text() + assert "learner ready" in text + assert "Traceback (most recent call last)" in text + assert "ValueError: learner failure" in text + assert "unrelated" not in text + assert not output.getvalue() + assert scope.handlers == [handler] + assert scope.level == logging.WARNING + assert scope.propagate is True + scope.warning("restored") + assert "restored" in output.getvalue() + finally: + scope.handlers, scope.propagate = original_handlers, original_propagate + scope.setLevel(original_level) + handler.close() + + +def test_nested_scopes_restore_the_outer_file(tmp_path) -> None: + outer, inner = tmp_path / "outer.log", tmp_path / "inner.log" + logger = logging.getLogger("test_nested_logging") + with scoped_file_logging("test_nested_logging", outer): + logger.info("outer before") + with scoped_file_logging(logger, inner): + logger.info("inner only") + logger.info("outer after") + assert "outer before" in outer.read_text() and "outer after" in outer.read_text() + assert "inner only" not in outer.read_text() + assert "inner only" in inner.read_text() diff --git a/motrix_rl/tests/test_rl_contracts.py b/motrix_rl/tests/test_rl_contracts.py index 67f705a21..e520c9b17 100644 --- a/motrix_rl/tests/test_rl_contracts.py +++ b/motrix_rl/tests/test_rl_contracts.py @@ -6,7 +6,7 @@ from dataclasses import dataclass from motrix_rl.contracts import AgentProvider, RlFramework, TrainerBase, TrainerContext, TrainerHandle -from motrix_rl.metrics import JSONL_FILENAME, JsonlSink, MetricsLogger +from motrix_rl.log.live import JSONL_FILENAME, JsonlSink, MotrixLiveLogger @dataclass @@ -66,7 +66,7 @@ def play(self, policy): def _train(tmp_path, error=None): - metrics = MetricsLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME)) + metrics = MotrixLiveLogger("run-1", jsonl=JsonlSink(tmp_path / JSONL_FILENAME)) handle = TrainerHandle(run=_Run(tmp_path), trainer=_Trainer(error), metrics=metrics, run_info={"total_steps": 8}) raised = None try: @@ -95,7 +95,7 @@ def _write_batch(self, batch): super()._write_batch(batch) sink = StuckDisk(tmp_path / JSONL_FILENAME) - handle = TrainerHandle(run=_Run(tmp_path), trainer=_Trainer(), metrics=MetricsLogger("run-1", jsonl=sink)) + handle = TrainerHandle(run=_Run(tmp_path), trainer=_Trainer(), metrics=MotrixLiveLogger("run-1", jsonl=sink)) handle.train() diff --git a/motrix_rl/tests/test_runner.py b/motrix_rl/tests/test_runner.py index 770a70532..6eb973291 100644 --- a/motrix_rl/tests/test_runner.py +++ b/motrix_rl/tests/test_runner.py @@ -14,7 +14,7 @@ from motrix_rl import frameworks, runner, runs, utils from motrix_rl.config import CheckpointConfig, LoggingConfig, TaskMeta, TrainConfig from motrix_rl.frameworks import RlFramework -from motrix_rl.metrics import JSONL_FILENAME +from motrix_rl.log.live import JSONL_FILENAME RUNNING_FIXTURE = Path(__file__).parent / "fixtures" / "metrics_v1" / "motrixlab_running.json" diff --git a/motrix_rl/tests/test_tensor_window.py b/motrix_rl/tests/test_tensor_window.py new file mode 100644 index 000000000..e98fd0ccb --- /dev/null +++ b/motrix_rl/tests/test_tensor_window.py @@ -0,0 +1,46 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import torch + +from motrix_rl.log.tensor_window import TensorMetricWindow + + +def test_tensor_metric_window_owns_samples_and_counts_each_key_independently(monkeypatch): + window = TensorMetricWindow({"loss": "mean", "entropy": "range"}) + value = torch.tensor(2.0, requires_grad=True) + original_item = torch.Tensor.item + + def forbid_host_conversion(self): + raise AssertionError("record must not synchronize a tensor to the host") + + with monkeypatch.context() as patch: + patch.setattr(torch.Tensor, "item", forbid_host_conversion) + window.record("loss", value) + window.record("loss", torch.tensor(6.0)) + window.record("entropy", torch.tensor(9.0)) + window.record("entropy", torch.tensor(1.0)) + assert torch.Tensor.item is original_item + with torch.no_grad(): + value.fill_(100) + assert window.stats_and_reset() == {"loss": 4.0, "entropy": 5.0, "entropy_min": 1.0, "entropy_max": 9.0} + assert window.stats_and_reset() == {} + window.record("loss", torch.tensor(7.0)) + assert window.stats_and_reset() == {"loss": 7.0} + + +def test_tensor_metric_window_requires_declared_reductions(): + with pytest.raises(ValueError, match="Unsupported tensor metric reduction"): + TensorMetricWindow({"loss": "sum"}) + with pytest.raises(KeyError, match="unknown"): + TensorMetricWindow({"loss": "mean"}).record("unknown", torch.tensor(1.0)) + + +def test_dynamic_keys_use_explicit_construction_default_and_drain_independently(): + window = TensorMetricWindow({}, default_reduction="mean") + window.record("alive", torch.tensor(1.0)) + window.record("alive", torch.tensor(3.0)) + assert window.stats_and_reset() == {"alive": 2.0} + window.record("contact", torch.tensor(0.5)) + assert window.stats_and_reset() == {"contact": 0.5} diff --git a/motrix_rl/tests/test_timing.py b/motrix_rl/tests/test_timing.py new file mode 100644 index 000000000..f7f5267dd --- /dev/null +++ b/motrix_rl/tests/test_timing.py @@ -0,0 +1,105 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +from types import MappingProxyType + +import pytest + +from motrix_env_core.perf import Perf +from motrix_rl.console.panel import TimingNode +from motrix_rl.console.timing import PerfTimingWindow, timing_nodes_from_paths + + +def test_empty_timing_paths() -> None: + assert timing_nodes_from_paths({}) == () + + +@pytest.mark.parametrize("parent_first", [True, False]) +def test_explicit_parent_duration_is_independent_of_children(parent_first: bool) -> None: + parent = ("learner", 0.0) + children = [("learner.update", 3.0), ("learner.update.critic", 8.0)] + values = dict([parent, *children] if parent_first else [*children, parent]) + + assert timing_nodes_from_paths(values) == ( + TimingNode("learner", 0.0, (TimingNode("update", 3.0, (TimingNode("critic", 8.0),)),)), + ) + + +def test_implicit_parents_have_no_inferred_duration() -> None: + values = {"collector.step.physics": 4.0, "collector.step.reset": 2.0} + + assert timing_nodes_from_paths(values) == ( + TimingNode( + "collector", + None, + (TimingNode("step", None, (TimingNode("physics", 4.0), TimingNode("reset", 2.0))),), + ), + ) + + +def test_roots_and_siblings_keep_first_seen_order() -> None: + values = MappingProxyType( + { + "learner.update.actor": 1.0, + "collector.step": 4.0, + "learner.drain": 0.5, + "learner.update.critic": 2.0, + "learner.update": 3.0, + "collector": 5.0, + } + ) + + assert timing_nodes_from_paths(values) == ( + TimingNode( + "learner", + None, + ( + TimingNode("update", 3.0, (TimingNode("actor", 1.0), TimingNode("critic", 2.0))), + TimingNode("drain", 0.5), + ), + ), + TimingNode("collector", 5.0, (TimingNode("step", 4.0),)), + ) + + +def test_total_is_an_ordinary_path_segment() -> None: + assert timing_nodes_from_paths({"learner.total": 2.0, "learner": 5.0}) == ( + TimingNode("learner", 5.0, (TimingNode("total", 2.0),)), + ) + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_perf_window_preserves_nested_scopes_and_restores_enabled_state(enabled) -> None: + perf = Perf(enabled=enabled, clock=iter((0, 1_000_000, 2_000_000, 4_000_000, 6_000_000, 9_000_000)).__next__) + window = PerfTimingWindow(perf) + window.start() + with perf.scope("step"): + with perf.scope("physics"): + with perf.scope("read"): + pass + children = window.snapshot() + assert children == (TimingNode("physics", 5.0, (TimingNode("read", 2.0),)),) + assert perf.snapshot() == () and perf.enabled + assert window.snapshot() == () + window.close() + assert perf.enabled == enabled + window.close() + + +def test_perf_tracker_keeps_outer_wall_duration_as_parent_denominator() -> None: + import torch + + from motrix_rl.log.collector_stats import CollectorStatsTracker + + perf = Perf(clock=iter((0, 1_000_000, 3_000_000, 4_000_000)).__next__) + window = PerfTimingWindow(perf) + tracker = CollectorStatsTracker(0, num_envs=1, device=torch.device("cpu"), perf_window=window) + window.start() + with perf.scope("step"): + with perf.scope("physics"): + pass + tracker.record_timings({"env_step": 0.010}) + snapshot = tracker.snapshot() + assert snapshot.timings == (TimingNode("env_step", 10.0, (TimingNode("physics", 2.0),)),) + assert tracker.snapshot().timings == (TimingNode("env_step", 0.0),) + window.close() diff --git a/motrix_rl/tests/test_training_logger.py b/motrix_rl/tests/test_training_logger.py index 16fe9e50f..488a14195 100644 --- a/motrix_rl/tests/test_training_logger.py +++ b/motrix_rl/tests/test_training_logger.py @@ -7,11 +7,11 @@ import pytest import torch.utils.tensorboard -from motrix_rl.metrics import MetricsLogger -from motrix_rl.training_logger import TrainingLogger +from motrix_rl.log.live import MotrixLiveLogger +from motrix_rl.log.training_logger import TrainingLogger -class _Live(MetricsLogger): +class _Live(MotrixLiveLogger): """An enabled live logger that keeps what it is sent.""" def __init__(self): @@ -37,22 +37,15 @@ def tensorboard(monkeypatch): return factory, writer -def test_scalars_reach_tensorboard_and_live_from_one_call(tmp_path, tensorboard): +def test_record_flush_routes_by_constructor_policy(tmp_path, tensorboard): factory, writer = tensorboard live = _Live() - log = TrainingLogger(tmp_path, live) - - log.scalars( - {"rollout/mean_return": math.nan, "train/qf_loss": 0.5}, - 7, - env_steps=56, - live_extra=lambda: {"sys/cpu_percent": 12.0}, - placeholders=("rollout/mean_return",), - ) - + log = TrainingLogger(tmp_path, live, live_only_prefixes=("sys/",)) + log.record({"train/qf_loss": 0.5, "sys/cpu_percent": 12.0}) + log.advance(iterations=7, env_steps=56) + log.flush() factory.assert_called_once_with(log_dir=str(tmp_path)) - tags = [(call.args[0], call.args[2]) for call in writer.add_scalar.call_args_list] - assert tags == [("rollout/mean_return", 7), ("train/qf_loss", 7)] # placeholders still reach TensorBoard + writer.add_scalar.assert_called_once_with("train/qf_loss", 0.5, 7) assert live.sent == [("scalars", {"train/qf_loss": 0.5, "sys/cpu_percent": 12.0}, 7, 56)] @@ -61,7 +54,7 @@ def test_tensorboard_opens_on_the_first_scalars_only(tmp_path, tensorboard): live = _Live() log = TrainingLogger(tmp_path, live) - log.event("run_started", step=0) + log.event("run_started", iteration=0, data={}) log.close() factory.assert_not_called() # a run that never logged leaves no event file @@ -72,7 +65,8 @@ def test_close_closes_tensorboard_once_and_never_raises(tmp_path, tensorboard): _, writer = tensorboard writer.close.side_effect = OSError("disk gone") log = TrainingLogger(tmp_path, _Live()) - log.scalars({"a": 1.0}, 0, env_steps=1) + log.record({"a": 1.0}) + log.flush(force=True) log.close() log.close() @@ -85,18 +79,191 @@ def test_live_still_gets_scalars_without_tensorboard(tmp_path, monkeypatch): live = _Live() log = TrainingLogger(tmp_path, live) - log.scalars({"a": 1.0}, 0, env_steps=1) - log.scalars({"a": 2.0}, 1, env_steps=2) + log.record({"a": 1.0}) + log.flush(force=True) + log.advance(env_steps=2) + log.record({"a": 2.0}) + log.flush() assert [sent[1] for sent in live.sent] == [{"a": 1.0}, {"a": 2.0}] def test_disabled_live_writes_tensorboard_only(tmp_path, tensorboard): _, writer = tensorboard - log = TrainingLogger(tmp_path, MetricsLogger.disabled()) + log = TrainingLogger(tmp_path, MotrixLiveLogger.disabled()) - log.scalars({"a": 1.0}, 0, env_steps=1, live_extra=Mock(side_effect=AssertionError("sampled for live"))) - log.event("run_started", step=0) + log.record({"a": 1.0}) + log.flush(force=True) + log.event("run_started", iteration=0, data={}) writer.add_scalar.assert_called_once_with("a", 1.0, 0) assert list(tmp_path.iterdir()) == [] + + +@pytest.fixture +def output(monkeypatch): + calls = [] + monkeypatch.setattr( + TrainingLogger, + "_emit", + lambda self, values, **kw: calls.append((values, self.iteration, {"env_steps": self.env_steps})), + ) + return TrainingLogger("unused", MotrixLiveLogger.disabled()), calls + + +def test_means_weight_samples_not_calls_and_last_uses_newest(output) -> None: + _, calls = output + window = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=3, reductions={"reward": "mean"}) + window.record({"reward": [1.0]}) + window.record({"loss": 10.0}) + window.advance(iterations=1 - window.iteration, env_steps=4 - window.env_steps) + window.flush() + assert not calls + window.record({"reward": [3.0, 5.0]}) + window.record({"loss": [20.0, 30.0]}) + window.advance(iterations=3 - window.iteration, env_steps=12 - window.env_steps) + window.flush() + assert calls == [({"reward": 3.0, "loss": 30.0}, 3, {"env_steps": 12})] + window.advance(iterations=3 - window.iteration, env_steps=12 - window.env_steps) + window.flush(force=True) + assert len(calls) == 1 # no duplicate empty window + window.record({"loss": 2.0}) + window.record({"reward": []}) + window.advance(iterations=6 - window.iteration, env_steps=24 - window.env_steps) + window.flush() + assert calls[-1][0] == {"loss": 2.0} # old/empty keys are not repeated + + +def test_force_flushes_unaligned_resume_step(output) -> None: + _, calls = output + window = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=4, initial_iteration=100) + window.record({"x": 1.0}) + window.advance(iterations=101 - window.iteration, env_steps=404 - window.env_steps) + window.flush() + assert not calls + window.advance(iterations=101 - window.iteration, env_steps=404 - window.env_steps) + window.flush(force=True) + assert calls[0][1] == 101 + + +@pytest.mark.parametrize("interval", [0, -1]) +def test_nonpositive_interval_outputs_each_step(output, interval) -> None: + _, calls = output + window = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=interval) + window.record({"x": 1.0}) + window.advance(iterations=1 - window.iteration, env_steps=4 - window.env_steps) + window.flush() + assert len(calls) == 1 + + +def test_reductions_are_copied_and_validated_at_construction(output) -> None: + _, calls = output + reductions = {"x": "mean"} + window = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=1, reductions=reductions) + reductions["x"] = "last" + window.record({"x": [2.0, 4.0]}) + window.advance(iterations=1 - window.iteration, env_steps=1 - window.env_steps) + window.flush() + assert calls[0][0] == {"x": 3.0} + with pytest.raises(ValueError, match="Unsupported metric reduction"): + TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=1, reductions={"x": "sum"}) + + +def test_failed_output_retains_window(output, monkeypatch) -> None: + _, calls = output + window = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=1, default_reduction="mean") + window.record({"x": 2.0}) + original = TrainingLogger._emit + + def fail(self, values, **kwargs): + raise RuntimeError("sink failed") + + monkeypatch.setattr(TrainingLogger, "_emit", fail) + with pytest.raises(RuntimeError, match="sink failed"): + window.advance(iterations=1 - window.iteration, env_steps=1 - window.env_steps) + window.flush() + monkeypatch.setattr(TrainingLogger, "_emit", original) + window.advance(iterations=1 - window.iteration, env_steps=1 - window.env_steps) + window.flush() + assert calls[0][0] == {"x": 2.0} + + +def test_events_do_not_consume_or_flush_buffered_window(tmp_path, tensorboard): + _, writer = tensorboard + live = _Live() + log = TrainingLogger(tmp_path, live, interval=10, reductions={"mean": "mean"}) + log.record({"mean": [2.0, 4.0], "loss": 1.0}) + log.advance(iterations=3, env_steps=12) + log.event("checkpoint_saved", iteration=log.iteration, data={}) + log.flush() + assert live.sent == [("event", "checkpoint_saved", 3, {})] + log.advance(iterations=7, env_steps=28) + log.flush() + assert live.sent[-1] == ("scalars", {"mean": 3.0, "loss": 1.0}, 10, 40) + assert writer.add_scalar.call_count == 2 + + +def test_record_and_close_never_implicitly_output_pending_samples(tmp_path, tensorboard): + factory, _ = tensorboard + live = _Live() + log = TrainingLogger(tmp_path, live) + log.record({"loss": 2.0}) + log.close() + factory.assert_not_called() + assert live.sent == [] + + +def test_progress_baseline_zero_delta_and_historical_events(tmp_path, tensorboard): + live = _Live() + log = TrainingLogger(tmp_path, live, initial_iteration=100, initial_env_steps=1000) + log.advance(iterations=0, env_steps=0) + log.event("current", iteration=log.iteration, data={}) + log.advance(iterations=3, env_steps=24) + log.event("historical", iteration=99, data={}) + log.record({"x": 1.0}) + log.flush(force=True) + assert live.sent == [ + ("event", "current", 100, {}), + ("event", "historical", 99, {}), + ("scalars", {"x": 1.0}, 103, 1024), + ] + with pytest.raises(ValueError, match="nonnegative"): + log.advance(iterations=-1, env_steps=0) + assert (log.iteration, log.env_steps) == (103, 1024) + + +def test_due_has_no_output_or_boundary_side_effects(tmp_path, tensorboard): + factory, _ = tensorboard + log = TrainingLogger(tmp_path, _Live(), interval=3) + assert not log.due() + log.advance(iterations=5, env_steps=20) + assert log.due() and log.due() + log.flush() # empty output must not consume boundary + assert log.due() + factory.assert_not_called() + log.record({"x": 1.0}) + log.flush() + assert not log.due() + + +def test_missing_samples_omitted_but_real_nonfinite_values_preserved(tmp_path, tensorboard): + _, writer = tensorboard + live = _Live() + log = TrainingLogger(tmp_path, live, reductions={"missing": "mean"}) + log.record({"missing": [], "diverged": math.nan}) + log.advance(env_steps=4) + log.flush() + writer.add_scalar.assert_called_once() + assert writer.add_scalar.call_args.args[0] == "diverged" + assert math.isnan(live.sent[0][1]["diverged"]) + + +def test_live_only_output_does_not_open_tensorboard(tmp_path, tensorboard): + factory, _ = tensorboard + live = _Live() + log = TrainingLogger(tmp_path, live, live_only_prefixes=("sys/",)) + log.record({"sys/cpu_percent": 1.0}) + log.advance(env_steps=4) + log.flush() + factory.assert_not_called() + assert live.sent[0][1] == {"sys/cpu_percent": 1.0} diff --git a/motrix_rl/tests/test_training_metrics.py b/motrix_rl/tests/test_training_metrics.py new file mode 100644 index 000000000..c66e81878 --- /dev/null +++ b/motrix_rl/tests/test_training_metrics.py @@ -0,0 +1,221 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +from motrix_rl.console.panel import TrainingPanelSession +from motrix_rl.log.live import MotrixLiveLogger +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics + + +def test_single_record_fans_generator_to_independent_output_windows(monkeypatch): + emitted, frames = [], [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: emitted.append((self.iteration, values))) + panel = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(panel, "_draw", lambda stats, **kwargs: frames.append(stats)) + log = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=2, reductions={"train/x": "mean"}) + phase = panel.metrics_panel(total_iterations=3, reductions=log.reductions, default_reduction=log.default_reduction) + output = TrainingMetrics( + [log, phase], + ) + output.record({"train/x": (value for value in [1.0, 3.0]), "custom/z": 7.0}) + output.advance(env_steps=8) + output.flush() + assert frames[-1].metrics["train/x"] == 2.0 + assert not emitted + output.record({"train/x": [5.0]}) + output.advance(env_steps=8) + output.flush() + assert frames[-1].metrics["train/x"] == 5.0 + assert emitted[0][0] == 2 + assert emitted[0][1]["train/x"] == 3.0 + assert emitted[0][1]["custom/z"] == 7.0 + assert emitted[0][1]["throughput/env_steps_per_s"] > 0.0 + assert frames[-1].iteration == output.iteration == 2 + + +def test_forced_repeat_does_not_create_system_only_log(monkeypatch): + emitted = [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: emitted.append(values)) + panel = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(panel, "_draw", lambda stats, **kwargs: None) + log = TrainingLogger("unused", MotrixLiveLogger.disabled()) + output = TrainingMetrics([log, panel.metrics_panel(total_iterations=2)], system_sink=log) + output.record({"train/loss": 1.0}) + output.advance(env_steps=8) + output.flush(force=True) + output.flush(force=True) + assert len(emitted) == 1 + + +def test_training_start_excludes_boot_time_from_both_output_rates(monkeypatch): + now = [0.0] + monkeypatch.setattr("time.monotonic", lambda: now[0]) + emitted, frames = [], [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: emitted.append(values)) + panel = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(panel, "_draw", lambda stats, **kwargs: frames.append(stats)) + log = TrainingLogger("unused", MotrixLiveLogger.disabled(), initial_iteration=40, initial_env_steps=400) + output = TrainingMetrics( + [log, panel.metrics_panel(total_iterations=100, initial_iteration=40, initial_env_steps=400)], + initial_iteration=40, + initial_env_steps=400, + ) + now[0] = 60.0 # spawn/compile/barrier + output.start() + now[0] = 62.0 + output.record({"train/loss": 1.0}) + output.advance(iterations=2, env_steps=20) + output.flush() + assert emitted[0]["throughput/env_steps_per_s"] == 10.0 + assert emitted[0]["throughput/iterations_per_s"] == 1.0 + assert frames[0].elapsed_seconds == 2.0 + assert frames[0].steps_per_second == 10.0 + assert frames[0].initial_iteration == 40 + assert frames[0].iteration == 42 + + +def test_recent_episodes_shared_between_outputs_and_survive_flushes(monkeypatch): + emitted, frames = [], [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: emitted.append(values)) + panel = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(panel, "_draw", lambda stats, **kwargs: frames.append(stats)) + log = TrainingLogger("unused", MotrixLiveLogger.disabled(), interval=2, initial_iteration=40, initial_env_steps=400) + output = TrainingMetrics( + [log, panel.metrics_panel(total_iterations=50, initial_iteration=40, initial_env_steps=400)], + initial_iteration=40, + initial_env_steps=400, + recent_episodes=2, + ) + output.record_episodes([], []) + output.advance(env_steps=4) + output.flush() + assert frames[-1].mean_return is None + output.record_episodes([1.0, 3.0, 5.0], [10, 30, 50]) + output.advance(env_steps=4) + output.flush() + assert emitted[-1]["episode/recent_return_mean"] == frames[-1].mean_return == 4.0 + assert "episode/completed" not in emitted[-1] + output.record_episodes([], []) + output.advance(env_steps=4) + output.flush(force=True) + assert emitted[-1]["episode/recent_return_mean"] == frames[-1].mean_return == 4.0 + assert "episode/completed" not in frames[-1].metrics + + +class ExternalSink: + """Independent user object: no inheritance from any framework class.""" + + def __init__(self, boundary=2): + self.iteration = 40 + self.env_steps = 400 + self.boundary = boundary + self.values = {} + self.outputs = [] + self.events = [] + self.started = [] + + def record(self, metrics): + self.values.update(metrics) + + def advance(self, *, iterations=1, env_steps): + self.iteration += iterations + self.env_steps += env_steps + + def flush(self, *, force=False): + if self.values and (force or self.iteration >= self.boundary): + self.outputs.append(dict(self.values)) + self.values.clear() + + def event(self, name, *, iteration, data): + self.events.append((name, iteration, dict(data))) + + def start(self, *, now): + self.started.append(now) + + +def test_arbitrary_sinks_choose_independent_cadences_without_due_protocol(): + sampling = ExternalSink(boundary=42) + fast = ExternalSink(boundary=0) + output = TrainingMetrics([sampling, fast], initial_iteration=40, initial_env_steps=400) + output.start() + output.record({"custom/x": (value for value in (1.0, 2.0))}) + output.advance(env_steps=8) + output.flush() + assert not sampling.outputs and fast.outputs[0]["custom/x"] == (1.0, 2.0) + output.advance(env_steps=8) + assert output.iteration == 42 and output.env_steps == 416 + output.checkpoint("saved.pt", iteration=39) + assert sampling.events == fast.events == [("checkpoint_saved", 39, {"path": "saved.pt"})] + assert sampling.started == fast.started + output.flush() + assert sampling.outputs[0]["custom/x"] == (1.0, 2.0) + + +def test_system_observations_use_wall_clock_not_sink_output_cadence(monkeypatch): + from motrix_rl.system_metrics import SystemStats + + now = [0.0] + samples = [] + monkeypatch.setattr("time.monotonic", lambda: now[0]) + + class Sampler: + def sample(self): + samples.append(now[0]) + return SystemStats(None, None, None, None, None) + + monkeypatch.setattr("motrix_rl.log.training_metrics.SystemSampler", Sampler) + monkeypatch.setattr("motrix_rl.log.training_metrics.system_scalars", lambda stats: {"sys/cpu_percent": 12.0}) + slow, fast = ExternalSink(boundary=100), ExternalSink(boundary=0) + output = TrainingMetrics( + [slow, fast], initial_iteration=40, initial_env_steps=400, system_sink=slow, system_interval_seconds=2.0 + ) + for timestamp in (0.0, 0.5, 1.0, 2.0): + now[0] = timestamp + output.record({"custom/x": timestamp}) + output.advance(env_steps=1) + output.flush() + assert samples == [0.0, 2.0] + assert len(fast.outputs) == 4 and slow.outputs == [] + output.flush(force=True) + assert len(samples) == 2 # no new observation, no extra system-only report + assert len(slow.outputs) == 1 + assert slow.outputs[0]["sys/cpu_percent"] == 12.0 + assert all("sys/cpu_percent" not in report for report in fast.outputs) + + +def test_waiting_refresh_observes_shared_zero_throughput(monkeypatch): + now = [0.0] + monkeypatch.setattr("time.monotonic", lambda: now[0]) + reports, frames = [], [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: reports.append(values)) + session = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(session, "_draw", lambda stats: frames.append(stats)) + log = TrainingLogger("unused", MotrixLiveLogger.disabled()) + output = TrainingMetrics([log, session.metrics_panel(total_iterations=10)]) + now[0] = 1.0 + output.advance(env_steps=10) + output.flush() + assert frames[-1].steps_per_second == reports[-1]["throughput/env_steps_per_s"] == 10.0 + # No new advance: waiting is sampled by the shared source, not the panel. + now[0] = 12.0 + output.flush(force=True) + now[0] = 23.0 + output.flush(force=True) + assert reports[-1]["throughput/env_steps_per_s"] == frames[-1].steps_per_second == 0.0 + assert frames[-1].metrics["throughput/env_steps_per_s"] == 0.0 + + +def test_panel_health_is_not_duplicated_but_user_sys_metrics_stay_visible(monkeypatch): + reports, frames = [], [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: reports.append(values)) + monkeypatch.setattr("motrix_rl.log.training_metrics.system_scalars", lambda stats: {"sys/cpu_percent": 12.0}) + session = TrainingPanelSession(interval_seconds=0) + monkeypatch.setattr(session, "_draw", lambda stats: frames.append(stats)) + log = TrainingLogger("unused", MotrixLiveLogger.disabled()) + output = TrainingMetrics([log, session.metrics_panel(total_iterations=2)], system_sink=log) + output.record({"train/loss": 1.0, "sys/custom": 7.0}) + output.advance(env_steps=4) + output.flush() + assert reports[0]["sys/cpu_percent"] == 12.0 + assert "sys/cpu_percent" not in frames[0].metrics + assert frames[0].metrics["sys/custom"] == 7.0 diff --git a/motrix_rl/tests/test_worker.py b/motrix_rl/tests/test_worker.py index ec769dc69..981ee3367 100644 --- a/motrix_rl/tests/test_worker.py +++ b/motrix_rl/tests/test_worker.py @@ -11,7 +11,7 @@ import numpy as np import pytest -from motrix_rl.worker import Worker, WorkerHandle, WorkerPlacement, WorkerRuntime +from motrix_rl.worker import Worker, WorkerError, WorkerHandle, WorkerPlacement, WorkerRuntime @dataclass @@ -95,7 +95,7 @@ def test_worker_runtime_is_applied_before_task_and_does_not_change_parent(seed: if handle.is_alive: handle.terminate() handle.join(timeout=5) - handle.process.close() + handle.close() results.close() results.join_thread() @@ -133,3 +133,103 @@ def test_slotted_worker_spawn_preserves_state() -> None: assert handle.exitcode == 0 assert result_queue.get(timeout=2) == 42 + + +class _NoisyWorker(Worker): + """Write through every layer that could reach a parent-owned terminal.""" + + def __init__(self, log_path, done) -> None: + self.log_path = log_path + self.done = done + + def run(self) -> None: + import logging + import os + import sys + + print("python stdout line") + sys.stderr.write("python stderr line\n") + os.write(1, b"native fd1 line\n") + logging.getLogger("noisy").info("logging line") + self.done.put(str(self.log_path.read_text())) + + +def test_worker_log_path_captures_stdio_logging_and_restores_parent(tmp_path) -> None: + ctx = mp.get_context("fork") + done = ctx.Queue() + log_path = tmp_path / "collector.log" + handle = _NoisyWorker(log_path, done).start(ctx, name="noisy", runtime=WorkerRuntime(log_path=log_path)) + handle.join(timeout=10) + assert handle.exitcode == 0 + text = done.get(timeout=5) + assert "python stdout line" in text + assert "python stderr line" in text + assert "native fd1 line" in text + assert "logging line" in text + # The parent's fds must be back on the captured pipes after start(). + assert os.dup2(1, 1) == 1 + + +def test_worker_without_log_path_keeps_default_stdio(tmp_path) -> None: + ctx = mp.get_context("fork") + done = ctx.Queue() + + class _QuietWorker(Worker): + def __init__(self, done) -> None: + self.done = done + + def run(self) -> None: + self.done.put(True) + + handle = _QuietWorker(done).start(ctx, name="quiet", runtime=WorkerRuntime()) + handle.join(timeout=10) + assert handle.exitcode == 0 and done.get(timeout=5) is True + + +class _FailingWorker(Worker): + def run(self) -> None: + raise ValueError("large report " + "x" * 100_000 + " failure-tail") + + +class _NativeExitWorker(Worker): + def run(self) -> None: + os._exit(7) + + +@pytest.mark.integration +@pytest.mark.parametrize("task,expected", [(_FailingWorker, "failure-tail"), (_NativeExitWorker, "code 7")]) +def test_worker_failure_is_nonblocking_repeatable_and_bounded(task, expected, tmp_path) -> None: + handle = task().start( + mp.get_context("spawn"), name="failing", runtime=WorkerRuntime(log_path=tmp_path / "worker.log") + ) + try: + handle.join(timeout=15) + assert not handle.is_alive # even a large traceback cannot block the child send + for _ in range(2): + with pytest.raises(WorkerError, match=expected): + handle.check() + if task is _FailingWorker: + assert "large report" in (tmp_path / "worker.log").read_text() + finally: + if handle.is_alive: + handle.kill() + handle.join(5) + handle.close() + handle.close() + + +def test_normal_exit_passes_health_check_and_close_releases_pipe() -> None: + ctx = mp.get_context("spawn") + queue = ctx.Queue() + handle = _ExampleWorker(queue, _WorkerConfig(42)).start(ctx) + try: + assert queue.get(timeout=10) == 42 + handle.join(10) + handle.check() + finally: + if handle.is_alive: + handle.terminate() + handle.join(5) + handle.close() + handle.close() + queue.close() diff --git a/motrix_rl_appo/README.md b/motrix_rl_appo/README.md index dcd85a53c..5e76ebecb 100644 --- a/motrix_rl_appo/README.md +++ b/motrix_rl_appo/README.md @@ -56,4 +56,18 @@ fixed, equally sized minibatches. Compile/capture startup cost is separate from steady-state performance. Floating-point fusion can change adaptive KL decisions near a threshold; accelerated runs are not promised to be bitwise identical. +Training runs a live console in the parent process: overview/timing/system +views switch with 1/2/3 in a TTY, plain text is throttled when stdout is not a +TTY, and startup stages plus the last saved checkpoint are shown. FPS counts +learner-consumed transitions; episode return/length use raw completed episodes +from consumed chunks; queue depth is the rollout queue in chunks; stage +timings are host wall times of concurrent collector and learner processes and +are never summed into a serial total. Collector stdout/stderr/warnings are +redirected to `run_dir/logs/collector.log`; collector failures still travel +the error channel with the log path reported. Console and persisted metrics +share canonical learner/environment/diagnostic values and recent-100 completed +episode means. Timing values use the same measured boundaries and mean reduction, +with independent console and logging windows; see the +[training console contract](../wiki/design/training-console.md). + Algorithm and data ownership details: [APPO design](../wiki/design/appo.md). diff --git a/motrix_rl_appo/src/motrix_rl_appo/collector.py b/motrix_rl_appo/src/motrix_rl_appo/collector.py index da8ef1f1e..a13b7647e 100644 --- a/motrix_rl_appo/src/motrix_rl_appo/collector.py +++ b/motrix_rl_appo/src/motrix_rl_appo/collector.py @@ -7,7 +7,6 @@ import logging import time -import traceback from dataclasses import dataclass from multiprocessing.connection import Connection from multiprocessing.queues import Queue @@ -18,6 +17,8 @@ from motrix_env_core import registry as env_registry from motrix_env_core.array.env import ArrayEnv +from motrix_rl.log.collector_stats import CollectorStatsTracker +from motrix_rl.log.tensor_window import TensorMetricWindow from motrix_rl.transport.common import bind_flat_params from motrix_rl.transport.gpu_ipc_ring import GpuIpcTransitionRing from motrix_rl.transport.ring import HostTransitionRing @@ -57,12 +58,20 @@ def publish_chunk( @dataclass(frozen=True) class CollectorMetrics: + """Per-chunk sideband reported through the metrics queue. + + ``returns``/``lengths`` are raw completed-episode statistics accumulated + from unmodified rewards, before any timeout bootstrap reaches the chunk; + consumers must not recompute them from the chunk's rewards. + """ + returns: list[float] lengths: list[int] latency_s: float weight_version: int published_version: int env_metrics: dict[str, float] + reward_terms: dict[str, float] class ChunkCollector: @@ -86,8 +95,10 @@ def __init__( self.state = env.initialize() self.env_device = self.state.obs.policy.device self._warned_timeout_approximation = False - self.returns = torch.zeros(env.num_envs, device=self.env_device) - self.lengths = torch.zeros(env.num_envs, dtype=torch.long, device=self.env_device) + self.stats = CollectorStatsTracker( + 0, num_envs=env.num_envs, device=self.env_device, collect_episode_deltas=True + ) + self._reward_terms = TensorMetricWindow({}, default_reduction="mean") spec = env.observation_spec self.dims = CollectorMetadata( spec.policy.space.shape[0], @@ -123,15 +134,13 @@ def _copy_observation(self, name: str, observation: torch.Tensor, history: int, self._storage[name][:, step].copy_(window[:, -1]) @torch.no_grad() - def collect(self) -> tuple[dict[str, torch.Tensor], list[float], list[int], dict[str, float]]: + def collect(self) -> tuple[dict[str, torch.Tensor], list[float], list[int], dict[str, float], dict[str, float]]: """Return borrowed storage, valid until the next collect call. The caller must finish publication (including device-copy completion) before collecting again and overwriting this carrier. """ chunk = self._storage - returns: list[float] = [] - lengths: list[int] = [] for step in range(self.cfg.rollout_steps): obs = self.state.obs.policy.to(self.device) self._copy_observation("obs", obs, self.dims.obs_history, step) @@ -171,18 +180,18 @@ def collect(self) -> tuple[dict[str, torch.Tensor], list[float], list[int], dict raise RuntimeError("APPO final observations do not cover all timeout rows") values = self.critic(final.obs.value_or_policy[selected].to(self.device)) reward[ids] += self.cfg.algorithm.gamma * values - self.returns += state.reward - self.lengths += 1 done = state.done - returns.extend(self.returns[done].cpu().tolist()) - lengths.extend(self.lengths[done].cpu().tolist()) - self.returns[done] = 0 - self.lengths[done] = 0 + self.stats.record_step(state.reward, done, reward_terms={}, metrics={}) + for name, value in state.reward_terms.items(): + self._reward_terms.record(name, value.detach().float().mean()) chunk["rewards"][:, step].copy_(reward) chunk["dones"][:, step].copy_(done) self.state = state chunk["last_critic_obs"].copy_(self.state.obs.value_or_policy) - return chunk, returns, lengths, self.state.process_metrics() + env_metrics = self.state.process_metrics() + self.stats.set_env_metrics(env_metrics) + episodes = self.stats.take_episodes() + return chunk, list(episodes.returns), list(episodes.lengths), env_metrics, self._reward_terms.stats_and_reset() @dataclass(frozen=True) @@ -194,7 +203,6 @@ class CollectorWorker(Worker): cfg: AppoCfg policy_device: str stop: Event - errors: Connection startup: Connection metrics: Queue @@ -234,7 +242,7 @@ def run(self) -> None: while not self.stop.is_set(): receiver.maybe_load(modules, norms, flat) started = time.monotonic() - chunk, returns, lengths, env_metrics = collector.collect() + chunk, returns, lengths, env_metrics, reward_terms = collector.collect() # A metrics record precedes its ring publication, so the parent # can always pair exactly one record with the next chunk. self.metrics.put( @@ -245,19 +253,13 @@ def run(self) -> None: receiver.loaded_version, receiver.version, env_metrics, + reward_terms, ) ) if not publish_chunk(ring, chunk, self.stop, self.cfg.worker_timeout): return - except BaseException: - try: - self.errors.send(traceback.format_exc()) - except (BrokenPipeError, EOFError, OSError): - pass - raise finally: self.startup.close() - self.errors.close() # Do not wait for a queue feeder after the consumer has stopped. self.metrics.cancel_join_thread() self.metrics.close() diff --git a/motrix_rl_appo/src/motrix_rl_appo/metrics.py b/motrix_rl_appo/src/motrix_rl_appo/metrics.py new file mode 100644 index 000000000..cf15d447a --- /dev/null +++ b/motrix_rl_appo/src/motrix_rl_appo/metrics.py @@ -0,0 +1,60 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Canonical APPO observations shared by terminal and persisted metrics.""" + +from collections.abc import Mapping +from dataclasses import dataclass + +from motrix_rl_appo.collector import CollectorMetrics + + +@dataclass(frozen=True) +class StageTimings: + """Measured host durations, in seconds; update includes optimize and publish.""" + + ingest_s: float + optimize_s: float + weight_publish_s: float + update_s: float + + @property + def processing_s(self) -> float: + return self.ingest_s + self.update_s + + +TIMING_KEYS = ( + "timing/collector/total_s", + "timing/collector/rollout_s", + "timing/learner/ingest_s", + "timing/learner/update/optimize_s", + "timing/learner/update/weight_publish_s", + "timing/learner/update_s", + "timing/learner/total_s", +) + + +def metric_values( + learner_metrics: Mapping[str, float], + collector: CollectorMetrics, + timings: StageTimings, + *, + queue_depth: int, +) -> dict[str, float]: + """Map APPO sources to canonical keys without owning progress or episode state.""" + return ( + {f"train/{key}": value for key, value in learner_metrics.items()} + | {f"env/{key}": value for key, value in collector.env_metrics.items()} + | {f"reward/{key}": value for key, value in collector.reward_terms.items()} + | { + "collector/weight_lag": float(collector.published_version - collector.weight_version), + "collector/queue_depth": float(queue_depth), + "timing/collector/total_s": collector.latency_s, + "timing/collector/rollout_s": collector.latency_s, + "timing/learner/ingest_s": timings.ingest_s, + "timing/learner/update/optimize_s": timings.optimize_s, + "timing/learner/update/weight_publish_s": timings.weight_publish_s, + "timing/learner/update_s": timings.update_s, + "timing/learner/total_s": timings.processing_s, + } + ) diff --git a/motrix_rl_appo/src/motrix_rl_appo/trainer.py b/motrix_rl_appo/src/motrix_rl_appo/trainer.py index a25f52fe3..fc50e6ff5 100644 --- a/motrix_rl_appo/src/motrix_rl_appo/trainer.py +++ b/motrix_rl_appo/src/motrix_rl_appo/trainer.py @@ -9,20 +9,26 @@ import multiprocessing as mp import random import time +from collections.abc import Callable +from contextlib import ExitStack from multiprocessing.connection import Connection from pathlib import Path from queue import Empty import numpy as np import torch -from torch.utils.tensorboard import SummaryWriter from motrix_env_core import registry as env_registry from motrix_env_core.array.env import ArrayEnv from motrix_env_core.renderer import create_renderer from motrix_rl import checkpoints +from motrix_rl.console.boot import BootWorker +from motrix_rl.console.panel import TrainingPanelSession from motrix_rl.contracts import TrainerBase, TrainerContext from motrix_rl.device import resolve_default_device +from motrix_rl.log.python_logging import scoped_file_logging +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics from motrix_rl.transport.ring import HostTransitionRing, RingCursors from motrix_rl.transport.weight_channel import ( GpuIpcWeightSender, @@ -34,6 +40,7 @@ from motrix_rl_appo.config import AppoCfg from motrix_rl_appo.history import ChunkHistory from motrix_rl_appo.learner import APPOLearner +from motrix_rl_appo.metrics import TIMING_KEYS, StageTimings, metric_values from motrix_rl_appo.networks import build_actor from motrix_rl_appo.transport import ( CollectorConnection, @@ -47,22 +54,24 @@ logger = logging.getLogger(__name__) -def check_worker(worker: WorkerHandle, errors: Connection) -> None: - if errors.poll(): - try: - message = errors.recv() - except EOFError: - message = None - if message is not None: - raise RuntimeError(f"APPO collector failed:\n{message}") +def check_worker(worker: WorkerHandle) -> None: + worker.check() if not worker.is_alive: raise RuntimeError(f"APPO collector exited unexpectedly (exitcode={worker.exitcode})") -def wait_ready(worker: WorkerHandle, errors: Connection, ready: Connection, timeout: float) -> None: +def wait_ready( + worker: WorkerHandle, + ready: Connection, + timeout: float, + *, + on_wait: Callable[[], None] | None = None, +) -> None: started = time.monotonic() while not ready.poll(0.01): - check_worker(worker, errors) + check_worker(worker) + if on_wait is not None: + on_wait() if time.monotonic() - started > timeout: raise TimeoutError(f"No APPO collector startup metadata for {timeout}s") @@ -75,7 +84,7 @@ def stop_worker(worker: WorkerHandle) -> None: if worker.is_alive: worker.kill() worker.join(timeout=5) - worker.process.close() + worker.close() def rng_state() -> dict: @@ -137,14 +146,6 @@ def train(self) -> None: transport = resolve_transport(cfg.transition_transport, device, collector_device) weight_transport = resolve_transport(cfg.weight_transport, device, collector_device) chunk_device = collector_device if transport == "cuda_ipc" else torch.device("cpu") - logger.info( - "APPO transition transport=%s weight_transport=%s chunk_device=%s learner=%s collector=%s", - transport, - weight_transport, - chunk_device, - device, - collector_device, - ) checkpoint = ( torch.load(context.resume_from, map_location=device, weights_only=False) if context.resume_from else None ) @@ -157,132 +158,173 @@ def train(self) -> None: np.random.seed(seed) torch.manual_seed(seed) ctx = mp.get_context("spawn") - stop = ctx.Event() - error_rx, error_tx = ctx.Pipe(duplex=False) - startup_rx, startup_tx = ctx.Pipe() - metrics_queue = ctx.Queue(maxsize=cfg.queue_chunks + 1) - worker: WorkerHandle | None = None - writer: SummaryWriter | None = None - started = time.monotonic() - try: - worker = CollectorWorker( - context.env_name, - context.sim, - context.num_envs, - seed, - cfg, - str(collector_device), - stop, - error_tx, - startup_tx, - metrics_queue, - ).start(ctx, name="appo-collector", runtime=WorkerRuntime(seed=seed)) - error_tx.close() - startup_tx.close() - wait_ready(worker, error_rx, startup_rx, cfg.worker_timeout) - dims = startup_rx.recv() - learner = APPOLearner(cfg, dims.obs_dim, dims.critic_dim, dims.action_dim, device) - if checkpoint is not None: - learner.load_state_dict(checkpoint["learner"]) - restore_rng(checkpoint["rng"]) - modules = {"actor": learner.actor, "critic": learner.critic} - norms = {"actor_norm": learner.actor.obs_normalizer, "critic_norm": learner.critic.obs_normalizer} - spec = inference_spec(learner.actor, learner.critic, dims) - # Keep shared stats and sender allocations alive until the child exits. - weights = WeightChannelShared(spec) - sender = ( - GpuIpcWeightSender(weights, device) if weight_transport == "cuda_ipc" else HostWeightSender(weights) - ) - sender.publish(modules, norms) - schema = chunk_schema( - cfg.rollout_steps, - dims.obs_dim // dims.obs_history, - dims.critic_dim // dims.critic_history, - dims.action_dim, - critic_history=dims.critic_history, - critic_uses_policy=dims.critic_uses_policy, + with ExitStack() as resources: + session = TrainingPanelSession.open(title=f"{context.env_name}/motrix.appo", screen=True) + resources.callback(session.close) + log_dir = context.run_dir / "logs" + resources.enter_context(scoped_file_logging("motrix_rl_appo", log_dir / "learner.log")) + training_log = TrainingLogger( + context.run_dir, + context.metrics, + interval=context.logging.interval, + initial_iteration=checkpoint["iteration"] if checkpoint else 0, + initial_env_steps=checkpoint["learner"]["global_step"] if checkpoint else 0, + reductions=dict.fromkeys(TIMING_KEYS, "mean"), ) - if transport == "cuda_ipc": - # Parent owns the allocation until the collector has stopped. - slots = torch.empty( - (cfg.queue_chunks, context.num_envs, schema.feature_width), device=device, dtype=torch.float32 + resources.callback(training_log.close) + stop = ctx.Event() + startup_rx, startup_tx = ctx.Pipe() + resources.callback(startup_rx.close) + resources.callback(startup_tx.close) + metrics_queue = ctx.Queue(maxsize=cfg.queue_chunks + 1) + resources.callback(metrics_queue.join_thread) + resources.callback(metrics_queue.close) + try: + logger.info( + "APPO transition transport=%s weight_transport=%s chunk_device=%s learner=%s collector=%s", + transport, + weight_transport, + chunk_device, + device, + collector_device, + ) + boot = session.boot_panel( + ( + BootWorker("collector", log_dir / "collector.log"), + BootWorker("learner", log_dir / "learner.log"), + ) + ) + boot.message("starting collector") + worker = CollectorWorker( + context.env_name, + context.sim, + context.num_envs, + seed, + cfg, + str(collector_device), + stop, + startup_tx, + metrics_queue, + ).start( + ctx, + name="appo-collector", + runtime=WorkerRuntime(seed=seed, log_path=log_dir / "collector.log"), + ) + resources.callback(stop_worker, worker) + resources.callback(stop.set) + startup_tx.close() + boot.message("waiting for collector environment metadata") + wait_ready( + worker, + startup_rx, + cfg.worker_timeout, + on_wait=boot.refresh, + ) + dims = startup_rx.recv() + boot.mark_ready("collector") + boot.message("building learner") + learner = APPOLearner(cfg, dims.obs_dim, dims.critic_dim, dims.action_dim, device) + if checkpoint is not None: + learner.load_state_dict(checkpoint["learner"]) + restore_rng(checkpoint["rng"]) + modules = {"actor": learner.actor, "critic": learner.critic} + norms = {"actor_norm": learner.actor.obs_normalizer, "critic_norm": learner.critic.obs_normalizer} + spec = inference_spec(learner.actor, learner.critic, dims) + # Keep shared stats and sender allocations alive until the child exits. + weights = WeightChannelShared(spec) + sender = ( + GpuIpcWeightSender(weights, device) if weight_transport == "cuda_ipc" else HostWeightSender(weights) ) - ring_connection = GpuRingConnection(RingCursors(), slots, schema, cfg.queue_chunks, context.num_envs) - ring = ring_connection.endpoint() - else: - ring = HostTransitionRing(schema, cfg.queue_chunks, context.num_envs) - ring_connection = ring - history = ChunkHistory(dims.obs_history, dims.critic_history, dims.critic_uses_policy) - startup_rx.send(CollectorConnection(ring_connection, weights, sender.params, str(chunk_device))) - writer = SummaryWriter(log_dir=str(context.run_dir)) - last_received = time.monotonic() - episode_returns: list[float] = [] - episode_lengths: list[int] = [] - while learner.update_count < cfg.max_iterations: - check_worker(worker, error_rx) - if not ring.has_next(): - if time.monotonic() - last_received > cfg.worker_timeout: - raise TimeoutError(f"No APPO collector chunk for {cfg.worker_timeout}s") - stop.wait(0.001) - continue - ingest_started = time.monotonic() - batch = take_chunk(ring, device, history) - # Host wall time for owned copies/enqueues; no extra CUDA sync. - ingest_s = time.monotonic() - ingest_started - try: - record = metrics_queue.get(timeout=cfg.worker_timeout) - except Empty as exc: - check_worker(worker, error_rx) - raise TimeoutError("Missing APPO collector metrics for published chunk") from exc - last_received = time.monotonic() - update_started = time.monotonic() - metrics = learner.update(batch) - optimize_s = time.monotonic() - update_started - publish_started = time.monotonic() sender.publish(modules, norms) - weight_publish_s = time.monotonic() - publish_started - # Wall-clock boundaries only; publication owns its required CUDA completion. - update_s = time.monotonic() - update_started - episode_returns.extend(record.returns) - episode_lengths.extend(record.lengths) - metrics.update( - { - "collector/latency_s": record.latency_s, - "collector/weight_lag": float(record.published_version - record.weight_version), - "collector/queue_depth": float(ring.size()), - "learner/update_s": update_s, - "learner/optimize_s": optimize_s, - "learner/weight_publish_s": weight_publish_s, - "learner/ingest_s": ingest_s, - "env_steps": float(learner.global_step), - "wall_s": time.monotonic() - started, - } + boot.mark_ready("learner") + schema = chunk_schema( + cfg.rollout_steps, + dims.obs_dim // dims.obs_history, + dims.critic_dim // dims.critic_history, + dims.action_dim, + critic_history=dims.critic_history, + critic_uses_policy=dims.critic_uses_policy, ) - metrics.update({f"env/{key}": value for key, value in record.env_metrics.items()}) - iteration = learner.update_count - if iteration % max(context.logging.interval, 1) == 0 or iteration == cfg.max_iterations: - if episode_returns: - # Raw completed-episode return, without timeout bootstrap. - metrics["Train/mean_reward"] = float(np.mean(episode_returns)) - metrics["Train/mean_episode_length"] = float(np.mean(episode_lengths)) - episode_returns.clear() - episode_lengths.clear() - for name, value in metrics.items(): - writer.add_scalar(name, value, iteration) - context.metrics.scalars(metrics, step=iteration, env_steps=learner.global_step) - if context.checkpoint.interval > 0 and iteration % context.checkpoint.interval == 0: - self._save(learner, seed, context.checkpoint_dir / f"checkpoint_{iteration}.pt") - self._save(learner, seed, checkpoints.final_checkpoint_path(context.checkpoint_format, context.run_dir)) - finally: - stop.set() - if worker is not None: - stop_worker(worker) - for pipe in (error_rx, error_tx, startup_rx, startup_tx): - pipe.close() - metrics_queue.close() - metrics_queue.join_thread() - if writer is not None: - writer.close() + if transport == "cuda_ipc": + # Parent owns the allocation until the collector has stopped. + slots = torch.empty( + (cfg.queue_chunks, context.num_envs, schema.feature_width), device=device, dtype=torch.float32 + ) + ring_connection = GpuRingConnection( + RingCursors(), slots, schema, cfg.queue_chunks, context.num_envs + ) + ring = ring_connection.endpoint() + else: + ring = HostTransitionRing(schema, cfg.queue_chunks, context.num_envs) + ring_connection = ring + history = ChunkHistory(dims.obs_history, dims.critic_history, dims.critic_uses_policy) + startup_rx.send(CollectorConnection(ring_connection, weights, sender.params, str(chunk_device))) + boot.start() + panel = session.metrics_panel( + total_iterations=cfg.max_iterations, + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + reductions=training_log.reductions, + default_reduction=training_log.default_reduction, + ) + metrics_logger = TrainingMetrics( + [training_log, panel], + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + ) + metrics_logger.start() + last_received = time.monotonic() + while learner.update_count < cfg.max_iterations: + check_worker(worker) + if not ring.has_next(): + if time.monotonic() - last_received > cfg.worker_timeout: + raise TimeoutError(f"No APPO collector chunk for {cfg.worker_timeout}s") + metrics_logger.flush() + stop.wait(0.001) + continue + ingest_started = time.monotonic() + batch = take_chunk(ring, device, history) + # Host wall time for owned copies/enqueues; no extra CUDA sync. + ingest_s = time.monotonic() - ingest_started + try: + record = metrics_queue.get(timeout=cfg.worker_timeout) + except Empty as exc: + check_worker(worker) + raise TimeoutError("Missing APPO collector metrics for published chunk") from exc + last_received = time.monotonic() + update_started = time.monotonic() + metrics = learner.update(batch) + optimize_s = time.monotonic() - update_started + publish_started = time.monotonic() + sender.publish(modules, norms) + weight_publish_s = time.monotonic() - publish_started + # Wall-clock boundaries only; publication owns its required CUDA completion. + update_s = time.monotonic() - update_started + metrics_logger.record_episodes(record.returns, record.lengths) + metrics_logger.record( + metric_values( + metrics, + record, + StageTimings(ingest_s, optimize_s, weight_publish_s, update_s), + queue_depth=ring.size(), + ) + ) + metrics_logger.advance( + iterations=learner.update_count - metrics_logger.iteration, + env_steps=learner.global_step - metrics_logger.env_steps, + ) + iteration = learner.update_count + metrics_logger.flush(force=iteration == cfg.max_iterations) + if context.checkpoint.interval > 0 and iteration % context.checkpoint.interval == 0: + path = context.checkpoint_dir / f"checkpoint_{iteration}.pt" + self._save(learner, seed, path) + metrics_logger.checkpoint(str(path)) + final_path = checkpoints.final_checkpoint_path(context.checkpoint_format, context.run_dir) + self._save(learner, seed, final_path) + metrics_logger.checkpoint(str(final_path)) + except BaseException: + logger.exception("APPO learner failed") + raise def play(self, policy: str) -> None: context = self.context diff --git a/motrix_rl_appo/tests/test_appo_collector.py b/motrix_rl_appo/tests/test_appo_collector.py index 17e235826..4b929fe64 100644 --- a/motrix_rl_appo/tests/test_appo_collector.py +++ b/motrix_rl_appo/tests/test_appo_collector.py @@ -76,7 +76,7 @@ def test_chunk_alignment_timeout_and_endpoint() -> None: cfg.algorithm.gamma = 0.5 env = FakeEnv() collector = ChunkCollector(env, FakeActor(), FakeCritic(), cfg, torch.device("cpu")) - chunk, returns, lengths, _ = collector.collect() + chunk, returns, lengths, _, _ = collector.collect() torch.testing.assert_close(chunk["obs"][:, :, 0], torch.tensor([[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]])) torch.testing.assert_close(chunk["critic_obs"], chunk["obs"] + 10) torch.testing.assert_close(chunk["actions"], chunk["obs"] * 10) @@ -93,6 +93,22 @@ def test_chunk_alignment_timeout_and_endpoint() -> None: assert chunk["last_critic_obs"][0, 0] == 13 +def test_chunk_episode_deltas_are_consumed_and_unfinished_returns_cross_chunks() -> None: + class DelayedEnv(FakeEnv): + def step(self, actions: torch.Tensor) -> ArrayEnvState: + self.actions.append(actions.clone()) + done = torch.full((3,), len(self.actions) == 3, dtype=torch.bool) + return self.state(done, torch.zeros(3, dtype=torch.bool)) + + collector = ChunkCollector(DelayedEnv(), FakeActor(), FakeCritic(), AppoCfg(rollout_steps=2), torch.device("cpu")) + _, returns, lengths, _, _ = collector.collect() + assert returns == [] and lengths == [] + _, returns, lengths, _, _ = collector.collect() + assert returns == [3.0] * 3 and lengths == [3] * 3 + _, returns, lengths, _, _ = collector.collect() + assert returns == [] and lengths == [] + + def test_borrowed_carrier_reuse_only_after_publication() -> None: cfg = AppoCfg(rollout_steps=2) collector = ChunkCollector(FakeEnv(), FakeActor(), FakeCritic(), cfg, torch.device("cpu")) @@ -119,7 +135,7 @@ def test_timeout_without_final_obs_uses_owned_pre_action_value_and_warns_once(ca cfg = AppoCfg(rollout_steps=2) cfg.algorithm.gamma = 0.5 collector = ChunkCollector(FakeEnv(missing_final=True), FakeActor(), FakeCritic(), cfg, torch.device("cpu")) - chunk, returns, _, _ = collector.collect() + chunk, returns, _, _, _ = collector.collect() # Row2 is timeout-only: start values13,14, not overwritten next values14,15. # Row1 is both terminated and truncated and must never bootstrap. torch.testing.assert_close(chunk["rewards"], torch.tensor([[1.0, 1.0], [1.0, 1.0], [7.5, 8.0]])) @@ -140,3 +156,35 @@ def step(self, actions: torch.Tensor) -> ArrayEnvState: ) with pytest.raises(RuntimeError, match="do not cover"): collector.collect() + + +def test_reward_terms_are_chunk_means_and_do_not_leak_between_chunks(monkeypatch) -> None: + class RewardEnv(FakeEnv): + def __init__(self): + super().__init__() + self.term = torch.zeros(3) + + def step(self, actions): + state = super().step(actions) + self.term.fill_(len(self.actions)) + state.reward_terms["alive"] = self.term + return state + + env = RewardEnv() + collector = ChunkCollector(env, FakeActor(), FakeCritic(), AppoCfg(rollout_steps=2), torch.device("cpu")) + # Recording device samples never synchronizes via item; only chunk drain does. + original_record = collector._reward_terms.record + + def record_without_host_conversion(name, value): + with monkeypatch.context() as patch: + patch.setattr(torch.Tensor, "item", lambda self: pytest.fail("per-step item")) + original_record(name, value) + + monkeypatch.setattr(collector._reward_terms, "record", record_without_host_conversion) + chunk, returns, lengths, _, terms = collector.collect() + assert terms == {"alive": 1.5} + assert returns == [1.0] * 4 # raw returns not bootstrap reward or reward-term sum + assert lengths == [1] * 4 + _, _, _, _, next_terms = collector.collect() + assert next_terms == {"alive": 3.5} + assert terms == {"alive": 1.5} # prior report owns the scalar snapshot diff --git a/motrix_rl_appo/tests/test_appo_metrics_log.py b/motrix_rl_appo/tests/test_appo_metrics_log.py new file mode 100644 index 000000000..9bdaa32ed --- /dev/null +++ b/motrix_rl_appo/tests/test_appo_metrics_log.py @@ -0,0 +1,61 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import pytest +from motrix_rl_appo.collector import CollectorMetrics +from motrix_rl_appo.metrics import TIMING_KEYS, StageTimings, metric_values + +from motrix_rl.console.panel import TrainingPanelSession +from motrix_rl.log.live import MotrixLiveLogger +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics + + +def test_canonical_latest_scalars_and_mean_timings_share_recent_episode_snapshot(monkeypatch) -> None: + emitted = [] + monkeypatch.setattr(TrainingLogger, "_emit", lambda self, values: emitted.append(values)) + log = TrainingLogger( + "unused", MotrixLiveLogger.disabled(), interval=2, reductions=dict.fromkeys(TIMING_KEYS, "mean") + ) + session = TrainingPanelSession(interval_seconds=0) + frames = [] + monkeypatch.setattr(session, "_draw", lambda stats: frames.append(stats)) + panel = session.metrics_panel( + total_iterations=2, reductions=log.reductions, default_reduction=log.default_reduction + ) + output = TrainingMetrics([log, panel], initial_iteration=log.iteration, initial_env_steps=log.env_steps) + for iteration, returns in ((1, list(range(101))), (2, [])): + values = metric_values( + {"loss": float(iteration), "new_metric": 0.5}, + CollectorMetrics(returns, [10] * len(returns), iteration * 0.1, 2, 5, {"height": 0.4}, {"alive": 0.75}), + StageTimings(iteration * 0.01, 0.02, 0.005, 0.03), + queue_depth=3, + ) + output.record_episodes(returns, [10] * len(returns)) + output.record(values) + output.advance(env_steps=8) + output.flush() + assert len(emitted) == 1 + values = emitted[0] + assert values["train/loss"] == 2.0 and values["train/new_metric"] == 0.5 + assert values["env/height"] == 0.4 + assert values["reward/alive"] == 0.75 + assert frames[-1].metrics["reward/alive"] == 0.75 + assert values["collector/queue_depth"] == 3.0 and values["collector/weight_lag"] == 3.0 + # Latest recent-100 mean, NOT mean of per-observation means (or interval samples). + assert values["episode/recent_return_mean"] == 50.5 + assert "episode/completed" not in values + assert values["timing/collector/rollout_s"] == pytest.approx(0.15) + assert values["timing/learner/ingest_s"] == pytest.approx(0.015) + assert values["timing/learner/update_s"] == pytest.approx(0.03) + assert values["timing/learner/total_s"] == pytest.approx(0.045) + + +def test_observation_mapping_owns_values_without_extra_state() -> None: + metrics = {"loss": 1.0} + values = metric_values( + metrics, CollectorMetrics([], [], 0.1, 0, 0, {}, {}), StageTimings(0, 0, 0, 0), queue_depth=0 + ) + metrics["loss"] = 9.0 + assert values["train/loss"] == 1.0 + assert "episode/recent_return_mean" not in values diff --git a/motrix_rl_appo/tests/test_appo_trainer.py b/motrix_rl_appo/tests/test_appo_trainer.py index e3b676d2c..7278e3d82 100644 --- a/motrix_rl_appo/tests/test_appo_trainer.py +++ b/motrix_rl_appo/tests/test_appo_trainer.py @@ -33,6 +33,12 @@ def __init__(self, alive: bool = True) -> None: self.terminated = False self.killed = False + def check(self) -> None: + pass + + def close(self) -> None: + self.process.close() + def join(self, timeout: float) -> None: pass @@ -46,18 +52,16 @@ def kill(self) -> None: def test_startup_timeout_and_clean_exit_are_reported() -> None: ctx = mp.get_context("spawn") - errors, error_tx = ctx.Pipe(duplex=False) startup, startup_tx = ctx.Pipe() try: + waiting = [] with pytest.raises(TimeoutError, match="startup metadata"): - wait_ready(FakeWorker(), errors, startup, timeout=0.001) + wait_ready(FakeWorker(), startup, timeout=0.001, on_wait=lambda: waiting.append(True)) + assert waiting # startup polling offers a log refresh without weakening the timeout with pytest.raises(RuntimeError, match="unexpectedly"): - check_worker(FakeWorker(alive=False), errors) - error_tx.send("original traceback") - with pytest.raises(RuntimeError, match="original traceback"): - check_worker(FakeWorker(), errors) + check_worker(FakeWorker(alive=False)) finally: - for pipe in (errors, error_tx, startup, startup_tx): + for pipe in (startup, startup_tx): pipe.close() @@ -114,6 +118,32 @@ def test_real_cartpole_spawn_resume_and_deterministic_play(tmp_path, monkeypatch from motrix_env_core.renderer import RenderConfig from motrix_rl_appo import trainer as trainer_module + forced_updates = [] + refresh = trainer_module.TrainingMetrics.flush + + def capture_refresh(self, *, force: bool = False) -> None: + if force: + forced_updates.append((self.iteration, self.env_steps)) + refresh(self, force=force) + + monkeypatch.setattr(trainer_module.TrainingMetrics, "flush", capture_refresh) + from motrix_rl.console.metric_panel import MetricsPanel + + original_update = trainer_module.APPOLearner.update + original_metrics_panel = trainer_module.TrainingPanelSession.metrics_panel + active_sessions = [] + + def capture_metrics_panel(self, **kwargs): + phase = original_metrics_panel(self, **kwargs) + active_sessions.append(self) + return phase + + def require_metrics_stage(self, batch): + assert active_sessions and isinstance(active_sessions[-1]._active, MetricsPanel) + return original_update(self, batch) + + monkeypatch.setattr(trainer_module.TrainingPanelSession, "metrics_panel", capture_metrics_panel) + monkeypatch.setattr(trainer_module.APPOLearner, "update", require_metrics_stage) cfg = AppoCfg( actor=NetworkCfg(hidden_dims=[8]), critic=NetworkCfg(hidden_dims=[8]), @@ -148,6 +178,12 @@ def test_real_cartpole_spawn_resume_and_deterministic_play(tmp_path, monkeypatch AppoTrainer(context=replace(context, resume_from=str(final))).train() saved = torch.load(final, weights_only=False) assert saved["iteration"] == 3 and saved["learner"]["global_step"] == 12 + assert forced_updates == [(2, 8), (3, 12)] + # An already-complete resume still creates a training stage and saves the + # final artifact without fabricating another learner update. + AppoTrainer(context=replace(context, resume_from=str(final))).train() + assert torch.load(final, weights_only=False)["iteration"] == 3 + assert len(active_sessions) == 3 class OneStepRenderer: def __init__(self) -> None: @@ -215,7 +251,7 @@ def test_real_go2_timeout_hook_and_collector_bootstrap() -> None: parameter.zero_() critic.mlp[-1].bias.fill_(2.0) collector = ChunkCollector(env, actor, critic, cfg, torch.device("cpu")) - chunk, returns, lengths, _ = collector.collect() + chunk, returns, lengths, _, _ = collector.collect() state = env.state final = state.final_obs assert final is not None @@ -233,6 +269,69 @@ def test_real_go2_timeout_hook_and_collector_bootstrap() -> None: torch.testing.assert_close(final.obs.value, owned) +def test_cleanup_failure_still_closes_logging_and_panel(tmp_path, monkeypatch) -> None: + import logging + + from motrix_rl_appo import trainer as trainer_module + + closed = [] + + class Panel: + def boot_panel(self, workers): + return self + + def message(self, text): + pass + + def refresh(self): + pass + + def close(self): + closed.append("panel") + + class Log: + def __init__(self, run_dir, metrics, **kwargs): + pass + + def close(self): + closed.append("training_log") + + def fail_startup(*args, **kwargs): + raise ValueError("startup failed") + + def fail_cleanup(worker): + raise RuntimeError("worker cleanup failed") + + monkeypatch.setattr(trainer_module.TrainingPanelSession, "open", lambda **kwargs: Panel()) + monkeypatch.setattr(trainer_module, "TrainingLogger", Log) + monkeypatch.setattr(trainer_module.CollectorWorker, "start", lambda *args, **kwargs: FakeWorker()) + monkeypatch.setattr(trainer_module, "wait_ready", fail_startup) + monkeypatch.setattr(trainer_module, "stop_worker", fail_cleanup) + namespace = logging.getLogger("motrix_rl_appo") + original = (namespace.handlers[:], namespace.level, namespace.propagate) + cfg = AppoCfg(device="cpu", collector_device="cpu") + context = TrainerContext( + None, + "fake", + tmp_path, + tmp_path / "checkpoints", + None, + "pt", + 2, + 1, + 4, + cfg, + LoggingConfig("tensorboard", 1), + CheckpointConfig(1), + ) + with pytest.raises(RuntimeError, match="worker cleanup failed"): + AppoTrainer(context=context).train() + assert closed == ["training_log", "panel"] + assert (namespace.handlers, namespace.level, namespace.propagate) == original + text = (tmp_path / "logs" / "learner.log").read_text() + assert "Traceback (most recent call last)" in text and "ValueError: startup failed" in text + + def test_rng_roundtrip() -> None: state = rng_state() expected = (random.random(), np.random.rand(), torch.rand(2)) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/agent.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/agent.py index 3f03bac1f..68f022ca0 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/agent.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/agent.py @@ -21,10 +21,10 @@ from torch import nn, optim from motrix_env_core.observations import ObservationSpec +from motrix_rl.log.tensor_window import TensorMetricWindow from motrix_rl_builtin.fastsac.buffer import EmpiricalNormalization, SimpleReplayBuffer from motrix_rl_builtin.fastsac.config import FastSacAgentCfg from motrix_rl_builtin.fastsac.networks import Actor, Critic -from motrix_rl_builtin.fastsac.window_metrics import WindowMetrics class FastSacAgent: @@ -38,7 +38,6 @@ def __init__( device: torch.device, action_scale: torch.Tensor | None = None, action_bias: torch.Tensor | None = None, - writer=None, world_size: int = 1, final_obs_bootstrap: bool = False, observation_spec: ObservationSpec | None = None, @@ -65,7 +64,6 @@ def __init__( self.critic_obs_dim = critic_obs_dim self.act_dim = act_dim self.num_envs = num_envs - self.writer = writer self.global_step = 0 # Persistent gradient-update counter shared by all trainers. Used for # policy_frequency gating (so the actor/Q ratio is exactly 1/policy_freq @@ -73,10 +71,24 @@ def __init__( # publish-cadence bookkeeping. self.update_idx = 0 self._last_update_timing_ms: dict[str, float] = {} - # Window-aggregated diagnostics (see window_metrics.py): means and + # Device-resident window diagnostics: means and # per-key extremes accumulated across update() calls until the trainer # drains them at a logging boundary. - self.window_metrics = WindowMetrics() + self.window_metrics = TensorMetricWindow( + { + "qf_loss": "mean", + "qf_max": "range", + "qf_min": "range", + "alpha_loss": "mean", + "alpha_loss_abs": "range", + "alpha": "mean", + "policy_entropy": "range", + "actor_loss": "mean", + "batch_reward_max": "range", + "batch_reward_mean": "mean", + "final_obs_events": "mean", + } + ) self.actor = Actor( n_obs=obs_dim, @@ -293,9 +305,9 @@ def _update_main(self, b: dict): self._allreduce_module_grads([self.qnet]) if cfg.max_grad_norm > 0: torch.nn.utils.clip_grad_norm_(self.qnet.parameters(), cfg.max_grad_norm) - self.window_metrics.add("qf_loss", qf_loss) - self.window_metrics.add("qf_max", tv_max, track_range=True) - self.window_metrics.add("qf_min", tv_min, track_range=True) + self.window_metrics.record("qf_loss", qf_loss) + self.window_metrics.record("qf_max", tv_max) + self.window_metrics.record("qf_min", tv_min) self.q_optimizer.step() # Target-network soft update. Ordering constraints: after the target @@ -318,9 +330,9 @@ def _update_main(self, b: dict): # gradient manually to keep every rank's temperature identical. dist.all_reduce(self.log_alpha.grad, op=dist.ReduceOp.AVG) self.alpha_optimizer.step() - self.window_metrics.add("alpha_loss", alpha_loss) - self.window_metrics.add("alpha_loss_abs", alpha_loss.abs(), track_range=True) - self.window_metrics.add("alpha", self.log_alpha.exp()) + self.window_metrics.record("alpha_loss", alpha_loss) + self.window_metrics.record("alpha_loss_abs", alpha_loss.abs()) + self.window_metrics.record("alpha", self.log_alpha.exp()) return (qf_loss, alpha_loss.detach().float(), tv_max, tv_min) @@ -351,8 +363,8 @@ def _update_pol(self, b: dict): self._allreduce_module_grads([self.actor, self.qnet]) if self.cfg.max_grad_norm > 0: torch.nn.utils.clip_grad_norm_(self.actor.parameters(), self.cfg.max_grad_norm) - self.window_metrics.add("policy_entropy", neg_logp, track_range=True) - self.window_metrics.add("actor_loss", actor_loss) + self.window_metrics.record("policy_entropy", neg_logp) + self.window_metrics.record("actor_loss", actor_loss) self.actor_optimizer.step() return actor_loss, neg_logp @@ -405,8 +417,8 @@ def update(self, num_updates: int) -> None: for i in range(num_updates): b = prepared[i] - self.window_metrics.add("batch_reward_max", b["rewards"].max(), track_range=True) - self.window_metrics.add("batch_reward_mean", b["rewards"].mean()) + self.window_metrics.record("batch_reward_max", b["rewards"].max()) + self.window_metrics.record("batch_reward_mean", b["rewards"].mean()) # Required with reduce-overhead (CUDA graph trees): open a new graph # generation for this update. NOTE it does not preserve anything -- # it *invalidates* the previous generation's outputs, which is why diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py index ebe613e99..0af615490 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/collector.py @@ -16,10 +16,11 @@ import time -import numpy as np import torch from torch import nn +from motrix_rl.console.timing import PerfTimingWindow +from motrix_rl.log.collector_stats import CollectorStats, CollectorStatsTracker from motrix_rl_builtin.fastsac.async_impl.transport import ( Control, FinalObsPayload, @@ -85,12 +86,7 @@ def __init__( self.control = control self.collector_id = collector_id self.is_resume = is_resume - # Env-internal step profiling (Perf on the wrapped env, when present) - # feeds the panel's env_step sub-stage tree. ``env.env`` is the - # FastSacEnvWrap contract for reaching the original environment. - self._env_perf = getattr(env.env, "perf", None) - if self._env_perf is not None: - self._env_perf.enable() + self._perf_window = PerfTimingWindow(env.env.perf) self._learning_starts = acfg.learning_starts self.actor = Actor( @@ -144,31 +140,16 @@ def __init__( # rollout state self.obs = None self.critic_obs = None - # episode bookkeeping (owned here since the collector sees reward/done) - self.ep_return = torch.zeros(self.num_envs, device=self.env_device) - self.ep_len = torch.zeros(self.num_envs, device=self.env_device) - self.recent_returns: list[float] = [] - self.recent_lengths: list[float] = [] - self.n_episodes = 0 - self.term_accum: dict[str, float] = {} - self.term_count = 0 - self.last_env_metrics: dict[str, float] = {} - # windowed collector timing (wall-clock spent producing one env-step batch) - self._collect_t = 0.0 - self._sample_actions_t = 0.0 - self._env_step_t = 0.0 - self._push_t = 0.0 - self._bookkeep_t = 0.0 - self._sync_t = 0.0 - self._sync_wait_writer_t = 0.0 - self._sync_host_snapshot_t = 0.0 - self._sync_actor_load_t = 0.0 - self._wait_t = 0.0 + self.stats = CollectorStatsTracker( + collector_id, num_envs=self.num_envs, device=self.env_device, perf_window=self._perf_window + ) + self._sync_stage_seconds = {"sync.wait_writer": 0.0, "sync.host_snapshot": 0.0, "sync.actor_load": 0.0} self._wait_started: float | None = None - self._collect_n = 0 def reset(self) -> None: self.obs, self.critic_obs = self.env.reset() + self.stats.reset() + self._perf_window.start() def _autocast(self): if self._amp_enabled: @@ -213,9 +194,9 @@ def sync_weights(self, *, record_timing: bool = False) -> None: flat_params=None if self._flat_params is None else {"actor": self._flat_params}, ) if record_timing: - self._sync_wait_writer_t += wait_writer_s - self._sync_host_snapshot_t += host_snapshot_s - self._sync_actor_load_t += actor_load_s + self._sync_stage_seconds["sync.wait_writer"] = wait_writer_s + self._sync_stage_seconds["sync.host_snapshot"] = host_snapshot_s + self._sync_stage_seconds["sync.actor_load"] = actor_load_s @property def policy_lag(self) -> int: @@ -235,9 +216,8 @@ def step_once(self) -> bool: self._wait_started = now return False - if self._wait_started is not None: - self._wait_t += now - self._wait_started - self._wait_started = None + wait_s = now - self._wait_started if self._wait_started is not None else 0.0 + self._wait_started = None steps = self.control.collector_steps_at(self.collector_id) warming = steps < self._learning_starts @@ -274,103 +254,44 @@ def step_once(self) -> bool: ) t_bookkeep = time.perf_counter() - # episode bookkeeping (mirrors sync agent.py collect phase) - self.ep_return += rewards - self.ep_len += 1 - done_idx = torch.nonzero(terminated | truncated, as_tuple=False).flatten() - if done_idx.numel(): - # Vectorized: one batched gather + clear instead of per-episode - # Python-level scalar indexing — early in training hundreds of - # dones per step make the scalar loop dominate bookkeeping. - self.recent_returns.extend(self.ep_return[done_idx].tolist()) - self.recent_lengths.extend(self.ep_len[done_idx].tolist()) - self.ep_return[done_idx] = 0.0 - self.ep_len[done_idx] = 0.0 - self.n_episodes += int(done_idx.numel()) - self.recent_returns = self.recent_returns[-100:] - self.recent_lengths = self.recent_lengths[-100:] - - info = result.info - reward_terms = info.get("Reward") - if reward_terms: - for k, v in reward_terms.items(): - self.term_accum[k] = self.term_accum.get(k, 0.0) + float(v.mean()) - self.term_count += 1 - self.last_env_metrics = {k: float(np.mean(v)) for k, v in info.get("metrics", {}).items()} + self.stats.record_step( + rewards, + terminated | truncated, + reward_terms=result.info.get("Reward", {}), + metrics=result.info.get("metrics", {}), + ) self.obs = result.obs self.critic_obs = result.critic_obs self.control.inc_collector_steps(self.collector_id) t_sync = time.perf_counter() + for key in self._sync_stage_seconds: + self._sync_stage_seconds[key] = 0.0 if self.control.collector_steps_at(self.collector_id) % max(self.async_options.weight_poll_interval, 1) == 0: self.sync_weights(record_timing=True) t_done = time.perf_counter() - self._collect_t += t_done - t_sample - self._sample_actions_t += t_env - t_sample - self._env_step_t += t_payload - t_env - self._push_t += t_bookkeep - t_push - self._bookkeep_t += t_sync - t_bookkeep - self._sync_t += t_done - t_sync - self._collect_n += 1 + self.stats.record_timings( + { + "collect": t_done - t_sample, + "wait": wait_s, + "sample_actions": t_env - t_sample, + "env_step": t_payload - t_env, + "push": t_bookkeep - t_push, + "bookkeep": t_sync - t_bookkeep, + "sync": t_done - t_sync, + **self._sync_stage_seconds, + } + ) return True # ------------------------------------------------------------------ stats - def snapshot_stats(self) -> dict: - """Compact rollout-stats snapshot for the learner's log panel. - - Resets the windowed reward-term accumulator so each snapshot reflects the - interval since the last call. Used by the M1 collector process to ship - episode/reward info to the learner process (which owns logging). - """ - rr, rl = self.recent_returns, self.recent_lengths - term_means = {k: v / max(self.term_count, 1) for k, v in self.term_accum.items()} - stats = { - "collector_id": self.collector_id, - "return": (sum(rr) / len(rr)) if rr else float("nan"), - "ep_len": (sum(rl) / len(rl)) if rl else float("nan"), - "episodes": self.n_episodes, - "reward_terms": term_means, - "env_metrics": dict(self.last_env_metrics), - "policy_lag": self.policy_lag, - # Average wall-clock milliseconds per successful env-step batch. - # Nested stages use dotted paths (``sync.wait_writer``, - # ``env_step.physics.read``): the panel rebuilds one tree from - # them with a single rule, so key prefixes never encode structure. - "timing_ms": { - "collect": self._collect_t * 1000.0 / max(self._collect_n, 1), - "wait": self._wait_t * 1000.0 / max(self._collect_n, 1), - "sample_actions": self._sample_actions_t * 1000.0 / max(self._collect_n, 1), - "env_step": self._env_step_t * 1000.0 / max(self._collect_n, 1), - "push": self._push_t * 1000.0 / max(self._collect_n, 1), - "bookkeep": self._bookkeep_t * 1000.0 / max(self._collect_n, 1), - "sync": self._sync_t * 1000.0 / max(self._collect_n, 1), - "sync.wait_writer": self._sync_wait_writer_t * 1000.0 / max(self._collect_n, 1), - "sync.host_snapshot": self._sync_host_snapshot_t * 1000.0 / max(self._collect_n, 1), - "sync.actor_load": self._sync_actor_load_t * 1000.0 / max(self._collect_n, 1), - }, - } - env_perf = self._env_perf - if env_perf is not None: - for path, mean_ms in env_perf.stage_mean_ms("step").items(): - if "." in path: - # Only the first sub-stage level is reported: a parent's - # total already includes its children, so deeper paths - # would duplicate time without adding actionable signal. - continue - stats["timing_ms"][f"env_step.{path}"] = mean_ms - env_perf.reset() - self.term_accum, self.term_count = {}, 0 - self._collect_t = 0.0 - self._sample_actions_t = 0.0 - self._env_step_t = 0.0 - self._push_t = 0.0 - self._bookkeep_t = 0.0 - self._sync_t = 0.0 - self._sync_wait_writer_t = 0.0 - self._sync_host_snapshot_t = 0.0 - self._sync_actor_load_t = 0.0 - self._wait_t = 0.0 - self._collect_n = 0 - return stats + def snapshot_stats(self) -> CollectorStats: + """Report framework-maintained observation and profiler windows.""" + self.stats.set_diagnostics({"policy_lag": float(self.policy_lag)}) + return self.stats.snapshot() + + def close(self) -> None: + """Release profiling ownership without closing the borrowed environment.""" + self._perf_window.close() diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py index cd42f5489..ec403d954 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner.py @@ -355,7 +355,7 @@ def _flush_complete_generations(self) -> int: ingested = self._ingest_runs((stacked,), final_payloads=final_payloads) if final_payloads is not None: events = sum(p.env_ids.numel() for p in final_payloads if p is not None) - self.agent.window_metrics.add("final_obs_events", torch.tensor(float(events), device=self.agent.device)) + self.agent.window_metrics.record("final_obs_events", torch.tensor(float(events), device=self.agent.device)) for ring in self.rings: ring.commit_reads(ingested) if self._staging is not None: diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/panels.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/panels.py deleted file mode 100644 index fa6597b37..000000000 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/panels.py +++ /dev/null @@ -1,186 +0,0 @@ -# Copyright Motphys Technology Co., Ltd. 2025, 2026 -# SPDX-License-Identifier: Apache-2.0 - -"""Rich panel rendering for the async FastSAC trainer's parent process. - -The boot panel (worker startup table + worker-log tail) runs on the -alternate screen via ``rich.live.Live`` while workers boot at different -speeds. Everything here is pure rendering; the boot loop, readiness -tracking and error handling stay in ``train.py``. The post-boot training -panel is shared across frameworks and lives in ``motrix_rl.console``. - -Frame geometry is the core contract: the panel is a vertical ``Layout`` -where the worker table takes a fixed number of lines and the log region -expands to every remaining terminal line. Log lines are either cropped or -folded into full-width continuations, and the DISPLAY line count is capped -so the frame height never changes between refreshes — a Live redraw whose -frame grows, wraps or overflows the terminal cannot erase its previous -frame and tears. -""" - -from __future__ import annotations - -import math -import os -from collections.abc import Sequence -from pathlib import Path - -from rich.console import Console, Group -from rich.layout import Layout -from rich.panel import Panel -from rich.table import Table -from rich.text import Text - -_LOG_TAIL_PLACEHOLDER = "(waiting for worker logs…)" - - -def worker_log_tail( - log_dir: Path, - log_names: Sequence[str], - max_lines: int = 4, - line_width: int = 120, - per_file: int = 2, - wrap: bool = False, -) -> Text: - """Render the boot panel's worker-log region. - - Reads the last bytes of each worker log file and returns at most - ``max_lines`` display lines (the last ``per_file`` source lines per file, - newest last). Each source line becomes exactly one display line cropped - to ``line_width``, or — with ``wrap=True`` — as many full-width - continuation lines as it needs. Either way the panel's geometry stays - constant across refreshes (the display-line count is always capped at - ``max_lines``), which is what keeps the Live redraw tear-free. - - Lines are grouped per worker in ``log_names`` order (collectors first, - learners last), untagged — the surrounding panel/table names the worker. - Missing files (worker hasn't created its log yet) are skipped silently. - """ - display: list[str] = [] - for name in log_names: - path = Path(log_dir) / name - try: - with path.open("rb") as f: - f.seek(0, os.SEEK_END) - size = f.tell() - f.seek(max(0, size - 8192)) - chunk = f.read().decode(errors="replace") - except OSError: - continue - tail = [ln for ln in chunk.splitlines() if ln.strip()][-per_file:] - for ln in tail: - if wrap: - display.extend(ln[j : j + line_width] for j in range(0, len(ln), line_width)) - else: - display.append(ln[:line_width]) - return Text("\n".join(display[-max_lines:]) or _LOG_TAIL_PLACEHOLDER, style="dim") - - -class BootPanel: - """Worker-startup panel: worker table below a grid of per-worker log cells.""" - - def __init__(self, title: str, log_dir: Path, log_names: Sequence[str], workers: Sequence[tuple[str, int]]) -> None: - self._title = title - self._log_dir = Path(log_dir) - self._log_names = list(log_names) - self._workers = list(workers) - self.console = Console() - # Outer frame mirrors the training panel: task name on top, cyan - # border. Its border + padding cost 2 lines and 4 columns of the - # terminal, shrinking the inner regions accordingly. - self._frame_lines = 2 - self._frame_cols = 4 - # Table height = header + 3 rule rows + one row per worker, - # plus the always-reserved gate line. - # The log grid VERTICALLY EXPANDS to every remaining terminal line. - self._table_lines = len(self._workers) + 4 + 1 - # Near-square grid: 1-2 workers stay in one row, more pack into - # ceil(sqrt(n)) columns so cells keep a readable width. - n = max(1, len(self._log_names)) - self._grid_cols = math.ceil(math.sqrt(n)) - self._grid_rows = math.ceil(n / self._grid_cols) - # Cell inner size: the log region split by the grid shape, minus each - # cell Panel's border and padding columns/rows. - region_lines = max(self._grid_rows * 3, self.console.height - self._frame_lines - self._table_lines) - self.log_tail_lines = max(1, region_lines // self._grid_rows - 2) - inner_width = self.console.width - self._frame_cols - self.log_line_width = max(20, inner_width // self._grid_cols - 4) - # Without a TTY (piped/redirected stdout) Live cannot redraw in place - # and every refresh appends a new frame; the caller renders one - # static frame instead (auto_refresh=False, no updates). - self.interactive = self.console.is_terminal - - def _worker_panel(self, name: str) -> Panel: - """One worker's log cell: fixed-size Panel padded to full height.""" - worker = name.removesuffix(".log") - text = worker_log_tail( - self._log_dir, - [name], - self.log_tail_lines, - self.log_line_width, - per_file=self.log_tail_lines, - wrap=True, - ) - # Pad to a fixed line count so the panel (and thus the whole frame) - # keeps a constant height between refreshes. - body = text.plain.splitlines() - body += [""] * (self.log_tail_lines - len(body)) - return Panel( - Text("\n".join(body), style="dim"), - title=worker, - border_style="dim", - expand=True, - height=self.log_tail_lines + 2, - ) - - def render(self, ready: set[tuple[str, int]], gate: str | None = None, starting: bool = False) -> Panel: - """Render one boot/handoff frame. - - The whole view is wrapped in the same outer frame the training panel - uses (task name on top, cyan border). ``ready`` drives the boot phase - (booting…/ready). After the barrier releases, the caller sets - ``starting`` (every worker flips to a "starting" status) and passes - ``gate``, the one-line panel-data readiness summary; the same panel - then serves as the handoff view until the training panel's quiescence - gate opens, so the terminal never switches views mid-boot. - """ - inner_width = self.console.width - self._frame_cols - table = Table(expand=True, width=inner_width) - table.add_column("worker") - table.add_column("status") - for role, idx in sorted(self._workers): - name = f"{role}[{idx}]" - if starting: - table.add_row(name, "[yellow]starting[/yellow]") - elif (role, idx) in ready: - table.add_row(name, "[green]ready[/green]") - else: - table.add_row(name, "[dim]booting…[/dim]") - # Worker-log grid: rows of equal-height cells, each cell one worker. - logs = Layout(name="logs") - rows = [] - for r in range(self._grid_rows): - cells = self._log_names[r * self._grid_cols : (r + 1) * self._grid_cols] - row = Layout(name=f"log-row{r}") - row.split_row(*(Layout(name=name.removesuffix(".log"), ratio=1) for name in cells)) - rows.append(row) - logs.split_column(*rows) - for name in self._log_names: - logs[name.removesuffix(".log")].update(self._worker_panel(name)) - # The gate line is always reserved (empty during the boot phase) so - # the frame geometry is identical across the boot→handoff switch. - bottom = Group(table, Text(gate if gate else "", style="dim")) - layout = Layout() - layout.split_column( - Layout(name="logs"), - Layout(name="table", size=self._table_lines), - ) - layout["logs"].update(logs) - layout["table"].update(bottom) - return Panel( - layout, - title=self._title, - border_style="cyan", - padding=(0, 1), - height=self.console.height, - ) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py index e7ee4bb8f..171e1c7db 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py @@ -5,96 +5,81 @@ from __future__ import annotations -import math import time from collections.abc import Mapping, Sequence from dataclasses import dataclass from multiprocessing.queues import Queue as ProcessQueue from queue import Empty -from typing import Any, Protocol, TypedDict +from typing import Protocol, TypedDict -from motrix_rl.console import PanelSystemSampler, TrainingPanelSession, TrainingPanelStats -from motrix_rl.console.metrics import ROLLOUT_MEANS, system_scalars -from motrix_rl.training_logger import TrainingLogger - -TimingTree = dict[str, object] +from motrix_rl.console.data import RateTracker +from motrix_rl.console.panel import TimingNode +from motrix_rl.log.collector_stats import CollectorStats def timing_mean(values: list[float]) -> float: - """Mean of a non-empty timing sample list (ms).""" + """Mean of a non-empty timing sample list.""" return sum(values) / len(values) -def nest_timing_path(tree: dict[str, Any], parts: tuple[str, ...], value: float) -> None: - """Insert one dotted timing path into a nested mapping.""" - head, rest = parts[0], parts[1:] - node = tree.get(head) - if not rest: - if isinstance(node, dict): - node["total"] = value - else: - tree[head] = value - else: - if not isinstance(node, dict): - node = {"total": node} if node is not None else {} - tree[head] = node - nest_timing_path(node, rest, value) - - -def aggregate_collector_stats(per_collector: dict[int, dict | None]) -> dict: - """Merge per-collector rollout snapshots into one aggregate stats dict.""" - snapshots = [stats for stats in per_collector.values() if stats] - - def _nanmean(key: str) -> float: - values = [stats[key] for stats in snapshots if not math.isnan(stats.get(key, float("nan")))] - return (sum(values) / len(values)) if values else float("nan") - - def _mean_dicts(key: str) -> dict[str, float]: - keys = {k for stats in snapshots for k in stats.get(key, {})} +@dataclass(frozen=True) +class AggregatedCollectorStats: + mean_return: float | None + mean_episode_length: float | None + episodes: int + reward_terms: dict[str, float] + env_metrics: dict[str, float] + policy_lag: float + timing_ms: dict[str, float] + + +def _timing_values(nodes: tuple[TimingNode, ...], prefix: str = "") -> dict[str, float]: + values: dict[str, float] = {} + for node in nodes: + path = f"{prefix}.{node.name}" if prefix else node.name + if node.duration_ms is not None: + values[path] = node.duration_ms + values.update(_timing_values(node.children, path)) + return values + + +def aggregate_collector_stats(per_collector: Mapping[int, CollectorStats | None]) -> AggregatedCollectorStats: + """Preserve FastSAC's equal-collector means; cumulative counts are not weights.""" + snapshots = [stats for stats in per_collector.values() if stats is not None] + + def mean(values: list[float | None]) -> float | None: + present = [value for value in values if value is not None] + return sum(present) / len(present) if present else None + + def mean_dicts(values: list[Mapping[str, float]]) -> dict[str, float]: + keys = dict.fromkeys(key for items in values for key in items) return { - k: sum(stats[key][k] for stats in snapshots if k in stats.get(key, {})) - / sum(1 for stats in snapshots if k in stats.get(key, {})) - for k in keys + key: sum(items[key] for items in values if key in items) / sum(key in items for items in values) + for key in keys } - return { - "return": _nanmean("return"), - "ep_len": _nanmean("ep_len"), - "episodes": sum(stats.get("episodes", 0) for stats in snapshots), - "reward_terms": _mean_dicts("reward_terms"), - "env_metrics": _mean_dicts("env_metrics"), - "policy_lag": max((stats.get("policy_lag", 0) for stats in snapshots), default=0), - "timing_ms": _mean_dicts("timing_ms"), - } + return AggregatedCollectorStats( + mean_return=mean([stats.mean_return for stats in snapshots]), + mean_episode_length=mean([stats.mean_episode_length for stats in snapshots]), + episodes=sum(stats.episodes for stats in snapshots), + reward_terms=mean_dicts([stats.reward_terms for stats in snapshots]), + env_metrics=mean_dicts([stats.env_metrics for stats in snapshots]), + policy_lag=max((stats.diagnostics["policy_lag"] for stats in snapshots), default=0.0), + timing_ms=mean_dicts([_timing_values(stats.timings) for stats in snapshots]), + ) class ControlLike(Protocol): collector_steps: int -CollectorSnapshot = TypedDict( - "CollectorSnapshot", - { - "collector_id": int, - "return": float, - "ep_len": float, - "episodes": int, - "reward_terms": dict[str, float], - "env_metrics": dict[str, float], - "policy_lag": float, - "timing_ms": dict[str, float], - }, - total=False, -) - - class LearnerPayload(TypedDict, total=False): rank: int training_started: bool updates: int learn_ms: float | None learn_pct: float - learner_timing: dict[str, float | dict] + learner_timing: tuple[TimingNode, ...] buffer_size: float buffer_capacity: float metrics: dict[str, float] | None @@ -120,7 +105,7 @@ class AsyncTrainingStatsSource: num_learners: int num_iterations: int resume_step: int - per_collector_stats: dict[int, CollectorSnapshot | None] + per_collector_stats: dict[int, CollectorStats | None] learner_payloads: dict[int, LearnerPayload | None] def drain(self) -> list[CheckpointNotice]: @@ -129,7 +114,7 @@ def drain(self) -> list[CheckpointNotice]: try: while True: snapshot = queue.get_nowait() - self.per_collector_stats[snapshot["collector_id"]] = snapshot + self.per_collector_stats[snapshot.collector_id] = snapshot except Empty: pass try: @@ -169,47 +154,30 @@ def handoff_gate_line(self) -> str: return f"panel data — stats: {stats_marks} | payloads: {payload_marks} | steps: {self.control.collector_steps}" -@dataclass(frozen=True) -class TrainingLogRecord: - """One logging-window payload produced independently of terminal rendering.""" - - values: Mapping[str, float] - step: int - env_steps: int - placeholders: tuple[str, ...] - - @dataclass(frozen=True) class AsyncTrainingStats: """Normalized training statistics emitted for independent consumers.""" - stats: TrainingPanelStats step: int + env_steps: int warmup_done: bool updates: int - log_record: TrainingLogRecord | None = None + scalars: Mapping[str, float] checkpoint_notices: tuple[CheckpointNotice, ...] = () class AsyncTrainingStatsAggregator: """Aggregate source payloads into normalized training statistics.""" - def __init__(self, *, learning_starts: int, logging_interval: int) -> None: + def __init__(self, *, learning_starts: int) -> None: self._learning_starts = learning_starts - self._logging_interval = logging_interval self._num_envs = 0 self._num_collectors = 0 self._num_learners = 0 - self._num_iterations = 0 - self._system_sampler = PanelSystemSampler() - self._panel_start_time = time.time() - self._panel_anchored = False - self._rate_samples: list[tuple[float, int]] = [] - self._last_log_time = self._panel_start_time - self._last_log_step = 0 + self._update_rate = RateTracker() + self._last_observed_step: int | None = None self._last_updates = 0 self._last_weight_version = 0 - self._next_log = 0 self._was_warming = learning_starts > 0 def collect(self, source: AsyncTrainingStatsSource) -> AsyncTrainingStats | None: @@ -219,208 +187,111 @@ def collect(self, source: AsyncTrainingStatsSource) -> AsyncTrainingStats | None self._num_envs = source.num_envs self._num_collectors = source.num_collectors self._num_learners = source.num_learners - self._num_iterations = source.num_iterations - if self._next_log == 0: - self._last_log_step = source.resume_step - self._next_log = ( - ((source.resume_step // max(self._logging_interval, 1)) + 1) * self._logging_interval - if self._logging_interval > 0 - else 0 - ) + if self._last_observed_step is None: + self._last_observed_step = source.resume_step self._was_warming = source.resume_step < self._learning_starts collector_steps = source.control.collector_steps step = collector_steps // self._num_collectors - now = time.time() - if step > self._last_log_step and not self._panel_anchored: - self._panel_start_time = now - self._last_log_time = now - self._panel_anchored = True - + now = time.monotonic() last_stats = aggregate_collector_stats(source.per_collector_stats) payloads = [payload for payload in source.learner_payloads.values() if payload] primary = payloads[0] if payloads else None - self._rate_samples.append((now, step)) - while len(self._rate_samples) >= 2 and self._rate_samples[1][0] <= now - 10.0: - self._rate_samples.pop(0) - t0, s0 = self._rate_samples[0] - span = now - t0 - steps_per_second = (step - s0) * self._num_envs / max(span, 1.0) if span > 0 else None - iterations_per_second = (step - s0) / max(span, 1.0) if span > 0 else None warming = step < self._learning_starts - learn_ms = ( - timing_mean([payload["learn_ms"] for payload in payloads if payload["learn_ms"] is not None]) - if payloads - else 0.0 - ) learn_percent = timing_mean([payload["learn_pct"] for payload in payloads]) if payloads else 0.0 updates = primary["updates"] if primary else self._last_updates utd = updates / max(step, 1) - collector_timing_ms = last_stats.get("timing_ms", {}) - collector_detail_ms = {key: value for key, value in collector_timing_ms.items() if key != "collect"} - collector_items: TimingTree = {} - for key, value in collector_detail_ms.items(): - nest_timing_path(collector_items, tuple(key.split(".")), value) - timing_groups: dict[str, TimingTree] = {"collector": collector_items} - for payload in payloads: - rank_key = "learner" if self._num_learners == 1 else f"learner[{payload['rank']}]" - if payload["learner_timing"]: - timing_groups[rank_key] = payload["learner_timing"] - system = self._system_sampler.sample() - panel_stats = TrainingPanelStats( - iteration=step, - total_iterations=self._num_iterations, - steps_per_second=steps_per_second, - iterations_per_second=iterations_per_second, - elapsed_seconds=now - self._panel_start_time, - mean_return=last_stats["return"], - mean_episode_length=last_stats["ep_len"], - episodes=last_stats["episodes"], - buffer_size=primary["buffer_size"] if primary else 0, - buffer_capacity=primary["buffer_capacity"] if primary else 0, - collect_ms=collector_timing_ms.get("collect", 0.0), - learn_ms=learn_ms, - learn_percent=learn_percent, - warming=warming, - training_metrics=primary["metrics"] if primary else None, - reward_terms=last_stats["reward_terms"], - env_metrics=last_stats["env_metrics"], - timing_groups=timing_groups, - diagnostics={"UTD": utd}, - cpu_load=system.cpu_load, - gpu_utilization_percent=system.gpu_utilization_percent, - memory_usage=system.memory_usage, - gpu_memory_usage=system.gpu_memory_usage, - gpu_devices=system.gpu_devices, - checkpoint_path=primary["checkpoint_path"] if primary else None, - ) scalars = self._scalars( last_stats, primary, + payloads, source.per_collector_stats, step, now, - steps_per_second, updates, utd, - learn_ms, learn_percent, ) warmup_done = self._was_warming and not warming self._was_warming = warming - log_record = None - if step >= self._next_log: - log_record = TrainingLogRecord( - values=scalars, - step=step, - env_steps=collector_steps * (self._num_envs // self._num_collectors), - placeholders=() if last_stats["episodes"] else ROLLOUT_MEANS, - ) - self.mark_logged( - step=step, - now=now, - updates=updates, - weight_version=primary.get("weight_version") if primary else None, - ) + self._last_observed_step = step + self._last_updates = updates + if primary is not None and primary.get("weight_version") is not None: + self._last_weight_version = primary["weight_version"] return AsyncTrainingStats( - stats=panel_stats, step=step, + env_steps=collector_steps * (self._num_envs // self._num_collectors), warmup_done=warmup_done, updates=updates, - log_record=log_record, + scalars=scalars, checkpoint_notices=tuple(checkpoint_notices), ) - def mark_logged(self, *, step: int, now: float, updates: int, weight_version: int | None) -> None: - self._last_log_time, self._last_log_step, self._last_updates = now, step, updates - if weight_version is not None: - self._last_weight_version = weight_version - self._next_log += self._logging_interval - def _scalars( self, - last_stats: Mapping[str, object], + last_stats: AggregatedCollectorStats, primary: LearnerPayload | None, - per_collector_stats: Mapping[int, CollectorSnapshot | None], + payloads: list[LearnerPayload], + per_collector_stats: Mapping[int, CollectorStats | None], step: int, now: float, - steps_per_second: float | None, updates: int, utd: float, - learn_ms: float, learn_percent: float, ) -> dict[str, float]: - scalars: dict[str, float] = { - "rollout/mean_return": last_stats["return"], - "rollout/mean_ep_len": last_stats["ep_len"], - } - if steps_per_second is not None: - scalars["perf/env_steps_per_s"] = steps_per_second - scalars["perf/updates_per_s"] = (updates - self._last_updates) / max(now - self._last_log_time, 1e-6) - scalars["async/policy_lag"] = last_stats["policy_lag"] + scalars: dict[str, float] = {} + if last_stats.mean_return is not None: + scalars["episode/recent_return_mean"] = last_stats.mean_return + if last_stats.mean_episode_length is not None: + scalars["episode/recent_length_mean"] = last_stats.mean_episode_length + updates_per_second = self._update_rate.update(updates, now=now) + if updates_per_second is not None: + scalars["learner/updates_per_s"] = updates_per_second + scalars["collector/policy_lag"] = last_stats.policy_lag if primary and primary.get("weight_version") is not None: - scalars["async/weight_publishes_per_iter"] = (primary["weight_version"] - self._last_weight_version) / max( - step - self._last_log_step, 1 - ) + scalars["learner/weight_publishes_per_iteration"] = ( + primary["weight_version"] - self._last_weight_version + ) / max(step - self._last_observed_step, 1) if primary: fills = primary.get("ring_fill") or [] - scalars["async/ring_fill"] = sum(fill for fill in fills if fill is not None) + scalars["collector/ring_fill"] = sum(fill for fill in fills if fill is not None) if primary.get("weight_version") is not None: - scalars["async/weight_version"] = primary["weight_version"] - scalars["async/utd"] = utd + scalars["learner/weight_version"] = primary["weight_version"] + scalars["train/UTD"] = utd if self._num_collectors > 1: for index in range(self._num_collectors): stats = per_collector_stats.get(index) if stats: - scalars[f"async/policy_lag_collector{index}"] = stats["policy_lag"] + scalars[f"collector/{index}/policy_lag"] = stats.diagnostics["policy_lag"] if primary: fill = (primary.get("ring_fill") or [None] * self._num_collectors)[index] if fill is not None: - scalars[f"async/ring_fill_collector{index}"] = fill - collector_timing_ms = last_stats.get("timing_ms", {}) - collector_detail = {key: value for key, value in collector_timing_ms.items() if key != "collect"} - scalars["perf/collect_ms_per_batch"] = collector_timing_ms.get("collect", 0.0) - scalars.update({f"perf/collector_{key}_ms": value for key, value in collector_detail.items()}) - scalars["perf/learn_ms_total"] = learn_ms - scalars["perf/learn_pct"] = learn_percent - scalars.update({f"metrics/{key}": value for key, value in last_stats["env_metrics"].items()}) - scalars.update({f"reward/{key}": value for key, value in last_stats["reward_terms"].items()}) + scalars[f"collector/{index}/ring_fill"] = fill + scalars["learner/replay_warming"] = float(step < self._learning_starts) + scalars["learner/learn_percent"] = learn_percent + scalars["timing/collector/total_s"] = last_stats.timing_ms.get("collect", 0.0) / 1000.0 + scalars.update( + { + f"timing/collector/{key.replace('.', '/')}_s": value / 1000.0 + for key, value in last_stats.timing_ms.items() + if key != "collect" + } + ) + for payload in payloads: + root = "learner" if self._num_learners == 1 else f"learner[{payload['rank']}]" + if payload["learn_ms"] is not None: + scalars[f"timing/{root}/total_s"] = payload["learn_ms"] / 1000.0 + scalars.update( + { + f"timing/{root}/{key.replace('.', '/')}_s": value / 1000.0 + for key, value in _timing_values(payload["learner_timing"]).items() + } + ) + if primary: + scalars["learner/buffer_size"] = primary["buffer_size"] + scalars["learner/buffer_capacity"] = primary["buffer_capacity"] + scalars.update({f"env/{key}": value for key, value in last_stats.env_metrics.items()}) + scalars.update({f"reward/{key}": value for key, value in last_stats.reward_terms.items()}) if primary and primary["metrics"] is not None: scalars.update({f"train/{key}": value for key, value in primary["metrics"].items()}) return scalars - - -def log_training_stats(training_log: TrainingLogger, sample: AsyncTrainingStats) -> None: - """Forward one normalized sample to TensorBoard/live training logging.""" - for notice in sample.checkpoint_notices: - training_log.event("checkpoint_saved", step=notice["step"], path=notice["path"]) - if sample.warmup_done: - training_log.event("warmup_done", step=sample.step) - if sample.log_record is not None: - record = sample.log_record - training_log.scalars( - record.values, - record.step, - env_steps=record.env_steps, - live_extra=lambda: system_scalars(sample.stats), - placeholders=record.placeholders, - ) - - -class AsyncPanelRenderer: - """Render normalized training statistics in the terminal panel.""" - - def __init__(self, *, env_name: str) -> None: - self._title = f"{env_name}/motrix.fastsac" - self._panel: TrainingPanelSession | None = None - - def render(self, sample: AsyncTrainingStats, *, force: bool = False) -> None: - if self._panel is None: - self._panel = TrainingPanelSession.open(title=self._title) - if self._panel.console is not None: - self._panel.console.clear() - self._panel.submit(sample.stats, force=force) - - def close(self) -> None: - if self._panel is not None: - self._panel.close() diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py index b08b9830b..2a69f6a06 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/train.py @@ -20,7 +20,6 @@ import random import time from pathlib import Path -from queue import Empty import numpy as np import torch @@ -29,19 +28,19 @@ from motrix_env_core import registry as env_registry from motrix_env_core.renderer import RenderConfig from motrix_rl import checkpoints +from motrix_rl.console import TrainingPanelSession +from motrix_rl.console.boot import BootWorker from motrix_rl.contracts import TrainerBase, TrainerContext from motrix_rl.device import resolve_default_device -from motrix_rl.numa import spawn_placement +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics from motrix_rl.runs import annotate_run from motrix_rl.system_metrics import capture_system_info -from motrix_rl.training_logger import TrainingLogger +from motrix_rl.worker import WorkerError, WorkerHandle, WorkerPlacement, WorkerRuntime from motrix_rl_builtin.fastsac.agent import FastSacAgent -from motrix_rl_builtin.fastsac.async_impl.panels import BootPanel from motrix_rl_builtin.fastsac.async_impl.stats import ( - AsyncPanelRenderer, AsyncTrainingStatsAggregator, AsyncTrainingStatsSource, - log_training_stats, ) from motrix_rl_builtin.fastsac.async_impl.topology import resolve_fastsac_topology from motrix_rl_builtin.fastsac.async_impl.transport import ( @@ -55,11 +54,10 @@ ) from motrix_rl_builtin.fastsac.async_impl.transport.handshake import StartupHandshake from motrix_rl_builtin.fastsac.async_impl.worker import ( + CollectorWorker, + LearnerWorker, actor_param_numel, build_env, - inherit_log_stdio, - run_collector_process, - run_learner_process, ) from motrix_rl_builtin.fastsac.config import FastSacCfg from motrix_rl_builtin.fastsac.wrap import FastSacEnvWrap @@ -76,7 +74,6 @@ def __init__(self, *, context: TrainerContext[FastSacCfg]) -> None: self._render = context.render self._resume_from = context.resume_from self._context = context - self._writer = None # ------------------------------------------------------------------ setup def _device(self) -> torch.device: @@ -122,7 +119,6 @@ def _make_agent(self, env: FastSacEnvWrap) -> FastSacAgent: device=self._device(), action_scale=action_scale, action_bias=action_bias, - writer=self._writer, observation_spec=env.observation_spec, ) @@ -142,8 +138,6 @@ def train(self) -> None: async_options = cfg.trainer.async_options logging_interval = self._context.logging.interval save_interval = self._context.checkpoint.interval - # Parent-only: the live logger holds a thread and locks and never reaches the workers. - training_log = TrainingLogger(self._context.run_dir, self._context.metrics) train_started_at = time.perf_counter() if self._context.logging.backend != "tensorboard": @@ -261,11 +255,23 @@ def train(self) -> None: is_resume = resume_step > 0 control.resume_collector_steps(resume_step) control.global_step = resume_step - training_log.event("resumed", step=resume_step, path=str(self._resume_from), global_step=resume_step) + + # Parent-only: the live logger holds a thread and locks and never reaches the workers. + training_log = TrainingLogger( + self._context.run_dir, + self._context.metrics, + interval=logging_interval, + live_only_prefixes=("sys/",), + initial_iteration=resume_step, + initial_env_steps=resume_step * num_envs, + ) + if self._resume_from: + training_log.event( + "resumed", iteration=resume_step, data={"path": str(self._resume_from), "global_step": resume_step} + ) ctx = mp.get_context("spawn") collector_data_queues = [ctx.Queue(maxsize=8) for _ in range(num_collectors)] - error_queue = ctx.Queue(maxsize=8) # Parent-owned panel data pipeline: collectors publish rollout snapshots # through collector_data_queues, while learners publish training payloads # through learner_data_queue. The parent aggregates both streams and @@ -276,34 +282,7 @@ def train(self) -> None: # queues; workers report readiness, the parent renders a boot panel # and releases everyone at once. handshake = StartupHandshake(ctx, num_collectors) - reported_errors: set[tuple[str, str]] = set() seed = self._context.seed - - def _record_error_trace(process_name: str, traceback_text: str) -> Path: - error_dir = self._context.run_dir / "async_errors" - error_dir.mkdir(parents=True, exist_ok=True) - error_path = error_dir / f"{process_name}_error.log" - error_path.write_text(traceback_text) - return error_path - - def _drain_child_errors() -> list[tuple[str, str]]: - errors = [] - while True: - try: - process_name, traceback_text = error_queue.get_nowait() - except Empty: - break - key = (process_name, traceback_text) - if key in reported_errors: - continue - reported_errors.add(key) - errors.append(key) - - error_path = _record_error_trace(process_name, traceback_text) - print(f"[motrix.fastsac async] {process_name} traceback written to {error_path}") - print(traceback_text.rstrip()) - return errors - unique_collector_devices = list(dict.fromkeys(str(d) for d in collector_devices)) collector_banner = ( unique_collector_devices[0] if len(unique_collector_devices) == 1 else unique_collector_devices @@ -327,127 +306,161 @@ def _drain_child_errors() -> list[tuple[str, str]]: rendezvous_path.parent.mkdir(parents=True, exist_ok=True) rendezvous_path.unlink(missing_ok=True) # the file store requires a fresh file rendezvous_file = str(rendezvous_path) - p_learners = [ - ctx.Process( - target=run_learner_process, - args=( - cfg, - num_envs, - dims, - action_scale, - action_bias, - [ - rings[index] - for index in range(num_collectors) - if topology.transition_channels[index].consumer_id == rank - ], - # every rank publishes to its OWN collectors; rank 0 is - # additionally the logger / checkpointer. - [weights[index] for index in range(num_collectors) if weight_channels[index].producer_id == rank], - control, - error_queue, - num_iterations, - logging_interval, - save_interval, - str(self._context.run_dir), - str(self._context.checkpoint_dir), - self._context.checkpoint_format, - self._resume_from, - seed, - handshake, + learner_tasks = [ + LearnerWorker( + cfg=cfg, + num_envs=num_envs, + dims=dims, + action_scale=action_scale, + action_bias=action_bias, + rings=[rings[i] for i in range(num_collectors) if transition_channels[i].consumer_id == rank], + weights=[weights[i] for i in range(num_collectors) if weight_channels[i].producer_id == rank], + control=control, + num_iterations=num_iterations, + logging_interval=logging_interval, + save_interval=save_interval, + run_dir=str(self._context.run_dir), + checkpoint_dir=str(self._context.checkpoint_dir), + checkpoint_format=self._context.checkpoint_format, + resume_from=self._resume_from, + handshake=handshake, + rank=rank, + observation_spec=observation_spec, + learner_data_queue=learner_data_queue, + num_learners=num_learners, + rendezvous_file=rendezvous_file, + learner_device=topology.learners[rank].device, + notify_checkpoints=training_log.live.enabled, + all_rings=rings, + weight_ipc=[weight_ipc[i] for i in range(num_collectors) if weight_channels[i].producer_id == rank], + collector_ids=[ + transition_channels[i].channel_id + for i in range(num_collectors) + if transition_channels[i].consumer_id == rank + ], + final_stores=( + [final_stores[i] for i in range(num_collectors) if transition_channels[i].consumer_id == rank] + if final_stores is not None + else None ), - kwargs={ - "rank": rank, - "observation_spec": observation_spec, - "learner_data_queue": learner_data_queue, - "num_learners": num_learners, - "rendezvous_file": rendezvous_file, - "learner_device": str(topology.learners[rank].device), - "notify_checkpoints": training_log.live.enabled, - "all_rings": rings, - "weight_ipc": [ - weight_ipc[index] - for index in range(num_collectors) - if weight_channels[index].producer_id == rank - ], - "collector_ids": [ - topology.transition_channels[index].channel_id - for index in range(num_collectors) - if topology.transition_channels[index].consumer_id == rank - ], - "learner_cpus": topology.learners[rank].cpus if learner_numa_nodes else None, - "learner_numa_node": learner_numa_nodes[rank] if learner_numa_nodes else None, - "final_stores": ( - [ - final_stores[index] - for index in range(num_collectors) - if topology.transition_channels[index].consumer_id == rank - ] - if final_stores is not None - else None - ), - }, - name="fastsac-async-learner" if num_learners == 1 else f"fastsac-async-learner-{rank}", ) for rank in range(num_learners) ] - p_collectors = [ - ctx.Process( - target=run_collector_process, - kwargs={ - "env_spec": self._env_spec, - "cfg": cfg, - "num_envs": env_shards[i], - "dims": dims, - "action_scale": action_scale, - "action_bias": action_bias, - "ring": rings[i], - "weights": weights[i], - "control": control, - "collector_data_queue": collector_data_queues[i], - "error_queue": error_queue, - "num_iterations": num_iterations, - "logging_interval": logging_interval, - "is_resume": is_resume, - "seed": None if seed is None else seed + i, - "collector_id": i, - "numa_node": numa_nodes[i], - "cpus": topology.collectors[i].cpus, - "collector_device": topology.collectors[i].infer_device, - "run_dir": str(self._context.run_dir), - "handshake": handshake, - "final_store": final_stores[i] if final_stores is not None else None, - }, - name=f"fastsac-async-collector-{i}", + collector_tasks = [ + CollectorWorker( + env_spec=self._env_spec, + cfg=cfg, + num_envs=env_shards[i], + dims=dims, + action_scale=action_scale, + action_bias=action_bias, + ring=rings[i], + weights=weights[i], + control=control, + collector_data_queue=collector_data_queues[i], + num_iterations=num_iterations, + logging_interval=logging_interval, + is_resume=is_resume, + seed=None if seed is None else seed + i, + collector_id=i, + collector_device=topology.collectors[i].infer_device, + handshake=handshake, + final_store=final_stores[i] if final_stores is not None else None, ) for i in range(num_collectors) ] - # Process name -> the role a worker reports its traceback under (see worker.py). - error_roles = { - p.name: ("learner" if num_learners == 1 else f"learner[{rank}]") for rank, p in enumerate(p_learners) - } - error_roles.update({p.name: f"collector[{i}]" for i, p in enumerate(p_collectors)}) - - # Start each child while the parent is pre-placed on the child's NUMA - # node: spawn children re-import torch/simulator before their entry - # function runs, and affinity + memory policy survive fork+exec, so - # the child's import-time allocations are node-local from the start - # (the worker re-binds itself afterwards as a no-op refinement). log_dir = self._context.run_dir / "logs" log_dir.mkdir(parents=True, exist_ok=True) learner_log_name = (lambda rank: f"learner{rank}.log") if num_learners > 1 else (lambda rank: "learner.log") - for rank, p in enumerate(p_learners): - with ( - spawn_placement(learner_numa_nodes[rank] if learner_numa_nodes else None, f"learner-spawn[{rank}]"), - inherit_log_stdio(log_dir / learner_log_name(rank)), - ): - p.start() - for i, p in enumerate(p_collectors): - with ( - spawn_placement(numa_nodes[i], f"collector-spawn[{i}]"), - inherit_log_stdio(log_dir / f"collector{i}.log"), - ): - p.start() + p_learners: list[WorkerHandle] = [] + p_collectors: list[WorkerHandle] = [] + worker_logs: dict[str, Path] = {} + failures: dict[str, WorkerError] = {} + session = TrainingPanelSession.open(title=f"{self._env_name}/motrix.fastsac", screen=True) + + def check_workers() -> bool: + for worker in (*p_learners, *p_collectors): + if worker.name in failures: + continue + try: + worker.check() + except WorkerError as exc: + failures[worker.name] = exc + control.set_stop() + training_log.event( + "worker_crashed", + iteration=control.collector_steps // num_collectors, + data={ + "worker": worker.name, + "exitcode": worker.exitcode, + "error_log": worker_logs[worker.name].relative_to(self._context.run_dir).as_posix(), + }, + ) + return bool(failures) + + def shutdown(workers: list[WorkerHandle]) -> None: + for worker in workers: + try: + worker.join(timeout=8.0) + if worker.is_alive: + worker.terminate() + worker.join(timeout=3.0) + if worker.is_alive: + worker.kill() + worker.join(timeout=3.0) + except Exception as exc: + print(f"[motrix.fastsac async] shutdown of {worker.name} failed: {exc}") + + def close_resources() -> None: + # Independent cleanup attempts preserve the original training failure. + resources = [ + session, + training_log, + handshake, + learner_data_queue, + *collector_data_queues, + *p_learners, + *p_collectors, + ] + for resource in resources: + try: + resource.close() + except Exception as exc: + print(f"[motrix.fastsac async] closing resource failed: {exc}") + + try: + for rank, task in enumerate(learner_tasks): + name = "fastsac-async-learner" if num_learners == 1 else f"fastsac-async-learner-{rank}" + worker_logs[name] = log_dir / learner_log_name(rank) + p_learners.append( + task.start( + ctx, + name=name, + placement=WorkerPlacement( + numa_node=learner_numa_nodes[rank] if learner_numa_nodes else None, + cpus=tuple(topology.learners[rank].cpus) if learner_numa_nodes else (), + ), + runtime=WorkerRuntime(seed=None if seed is None else seed + rank, log_path=worker_logs[name]), + ) + ) + for i, task in enumerate(collector_tasks): + name = f"fastsac-async-collector-{i}" + worker_logs[name] = log_dir / f"collector{i}.log" + p_collectors.append( + task.start( + ctx, + name=name, + placement=WorkerPlacement(numa_node=numa_nodes[i], cpus=tuple(topology.collectors[i].cpus)), + runtime=WorkerRuntime(seed=task.seed, log_path=worker_logs[name]), + ) + ) + except BaseException: + control.set_stop() + handshake.release() + shutdown(p_collectors) + shutdown(p_learners) + close_resources() + raise # -------------------------------------------------- startup panel + barrier # Workers boot at different speeds (env/kernel compile vs CUDA init and @@ -456,148 +469,107 @@ def _drain_child_errors() -> list[tuple[str, str]]: # crash or the boot timeout aborts via the shared stop flag. expected = {("collector", i) for i in range(num_collectors)} | {("learner", r) for r in range(num_learners)} ready: set[tuple[str, int]] = set() - boot_deadline = time.time() + max(float(os.environ.get("MOTRIX_BOOT_TIMEOUT_S", "600")), 30.0) - from rich.live import Live - - log_names = [f"collector{i}.log" for i in range(num_collectors)] - log_names += [learner_log_name(rank) for rank in range(num_learners)] - boot_panel = BootPanel( - title=f"{self._env_name}/motrix.fastsac", - log_dir=log_dir, - log_names=log_names, - workers=sorted(expected), - ) - interactive = boot_panel.interactive + boot_deadline = time.monotonic() + max(float(os.environ.get("MOTRIX_BOOT_TIMEOUT_S", "600")), 30.0) + boot_logs = { + **{("collector", i): log_dir / f"collector{i}.log" for i in range(num_collectors)}, + **{("learner", rank): log_dir / learner_log_name(rank) for rank in range(num_learners)}, + } + # Worker identities are spawn-fixed; readiness is reported as events. + workers = tuple(BootWorker(f"{role}[{index}]", boot_logs[role, index]) for role, index in sorted(expected)) + boot = session.boot_panel(workers) # Panel-data state must exist BEFORE the boot barrier: the handoff # loop below drains the same queues the training panel will use, so # the transition between panels is a data-source switch, not a wait. - per_collector_stats: dict[int, dict | None] = {i: None for i in range(num_collectors)} - learner_payloads: dict[int, dict | None] = {r: None for r in range(num_learners)} - - def _drain_worker_stats() -> None: - for queue in collector_data_queues: - try: - while True: - snapshot = queue.get_nowait() - per_collector_stats[snapshot["collector_id"]] = snapshot - except Empty: - pass - try: - while True: - payload = learner_data_queue.get_nowait() - notice = payload.get("checkpoint_saved") - if notice is not None: - # Reported at the learner's own step as soon as it arrives. - training_log.event("checkpoint_saved", step=notice["step"], path=notice["path"]) - else: - learner_payloads[payload["rank"]] = payload - except Empty: - pass - - def _panel_data_ready() -> bool: - """Wait for all learners' first updates, including lazy compilation.""" - return ( - all(v is not None for v in per_collector_stats.values()) - # Initial payloads do not mean lazy compilation/first updates - # completed. Short runs may legitimately finish in replay warmup. - and all( - v is not None - and (v["training_started"] or control.collector_steps >= num_iterations * num_collectors) - for v in learner_payloads.values() - ) - and control.collector_steps > 0 - ) - - def _handoff_gate_line() -> str: - """One-line panel-data readiness summary for the handoff view.""" - stats_marks = " ".join( - f"c{i} {'✓' if per_collector_stats[i] is not None else '…'}" for i in range(num_collectors) - ) - payload_marks = " ".join( - f"l{r} " + ("✓" if p is not None and p["training_started"] else "initializing first update…") - for r, p in learner_payloads.items() - ) - return f"panel data — stats: {stats_marks} | payloads: {payload_marks} | steps: {control.collector_steps}" + stats_source = AsyncTrainingStatsSource( + num_envs=num_envs, + num_collectors=num_collectors, + num_learners=num_learners, + num_iterations=num_iterations, + resume_step=resume_step, + collector_data_queues=collector_data_queues, + learner_data_queue=learner_data_queue, + control=control, + per_collector_stats=dict.fromkeys(range(num_collectors)), + learner_payloads=dict.fromkeys(range(num_learners)), + ) try: - # Bare prints inside Live would tear its frame; collect abort - # reasons here and print them after Live has exited. abort_reason: str | None = None - # On a real terminal the panel runs on the alternate screen - # (htop-style): every refresh redraws the whole screen, so no - # frame can ever survive to tear — even when the frame fills the - # full terminal height, where cursor-up erasure is unreliable. - # On pipes/files Live cannot redraw in place at all; the - # per-refresh prints are skipped and stop() emits one final frame. - with Live( - boot_panel.render(ready), - refresh_per_second=4, - auto_refresh=interactive, - screen=interactive, - ) as boot_live: - while len(ready) < len(expected): - fresh = handshake.drain_ready() - if fresh: - ready |= fresh - if interactive: - boot_live.update(boot_panel.render(ready)) # log tail advances even without new readiness - try: - process_name, traceback_text = error_queue.get_nowait() - except Empty: - process_name = None - if process_name is not None: - control.set_stop() - _record_error_trace(process_name, traceback_text) - abort_reason = ( - f"worker {process_name} failed during startup " - f"(traceback: async_errors/{process_name}_error.log)" - ) - break - if time.time() > boot_deadline: - control.set_stop() - missing = sorted(expected - ready) - abort_reason = f"worker startup timed out after 600s; missing: {missing}" + boot.refresh() + while len(ready) < len(expected): + fresh = handshake.drain_ready() + if fresh: + ready |= fresh + boot.mark_ready(*(f"{role}[{index}]" for role, index in fresh)) + boot.refresh() # log tails advance even without new readiness + if check_workers(): + raise next(iter(failures.values())) + if time.monotonic() > boot_deadline: + control.set_stop() + missing = sorted(expected - ready) + abort_reason = f"worker startup timed out after 600s; missing: {missing}" + break + time.sleep(0.25) + # ------------------------------------------------ handoff phase + # Release the barrier NOW: the handoff gate below waits for + # collectors to step (shared counters), and workers held at + # wait_for_start cannot step — waiting for the gate before + # releasing is a parent/child deadlock. + if abort_reason is None: + handshake.release() + # The barrier released every worker, but the training panel's + # queue-fed stats have not converged yet. Keep the SAME Live + # (and alt screen) running with a shared-counter progress + # view — every field is well-defined immediately — until the + # quiescence gate opens, then fall through to the training + # panel whose first frame is therefore fully aggregated. + if abort_reason is None: + boot.start() + while not stats_source.data_ready(): + for notice in stats_source.drain(): + training_log.event("checkpoint_saved", iteration=notice["step"], data={"path": notice["path"]}) + # A run shorter than replay warmup may end without an + # update payload; let normal shutdown collect its result. + if all(not p.is_alive for p in p_learners): break + if check_workers(): + raise next(iter(failures.values())) + boot.message(stats_source.handoff_gate_line()) time.sleep(0.25) - # ------------------------------------------------ handoff phase - # Release the barrier NOW: the handoff gate below waits for - # collectors to step (shared counters), and workers held at - # wait_for_start cannot step — waiting for the gate before - # releasing is a parent/child deadlock. - if abort_reason is None: - handshake.release() - # The barrier released every worker, but the training panel's - # queue-fed stats have not converged yet. Keep the SAME Live - # (and alt screen) running with a shared-counter progress - # view — every field is well-defined immediately — until the - # quiescence gate opens, then fall through to the training - # panel whose first frame is therefore fully aggregated. - if abort_reason is None: - while not _panel_data_ready(): - _drain_worker_stats() - # A run shorter than replay warmup may end without an - # update payload; let normal shutdown collect its result. - if all(not p.is_alive() for p in p_learners): - break - try: - process_name, traceback_text = error_queue.get_nowait() - except Empty: - process_name = None - if process_name is not None: - control.set_stop() - _record_error_trace(process_name, traceback_text) - abort_reason = f"worker {process_name} failed after startup" - break - if interactive: - boot_live.update(boot_panel.render(ready, gate=_handoff_gate_line(), starting=True)) - time.sleep(0.25) - # Live has exited — plain prints are safe on the terminal again. if abort_reason is not None: + session.close() print(f"[motrix.fastsac async] {abort_reason}; aborting.") raise RuntimeError(abort_reason) - print(f"[motrix.fastsac async] all {len(expected)} workers ready — training starts") - training_log.event("run_started", step=resume_step, workers=len(expected)) + stats_aggregator = AsyncTrainingStatsAggregator( + learning_starts=cfg.agent.learning_starts, + ) + panel = session.metrics_panel( + total_iterations=num_iterations, + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + reductions=training_log.reductions, + default_reduction=training_log.default_reduction, + ) + metrics = TrainingMetrics( + [training_log, panel], + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + system_sink=training_log, + ) + metrics.advance( + iterations=control.collector_steps // num_collectors - metrics.iteration, + env_steps=control.collector_steps * per_collector_envs - metrics.env_steps, + ) + metrics.start() + training_log.event("run_started", iteration=resume_step, data={"workers": len(expected)}) + except BaseException: + control.set_stop() + handshake.release() + shutdown(p_collectors) + shutdown(p_learners) + close_resources() + raise finally: handshake.release() # idempotent; frees workers on an aborted boot # -------------------------------------------------- parent-owned panel @@ -605,52 +577,25 @@ def _handoff_gate_line() -> str: # rollout snapshots + every learner rank's payload) AND the whole # machine: it is unbound, so the system panel shows all cores, and # workers stay peers with no "primary renderer" role. - stats_source = AsyncTrainingStatsSource( - num_envs=num_envs, - num_collectors=num_collectors, - num_learners=num_learners, - num_iterations=num_iterations, - resume_step=resume_step, - collector_data_queues=collector_data_queues, - learner_data_queue=learner_data_queue, - control=control, - per_collector_stats=per_collector_stats, - learner_payloads=learner_payloads, - ) - stats_aggregator = AsyncTrainingStatsAggregator( - learning_starts=cfg.agent.learning_starts, - logging_interval=logging_interval, - ) - - panel_renderer = AsyncPanelRenderer(env_name=self._env_name) try: # monitor: exit when every learner has finished; abort all if any worker crashes. while True: - crashed = [p for p in (*p_learners, *p_collectors) if not p.is_alive() and p.exitcode not in (0, None)] - learners_done = [p for p in p_learners if not p.is_alive()] - if crashed: - for p in crashed: - print(f"[motrix.fastsac async] {p.name} crashed (exit {p.exitcode}); stopping.") - _drain_child_errors() - crash_step = control.collector_steps // num_collectors - for p in crashed: - error_log = Path("async_errors") / f"{error_roles[p.name]}_error.log" - training_log.event( - "worker_crashed", - step=crash_step, - worker=p.name, - exitcode=p.exitcode, - error_log=error_log.as_posix() if (self._context.run_dir / error_log).exists() else None, - ) + if check_workers(): + break + if all(not worker.is_alive for worker in p_learners): break - if learners_done: - _drain_child_errors() - if len(learners_done) == len(p_learners): - break if (sample := stats_aggregator.collect(stats_source)) is not None: - panel_renderer.render(sample) - log_training_stats(training_log, sample) + metrics.record(sample.scalars) + metrics.advance( + iterations=sample.step - metrics.iteration, + env_steps=sample.env_steps - metrics.env_steps, + ) + for notice in sample.checkpoint_notices: + metrics.checkpoint(notice["path"], iteration=notice["step"]) + if sample.warmup_done: + metrics.event("warmup_done") + metrics.flush() time.sleep(0.5) finally: # Ctrl+C reaches the parent as KeyboardInterrupt and every worker via @@ -660,85 +605,54 @@ def _handoff_gate_line() -> str: # GPU memory were produced). control.set_stop() - def _shutdown(processes, grace_s): - for p in processes: - try: - p.join(timeout=grace_s) - if not p.is_alive(): - continue - print(f"[motrix.fastsac async] terminating {p.name}") - p.terminate() # SIGTERM: unwinds queue feeder threads - p.join(timeout=3.0) - if p.is_alive(): - print(f"[motrix.fastsac async] killing {p.name}") - p.kill() # SIGKILL: e.g. blocked inside a NCCL collective - p.join(timeout=3.0) - except Exception as exc: # noqa: BLE001 - isolation by design - print(f"[motrix.fastsac async] shutdown of {p.name} failed: {exc}") - - _shutdown(p_collectors, grace_s=8.0) - _shutdown(p_learners, grace_s=8.0) - try: - _drain_child_errors() - except Exception: - pass + shutdown(p_collectors) + shutdown(p_learners) + check_workers() try: if (sample := stats_aggregator.collect(stats_source)) is not None: - panel_renderer.render(sample, force=True) - log_training_stats(training_log, sample) + metrics.record(sample.scalars) + metrics.advance( + iterations=sample.step - metrics.iteration, + env_steps=sample.env_steps - metrics.env_steps, + ) + for notice in sample.checkpoint_notices: + metrics.checkpoint(notice["path"], iteration=notice["step"]) + if sample.warmup_done: + metrics.event("warmup_done") except Exception: pass try: - panel_renderer.close() - except Exception: - pass - wall_time_s = time.perf_counter() - train_started_at - total_env_steps = control.collector_steps * per_collector_envs - annotate_run( - self._context.run_dir, - performance={ - "num_envs": num_envs, - "iterations": num_iterations, - "total_env_steps": total_env_steps, - "wall_time_s": round(wall_time_s, 1), - "mean_env_steps_per_s": int(total_env_steps / max(wall_time_s, 1e-9)), - }, - ) - training_log.close() - try: - learner_data_queue.close() - except Exception: - pass - handshake.close() - for collector_data_queue in collector_data_queues: - try: - while True: - collector_data_queue.get_nowait() - except Exception: - pass - collector_data_queue.close() - try: - error_queue.close() - except Exception: - pass - - for p in p_learners: - if p.exitcode not in (0, None): - raise RuntimeError( - f"motrix.fastsac async learner process '{p.name}' failed with exit code {p.exitcode}" + wall_time_s = time.perf_counter() - train_started_at + collector_steps = control.collector_steps + total_env_steps = collector_steps * per_collector_envs + metrics.advance( + iterations=collector_steps // num_collectors - metrics.iteration, + env_steps=total_env_steps - metrics.env_steps, ) - for i, p in enumerate(p_collectors): - if p.exitcode not in (0, None): - raise RuntimeError(f"motrix.fastsac async collector {i} process failed with exit code {p.exitcode}") + metrics.flush(force=True) + annotate_run( + self._context.run_dir, + performance={ + "num_envs": num_envs, + "iterations": num_iterations, + "total_env_steps": total_env_steps, + "wall_time_s": round(wall_time_s, 1), + "mean_env_steps_per_s": int(total_env_steps / max(wall_time_s, 1e-9)), + }, + ) + finally: + close_resources() + + if failures: + raise next(iter(failures.values())) # The primary learner wrote the final checkpoint before exiting cleanly. final_path = checkpoints.final_checkpoint_path(self._context.checkpoint_format, self._context.run_dir) if final_path.exists(): - training_log.event("checkpoint_saved", step=control.collector_steps // num_collectors, path=str(final_path)) + training_log.event("checkpoint_saved", iteration=training_log.iteration, data={"path": str(final_path)}) # ------------------------------------------------------------------ play def play(self, policy: str) -> None: self._set_seed(self._context.seed) - self._writer = None env = self._make_env( self._context.play_num_envs, render=self._render, diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py index c7fe4cf82..06b34e6c1 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py @@ -7,8 +7,9 @@ transition ring; the learner process (GPU) drains the ring, trains, publishes weights, and sends normalized training payloads to the parent. The parent owns panel rendering, TensorBoard/live logging, and checkpoint event recording. Both are spawned by -:class:`~motrix_rl_builtin.fastsac.async_impl.train.Trainer`. Entry functions are module-level -so ``torch.multiprocessing`` (``spawn``) can pickle them by qualified name. +:class:`~motrix_rl_builtin.fastsac.async_impl.train.Trainer`. Workers store explicit +configuration and IPC handles; the core worker bootstrap applies logging, +placement and runtime settings before their task runs. Build helpers (``build_env`` / ``build_agent``) are shared with the single-process (M0) path so both trainers construct env/agent identically. @@ -17,33 +18,26 @@ from __future__ import annotations import logging -import os -import random -import sys import time -import traceback -from contextlib import contextmanager +from dataclasses import dataclass from multiprocessing.queues import Queue from pathlib import Path from queue import Empty, Full -from typing import TYPE_CHECKING, Any -import numpy as np import torch -if TYPE_CHECKING: - from torch.utils.tensorboard import SummaryWriter - from motrix_env_core.observations import ObservationSpec from motrix_env_core.registry import EnvBuildSpec from motrix_env_core.renderer import RenderConfig from motrix_rl import checkpoints -from motrix_rl.device import resolve_default_device -from motrix_rl.numa import apply_binding, pin_worker_cpus, resolve_worker_cpus +from motrix_rl.console.data import TimingWindow +from motrix_rl.console.panel import TimingNode +from motrix_rl.log.schedule import IterationLogSchedule +from motrix_rl.numa import pin_worker_cpus, resolve_worker_cpus +from motrix_rl.worker import Worker from motrix_rl_builtin.fastsac.agent import FastSacAgent from motrix_rl_builtin.fastsac.async_impl.collector import Collector from motrix_rl_builtin.fastsac.async_impl.learner import CollectorEndpoint, Learner -from motrix_rl_builtin.fastsac.async_impl.stats import timing_mean from motrix_rl_builtin.fastsac.async_impl.transport import ( Control, FinalObsStorage, @@ -63,16 +57,6 @@ logger = logging.getLogger(__name__) -def set_seed(seed: int | None) -> None: - if seed is None: - return - random.seed(seed) - np.random.seed(seed) - torch.manual_seed(seed) - if torch.cuda.is_available(): - torch.cuda.manual_seed_all(seed) - - def build_env( env_spec: EnvBuildSpec, num_envs: int, @@ -123,7 +107,6 @@ def build_agent( device: torch.device, action_scale: torch.Tensor | None, action_bias: torch.Tensor | None, - writer: SummaryWriter | None = None, world_size: int = 1, final_obs_bootstrap: bool = False, observation_spec: ObservationSpec | None = None, @@ -132,8 +115,7 @@ def build_agent( ``dims`` is ``(obs_dim, critic_obs_dim, act_dim)``. ``action_scale`` / ``action_bias`` map the tanh-squashed policy output to the env action - range (``None`` = identity). ``writer`` is the parent-created - TensorBoard writer; ``world_size`` is the DDP learner-rank count. + range (``None`` = identity). ``world_size`` is the DDP learner-rank count. ``final_obs_bootstrap`` enables the replay buffer's terminal-observation storage for time-limit-truncated bootstrapping. """ @@ -147,7 +129,6 @@ def build_agent( device=device, action_scale=action_scale, action_bias=action_bias, - writer=writer, world_size=world_size, final_obs_bootstrap=final_obs_bootstrap, observation_spec=observation_spec, @@ -175,224 +156,137 @@ def _handler(signum, frame): # noqa: ARG001 pass -@contextmanager -def inherit_log_stdio(log_file: Path): - """Parent-side spawn guard: point fd 1/2 at the worker's log file while starting it. - - Spawn children inherit the parent's terminal fds and re-import - torch/simulator modules BEFORE their entry function runs - (``_configure_process_logging``), so import-time prints (library banners, - profiler messages, warnings) would land raw on the shared terminal and - jitter the parent's live panel. Holding the log file on fd 1/2 across - ``Process.start()`` makes the child inherit it from its first - instruction; the parent's own fds are restored immediately afterwards. - """ - log_fd = os.open(str(log_file), os.O_WRONLY | os.O_CREAT | os.O_APPEND) - saved_stdout, saved_stderr = os.dup(1), os.dup(2) - try: - os.dup2(log_fd, 1) - os.dup2(log_fd, 2) - yield - finally: - os.dup2(saved_stdout, 1) - os.dup2(saved_stderr, 2) - os.close(saved_stdout) - os.close(saved_stderr) - os.close(log_fd) - - -def _configure_process_logging(log_file: Path) -> None: - """Route worker logs (e.g. manager env startup) to a file, not the terminal. - - The parent renders the live panel on the shared terminal; raw worker log - bytes would tear the rich Live frames apart. Startup records stay - inspectable under the run's ``logs/`` directory; errors additionally - travel the error-queue channel as before. - """ - logging.basicConfig( - level=logging.INFO, - format="%(asctime)s %(levelname)s %(name)s: %(message)s", - filename=str(log_file), - filemode="a", - force=True, - ) - # Hard hat: dup the log file onto stdout/stderr so C-level output - # (third-party import banners, library warnings) can never reach the - # shared terminal and tear the parent's Rich panel. - log_fd = os.open(str(log_file), os.O_WRONLY | os.O_CREAT | os.O_APPEND) - os.dup2(log_fd, 1) - os.dup2(log_fd, 2) - os.close(log_fd) - - -def run_collector_process( - env_spec: EnvBuildSpec, - cfg: FastSacCfg, - num_envs: int, - dims: tuple[int, int, int], - action_scale: torch.Tensor, - action_bias: torch.Tensor, - ring: HostTransitionRing | RingCursors, - weights: WeightChannelShared, - control: Control, - collector_data_queue: Queue, - error_queue: Queue, - num_iterations: int, - logging_interval: int, - is_resume: bool, - seed: int | None, - run_dir: str, - handshake: StartupHandshake, - collector_device: torch.device, - collector_id: int = 0, - numa_node: int | None = None, - cpus: list[int] | None = None, - final_store: FinalObsStorage | None = None, -) -> None: - role = f"collector[{collector_id}]" - _install_graceful_sigint(control) - try: - log_dir = Path(run_dir) / "logs" - log_dir.mkdir(parents=True, exist_ok=True) - _configure_process_logging(log_dir / f"collector{collector_id}.log") - # Bind before any env / staging allocation: the memory policy only - # affects future pages, so this must be the first thing the worker does. - # The binding itself was decided by the parent topology pass. - apply_binding(role, numa_node, cpus or []) - set_seed(seed) - opts = cfg.trainer.async_options - pin_worker_cpus(resolve_worker_cpus(opts.collector_cpu_cores, "collector_cpu_cores")) - obs_dim, critic_obs_dim, act_dim = dims - device = torch.device("cpu") - env_started = time.perf_counter() - env = build_env(env_spec, num_envs, device, seed=seed) - logger.info( - "collector startup: env build (scene + manager kernels) finished in %.3fs", - time.perf_counter() - env_started, - ) - # Handshake: build the endpoints from the slot tensors the learners - # shipped before the collector is wired up. Weight slots come from - # the publishing learner (rank 0), CUDA-IPC transition-ring slots - # from the learner that drains this collector's ring (its owner — - # always rank 0 in the single-learner topology). - weight_slots = handshake.await_weight_slots(collector_id) - ring_slots = handshake.await_ring_slots(collector_id) - weight_rx = weight_receiver_for(weights, weight_slots) - if isinstance(ring, RingCursors): - if ring_slots is None: - raise RuntimeError("the learner shipped no transition-ring slots for the IPC ring handshake") - ring = GpuIpcTransitionRing( +@dataclass(kw_only=True) +class CollectorWorker(Worker): + """Collect transitions with child-owned environment and inference endpoints.""" + + env_spec: EnvBuildSpec + cfg: FastSacCfg + num_envs: int + dims: tuple[int, int, int] + action_scale: torch.Tensor + action_bias: torch.Tensor + ring: HostTransitionRing | RingCursors + weights: WeightChannelShared + control: Control + collector_data_queue: Queue + num_iterations: int + logging_interval: int + is_resume: bool + seed: int | None + handshake: StartupHandshake + collector_device: torch.device + collector_id: int = 0 + final_store: FinalObsStorage | None = None + + def run(self) -> None: + ring = self.ring + _install_graceful_sigint(self.control) + env: FastSacEnvWrap | None = None + collector: Collector | None = None + try: + opts = self.cfg.trainer.async_options + pin_worker_cpus(resolve_worker_cpus(opts.collector_cpu_cores, "collector_cpu_cores")) + obs_dim, critic_obs_dim, act_dim = self.dims + device = torch.device("cpu") + env_started = time.perf_counter() + env = build_env(self.env_spec, self.num_envs, device, seed=self.seed) + logger.info( + "collector startup: env build (scene + manager kernels) finished in %.3fs", + time.perf_counter() - env_started, + ) + # Handshake: build the endpoints from the slot tensors the learners + # shipped before the collector is wired up. Weight slots come from + # the publishing learner (rank 0), CUDA-IPC transition-ring slots + # from the learner that drains this collector's ring (its owner — + # always rank 0 in the single-learner topology). + weight_slots = self.handshake.await_weight_slots(self.collector_id) + ring_slots = self.handshake.await_ring_slots(self.collector_id) + weight_rx = weight_receiver_for(self.weights, weight_slots) + if isinstance(ring, RingCursors): + if ring_slots is None: + raise RuntimeError("the learner shipped no transition-ring slots for the IPC ring handshake") + ring = GpuIpcTransitionRing( + ring, + ring_slots, + fastsac_transition_schema( + env.observation_spec.policy.frame_space.shape[-1], + env.observation_spec.value_or_policy.frame_space.shape[-1], + act_dim, + ), + opts.ring_capacity, + self.num_envs, + payload_store=self.final_store, + ) + collector = Collector( + env, + self.cfg, + obs_dim, + act_dim, + self.action_scale, + self.action_bias, ring, - ring_slots, - fastsac_transition_schema( - env.observation_spec.policy.frame_space.shape[-1], - env.observation_spec.value_or_policy.frame_space.shape[-1], - act_dim, - ), - opts.ring_capacity, - num_envs, - payload_store=final_store, + weight_rx, + self.control, + collector_device=self.collector_device, + is_resume=self.is_resume, + collector_id=self.collector_id, + ) + collector.reset() + collector.sync_weights() + warmup_started = time.perf_counter() + collector.warmup_inference() + logger.info( + "collector startup: inference warmup (torch.compile + CUDA graphs) finished in %.3fs", + time.perf_counter() - warmup_started, ) - collector = Collector( - env, - cfg, - obs_dim, - act_dim, - action_scale, - action_bias, - ring, - weight_rx, - control, - collector_device=collector_device, - is_resume=is_resume, - collector_id=collector_id, - ) - collector.reset() - collector.sync_weights() - warmup_started = time.perf_counter() - collector.warmup_inference() - logger.info( - "collector startup: inference warmup (torch.compile + CUDA graphs) finished in %.3fs", - time.perf_counter() - warmup_started, - ) - - # Startup barrier: report readiness and hold until every worker (all - # collectors AND learners) has booted, so stepping starts in lockstep - # — warmup counters, weight generations and generation merge align - # from step one instead of converging mid-run. - handshake.report_ready("collector", collector_id) - handshake.wait_for_start(control) - if control.stop: - return - - # First snapshot once a few steps have landed: the parent's panel - # quiescence gate opens early (not after a full logging window of - # silence) while the handoff progress view gets to show real steps, - # and the snapshot already carries a little real data. The - # per-interval send below then replaces it. - first_stats_steps = 10 - first_stats_sent = False - - while not control.stop and control.collector_steps_at(collector_id) < num_iterations: - if not collector.step_once(): - time.sleep(opts.idle_sleep_s) # ring full -> backpressure - continue - steps = control.collector_steps_at(collector_id) - if not first_stats_sent and steps >= first_stats_steps: - first_stats_sent = True - collector_data_queue.put(collector.snapshot_stats()) - elif steps % max(logging_interval, 1) == 0: - # replace any stale snapshot so the learner always sees the latest. - try: - while True: - collector_data_queue.get_nowait() - except Empty: - pass - collector_data_queue.put(collector.snapshot_stats()) - except BaseException: - if not isinstance(sys.exc_info()[1], (KeyboardInterrupt, SystemExit)): - # Ctrl+C is an operator action, not a defect: the stop flag is - # already set by the SIGINT handler; don't spam async_errors. - error_queue.put((role, traceback.format_exc())) - raise - finally: - control.set_stop() # signal the learner if the collector exits for any reason + + # Startup barrier: report readiness and hold until every worker (all + # collectors AND learners) has booted, so stepping starts in lockstep + # — warmup counters, weight generations and generation merge align + # from step one instead of converging mid-run. + self.handshake.report_ready("collector", self.collector_id) + self.handshake.wait_for_start(self.control) + if self.control.stop: + return + + # First snapshot once a few steps have landed: the parent's panel + # quiescence gate opens early (not after a full logging window of + # silence) while the handoff progress view gets to show real steps, + # and the snapshot already carries a little real data. The + # per-interval send below then replaces it. + first_stats_steps = 10 + first_stats_sent = False + + while not self.control.stop and self.control.collector_steps_at(self.collector_id) < self.num_iterations: + if not collector.step_once(): + time.sleep(opts.idle_sleep_s) # ring full -> backpressure + continue + steps = self.control.collector_steps_at(self.collector_id) + if not first_stats_sent and steps >= first_stats_steps: + first_stats_sent = True + self.collector_data_queue.put(collector.snapshot_stats()) + elif steps % max(self.logging_interval, 1) == 0: + # replace any stale snapshot so the learner always sees the latest. + try: + while True: + self.collector_data_queue.get_nowait() + except Empty: + pass + self.collector_data_queue.put(collector.snapshot_stats()) + finally: + self.control.set_stop() # signal the learner if the collector exits for any reason + try: + if collector is not None: + collector.close() + finally: + if env is not None: + env.close() # ------------------------------------------------------------------ learner process -def run_learner_process( - cfg: FastSacCfg, - num_envs: int, - dims: tuple[int, int, int], - action_scale: torch.Tensor, - action_bias: torch.Tensor, - rings: list[HostTransitionRing | RingCursors], - weights: list[WeightChannelShared], - control: Control, - error_queue, - num_iterations: int, - logging_interval: int, - save_interval: int, - run_dir: str, - checkpoint_dir: str, - checkpoint_format: str, - resume_from: str | None, - seed: int | None, - handshake: StartupHandshake, - all_rings: list[HostTransitionRing], - weight_ipc: list[bool], - collector_ids: list[int], - learner_data_queue: Queue, - learner_cpus: list[int] | None = None, - learner_numa_node: int | None = None, - rank: int = 0, - num_learners: int = 1, - rendezvous_file: str | None = None, - learner_device: str | None = None, - final_stores: list[FinalObsStorage] | None = None, - notify_checkpoints: bool = False, - observation_spec: ObservationSpec | None = None, -) -> None: +@dataclass(kw_only=True) +class LearnerWorker(Worker): """One learner process; ``rank 0`` additionally owns stats aggregation, logging and checkpointing. @@ -408,228 +302,188 @@ def run_learner_process( counts are derived from the global progress basis (see ``Learner.maybe_train``). """ - is_primary = num_learners == 1 or rank == 0 - if num_learners > 1: - import torch.distributed as dist - else: - dist = None - _install_graceful_sigint(control) - _learner_log_dir = Path(run_dir) / "logs" - _learner_log_dir.mkdir(parents=True, exist_ok=True) - _configure_process_logging(_learner_log_dir / (f"learner{rank}.log" if num_learners > 1 else "learner.log")) - try: - apply_binding(f"learner[{rank}]" if num_learners > 1 else "learner", learner_numa_node, learner_cpus) - set_seed(None if seed is None else seed + rank) - opts = cfg.trainer.async_options - pin_worker_cpus(resolve_worker_cpus(opts.learner_cpu_cores, "learner_cpu_cores")) - num_collectors = len(all_rings) - if learner_device is not None: - device = torch.device(learner_device) - elif cfg.device: - device = torch.device(cfg.device) + + cfg: FastSacCfg + num_envs: int + dims: tuple[int, int, int] + action_scale: torch.Tensor + action_bias: torch.Tensor + rings: list[HostTransitionRing | RingCursors] + weights: list[WeightChannelShared] + control: Control + num_iterations: int + logging_interval: int + save_interval: int + run_dir: str + checkpoint_dir: str + checkpoint_format: str + resume_from: str | None + handshake: StartupHandshake + all_rings: list[HostTransitionRing | RingCursors] + weight_ipc: list[bool] + collector_ids: list[int] + learner_data_queue: Queue + rank: int = 0 + num_learners: int = 1 + rendezvous_file: str | None = None + learner_device: torch.device + final_stores: list[FinalObsStorage] | None = None + notify_checkpoints: bool = False + observation_spec: ObservationSpec | None = None + + def run(self) -> None: + is_primary = self.num_learners == 1 or self.rank == 0 + if self.num_learners > 1: + import torch.distributed as dist else: - device = resolve_default_device() - if num_learners > 1: - if device.type != "cuda" or device.index is None: - raise ValueError(f"multi-learner requires explicit indexed CUDA learner devices, got {device}") - torch.cuda.set_device(device) - # Bounded collective timeout: with the default 30-minute timeout a - # rank waiting on a crashed/blocked peer hangs until the parent's - # force-kill instead of unwinding through its own error path. - import datetime as _dt - - dist.init_process_group( - "nccl", - init_method=f"file://{rendezvous_file}", - rank=rank, - world_size=num_learners, - timeout=_dt.timedelta(seconds=90), - ) - # Replay buffer sized by THIS rank's env shard: each learner drains only - # its collectors' rings, so every ingested batch carries - # num_envs // num_learners envs (env-level sharding keeps each env's - # full trajectory — and n-step adjacency — inside one rank). The batch - # math still divides the GLOBAL batch_size by world_size, so per-rank - # sample rows == batch_size / num_learners, matching DDP averaging. - agent_started = time.perf_counter() - agent = build_agent( - cfg, - dims, - num_envs // num_learners, - device, - action_scale, - action_bias, - world_size=num_learners, - final_obs_bootstrap=final_stores is not None, - observation_spec=observation_spec, - ) - if resume_from: - ckpt = torch.load(resume_from, map_location=device, weights_only=False) - agent.load_state_dict(ckpt, load_optimizers=True) - logger.info( - "learner startup: agent build%s finished in %.3fs", - " + checkpoint load" if resume_from else "", - time.perf_counter() - agent_started, - ) - - resume_step = control.collector_steps // num_collectors # full-batch equivalents - per_collector_envs = num_envs // num_collectors - # Build one sender endpoint per collector owned by this rank and ship - # the slot tensors BEFORE - # the first publish so each collector (blocking on its handshake queue) - # builds the matching receiver from step one. The IPC transition-ring - # slots ship in the same one-shot message: this process is the owner - # (it allocated the device tensor and must keep it alive), the - # collector maps it through the queue's CUDA-IPC reducers. - # Transport per channel was decided by the parent topology pass - # (weight_channels, indexed per collector); this process only - # constructs the endpoints — the bundle spec (sized by the parent - # with one throwaway CPU actor) already fixes both transports' - # buffer sizes. - weight_txs = [] - for j, shared in enumerate(weights): - channel = collector_ids[j] - # CUDA-IPC device slots when the topology resolved IPC for this - # channel (the collector infers on this rank's GPU), host - # shared-memory slots otherwise; this rank is the exporter (its - # CUDA context must keep the slot tensors alive). - tx = GpuIpcWeightSender(shared, device) if weight_ipc[j] else HostWeightSender(shared) - handshake.ship_weight_slots(channel, tx.params) - weight_txs.append(tx) - # Wrap RingCursors into GpuIpcTransitionRing (allocating the device slots - # and shipping them to the collector) BEFORE building the endpoints — - # the endpoints must hold the FINAL ring objects the drain path uses. - for j, ring in enumerate(rings): - collector_id = collector_ids[j] - ring_slots = None - if isinstance(ring, RingCursors): - if device.type != "cuda": - raise RuntimeError("the IPC transition ring was selected but the learner device is not CUDA") - obs_dim, critic_obs_dim, act_dim = dims - schema = fastsac_transition_schema(agent.rb.n_obs, agent.rb.n_critic_obs, act_dim) - ring_slots = torch.zeros( - opts.ring_capacity, - per_collector_envs, - schema.feature_width, - dtype=torch.float32, - device=device, - ) - rings[j] = GpuIpcTransitionRing( - ring, - ring_slots, - schema, - opts.ring_capacity, - per_collector_envs, - payload_store=final_stores[j] if final_stores is not None else None, + dist = None + _install_graceful_sigint(self.control) + try: + opts = self.cfg.trainer.async_options + pin_worker_cpus(resolve_worker_cpus(opts.learner_cpu_cores, "learner_cpu_cores")) + num_collectors = len(self.all_rings) + device = self.learner_device + if self.num_learners > 1: + if device.type != "cuda" or device.index is None: + raise ValueError(f"multi-learner requires explicit indexed CUDA learner devices, got {device}") + torch.cuda.set_device(device) + # Bounded collective timeout: with the default 30-minute timeout a + # rank waiting on a crashed/blocked peer hangs until the parent's + # force-kill instead of unwinding through its own error path. + import datetime as _dt + + dist.init_process_group( + "nccl", + init_method=f"file://{self.rendezvous_file}", + rank=self.rank, + world_size=self.num_learners, + timeout=_dt.timedelta(seconds=90), ) - handshake.ship_ring_slots(collector_id, ring_slots) - - endpoints = [CollectorEndpoint(ring=rings[j], weight_sender=weight_txs[j]) for j in range(len(weight_txs))] - - learner = Learner( - agent, - cfg, - endpoints, - control, - ddp_rank=rank if num_learners > 1 else None, - ) - learner._last_train_gstep = resume_step # lockstep basis continues from the checkpoint - learner.publish_weights() # give every collector an initial policy before it warms up - - # Elapsed/ETA anchor. The collector's env build (scene compile, kernel - # compile) runs concurrently with the learner build and can outlast it by - # tens of seconds; timing from this point would bill that startup wait - # to elapsed and the first window's rates. The anchor moves to the - # first ingested collector batch below. - start_time = time.time() - start_anchored = False - last_log_time = start_time - last_log_step = resume_step - train_started = False - # First payload goes out immediately (step 0) so the parent's panel - # quiescence gate opens as soon as collectors take their first steps, - # instead of after a silent full log window; resume keeps window - # alignment. - if logging_interval > 0 and resume_step: - next_log = ((resume_step // logging_interval) + 1) * logging_interval - else: - next_log = 0 - next_save = ((resume_step // save_interval) + 1) * save_interval if save_interval > 0 else 0 - t_learn_win = 0.0 # wall-clock spent in learner train calls this log window - learner_train_samples_ms: list[float] = [] - learner_drain_samples_ms: list[float] = [] - learner_breakdown_samples_ms: dict[str, list[float]] = {} - learner_ring_wait_samples_ms: list[float] = [] - learner_gate_wait_samples_ms: list[float] = [] - last_checkpoint_path: str | None = None - # The parent process renders the panel and writes TensorBoard: this - # worker ships one compact payload per log window (all learner ranks - # send — workers are peers, the parent is the recorder). - - # Startup barrier: report readiness and hold until every worker booted - # (see run_collector_process). Weight slots were already shipped and - # the initial weights published, so collectors blocking on their - # handshakes complete as soon as every learner reaches this point. - handshake.report_ready("learner", rank) - handshake.wait_for_start(control) - if control.stop: - return - - # Each collector runs until its own counter reaches num_iterations; the - # aggregate (sum) therefore reaches num_iterations * num_collectors. - total_collector_steps = num_iterations * num_collectors - while not control.stop and control.collector_steps < total_collector_steps: - # Progress basis: full num_envs-batch equivalents — the aggregate - # counter counts per-collector batches of per_collector_envs - # transitions each, so dividing by num_collectors recovers the - # sync-trainer "iteration collects num_envs transitions" unit - # (identical to the raw counter when num_collectors == 1). All - # ranks read the same shared value. - step = control.collector_steps // num_collectors - control.global_step = step - t_drain = time.perf_counter() - ingested = learner.drain() - if ingested: - if not start_anchored: - start_time = time.time() - last_log_time = start_time - start_anchored = True - learner_drain_samples_ms.append((time.perf_counter() - t_drain) * 1000.0) - t_l = time.perf_counter() - # One decision path for both topologies: updates are gated on the - # global progress basis (identical on every DDP rank; the single - # learner's own position when num_collectors == 1). - trained = learner.maybe_train(step) - first_update = trained and not train_started - if trained: - train_started = True - elapsed_learn_s = time.perf_counter() - t_l - t_learn_win += elapsed_learn_s - learner_train_samples_ms.append(elapsed_learn_s * 1000.0) - # Keep the raw total cost of one agent.update(n) call. The - # timing tree uses total-cost semantics, not per-gradient-step - # normalization. - for key, value in learner.agent._last_update_timing_ms.items(): - learner_breakdown_samples_ms.setdefault(key, []).append(value) - learner_breakdown_samples_ms.setdefault("publish", []).append(learner._last_publish_ms) - else: - # warmup or starved: avoid a hot spin. - t_idle = time.perf_counter() - time.sleep(opts.idle_sleep_s) - idle_ms = (time.perf_counter() - t_idle) * 1000.0 - if ingested == 0: - # No ring slot was available: learner is waiting for collector data. - learner_ring_wait_samples_ms.append(idle_ms) - else: - # Data arrived, but replay/batch readiness still gated training. - learner_gate_wait_samples_ms.append(idle_ms) - if step >= next_log or first_update: - # Publish first-update completion immediately: the startup - # handoff must not wait an entire user logging interval. - # One compact payload per log window to the parent (panel + - # TensorBoard live there; see train.py). All ranks send. - now = time.time() - sps = (step - last_log_step) * num_envs / max(now - last_log_time, 1e-6) + # Replay buffer sized by THIS rank's env shard: each learner drains only + # its collectors' rings, so every ingested batch carries + # num_envs // num_learners envs (env-level sharding keeps each env's + # full trajectory — and n-step adjacency — inside one rank). The batch + # math still divides the GLOBAL batch_size by world_size, so per-rank + # sample rows == batch_size / num_learners, matching DDP averaging. + agent_started = time.perf_counter() + agent = build_agent( + self.cfg, + self.dims, + self.num_envs // self.num_learners, + device, + self.action_scale, + self.action_bias, + world_size=self.num_learners, + final_obs_bootstrap=self.final_stores is not None, + observation_spec=self.observation_spec, + ) + if self.resume_from: + ckpt = torch.load(self.resume_from, map_location=device, weights_only=False) + agent.load_state_dict(ckpt, load_optimizers=True) + logger.info( + "learner startup: agent build%s finished in %.3fs", + " + checkpoint load" if self.resume_from else "", + time.perf_counter() - agent_started, + ) + + resume_step = self.control.collector_steps // num_collectors # full-batch equivalents + per_collector_envs = self.num_envs // num_collectors + # Build one sender endpoint per collector owned by this rank and ship + # the slot tensors BEFORE + # the first publish so each collector (blocking on its handshake queue) + # builds the matching receiver from step one. The IPC transition-ring + # slots ship in the same one-shot message: this process is the owner + # (it allocated the device tensor and must keep it alive), the + # collector maps it through the queue's CUDA-IPC reducers. + # Transport per channel was decided by the parent topology pass + # (weight_channels, indexed per collector); this process only + # constructs the endpoints — the bundle spec (sized by the parent + # with one throwaway CPU actor) already fixes both transports' + # buffer sizes. + weight_txs = [] + for j, shared in enumerate(self.weights): + channel = self.collector_ids[j] + # CUDA-IPC device slots when the topology resolved IPC for this + # channel (the collector infers on this rank's GPU), host + # shared-memory slots otherwise; this rank is the exporter (its + # CUDA context must keep the slot tensors alive). + tx = GpuIpcWeightSender(shared, device) if self.weight_ipc[j] else HostWeightSender(shared) + self.handshake.ship_weight_slots(channel, tx.params) + weight_txs.append(tx) + # Wrap RingCursors into GpuIpcTransitionRing (allocating the device slots + # and shipping them to the collector) BEFORE building the endpoints — + # the endpoints must hold the FINAL ring objects the drain path uses. + for j, ring in enumerate(self.rings): + collector_id = self.collector_ids[j] + ring_slots = None + if isinstance(ring, RingCursors): + if device.type != "cuda": + raise RuntimeError("the IPC transition ring was selected but the learner device is not CUDA") + obs_dim, critic_obs_dim, act_dim = self.dims + schema = fastsac_transition_schema(agent.rb.n_obs, agent.rb.n_critic_obs, act_dim) + ring_slots = torch.zeros( + opts.ring_capacity, + per_collector_envs, + schema.feature_width, + dtype=torch.float32, + device=device, + ) + self.rings[j] = GpuIpcTransitionRing( + ring, + ring_slots, + schema, + opts.ring_capacity, + per_collector_envs, + payload_store=self.final_stores[j] if self.final_stores is not None else None, + ) + self.handshake.ship_ring_slots(collector_id, ring_slots) + + endpoints = [ + CollectorEndpoint(ring=self.rings[j], weight_sender=weight_txs[j]) for j in range(len(weight_txs)) + ] + + learner = Learner( + agent, + self.cfg, + endpoints, + self.control, + ddp_rank=self.rank if self.num_learners > 1 else None, + ) + learner._last_train_gstep = resume_step # lockstep basis continues from the checkpoint + learner.publish_weights() # give every collector an initial policy before it warms up + + # Elapsed/ETA anchor. The collector's env build (scene compile, kernel + # compile) runs concurrently with the learner build and can outlast it by + # tens of seconds; timing from this point would bill that startup wait + # to elapsed and the first window's rates. The anchor moves to the + # first ingested collector batch below. + start_time = time.monotonic() + start_anchored = False + last_log_time = start_time + train_started = False + first_payload = True + log_schedule = IterationLogSchedule(self.logging_interval, initial_iteration=resume_step) + next_save = ((resume_step // self.save_interval) + 1) * self.save_interval if self.save_interval > 0 else 0 + timing = TimingWindow() + phase_keys: set[str] = set() + breakdown_keys: set[str] = set() + last_checkpoint_path: str | None = None + # The parent process renders the panel and writes TensorBoard: this + # worker ships one compact payload per log window (all learner ranks + # send — workers are peers, the parent is the recorder). + + # Startup barrier: report readiness and hold until every worker booted + # (see CollectorWorker). Weight slots were already shipped and + # the initial weights published, so collectors blocking on their + # handshakes complete as soon as every learner reaches this point. + self.handshake.report_ready("learner", self.rank) + self.handshake.wait_for_start(self.control) + if self.control.stop: + return + + def publish_stats(step: int) -> None: + nonlocal last_log_time, first_payload + now = time.monotonic() warming = step < agent.cfg.learning_starts metrics_log = None if train_started and not warming: @@ -639,37 +493,44 @@ def run_learner_process( # meter logging. train_started just gates "training # started". metrics_log = learner.agent.window_metrics.stats_and_reset() - learn_pct = 100.0 * t_learn_win / max(now - last_log_time, 1e-9) - learner_items: dict[str, Any] = {} - if learner_drain_samples_ms: - learner_items["drain"] = timing_mean(learner_drain_samples_ms) - if learner_ring_wait_samples_ms: - learner_items["ring wait"] = timing_mean(learner_ring_wait_samples_ms) - if learner_gate_wait_samples_ms: - learner_items["gate wait"] = timing_mean(learner_gate_wait_samples_ms) - update_items = {key: timing_mean(values) for key, values in learner_breakdown_samples_ms.items()} - if update_items: - # publish is a child stage of the learner update in the - # panel, so include it in the displayed update total too. - if "publish" in update_items and "total" in update_items: - update_items["total"] += update_items["publish"] - learner_items["update"] = update_items + learn_pct = 100.0 * timing.total_seconds("train") / max(now - last_log_time, 1e-9) + learner_items = [ + TimingNode(key, timing.mean_ms(key)) + for key in ("drain", "ring wait", "gate wait") + if key in phase_keys + ] + if breakdown_keys: + # The measured agent total excludes publication; keep the + # parent unknown when no total was sampled, never sum stages. + update_ms = ( + timing.mean_ms("update.total") + timing.mean_ms("update.publish") + if "total" in breakdown_keys + else None + ) + learner_items.append( + TimingNode( + "update", + update_ms, + tuple( + TimingNode(key, timing.mean_ms(f"update.{key}")) + for key in sorted(breakdown_keys) + if key != "total" + ), + ) + ) payload = { - "rank": rank, - "step": step, - "sps": sps, + "rank": self.rank, "updates": learner.update_idx, "training_started": train_started, "metrics": metrics_log, - "warming": warming, - "learn_ms": timing_mean(learner_train_samples_ms) if learner_train_samples_ms else 0.0, + "learn_ms": timing.mean_ms("train"), "learn_pct": learn_pct, - "learner_timing": learner_items, + "learner_timing": tuple(learner_items), "buffer_size": agent.rb.num_stored * agent.num_envs, "buffer_capacity": agent.rb.buffer_size * agent.num_envs, # bare RingCursors (IPC transport) carry no size; the # wrapped GpuIpcTransitionRing lives in this worker. - "ring_fill": [None if isinstance(ring, RingCursors) else ring.size() for ring in all_rings], + "ring_fill": [None if isinstance(ring, RingCursors) else ring.size() for ring in self.all_rings], "weight_version": max((tx.version for tx in weight_txs), default=None), "checkpoint_path": last_checkpoint_path, } @@ -677,80 +538,134 @@ def run_learner_process( # drop the window's payload if the queue is full (the next # window's numbers supersede it anyway). try: - learner_data_queue.put_nowait(payload) + self.learner_data_queue.put_nowait(payload) except Full: pass - last_log_time, last_log_step = now, step - t_learn_win = 0.0 - learner_train_samples_ms = [] - learner_drain_samples_ms = [] - learner_breakdown_samples_ms = {} - learner_ring_wait_samples_ms = [] - learner_gate_wait_samples_ms = [] - # Recompute the window edge (not +=) so the immediate first - # payload cannot shift every later window off the interval. - next_log = ((step // logging_interval) + 1) * logging_interval if logging_interval > 0 else 0 - - if is_primary and save_interval > 0 and step >= next_save and step > 0: - agent.global_step = step + last_log_time = now + first_payload = False + timing.reset() + phase_keys.clear() + breakdown_keys.clear() + log_schedule.mark_logged(step) + + # Each collector runs until its own counter reaches num_iterations; the + # aggregate (sum) therefore reaches num_iterations * num_collectors. + total_collector_steps = self.num_iterations * num_collectors + while not self.control.stop and self.control.collector_steps < total_collector_steps: + # Progress basis: full num_envs-batch equivalents — the aggregate + # counter counts per-collector batches of per_collector_envs + # transitions each, so dividing by num_collectors recovers the + # sync-trainer "iteration collects num_envs transitions" unit + # (identical to the raw counter when num_collectors == 1). All + # ranks read the same shared value. + step = self.control.collector_steps // num_collectors + self.control.global_step = step + t_drain = time.perf_counter() + ingested = learner.drain() + if ingested: + if not start_anchored: + start_time = time.monotonic() + last_log_time = start_time + start_anchored = True + timing.add("drain", time.perf_counter() - t_drain) + phase_keys.add("drain") + t_l = time.perf_counter() + # One decision path for both topologies: updates are gated on the + # global progress basis (identical on every DDP rank; the single + # learner's own position when num_collectors == 1). + trained = learner.maybe_train(step) + first_update = trained and not train_started + if trained: + train_started = True + elapsed_learn_s = time.perf_counter() - t_l + timing.add("train", elapsed_learn_s) + # Keep the raw total cost of one agent.update(n) call. The + # timing tree uses total-cost semantics, not per-gradient-step + # normalization. + for key, value in learner.agent._last_update_timing_ms.items(): + timing.add(f"update.{key}", value / 1000.0) + breakdown_keys.add(key) + timing.add("update.publish", learner._last_publish_ms / 1000.0) + breakdown_keys.add("publish") + else: + # warmup or starved: avoid a hot spin. + t_idle = time.perf_counter() + time.sleep(opts.idle_sleep_s) + idle_ms = (time.perf_counter() - t_idle) * 1000.0 + if ingested == 0: + # No ring slot was available: learner is waiting for collector data. + timing.add("ring wait", idle_ms / 1000.0) + phase_keys.add("ring wait") + else: + # Data arrived, but replay/batch readiness still gated training. + timing.add("gate wait", idle_ms / 1000.0) + phase_keys.add("gate wait") + if first_payload or log_schedule.due(step) or first_update: + # Publish first-update completion immediately: the startup + # handoff must not wait an entire user logging interval. + # One compact payload per log window to the parent (panel + + # TensorBoard live there; see train.py). All ranks send. + publish_stats(step) + + if is_primary and self.save_interval > 0 and step >= next_save and step > 0: + agent.global_step = step + learner.wait_ingest() # checkpoint reads the rb tensors + path = Path(self.checkpoint_dir) / f"model_{step:07d}.pt" + torch.save(agent.state_dict(), path) + checkpoints.record_checkpoint_artifact( + Path(self.run_dir), + checkpoints.LATEST_TRAINING_STATE, + path, + checkpoints.TRAINING_STATE, + checkpoint_format=self.checkpoint_format, + ) + last_checkpoint_path = str(path) + logger.info("saved checkpoint %s", path) + # A notice per save for live metrics, separate from the log-window + # payload: this step's payload already went out above, and a save + # after the last log window would otherwise never reach the parent. + # Never blocks the learner, like the log payloads. + if self.notify_checkpoints: + try: + self.learner_data_queue.put_nowait( + {"rank": self.rank, "checkpoint_saved": {"step": step, "path": str(path)}} + ) + except Full: + logger.warning("learner data queue full; checkpoint notice for %s dropped", path) + next_save += self.save_interval + + # A short or partial last window must reach the parent too. + publish_stats(self.control.collector_steps // num_collectors) + + if self.num_learners > 1: + # All ranks have consumed the identical global step count, so the + # collectives inside update() are matched; this barrier aligns + # teardown so no rank destroys the process group while another is + # still inside a collective. + dist.barrier() + if is_primary: + # final checkpoint (identical structure to sync fastsac) + agent.global_step = self.control.collector_steps // num_collectors learner.wait_ingest() # checkpoint reads the rb tensors - path = Path(checkpoint_dir) / f"model_{step:07d}.pt" - torch.save(agent.state_dict(), path) + ckpt_path = checkpoints.final_checkpoint_path(self.checkpoint_format, Path(self.run_dir)) + ckpt_path.parent.mkdir(parents=True, exist_ok=True) + torch.save(agent.state_dict(), ckpt_path) checkpoints.record_checkpoint_artifact( - Path(run_dir), + Path(self.run_dir), checkpoints.LATEST_TRAINING_STATE, - path, + ckpt_path, checkpoints.TRAINING_STATE, - checkpoint_format=checkpoint_format, + checkpoint_format=self.checkpoint_format, ) - last_checkpoint_path = str(path) - logger.info("saved checkpoint %s", path) - # A notice per save for live metrics, separate from the log-window - # payload: this step's payload already went out above, and a save - # after the last log window would otherwise never reach the parent. - # Never blocks the learner, like the log payloads. - if notify_checkpoints: - try: - learner_data_queue.put_nowait( - {"rank": rank, "checkpoint_saved": {"step": step, "path": str(path)}} - ) - except Full: - logger.warning("learner data queue full; checkpoint notice for %s dropped", path) - next_save += save_interval - - if num_learners > 1: - # All ranks have consumed the identical global step count, so the - # collectives inside update() are matched; this barrier aligns - # teardown so no rank destroys the process group while another is - # still inside a collective. - dist.barrier() - if is_primary: - # final checkpoint (identical structure to sync fastsac) - agent.global_step = control.collector_steps // num_collectors - learner.wait_ingest() # checkpoint reads the rb tensors - ckpt_path = checkpoints.final_checkpoint_path(checkpoint_format, Path(run_dir)) - ckpt_path.parent.mkdir(parents=True, exist_ok=True) - torch.save(agent.state_dict(), ckpt_path) - checkpoints.record_checkpoint_artifact( - Path(run_dir), - checkpoints.LATEST_TRAINING_STATE, - ckpt_path, - checkpoints.TRAINING_STATE, - checkpoint_format=checkpoint_format, - ) - checkpoints.record_checkpoint_artifact( - Path(run_dir), - checkpoints.BEST_POLICY, - ckpt_path, - checkpoints.POLICY, - checkpoint_format=checkpoint_format, - ) - logger.info("saved checkpoint to %s", ckpt_path) - except BaseException: - if not isinstance(sys.exc_info()[1], (KeyboardInterrupt, SystemExit)): - error_queue.put((f"learner[{rank}]" if num_learners > 1 else "learner", traceback.format_exc())) - raise - finally: - if num_learners > 1: - dist.destroy_process_group() - control.set_stop() # tell the collectors to exit + checkpoints.record_checkpoint_artifact( + Path(self.run_dir), + checkpoints.BEST_POLICY, + ckpt_path, + checkpoints.POLICY, + checkpoint_format=self.checkpoint_format, + ) + logger.info("saved checkpoint to %s", ckpt_path) + finally: + self.control.set_stop() # tell the collectors to exit, including failed DDP startup + if self.num_learners > 1 and dist.is_initialized(): + dist.destroy_process_group() diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py index 4c7d3a1e1..bbafd7c70 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py @@ -11,11 +11,13 @@ from motrix_env_core import registry as env_registry from motrix_env_core.renderer import RenderConfig from motrix_rl import checkpoints -from motrix_rl.console import EpisodeWindow, PanelSystemSampler, TrainingPanelSession, TrainingPanelStats -from motrix_rl.console.metrics import ROLLOUT_MEANS, system_scalars +from motrix_rl.console import TrainingPanelSession from motrix_rl.contracts import TrainerBase, TrainerContext from motrix_rl.device import resolve_default_device -from motrix_rl.training_logger import TrainingLogger +from motrix_rl.log.collector_stats import CollectorStatsTracker +from motrix_rl.log.schedule import IterationLogSchedule +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics from motrix_rl_builtin.fastsac.agent import FastSacAgent from motrix_rl_builtin.fastsac.config import FastSacCfg from motrix_rl_builtin.fastsac.wrap import FastSacEnvWrap @@ -101,19 +103,28 @@ def train(self) -> None: raise ValueError("FastSAC supports only the 'tensorboard' logging backend.") run_dir = self._context.run_dir - training_log = TrainingLogger(run_dir, self._context.metrics) + env = self._make_env(self._context.num_envs, render=self._render) + agent = self._make_agent(env) + num_iterations = self._rlcfg.trainer.num_learning_iterations + if self._resume_from: + ckpt = torch.load(self._resume_from, map_location=agent.device, weights_only=False) + agent.load_state_dict(ckpt, load_optimizers=True) + training_log = TrainingLogger( + run_dir, + self._context.metrics, + interval=self._context.logging.interval, + live_only_prefixes=("sys/",), + initial_iteration=agent.global_step, + initial_env_steps=agent.global_step * self._context.num_envs, + ) try: - env = self._make_env(self._context.num_envs, render=self._render) - agent = self._make_agent(env) - num_iterations = self._rlcfg.trainer.num_learning_iterations - if self._resume_from: - ckpt = torch.load(self._resume_from, map_location=agent.device, weights_only=False) - agent.load_state_dict(ckpt, load_optimizers=True) print(f"[motrix.fastsac sync] resumed from {self._resume_from} at global_step={agent.global_step}") training_log.event( - "resumed", step=agent.global_step, path=str(self._resume_from), global_step=agent.global_step + "resumed", + iteration=agent.global_step, + data={"path": str(self._resume_from), "global_step": agent.global_step}, ) if agent.global_step >= num_iterations: print( @@ -126,7 +137,7 @@ def train(self) -> None: f"[motrix.fastsac sync] training '{self._env_name}' on {agent.device} " f"num_envs={env.num_envs} iters={num_iterations} (from {agent.global_step})" ) - training_log.event("run_started", step=agent.global_step) + training_log.event("run_started", iteration=agent.global_step, data={}) def _record_periodic_checkpoint(path) -> None: # Record each periodic checkpoint as the latest resumable training @@ -145,7 +156,6 @@ def _record_periodic_checkpoint(path) -> None: env, training_log, num_iterations=num_iterations, - logging_interval=self._context.logging.interval, save_interval=self._context.checkpoint.interval, record_checkpoint=_record_periodic_checkpoint, ) @@ -168,7 +178,7 @@ def _record_periodic_checkpoint(path) -> None: checkpoint_format=self._context.checkpoint_format, ) print(f"[motrix.fastsac sync] saved checkpoint to {ckpt_path}") - training_log.event("checkpoint_saved", step=agent.global_step, path=str(ckpt_path)) + training_log.event("checkpoint_saved", iteration=training_log.iteration, data={"path": str(ckpt_path)}) finally: # Close on failure too, so buffered TensorBoard events are flushed. training_log.close() @@ -181,7 +191,6 @@ def _run_loop( training_log: TrainingLogger, *, num_iterations: int, - logging_interval: int, save_interval: int, record_checkpoint, ) -> None: @@ -203,23 +212,28 @@ def _run_loop( agent.set_train_mode() obs, critic_obs = env.reset() - ep_return = torch.zeros(agent.num_envs, device=device) - ep_len = torch.zeros(agent.num_envs, device=device) - episode_window = EpisodeWindow(max_episodes=100) - - # window accumulators for the console panel - start_time = time.time() - last_log_time = start_time + tracker = CollectorStatsTracker(0, num_envs=agent.num_envs, device=device) last_log_step = agent.global_step - term_accum: dict[str, float] = {} - term_count = 0 - # per-iter phase timing accumulators (collector vs learner), reset each log window + # Reuse the logging interval as the default observation publication cadence. + # This schedule only drains device observations; sinks own output cadence. + observation_schedule = IterationLogSchedule(self._context.logging.interval, initial_iteration=agent.global_step) + # Per-iteration phase timings are accumulated until the device drain. t_collect = 0.0 t_learn = 0.0 - system_sampler = PanelSystemSampler() - last_checkpoint_path: str | None = None - - panel = TrainingPanelSession.open(title=f"{self._env_name}/motrix.fastsac") + session = TrainingPanelSession.open(title=f"{self._env_name}/motrix.fastsac") + panel = session.metrics_panel( + total_iterations=num_iterations, + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + reductions=training_log.reductions, + default_reduction=training_log.default_reduction, + ) + metrics = TrainingMetrics( + [training_log, panel], + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + system_sink=training_log, + ) # `local` counts steps since this loop started; it gates the # warmup / learning_starts so a resumed run (global_step > 0) still @@ -235,8 +249,7 @@ def _run_loop( # ---------------- collector phase: decision + env.step + buffer write + bookkeeping t0 = time.perf_counter() warming = local < cfg.learning_starts - if cfg.learning_starts > 0 and local == cfg.learning_starts: - training_log.event("warmup_done", step=agent.global_step) + warmup_done = cfg.learning_starts > 0 and local == cfg.learning_starts if warming and not is_resume: actions = torch.empty(agent.num_envs, agent.act_dim, device=device).uniform_(-1.0, 1.0) actions = actions * agent.actor.action_scale + agent.actor.action_bias @@ -258,26 +271,14 @@ def _run_loop( final.env_ids, agent.rb.ptr - 1, final.obs.policy, final.obs.value_or_policy ) - ep_return += rewards - ep_len += 1 - done_idx = torch.nonzero(terminated | truncated, as_tuple=False).flatten() - if done_idx.numel(): - # Vectorized: one batched gather + clear instead of - # per-episode Python-level scalar indexing. - episode_window.add(ep_return[done_idx].tolist(), ep_len[done_idx].tolist()) - ep_return[done_idx] = 0.0 - ep_len[done_idx] = 0.0 + tracker.record_step( + rewards, + terminated | truncated, + reward_terms=result.info.get("Reward", {}), + metrics=result.info.get("metrics", {}), + ) obs = next_obs critic_obs = next_critic_obs - - # accumulate per-term reward means over the logging window. - # info["Reward"] holds each term's per-env contribution as a (N,) - # array (shared convention across backends); mean over envs here. - reward_terms = result.info.get("Reward") - if reward_terms: - for k, v in reward_terms.items(): - term_accum[k] = term_accum.get(k, 0.0) + float(v.mean()) - term_count += 1 t_collect += time.perf_counter() - t0 # ---------------- learner phase: num_updates gradient steps on a sampled batch @@ -286,93 +287,48 @@ def _run_loop( agent.update(cfg.num_updates) t_learn += time.perf_counter() - t1 - if agent.global_step % logging_interval == 0: - now = time.time() - sps = (agent.global_step - last_log_step) * agent.num_envs / max(now - last_log_time, 1e-6) - # Window-aggregated diagnostics (means + extremes since the - # last log window), shared semantics with the async - # trainer's payload. + local += 1 + agent.global_step += 1 + metrics.advance(env_steps=agent.num_envs) + final_step = agent.global_step >= num_iterations + scalars = {"learner/replay_warming": float(warming)} + if observation_schedule.due(agent.global_step) or final_step: metrics_log = agent.window_metrics.stats_and_reset() if not warming else None - episode_stats = episode_window.snapshot() - mean_ret = episode_stats.mean_return if episode_stats.mean_return is not None else float("nan") - mean_len = episode_stats.mean_length if episode_stats.mean_length is not None else float("nan") - term_means = {k: v / max(term_count, 1) for k, v in term_accum.items()} - # window-mean per-iter phase timings (ms); ratio shows collector/learner balance + episode_stats = tracker.snapshot() n_iter_win = max(agent.global_step - last_log_step, 1) - collect_ms = t_collect * 1000.0 / n_iter_win - learn_ms = t_learn * 1000.0 / n_iter_win phase_total = t_collect + t_learn - learn_pct = 100.0 * t_learn / max(phase_total, 1e-9) - info = result.info - # generic env metrics channel: the wrapper merges the state's - # metrics snapshot into infos["metrics"], so backends log them - # without hardcoding any metric name. - env_metrics = {k: float(np.mean(v)) for k, v in info.get("metrics", {}).items()} - system = system_sampler.sample() - stats = TrainingPanelStats( - iteration=agent.global_step, - total_iterations=num_iterations, - steps_per_second=sps, - elapsed_seconds=now - start_time, - mean_return=mean_ret, - mean_episode_length=mean_len, - episodes=episode_stats.episodes, - buffer_size=agent.rb.num_stored * agent.num_envs, - buffer_capacity=agent.rb.buffer_size * agent.num_envs, - collect_ms=collect_ms, - learn_ms=learn_ms, - learn_percent=learn_pct, - warming=warming, - training_metrics=metrics_log, - reward_terms=term_means, - env_metrics=env_metrics, - cpu_load=system.cpu_load, - gpu_utilization_percent=system.gpu_utilization_percent, - memory_usage=system.memory_usage, - gpu_memory_usage=system.gpu_memory_usage, - gpu_devices=system.gpu_devices, - checkpoint_path=last_checkpoint_path, - ) - panel.submit(stats) - scalars = { - "rollout/mean_return": mean_ret, - "rollout/mean_ep_len": mean_len, - "rollout/env_reward": float(rewards.mean()), - "perf/env_steps_per_s": sps, - "perf/collect_ms_per_iter": collect_ms, - "perf/learn_ms_per_iter": learn_ms, - "perf/learn_pct": learn_pct, - **{f"metrics/{k}": v for k, v in env_metrics.items()}, - **{f"reward/{k}": v for k, v in term_means.items()}, - **{f"train/{k}": v for k, v in (metrics_log or {}).items()}, + scalars |= { + "collector/reward_mean": float(rewards.mean()), + "learner/buffer_size": agent.rb.num_stored * agent.num_envs, + "learner/buffer_capacity": agent.rb.buffer_size * agent.num_envs, + "learner/learn_percent": 100.0 * t_learn / max(phase_total, 1e-9), + "timing/collector/total_s": t_collect / n_iter_win, + "timing/learner/total_s": t_learn / n_iter_win, + **{f"env/{key}": value for key, value in episode_stats.env_metrics.items()}, + **{f"reward/{key}": value for key, value in episode_stats.reward_terms.items()}, + **{f"train/{key}": value for key, value in (metrics_log or {}).items()}, } - # Iteration global_step has already collected (the counter - # advances at the end of the loop), so it is the - # (global_step + 1)-th batch of num_envs transitions. - training_log.scalars( - scalars, - agent.global_step, - env_steps=(agent.global_step + 1) * agent.num_envs, - live_extra=lambda: system_scalars(stats), - placeholders=() if episode_stats.episodes else ROLLOUT_MEANS, - ) - last_log_time, last_log_step = now, agent.global_step - term_accum, term_count = {}, 0 + if episode_stats.mean_return is not None: + scalars["episode/recent_return_mean"] = episode_stats.mean_return + if episode_stats.mean_episode_length is not None: + scalars["episode/recent_length_mean"] = episode_stats.mean_episode_length + last_log_step = agent.global_step t_collect, t_learn = 0.0, 0.0 + observation_schedule.mark_logged(agent.global_step) + metrics.record(scalars) + if warmup_done: + metrics.event("warmup_done") + metrics.flush(force=final_step) if save_interval > 0 and self._context.checkpoint_dir is not None and agent.global_step > 0: - if agent.global_step % save_interval == 0: + if agent.global_step % save_interval == 0 and not final_step: path = Path(self._context.checkpoint_dir) / f"model_{agent.global_step:07d}.pt" torch.save(agent.state_dict(), path) record_checkpoint(path) - training_log.event("checkpoint_saved", step=agent.global_step, path=str(path)) - last_checkpoint_path = str(path) - panel.checkpoint(str(path)) + metrics.checkpoint(str(path)) - local += 1 - agent.global_step += 1 finally: - panel.close() + session.close() # ------------------------------------------------------------------ play def play(self, policy: str) -> None: diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/window_metrics.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/window_metrics.py deleted file mode 100644 index a1d4b149f..000000000 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/window_metrics.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright Motphys Technology Co., Ltd. 2025, 2026 -# SPDX-License-Identifier: Apache-2.0 - -"""Window-aggregated training diagnostics. - -Mirrors holosoma's ``TensorAverageMeterDict`` plus per-key extremes: logging -only the last gradient step's values hides single-update events (e.g. a -one-iteration Q spike or entropy spike) inside a multi-iteration logging -window. Every key drains as the window mean; range-tracked keys additionally -drain ``{key}_max`` / ``{key}_min`` so transient spikes stay visible. - -Values are accumulated on their producing device (a few tensor adds per -update); the only host synchronization is the ``.item()`` at the drain, which -callers place at their logging boundary. -""" - -from __future__ import annotations - -import torch - - -class WindowMetrics: - """Accumulates per-update diagnostic scalars, drained once per log window.""" - - def __init__(self) -> None: - self._sums: dict[str, torch.Tensor] = {} - self._counts: dict[str, int] = {} - self._max: dict[str, torch.Tensor] = {} - self._min: dict[str, torch.Tensor] = {} - - def add(self, key: str, value: torch.Tensor, track_range: bool = False) -> None: - """Accumulate one scalar observation under ``key``. - - ``track_range=True`` also keeps the window max/min (drained as - ``{key}_max`` / ``{key}_min``) — used for the spike-sensitive - diagnostics (Q extrema and entropy). - """ - v = value.detach().float() - s = self._sums.get(key) - if s is None: - self._sums[key] = v.clone() - self._counts[key] = 1 - if track_range: - self._max[key] = v.clone() - self._min[key] = v.clone() - else: - self._sums[key] = s + v - self._counts[key] += 1 - if track_range: - self._max[key] = torch.maximum(self._max[key], v) - self._min[key] = torch.minimum(self._min[key], v) - - def stats_and_reset(self) -> dict[str, float]: - """Drain window means (plus tracked max/min) accumulated since the last call. - - Returns ``{key}`` window means plus ``{key}_max`` / ``{key}_min`` for - range-tracked keys, converted to floats; empty when nothing was - accumulated. Resets the accumulator for the next window. - """ - stats = {key: (total / self._counts[key]).item() for key, total in self._sums.items()} - stats.update({f"{key}_max": value.item() for key, value in self._max.items()}) - stats.update({f"{key}_min": value.item() for key, value in self._min.items()}) - self._sums, self._counts = {}, {} - self._max, self._min = {}, {} - return stats diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py index eeeb5ea26..0ff6b2a76 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/wrap.py @@ -6,8 +6,7 @@ import gymnasium as gym import torch -from motrix_env_core.array.env import EnvObs, FinalObs -from motrix_env_core.base import ABEnv +from motrix_env_core.array.env import ArrayEnv, EnvObs, FinalObs from motrix_env_core.observations import ObservationSpec from motrix_env_core.renderer import RenderConfig, create_renderer from motrix_rl.utils import env_infos @@ -43,7 +42,7 @@ class FastSacEnvWrap: is therefore the post-reset observation for those environments. """ - def __init__(self, env: ABEnv, device: torch.device, render: RenderConfig | None = None) -> None: + def __init__(self, env: ArrayEnv, device: torch.device, render: RenderConfig | None = None) -> None: action_space = env.action_space if not isinstance(action_space, gym.spaces.Box): raise TypeError("FastSAC supports only Box action spaces.") @@ -57,7 +56,7 @@ def __init__(self, env: ABEnv, device: torch.device, render: RenderConfig | None self._renderer = create_renderer(env, render) @property - def env(self) -> ABEnv: + def env(self) -> ArrayEnv: return self._env @property diff --git a/motrix_rl_builtin/tests/fastsac_async_mocks.py b/motrix_rl_builtin/tests/fastsac_async_mocks.py index c8fe04df9..4f9996424 100644 --- a/motrix_rl_builtin/tests/fastsac_async_mocks.py +++ b/motrix_rl_builtin/tests/fastsac_async_mocks.py @@ -16,10 +16,10 @@ from __future__ import annotations -import inspect import queue import threading from collections.abc import Callable +from dataclasses import fields from types import SimpleNamespace import torch @@ -66,8 +66,9 @@ def __init__(self, script: Callable[[ThreadProcess], int], target, args=(), kwar @property def arguments(self) -> dict: - """The worker entry point's arguments by parameter name.""" - return inspect.signature(self.target).bind(*self.args, **self.kwargs).arguments + """The bootstrap task's dataclass fields, without copying shared IPC state.""" + task = self.args[0] + return {field.name: getattr(task, field.name) for field in fields(task)} def _run(self) -> None: self.exitcode = self._script(self) @@ -81,6 +82,9 @@ def is_alive(self) -> bool: def join(self, timeout: float | None = None) -> None: self._thread.join(timeout) + def close(self) -> None: + self.args[5].close() + def terminate(self) -> None: pass @@ -91,11 +95,10 @@ def kill(self) -> None: class ThreadSpawnContext: """Thread-backed stand-in for ``mp.get_context("spawn")``. - ``scripts`` maps the worker entry point (``run_learner_process`` / - ``run_collector_process``) to the script its threads run. + ``scripts`` maps the bootstrap task type to the script its threads run. """ - def __init__(self, scripts: dict[Callable, Callable[[ThreadProcess], int]]) -> None: + def __init__(self, scripts: dict[type, Callable[[ThreadProcess], int]]) -> None: self.scripts = scripts self.processes: list[ThreadProcess] = [] @@ -106,6 +109,6 @@ def Event(self) -> threading.Event: # noqa: N802 - mirrors the multiprocessing return threading.Event() def Process(self, target, args=(), kwargs=None, name=None) -> ThreadProcess: # noqa: N802 - process = ThreadProcess(self.scripts[target], target, args, kwargs, name) + process = ThreadProcess(self.scripts[type(args[0])], target, args, kwargs, name) self.processes.append(process) return process diff --git a/motrix_rl_builtin/tests/test_builtin_sim_backend.py b/motrix_rl_builtin/tests/test_builtin_sim_backend.py index 2b9d42a17..cfa8162db 100644 --- a/motrix_rl_builtin/tests/test_builtin_sim_backend.py +++ b/motrix_rl_builtin/tests/test_builtin_sim_backend.py @@ -3,7 +3,6 @@ import platform from pathlib import Path -from queue import Empty from types import SimpleNamespace from unittest.mock import Mock @@ -21,7 +20,7 @@ fastsac_inference_bundle_spec, fastsac_transition_schema, ) -from motrix_rl_builtin.fastsac.async_impl.worker import actor_param_numel, run_collector_process +from motrix_rl_builtin.fastsac.async_impl.worker import CollectorWorker, actor_param_numel from motrix_rl_builtin.fastsac.wrap import FastSacEnvWrap, FastSacStepResult from motrix_env_core.array.env import ArrayEnvState, EnvObs @@ -31,6 +30,7 @@ from motrix_env_core.observations import ObservationGroupSpec, ObservationSpec from motrix_env_core.registry import EnvBuildSpec from motrix_env_core.renderer import RecordConfig, RenderConfig +from motrix_rl.worker import WorkerRuntime _NUM_ENVS = 2 @@ -112,6 +112,9 @@ def test_fastsac_clips_actions_for_sim_backend() -> None: class _AsyncEnv: def __init__(self, cfg: EnvCfg, num_envs: int = 1, backend=None) -> None: + from motrix_env_core.perf import Perf + + self.perf = Perf() self._cfg = cfg self._num_envs = num_envs self._device = torch.device("cpu") @@ -207,7 +210,6 @@ def _collect_in_spawn(tmp_path) -> tuple[torch.Tensor, ...]: control = Control() ctx = mp.get_context("spawn") collector_data_queue = ctx.Queue(maxsize=2) - error_queue = ctx.Queue(maxsize=2) weight_tx = HostWeightSender(weights) # Ship the real handshake messages: weight slots (publisher learner) and # ring slots (draining learner; None for the host HostTransitionRing). @@ -217,47 +219,36 @@ def _collect_in_spawn(tmp_path) -> tuple[torch.Tensor, ...]: env_cls = _AsyncTestEnv env_spec = EnvBuildSpec(env_cls, EnvCfg(scene=SceneCfg())) - process = ctx.Process( - target=run_collector_process, - kwargs={ - "env_spec": env_spec, - "cfg": cfg, - "num_envs": _NUM_ENVS, - "dims": dims, - "action_scale": action_scale, - "action_bias": action_bias, - "ring": ring, - "weights": weights, - "control": control, - "collector_data_queue": collector_data_queue, - "error_queue": error_queue, - "num_iterations": 1, - "logging_interval": 1, - "is_resume": False, - "seed": 7, - "run_dir": str(tmp_path), - "handshake": handshake, - "collector_device": torch.device("cpu"), - }, - ) - - process.start() - process.join(timeout=15) - if process.is_alive(): - process.terminate() - process.join(timeout=5) - pytest.fail("collector process did not exit") - + handle = CollectorWorker( + env_spec=env_spec, + cfg=cfg, + num_envs=_NUM_ENVS, + dims=dims, + action_scale=action_scale, + action_bias=action_bias, + ring=ring, + weights=weights, + control=control, + collector_data_queue=collector_data_queue, + num_iterations=1, + logging_interval=1, + is_resume=False, + seed=7, + handshake=handshake, + collector_device=torch.device("cpu"), + ).start(ctx, runtime=WorkerRuntime(seed=7, log_path=tmp_path / "collector0.log")) try: - child_error = error_queue.get_nowait() - except Empty: - child_error = None + handle.join(timeout=15) + if handle.is_alive: + handle.terminate() + handle.join(timeout=5) + pytest.fail("collector process did not exit") + handle.check() + assert handle.exitcode == 0 finally: collector_data_queue.close() - error_queue.close() + handle.close() - assert child_error is None - assert process.exitcode == 0 assert control.collector_steps == 1 count, views = ring.read_span() assert count >= 1 diff --git a/motrix_rl_builtin/tests/test_fastsac_async_multi.py b/motrix_rl_builtin/tests/test_fastsac_async_multi.py index f2819fd8f..9b2b78ac3 100644 --- a/motrix_rl_builtin/tests/test_fastsac_async_multi.py +++ b/motrix_rl_builtin/tests/test_fastsac_async_multi.py @@ -4,7 +4,6 @@ strict-UTD accounting across sharded slots, stats aggregation and NUMA helper selection. Process-level behavior is covered by end-to-end training.""" -import math from types import SimpleNamespace import pytest @@ -14,6 +13,9 @@ from motrix_rl_builtin.fastsac.async_impl.stats import aggregate_collector_stats from motrix_rl_builtin.fastsac.async_impl.transport import Control, HostTransitionRing, fastsac_transition_schema +from motrix_rl.console.panel import TimingNode +from motrix_rl.log.collector_stats import CollectorStats + def test_control_aggregates_per_collector_steps() -> None: control = Control(num_collectors=3) @@ -128,42 +130,42 @@ def test_single_ring_drain_batches_multiple_slots() -> None: assert ring.read_completed_count == 3 -def _snapshot(collector_id: int, ret: float, episodes: int, lag: int, collect_ms: float) -> dict: - return { - "collector_id": collector_id, - "return": ret, - "ep_len": 100.0, - "episodes": episodes, - "reward_terms": {"alive": 0.5}, - "env_metrics": {}, - "policy_lag": lag, - "timing_ms": {"collect": collect_ms}, - } +def _snapshot(collector_id: int, ret: float, episodes: int, lag: int, collect_ms: float) -> CollectorStats: + return CollectorStats( + collector_id=collector_id, + mean_return=ret, + mean_episode_length=100.0, + episodes=episodes, + reward_terms={"alive": 0.5}, + env_metrics={}, + diagnostics={"policy_lag": lag}, + timings=(TimingNode("collect", collect_ms),), + ) def test_aggregate_collector_stats_merges_snapshots() -> None: per_collector = {0: _snapshot(0, 10.0, 4, 1, 8.0), 1: _snapshot(1, 20.0, 6, 3, 12.0)} stats = aggregate_collector_stats(per_collector) - assert stats["return"] == pytest.approx(15.0) - assert stats["episodes"] == 10 - assert stats["policy_lag"] == 3 - assert stats["timing_ms"]["collect"] == pytest.approx(10.0) + assert stats.mean_return == pytest.approx(15.0) + assert stats.episodes == 10 + assert stats.policy_lag == 3 + assert stats.timing_ms["collect"] == pytest.approx(10.0) def test_aggregate_collector_stats_skips_missing_collectors() -> None: stats = aggregate_collector_stats({0: _snapshot(0, 10.0, 4, 1, 8.0), 1: None}) - assert stats["return"] == pytest.approx(10.0) - assert stats["episodes"] == 4 + assert stats.mean_return == pytest.approx(10.0) + assert stats.episodes == 4 def test_aggregate_collector_stats_defaults_without_snapshots() -> None: stats = aggregate_collector_stats({0: None, 1: None}) - assert math.isnan(stats["return"]) - assert stats["episodes"] == 0 - assert stats["policy_lag"] == 0 + assert stats.mean_return is None + assert stats.episodes == 0 + assert stats.policy_lag == 0 def test_extend_batch_matches_repeated_extend_including_wraparound() -> None: diff --git a/motrix_rl_builtin/tests/test_fastsac_collector.py b/motrix_rl_builtin/tests/test_fastsac_collector.py index 8e8ab8a01..459fd7b97 100644 --- a/motrix_rl_builtin/tests/test_fastsac_collector.py +++ b/motrix_rl_builtin/tests/test_fastsac_collector.py @@ -36,6 +36,7 @@ class _CpuEnv: """Wrapper stand-in: the collector reads the original env via ``.env``.""" def __init__(self): + self.perf = Perf() self.num_envs = _NUM_ENVS self.last_actions = None @@ -232,16 +233,48 @@ def test_collector_explicit_cpu_placement_and_timing() -> None: assert collector.step_once() stats = collector.snapshot_stats() - assert "collect" in stats["timing_ms"] - assert "sample_actions" in stats["timing_ms"] - assert "sync" in stats["timing_ms"] - assert "sync.wait_writer" in stats["timing_ms"] - assert "sync.host_snapshot" in stats["timing_ms"] - assert "sync.actor_load" in stats["timing_ms"] + timings = {node.name: node for node in stats.timings} + assert timings["collect"].duration_ms >= 0.0 + assert timings["sample_actions"].duration_ms >= 0.0 + assert timings["sync"].duration_ms >= 0.0 + assert {node.name for node in timings["sync"].children} == {"wait_writer", "host_snapshot", "actor_load"} + assert stats.collector_id == collector.collector_id + assert stats.episodes == 0 + assert stats.mean_return is None + assert stats.mean_episode_length is None + assert stats.diagnostics == {"policy_lag": 0.0} assert collector.ring.data["obs"].device.type == "cpu" assert collector.ring.data["critic_obs"].device.type == "cpu" +def test_collector_snapshot_preserves_episode_means_and_resets_reward_window() -> None: + collector, _, _, weight_tx = _collector("cpu") + # Earlier episodes leave the recent window but remain in the cumulative count. + collector.stats.add_episodes([100.0, 100.0], [100.0, 100.0]) + collector.stats.add_episodes([2.0, 6.0] * 50, [3.0, 7.0] * 50) + collector.stats.record_reward_terms({"alive": 2.0}) + collector.stats.record_reward_terms({"alive": 4.0}) + collector.stats.set_env_metrics({"error": 0.25}) + weight_tx.publish({"actor": collector.actor}, {"obs": collector.obs_normalizer}) + + stats = collector.snapshot_stats() + assert stats.episodes == 102 + assert stats.mean_return == 4.0 + assert stats.mean_episode_length == 5.0 + assert stats.reward_terms == {"alive": 3.0} + assert stats.env_metrics == {"error": 0.25} + assert stats.diagnostics == {"policy_lag": 1.0} + + collector.stats.set_env_metrics({"error": 0.5}) + next_stats = collector.snapshot_stats() + assert next_stats.episodes == stats.episodes + assert next_stats.mean_return == stats.mean_return + assert next_stats.mean_episode_length == stats.mean_episode_length + assert next_stats.reward_terms == {} + assert stats.env_metrics == {"error": 0.25} + assert next_stats.env_metrics == {"error": 0.5} + + def test_collector_reports_env_step_substage_timing() -> None: env = _PerfEnv() cfg = _cfg("cpu") @@ -271,15 +304,22 @@ def test_collector_reports_env_step_substage_timing() -> None: assert collector.step_once() stats = collector.snapshot_stats() - assert "env_step" in stats["timing_ms"] - assert "env_step.apply_action" in stats["timing_ms"] - assert "env_step.physics" in stats["timing_ms"] - assert stats["timing_ms"]["env_step.apply_action"] >= 0.0 - # only the first sub-stage level is reported — a parent's total already - # includes its children, deeper dotted paths are dropped at the stats layer - assert not any(key.count(".") > 1 for key in stats["timing_ms"]) - # sub-stage aggregation is windowed like the other timings + timings = {node.name: node for node in stats.timings} + env_step = timings["env_step"] + substages = {node.name: node for node in env_step.children} + assert set(substages) == {"apply_action", "physics"} + assert substages["apply_action"].duration_ms >= 0.0 + # Preserve nested scopes without adding their cost to the inclusive parent. + assert substages["physics"].children[0].name == "read" + assert substages["physics"].children[0].duration_ms >= 0.0 + # Sub-stage aggregation is windowed like the other timings. assert env.perf.snapshot() == () + next_stats = collector.snapshot_stats() + assert all(node.duration_ms == 0.0 for node in next_stats.timings) + next_env_step = next(node for node in next_stats.timings if node.name == "env_step") + assert next_env_step.children == () + collector.close() + assert not env.perf.enabled def test_collector_uses_resolved_device_without_config_re_resolution() -> None: @@ -395,6 +435,7 @@ class _BackpressureEnv(_CpuEnv): num_envs = 2 def __init__(self): + self.perf = Perf() self.steps = 0 self.outputs = None @@ -414,7 +455,7 @@ def step(self, actions): terminated=torch.zeros(2, dtype=torch.bool), truncated=torch.tensor([False, True]), final_obs=FinalObs(torch.tensor([1]), EnvObs({"policy": torch.full((1, 3), 7.0)})), - info={"Reward": {"alive": np.ones(2)}, "metrics": {"error": np.ones(2)}}, + info={"Reward": {"alive": np.ones(2)}, "metrics": {"error": 1.0}}, ) return self.outputs @@ -490,11 +531,20 @@ def push_once(*fields, **kwargs): assert ring.size() < ring.capacity assert ring.is_full() obs_before = collector.obs.clone() + stats = collector.stats.snapshot() + assert stats.episodes == published + assert stats.mean_return == 2.0 + assert stats.mean_episode_length == 1.0 + assert stats.reward_terms == {"alive": 1.0} for _ in range(3): assert not collector.step_once() assert env.steps == len(calls) == len(pushes) == published assert all(pushes) - assert control.collector_steps == collector._collect_n == collector.n_episodes == published + assert control.collector_steps == published + blocked_stats = collector.stats.snapshot() + assert blocked_stats.episodes == published + assert blocked_stats.reward_terms == {} + assert all(node.duration_ms == 0.0 for node in blocked_stats.timings) torch.testing.assert_close(collector.obs, obs_before) count, fields = ring.read_span() @@ -506,7 +556,12 @@ def push_once(*fields, **kwargs): assert collector.step_once() assert env.steps == len(calls) == len(pushes) == published + 1 assert all(pushes) - assert control.collector_steps == collector._collect_n == collector.n_episodes == published + 1 + assert control.collector_steps == published + 1 + resumed_stats = collector.stats.snapshot() + assert resumed_stats.episodes == published + 1 + assert resumed_stats.mean_return == 2.0 + assert resumed_stats.mean_episode_length == 1.0 + assert resumed_stats.reward_terms == {"alive": 1.0} count, fields = ring.read_span() assert count == published torch.testing.assert_close(fields["obs"][:, 0, 0], torch.arange(1, published + 1, dtype=torch.float32)) @@ -522,11 +577,13 @@ def test_published_step_owns_transition_and_final_payload_buffers(): initial_obs, initial_critic = collector.obs, collector.critic_obs assert collector.step_once() torch.testing.assert_close(collector.obs, torch.full((2, 3), 2.0)) - torch.testing.assert_close(collector.ep_return, torch.tensor([1.0, 0.0])) - assert collector.recent_returns == [2.0] - assert collector.recent_lengths == [1.0] - assert env.steps == len(calls) == 1 - assert collector.n_episodes == collector.term_count == collector._collect_n == control.collector_steps == 1 + stats = collector.stats.snapshot() + assert stats.mean_return == 2.0 + assert stats.mean_episode_length == 1.0 + assert stats.episodes == 1 + assert stats.reward_terms == {"alive": 1.0} + assert stats.env_metrics == {"error": 1.0} + assert env.steps == len(calls) == control.collector_steps == 1 # The environment, action staging, and previous observations may all be # reused as soon as step_once returns: the published slot owns its data. diff --git a/motrix_rl_builtin/tests/test_fastsac_final_obs.py b/motrix_rl_builtin/tests/test_fastsac_final_obs.py index 2d3dd492d..09a173057 100644 --- a/motrix_rl_builtin/tests/test_fastsac_final_obs.py +++ b/motrix_rl_builtin/tests/test_fastsac_final_obs.py @@ -377,7 +377,7 @@ def test_final_payload_ingested_and_released_during_warmup(device): learner = make_mock_learner([ring], []) learner.agent.device = torch.device(device) learner.agent.rb = SimpleReplayBuffer(2, 4, 1, 1, 1, device=device, final_obs_bootstrap=True) - learner.agent.window_metrics = SimpleNamespace(add=lambda *args, **kwargs: None) + learner.agent.window_metrics = SimpleNamespace(record=lambda *args, **kwargs: None) learner._learning_starts = 1000 learner._last_train_gstep = 0 learner.ddp_rank = None diff --git a/motrix_rl_builtin/tests/test_fastsac_learner.py b/motrix_rl_builtin/tests/test_fastsac_learner.py index 7d9db8756..683f53228 100644 --- a/motrix_rl_builtin/tests/test_fastsac_learner.py +++ b/motrix_rl_builtin/tests/test_fastsac_learner.py @@ -86,23 +86,67 @@ def test_policy_frequency_gating_spans_update_calls() -> None: assert agent.update_idx == 11 -def test_nest_timing_path_merges_scalar_total_with_children_in_any_order() -> None: - from motrix_rl_builtin.fastsac.async_impl.stats import nest_timing_path - - # the collector emits a stage's scalar before its dotted sub-stages; the - # rebuild must fold it into a "total" instead of nesting under a float - tree: dict = {} - nest_timing_path(tree, ("physics",), 15.0) - nest_timing_path(tree, ("physics", "read"), 12.0) - assert tree == {"physics": {"total": 15.0, "read": 12.0}} - - # reverse order must converge to the same tree - tree = {} - nest_timing_path(tree, ("physics", "read"), 12.0) - nest_timing_path(tree, ("physics",), 15.0) - assert tree == {"physics": {"total": 15.0, "read": 12.0}} - - # stages without sub-stages stay scalar - tree = {} - nest_timing_path(tree, ("apply_action",), 1.5) - assert tree == {"apply_action": 1.5} +def test_learner_timing_payload_preserves_explicit_and_unknown_parent_durations() -> None: + from queue import Queue + + from motrix_rl_builtin.fastsac.async_impl.stats import AsyncTrainingStatsAggregator, AsyncTrainingStatsSource + + from motrix_rl.console.panel import TimingNode + from motrix_rl.log.collector_stats import CollectorStats + + timings = ( + TimingNode( + "update", + 9.0, + ( + TimingNode("critic", 6.0, (TimingNode("backward", 4.0),)), + TimingNode("actor", None, (TimingNode("forward", 5.0),)), + ), + ), + ) + source = AsyncTrainingStatsSource( + collector_data_queues=[], + learner_data_queue=Queue(), + control=SimpleNamespace(collector_steps=1), + num_envs=1, + num_collectors=1, + num_learners=1, + num_iterations=2, + resume_step=0, + per_collector_stats={ + 0: CollectorStats( + collector_id=0, + mean_return=None, + mean_episode_length=None, + episodes=0, + reward_terms={}, + env_metrics={}, + diagnostics={"policy_lag": 0.0}, + timings=(), + ) + }, + learner_payloads={ + 0: { + "rank": 0, + "training_started": True, + "updates": 1, + "learn_ms": 10.0, + "learn_pct": 50.0, + "learner_timing": timings, + "buffer_size": 1, + "buffer_capacity": 2, + "metrics": None, + "checkpoint_path": None, + } + }, + ) + + sample = AsyncTrainingStatsAggregator(learning_starts=0).collect(source) + + assert sample is not None + assert sample.scalars["timing/learner/total_s"] == 0.010 + assert sample.scalars["timing/learner/update_s"] == 0.009 + assert sample.scalars["timing/learner/update/critic_s"] == 0.006 + assert sample.scalars["timing/learner/update/critic/backward_s"] == 0.004 + assert sample.scalars["timing/learner/update/actor/forward_s"] == 0.005 + assert "timing/learner/update/actor_s" not in sample.scalars diff --git a/motrix_rl_builtin/tests/test_fastsac_live_metrics.py b/motrix_rl_builtin/tests/test_fastsac_live_metrics.py index 958d20263..1fa57d919 100644 --- a/motrix_rl_builtin/tests/test_fastsac_live_metrics.py +++ b/motrix_rl_builtin/tests/test_fastsac_live_metrics.py @@ -3,15 +3,15 @@ """Live metrics emitted by the FastSAC sync and async trainers. -The TensorBoard tag sets below are a compatibility contract: live scalars reuse -the tags as canonical keys (see wiki/design/live-metrics.md), so renaming a tag -breaks dashboards as well as existing TensorBoard comparisons. +Canonical scalar keys are shared by live logging, TensorBoard and panel adapters. +The tests protect progress axes, missing observations, lifecycle events and the +live-only system-metrics boundary. """ from __future__ import annotations -import contextlib import math +import multiprocessing as mp import queue import re import threading @@ -26,51 +26,68 @@ import torch import torch.utils.tensorboard from fastsac_async_mocks import ThreadSpawnContext -from motrix_rl_builtin.fastsac.async_impl.stats import AsyncTrainingStatsAggregator, AsyncTrainingStatsSource +from motrix_rl_builtin.fastsac.async_impl.stats import ( + AsyncTrainingStatsAggregator, + AsyncTrainingStatsSource, + aggregate_collector_stats, +) from motrix_rl_builtin.fastsac.wrap import FastSacStepResult from motrix_env_core.observations import ObservationGroupSpec, ObservationSpec from motrix_rl import checkpoints from motrix_rl.config import CheckpointConfig, LoggingConfig +from motrix_rl.console import TrainingPanelSession +from motrix_rl.console.timing import timing_nodes_from_paths from motrix_rl.contracts import TrainerContext -from motrix_rl.metrics import JsonlSink, MetricsLogger -from motrix_rl.system_metrics import CpuLoad, GpuDeviceUsage, MemoryUsage +from motrix_rl.log.collector_stats import CollectorStats +from motrix_rl.log.live import JsonlSink, MotrixLiveLogger +from motrix_rl.log.training_logger import TrainingLogger +from motrix_rl.log.training_metrics import TrainingMetrics +from motrix_rl.worker import Worker, WorkerError, WorkerHandle, WorkerPlacement, WorkerRuntime SYNC_TB_TAGS = { - "rollout/mean_return", - "rollout/mean_ep_len", - "rollout/env_reward", - "perf/env_steps_per_s", - "perf/collect_ms_per_iter", - "perf/learn_ms_per_iter", - "perf/learn_pct", - "metrics/height", + "throughput/env_steps_per_s", + "throughput/iterations_per_s", + "episode/recent_return_mean", + "episode/recent_length_mean", + "learner/replay_warming", + "learner/buffer_size", + "learner/buffer_capacity", + "collector/reward_mean", + "timing/collector/total_s", + "timing/learner/total_s", + "learner/learn_percent", + "env/height", "reward/alive", "train/qf_loss", "train/actor_loss", } ASYNC_TB_TAGS = { - "rollout/mean_return", - "rollout/mean_ep_len", - "perf/env_steps_per_s", - "perf/updates_per_s", - "async/policy_lag", - "async/weight_publishes_per_iter", - "async/ring_fill", - "async/weight_version", - "async/utd", - "async/policy_lag_collector0", - "async/policy_lag_collector1", - "async/ring_fill_collector0", - "async/ring_fill_collector1", - "perf/collect_ms_per_batch", - "perf/collector_env_step_ms", - "perf/collector_sync_ms", - "perf/collector_sync.wait_writer_ms", - "perf/learn_ms_total", - "perf/learn_pct", - "metrics/height", + "throughput/env_steps_per_s", + "throughput/iterations_per_s", + "episode/recent_return_mean", + "episode/recent_length_mean", + "learner/replay_warming", + "learner/buffer_size", + "learner/buffer_capacity", + "learner/updates_per_s", + "collector/policy_lag", + "learner/weight_publishes_per_iteration", + "collector/ring_fill", + "learner/weight_version", + "train/UTD", + "collector/0/policy_lag", + "collector/1/policy_lag", + "collector/0/ring_fill", + "collector/1/ring_fill", + "timing/collector/total_s", + "timing/collector/env_step_s", + "timing/collector/sync_s", + "timing/collector/sync/wait_writer_s", + "timing/learner/total_s", + "learner/learn_percent", + "env/height", "reward/alive", "train/qf_loss", "train/actor_loss", @@ -131,9 +148,9 @@ def _context(tmp_path, rl_cfg, metrics, *, num_envs, logging_interval, save_inte ) -def _logger(tmp_path) -> tuple[MetricsLogger, _RecordingSink]: +def _logger(tmp_path) -> tuple[MotrixLiveLogger, _RecordingSink]: sink = _RecordingSink(tmp_path / "metrics.jsonl") - return MetricsLogger("unit-run", jsonl=sink), sink + return MotrixLiveLogger("unit-run", jsonl=sink), sink def _events(sink: _RecordingSink) -> list[tuple[str, int]]: @@ -148,7 +165,7 @@ def _paths(sink: _RecordingSink) -> list[tuple[str, int]]: ] -ROLLOUT_MEANS = {"rollout/mean_return", "rollout/mean_ep_len"} +ROLLOUT_MEANS = {"episode/recent_return_mean", "episode/recent_length_mean"} def _event(sink: _RecordingSink, name: str) -> dict: @@ -156,14 +173,8 @@ def _event(sink: _RecordingSink, name: str) -> dict: return record["data"] -def _assert_live_matches_tensorboard( - sink: _RecordingSink, writer: _RecordingWriter, *, no_episode_steps: tuple[int, ...] = () -) -> None: - """Each TB log point has one live point: the same tags and values plus fixed ``sys/*`` keys. - - The one difference: at ``no_episode_steps`` (no episode has ended yet) the - rollout means are a NaN placeholder that TensorBoard keeps and live leaves out. - """ +def _assert_live_matches_tensorboard(sink: _RecordingSink, writer: _RecordingWriter) -> None: + """Live and TensorBoard share observed keys and values, apart from system metrics.""" log_points: list[tuple[int, dict[str, float]]] = [] for tag, value, step in writer.scalars: if not log_points or log_points[-1][0] != step or tag in log_points[-1][1]: @@ -173,45 +184,12 @@ def _assert_live_matches_tensorboard( assert [r["step"] for r in records] == [step for step, _ in log_points] for record, (step, tensorboard) in zip(records, log_points): live = record["data"] - placeholders = ROLLOUT_MEANS if step in no_episode_steps else set() - assert {key for key in live if not key.startswith("sys/")} == set(tensorboard) - placeholders + assert {key for key in live if not key.startswith("sys/")} == set(tensorboard) assert all(SYS_KEY.match(key) for key in live if key.startswith("sys/")) for tag, value in tensorboard.items(): - if tag in placeholders: - continue assert live[tag] == (None if math.isnan(value) else pytest.approx(value)), tag -def test_system_scalars_use_the_fixed_key_list(): - from motrix_rl.console.metrics import system_scalars - - gib = 1024**3 - stats = SimpleNamespace( - cpu_load=CpuLoad( - utilization_percent=37.5, - used_logical_cpus=3.0, - logical_cpu_count=8, - physical_core_count=4, - iowait_percent=0.0, - steal_percent=0.0, - per_core_percent=(37.5,) * 8, - ), - memory_usage=MemoryUsage(used_bytes=3 * gib, total_bytes=16 * gib), - gpu_devices=[ - GpuDeviceUsage(index=0, utilization_percent=55.0, memory=MemoryUsage(used_bytes=2 * gib, total_bytes=gib)), - GpuDeviceUsage(index=1, utilization_percent=None, memory=None), - ], - ) - - assert system_scalars(stats) == { - "sys/cpu_percent": 37.5, - "sys/mem_used_gb": 3.0, - "sys/gpu0/util_percent": 55.0, - "sys/gpu0/mem_used_gb": 2.0, - } - assert system_scalars(SimpleNamespace(cpu_load=None, memory_usage=None, gpu_devices=None)) == {} - - # ---------------------------------------------------------------- sync trainer class _SyncEnv: """Two-step episodes, one reward term and one env metric; rewards turn NaN from step ``diverge_at``.""" @@ -240,7 +218,7 @@ def step(self, actions): terminated=torch.full((n,), self._t % 2 == 0), truncated=torch.zeros(n, dtype=torch.bool), final_obs=None, - info={"Reward": {"alive": np.full(n, 0.5)}, "metrics": {"height": np.full(n, 0.9)}}, + info={"Reward": {"alive": np.full(n, 0.5)}, "metrics": {"height": 0.9}}, ) @@ -273,7 +251,7 @@ def load_state_dict(self, state, load_optimizers=False) -> None: self.global_step = state["global_step"] -def _train_sync(tmp_path, monkeypatch, *, resume_from=None, diverge_at=None): +def _train_sync(tmp_path, monkeypatch, *, resume_from=None, diverge_at=None, logging_interval=2): from motrix_rl_builtin.fastsac.sync.train import Trainer writer = _RecordingWriter() @@ -284,7 +262,13 @@ def _train_sync(tmp_path, monkeypatch, *, resume_from=None, diverge_at=None): rl_cfg = SimpleNamespace(trainer=SimpleNamespace(num_learning_iterations=8)) metrics, sink = _logger(tmp_path) context = _context( - tmp_path, rl_cfg, metrics, num_envs=num_envs, logging_interval=2, save_interval=4, resume_from=resume_from + tmp_path, + rl_cfg, + metrics, + num_envs=num_envs, + logging_interval=logging_interval, + save_interval=4, + resume_from=resume_from, ) Trainer(context=context).train() @@ -295,12 +279,50 @@ def test_sync_trainer_emits_tensorboard_tags_as_live_scalars(tmp_path, monkeypat sink, writer = _train_sync(tmp_path, monkeypatch) scalars = [r for r in sink.records if r["kind"] == "scalars"] - assert [r["step"] for r in scalars] == [0, 2, 4, 6] - # Iteration global_step has already collected at its log point: env_steps = (global_step + 1) * num_envs, - # so the last point of 8 iterations reaches total_steps = 8 * num_envs. - assert [r["axes"]["env_steps"] for r in scalars] == [3, 9, 15, 21] + assert [r["step"] for r in scalars] == [2, 4, 6, 8] + # Steps count completed batches, including the final batch. + assert [r["axes"]["env_steps"] for r in scalars] == [6, 12, 18, 24] assert {tag for tag, _, _ in writer.scalars} == SYNC_TB_TAGS - _assert_live_matches_tensorboard(sink, writer, no_episode_steps=(0,)) + _assert_live_matches_tensorboard(sink, writer) + + +@pytest.mark.parametrize("interval", [0, 3, 100]) +def test_sync_trainer_logs_final_completed_batch_without_duplicate(tmp_path, monkeypatch, interval): + sink, _ = _train_sync(tmp_path, monkeypatch, logging_interval=interval) + records = [record for record in sink.records if record["kind"] == "scalars"] + steps = [record["step"] for record in records] + assert steps[-1] == 8 + assert len(steps) == len(set(steps)) + assert records[-1]["axes"]["env_steps"] == 24 + + +def test_sync_observations_follow_training_cadence_independently_of_output(tmp_path, monkeypatch): + drained_steps = [] + original_agent_init = _SyncAgent.__init__ + original_log_init = TrainingLogger.__init__ + + def agent_init(self, num_envs, learning_starts): + original_agent_init(self, num_envs, learning_starts=0) + + def drain(): + drained_steps.append(self.global_step) + return {"qf_loss": float(self.global_step)} + + self.window_metrics = SimpleNamespace(stats_and_reset=drain) + + def log_init(self, *args, **kwargs): + # A sink can choose a slower output cadence without delaying observations. + kwargs["interval"] = 100 + original_log_init(self, *args, **kwargs) + + monkeypatch.setattr(_SyncAgent, "__init__", agent_init) + monkeypatch.setattr(TrainingLogger, "__init__", log_init) + sink, _ = _train_sync(tmp_path, monkeypatch, logging_interval=3) + + assert drained_steps == [3, 6, 8] + records = [record for record in sink.records if record["kind"] == "scalars"] + assert [record["step"] for record in records] == [8] + assert records[0]["data"]["train/qf_loss"] == 8.0 def test_sync_trainer_emits_lifecycle_events(tmp_path, monkeypatch): @@ -308,7 +330,7 @@ def test_sync_trainer_emits_lifecycle_events(tmp_path, monkeypatch): assert _events(sink) == [ ("run_started", 0), - ("warmup_done", 3), # learning_starts iterations in + ("warmup_done", 4), # learning_starts iterations in ("checkpoint_saved", 4), ("checkpoint_saved", 8), ] @@ -318,14 +340,13 @@ def test_sync_trainer_emits_lifecycle_events(tmp_path, monkeypatch): ] -def test_sync_trainer_leaves_placeholder_rollout_means_out_of_live(tmp_path, monkeypatch): - sink, writer = _train_sync(tmp_path, monkeypatch) +def test_sync_trainer_omits_missing_rollout_means(tmp_path, monkeypatch): + sink, writer = _train_sync(tmp_path, monkeypatch, logging_interval=1) - # No episode has ended at step 0: TensorBoard keeps its NaN, live leaves the keys out - # instead of spending their one nonfinite event on the placeholder. - assert all(math.isnan(v) for tag, v, step in writer.scalars if tag in ROLLOUT_MEANS and step == 0) + # Missing observations are absent in both outputs, not nonfinite samples. + assert not any(tag in ROLLOUT_MEANS and step == 1 for tag, _, step in writer.scalars) first = next(r for r in sink.records if r["kind"] == "scalars") - assert first["step"] == 0 and not ROLLOUT_MEANS & set(first["data"]) + assert first["step"] == 1 and not ROLLOUT_MEANS & set(first["data"]) assert "nonfinite" not in {name for name, _ in _events(sink)} @@ -336,7 +357,7 @@ def test_sync_trainer_flags_a_real_divergence(tmp_path, monkeypatch): r["data"]["key"]: r["step"] for r in sink.records if r["kind"] == "event" and r["data"]["name"] == "nonfinite" } # Episodes ending at env step 4 and later carry NaN returns (logged at global_step 4). - assert nonfinite["rollout/mean_return"] == 4 + assert nonfinite["episode/recent_return_mean"] == 4 def test_sync_trainer_reports_resume(tmp_path, monkeypatch): @@ -349,11 +370,10 @@ def test_sync_trainer_reports_resume(tmp_path, monkeypatch): assert _events(sink) == [ ("resumed", 4), ("run_started", 4), - ("checkpoint_saved", 4), - ("warmup_done", 7), # warmup restarts on resume: the replay buffer is empty + ("warmup_done", 8), # warmup restarts on resume: the replay buffer is empty ("checkpoint_saved", 8), ] - assert [(r["step"], r["axes"]["env_steps"]) for r in sink.records if r["kind"] == "scalars"] == [(4, 15), (6, 21)] + assert [(r["step"], r["axes"]["env_steps"]) for r in sink.records if r["kind"] == "scalars"] == [(6, 18), (8, 24)] # ---------------------------------------------------------------- async trainer (parent process) @@ -369,7 +389,7 @@ def __init__(self, speedup: float) -> None: self._origin = time.time() self._speedup = speedup - def time(self) -> float: + def monotonic(self) -> float: return self._origin + (time.time() - self._origin) * self._speedup def sleep(self, seconds: float) -> None: @@ -417,33 +437,30 @@ class _Stage(NamedTuple): updates: int | None = None -def _snapshot(collector_id: int, stage: _Stage) -> dict: +def _snapshot(collector_id: int, stage: _Stage) -> CollectorStats: no_episode = stage.episodes == 0 - return { - "collector_id": collector_id, - "return": math.nan if no_episode else stage.mean_return, - "ep_len": math.nan if no_episode else 12.0, - "episodes": stage.episodes, - "reward_terms": {"alive": 0.5}, - "env_metrics": {"height": 0.9}, - "policy_lag": collector_id + 1, - "timing_ms": {"collect": 2.0, "env_step": 1.0, "sync": 0.5, "sync.wait_writer": 0.2}, - } + return CollectorStats( + collector_id=collector_id, + mean_return=None if no_episode else stage.mean_return, + mean_episode_length=None if no_episode else 12.0, + episodes=stage.episodes, + reward_terms={"alive": 0.5}, + env_metrics={"height": 0.9}, + diagnostics={"policy_lag": collector_id + 1}, + timings=timing_nodes_from_paths({"collect": 2.0, "env_step": 1.0, "sync": 0.5, "sync.wait_writer": 0.2}), + ) def _payload(step: int, checkpoint_path: str | None) -> dict: warming = step < LEARNING_STARTS return { "rank": 0, - "step": step, - "sps": 100.0, "updates": 2 * step, "training_started": True, "metrics": None if warming else {"qf_loss": 0.25, "actor_loss": -1.5}, - "warming": warming, "learn_ms": 1.0, "learn_pct": 40.0, - "learner_timing": {}, + "learner_timing": (), "buffer_size": 6, "buffer_capacity": 12, "ring_fill": [1, 2], @@ -471,7 +488,7 @@ def __init__( crash_collector: int | None = None, live: bool = True, ) -> None: - from motrix_rl_builtin.fastsac.async_impl.worker import run_collector_process, run_learner_process + from motrix_rl_builtin.fastsac.async_impl.worker import CollectorWorker, LearnerWorker self.sink = sink self.stages = stages @@ -479,7 +496,25 @@ def __init__( self.live = live self.logging_interval = logging_interval self.exitcodes: dict[int, int] = {} - self.ctx = ThreadSpawnContext({run_learner_process: self.learner, run_collector_process: self.collector}) + self.ctx = ThreadSpawnContext({LearnerWorker: self.learner, CollectorWorker: self.collector}) + + def start( + self, + task: Worker, + ctx: ThreadSpawnContext, + *, + name: str, + placement: WorkerPlacement, + runtime: WorkerRuntime, + ) -> WorkerHandle: + error_rx, error_tx = mp.Pipe(duplex=False) + process = ctx.Process( + target=task.run, + args=(task, placement, name, runtime, error_rx, error_tx), + name=name, + ) + process.start() + return WorkerHandle(process, name=name, placement=placement, errors=error_rx) def learner(self, process) -> int: args = process.arguments @@ -505,7 +540,7 @@ def learner(self, process) -> int: if payload["updates"] == 0: self._wait_until(lambda: args["learner_data_queue"].empty() or control.stop) continue - if self.live and payload["step"] % self.logging_interval == 0: + if self.live and (control.collector_steps // NUM_COLLECTORS) % self.logging_interval == 0: expected_logs += 1 self._wait_until(lambda: self.sink.count("scalars") >= expected_logs or control.stop) else: @@ -514,7 +549,6 @@ def learner(self, process) -> int: checkpoint_path = str(Path(args["checkpoint_dir"]) / f"model_{step:07d}.pt") args["learner_data_queue"].put({"rank": 0, "checkpoint_saved": {"step": step, "path": checkpoint_path}}) if self.crash_collector is not None: - args["error_queue"].put((f"collector[{self.crash_collector}]", "Traceback: boom\n")) self.exitcodes[self.crash_collector] = 1 self._wait_until(lambda: control.stop) return 0 @@ -537,7 +571,13 @@ def collector(self, process) -> int: handshake.report_ready("collector", collector_id) handshake.wait_for_start(control) self._wait_until(lambda: control.stop or collector_id in self.exitcodes) - return self.exitcodes.get(collector_id, 0) + exitcode = self.exitcodes.get(collector_id, 0) + if exitcode: + runtime = process.args[3] + runtime.log_path.parent.mkdir(parents=True, exist_ok=True) + runtime.log_path.write_text("Traceback: boom\n") + process.args[5].send_bytes(b"Traceback: boom\n") + return exitcode def _train_async( @@ -568,8 +608,16 @@ def _train_async( monkeypatch.setattr(async_train, "resolve_fastsac_topology", lambda *args, **kwargs: topology) monkeypatch.setattr(async_train, "actor_param_numel", lambda *args: 0) monkeypatch.setattr(async_train, "capture_system_info", lambda **kwargs: {}) - monkeypatch.setattr(async_train, "spawn_placement", lambda *args: contextlib.nullcontext()) - monkeypatch.setattr(async_train, "inherit_log_stdio", lambda *args: contextlib.nullcontext()) + monkeypatch.setattr( + async_train.CollectorWorker, + "start", + lambda task, ctx, **kwargs: workers.start(task, ctx, **kwargs), + ) + monkeypatch.setattr( + async_train.LearnerWorker, + "start", + lambda task, ctx, **kwargs: workers.start(task, ctx, **kwargs), + ) monkeypatch.setattr(async_train.Trainer, "_make_env", lambda self, *args, **kwargs: _ProbeEnv()) (tmp_path / "metadata.json").write_text("{}") rl_cfg = SimpleNamespace( @@ -588,7 +636,7 @@ def _train_async( ), ), ) - metrics = MetricsLogger("unit-run", jsonl=workers.sink) if live else MetricsLogger.disabled() + metrics = MotrixLiveLogger("unit-run", jsonl=workers.sink) if live else MotrixLiveLogger.disabled() context = _context( tmp_path, rl_cfg, @@ -609,9 +657,9 @@ def test_async_panel_waits_for_first_learner_update(tmp_path, monkeypatch): trainer, _ = _train_async(tmp_path, monkeypatch, workers, num_iterations=30) panels = [] monkeypatch.setattr( - async_train.AsyncPanelRenderer, - "render", - lambda self, sample, **kwargs: panels.append(sample.stats), + async_train.TrainingPanelSession, + "_draw", + lambda self, stats: panels.append(stats), ) trainer.train() @@ -630,10 +678,10 @@ def test_async_run_can_finish_without_any_training_update(tmp_path, monkeypatch) assert checkpoints.final_checkpoint_path("pt", tmp_path).exists() -def test_async_panel_reports_zero_throughput_after_collection_stalls(monkeypatch): +def test_async_learner_updates_rate_reports_zero_after_training_stalls(monkeypatch): from motrix_rl_builtin.fastsac.async_impl import stats as async_stats - monkeypatch.setattr(async_stats.time, "time", iter((0.0, 1.0, 2.0, 3.0)).__next__) + monkeypatch.setattr(async_stats, "time", SimpleNamespace(monotonic=iter((0.0, 1.0, 2.0, 3.0)).__next__)) control = SimpleNamespace(collector_steps=20) collector_queue = queue.Queue() learner_queue = queue.Queue() @@ -651,7 +699,7 @@ def test_async_panel_reports_zero_throughput_after_collection_stalls(monkeypatch per_collector_stats={0: None}, learner_payloads={0: None}, ) - aggregator = AsyncTrainingStatsAggregator(learning_starts=0, logging_interval=10) + aggregator = AsyncTrainingStatsAggregator(learning_starts=0) first = aggregator.collect(source) second = aggregator.collect(source) @@ -660,9 +708,8 @@ def test_async_panel_reports_zero_throughput_after_collection_stalls(monkeypatch assert first is not None assert second is not None assert stalled is not None - assert stalled.stats.steps_per_second == 0.0 - assert stalled.stats.iterations_per_second == 0.0 - assert not stalled.stats.warming + assert stalled.scalars["learner/updates_per_s"] == 0.0 + assert stalled.scalars["learner/replay_warming"] == 0.0 def test_async_trainer_emits_tensorboard_tags_events_and_collector_env_steps(tmp_path, monkeypatch): @@ -695,14 +742,63 @@ def test_async_trainer_emits_tensorboard_tags_events_and_collector_env_steps(tmp # The logger holds a thread and locks: it must never be pickled into a worker. assert len(workers.ctx.processes) == NUM_COLLECTORS + 1 for process in workers.ctx.processes: - values = (*process.args, *process.kwargs.values()) - assert not any(isinstance(value, (MetricsLogger, TrainerContext)) for value in values), process.name + values = (*process.args, *process.arguments.values()) + assert not any(isinstance(value, (MotrixLiveLogger, TrainerContext)) for value in values), process.name -def test_async_weight_publish_rate_uses_logging_window_baseline(monkeypatch): +def test_async_logging_progress_tracks_repeated_and_skipped_polls(tmp_path): + metrics, sink = _logger(tmp_path) + training_log = TrainingLogger(tmp_path, metrics, interval=10, initial_iteration=10, initial_env_steps=60) + session = TrainingPanelSession.open(title="test") + panel = session.metrics_panel( + total_iterations=50, + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + reductions=training_log.reductions, + default_reduction=training_log.default_reduction, + ) + training_metrics = TrainingMetrics( + [training_log, panel], + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + ) + control = SimpleNamespace(collector_steps=22) + source = AsyncTrainingStatsSource( + collector_data_queues=[], + learner_data_queue=queue.Queue(), + control=control, + num_envs=6, + num_collectors=2, + num_learners=1, + num_iterations=50, + resume_step=10, + per_collector_stats={0: _snapshot(0, _Stage((11, 11))), 1: _snapshot(1, _Stage((11, 11)))}, + learner_payloads={0: _payload(11, None)}, + ) + aggregator = AsyncTrainingStatsAggregator(learning_starts=0) + try: + for collector_steps, expected in ((22, (11, 66)), (22, (11, 66)), (23, (11, 69)), (35, (17, 105))): + control.collector_steps = collector_steps + sample = aggregator.collect(source) + assert sample is not None and sample.scalars + training_metrics.record(sample.scalars) + training_metrics.advance( + iterations=sample.step - training_metrics.iteration, + env_steps=sample.env_steps - training_metrics.env_steps, + ) + training_metrics.flush() + assert (training_log.iteration, training_log.env_steps) == expected + training_metrics.event("progress_observed") + finally: + session.close() + training_log.close() + assert _events(sink) == [("progress_observed", 17)] + + +def test_async_weight_publish_rate_uses_observation_baseline(monkeypatch): from motrix_rl_builtin.fastsac.async_impl import stats as async_stats - monkeypatch.setattr(async_stats.time, "time", iter((0.0, 1.0, 2.0, 3.0)).__next__) + monkeypatch.setattr(async_stats, "time", SimpleNamespace(monotonic=iter((0.0, 1.0, 2.0, 3.0)).__next__)) control = SimpleNamespace(collector_steps=10) collector_queue = queue.Queue() learner_queue = queue.Queue() @@ -720,21 +816,21 @@ def test_async_weight_publish_rate_uses_logging_window_baseline(monkeypatch): per_collector_stats={0: None}, learner_payloads={0: None}, ) - aggregator = AsyncTrainingStatsAggregator(learning_starts=0, logging_interval=10) + aggregator = AsyncTrainingStatsAggregator(learning_starts=0) first = aggregator.collect(source) - assert first is not None and first.log_record is not None + assert first is not None and first.scalars control.collector_steps = 15 source.learner_payloads[0] = _payload(15, None) middle = aggregator.collect(source) - assert middle is not None and middle.log_record is None + assert middle is not None and middle.scalars control.collector_steps = 20 source.learner_payloads[0] = _payload(20, None) final = aggregator.collect(source) - assert final is not None and final.log_record is not None - assert final.log_record.values["async/weight_publishes_per_iter"] == 1.0 + assert final is not None and final.scalars + assert final.scalars["learner/weight_publishes_per_iteration"] == 1.0 @pytest.mark.parametrize("live", [True, False]) @@ -747,7 +843,7 @@ def test_learner_sends_checkpoint_notices_only_for_live_metrics(tmp_path, monkey trainer.train() (learner,) = [process for process in workers.ctx.processes if "learner" in process.name] - assert learner.kwargs["notify_checkpoints"] is live + assert learner.arguments["notify_checkpoints"] is live def test_async_trainer_reports_worker_crash(tmp_path, monkeypatch): @@ -755,7 +851,7 @@ def test_async_trainer_reports_worker_crash(tmp_path, monkeypatch): workers = _Workers(sink, [_Stage((11, 10))], crash_collector=1) trainer, _ = _train_async(tmp_path, monkeypatch, workers, num_iterations=40) - with pytest.raises(RuntimeError, match="collector 1"): + with pytest.raises(WorkerError, match="collector-1"): trainer.train() crash = _event(sink, "worker_crashed") @@ -763,7 +859,7 @@ def test_async_trainer_reports_worker_crash(tmp_path, monkeypatch): "name": "worker_crashed", "worker": "fastsac-async-collector-1", "exitcode": 1, - "error_log": "async_errors/collector[1]_error.log", + "error_log": "logs/collector1.log", } assert (tmp_path / crash["error_log"]).read_text() == "Traceback: boom\n" assert "checkpoint_saved" not in {name for name, _ in _events(sink)} @@ -796,7 +892,7 @@ def _unavailable(**kwargs): scalars = [r for r in sink.records if r["kind"] == "scalars"] assert sorted({r["step"] for r in scalars}) == [10, 20] - assert {"rollout/mean_return", "train/qf_loss"} <= set(scalars[-1]["data"]) + assert {"episode/recent_return_mean", "train/qf_loss"} <= set(scalars[-1]["data"]) def test_async_trainer_reports_checkpoints_saved_after_the_last_log_window(tmp_path, monkeypatch): @@ -808,6 +904,9 @@ def test_async_trainer_reports_checkpoints_saved_after_the_last_log_window(tmp_p trainer.train() + records = [record for record in sink.records if record["kind"] == "scalars"] + assert records[-1]["step"] == 14 + assert records[-1]["axes"]["env_steps"] == 84 checkpoint_dir = tmp_path / "checkpoints" assert _paths(sink) == [ (str(checkpoint_dir / "model_0000010.pt"), 10), @@ -817,10 +916,20 @@ def test_async_trainer_reports_checkpoints_saved_after_the_last_log_window(tmp_p ] -def test_async_trainer_leaves_placeholder_rollout_means_out_of_live(tmp_path, monkeypatch): +def test_collector_aggregation_keeps_real_nan_among_finite_observations(): + stats = aggregate_collector_stats( + { + 0: _snapshot(0, _Stage((10, 10), mean_return=1.0)), + 1: _snapshot(1, _Stage((10, 10), mean_return=math.nan)), + } + ) + assert math.isnan(stats.mean_return) + + +def test_async_trainer_omits_missing_rollout_means(tmp_path, monkeypatch): sink = _RecordingSink(tmp_path / "metrics.jsonl") stages = [ - _Stage((10, 10), episodes=0), # nothing finished yet: NaN placeholders + _Stage((10, 10), episodes=0), # nothing finished yet: missing means _Stage((20, 20)), _Stage((30, 30), mean_return=math.nan), # a real divergence ] @@ -829,11 +938,40 @@ def test_async_trainer_leaves_placeholder_rollout_means_out_of_live(tmp_path, mo trainer.train() - _assert_live_matches_tensorboard(sink, writer, no_episode_steps=(10,)) + _assert_live_matches_tensorboard(sink, writer) scalars = {r["step"]: r["data"] for r in sink.records if r["kind"] == "scalars"} assert not ROLLOUT_MEANS & set(scalars[10]) - assert scalars[20]["rollout/mean_return"] == pytest.approx(1.5) + assert scalars[20]["episode/recent_return_mean"] == pytest.approx(1.5) nonfinite = [ (r["data"]["key"], r["step"]) for r in sink.records if r["kind"] == "event" and r["data"]["name"] == "nonfinite" ] - assert nonfinite == [("rollout/mean_return", 30)] + assert nonfinite == [("episode/recent_return_mean", 30)] + + +@pytest.mark.parametrize("resume_step", [0, 100]) +def test_async_update_rate_baselines_first_observation_not_historical_updates(monkeypatch, resume_step): + from motrix_rl_builtin.fastsac.async_impl import stats as async_stats + + monkeypatch.setattr(async_stats, "time", SimpleNamespace(monotonic=iter((1.0, 3.0)).__next__)) + step = resume_step + 10 + control = SimpleNamespace(collector_steps=step) + source = AsyncTrainingStatsSource( + collector_data_queues=[], + learner_data_queue=queue.Queue(), + control=control, + num_envs=1, + num_collectors=1, + num_learners=1, + num_iterations=step + 20, + resume_step=resume_step, + per_collector_stats={0: _snapshot(0, _Stage((step, step)))}, + learner_payloads={0: _payload(step, None)}, + ) + aggregator = AsyncTrainingStatsAggregator(learning_starts=0) + first = aggregator.collect(source) + assert first.scalars + assert "learner/updates_per_s" not in first.scalars + control.collector_steps += 10 + source.learner_payloads[0] = _payload(step + 10, None) + second = aggregator.collect(source) + assert second.scalars["learner/updates_per_s"] == 10.0 diff --git a/motrix_rl_builtin/tests/test_fastsac_multi_final_obs.py b/motrix_rl_builtin/tests/test_fastsac_multi_final_obs.py index 1e23ceca6..077783ade 100644 --- a/motrix_rl_builtin/tests/test_fastsac_multi_final_obs.py +++ b/motrix_rl_builtin/tests/test_fastsac_multi_final_obs.py @@ -75,7 +75,7 @@ def _learner(rings, *, device="cpu", n_steps=1, buffer_size=8, staging=False): device=device, final_obs_bootstrap=True, ) - learner.agent.window_metrics = SimpleNamespace(add=lambda *args, **kwargs: None) + learner.agent.window_metrics = SimpleNamespace(record=lambda *args, **kwargs: None) # IDs address this rank's replay, not global DDP environment IDs. learner.ddp_rank = 2 if staging: diff --git a/motrix_rl_builtin/tests/test_fastsac_sync_trainer.py b/motrix_rl_builtin/tests/test_fastsac_sync_trainer.py index 49ebd59c4..07ad7e6c2 100644 --- a/motrix_rl_builtin/tests/test_fastsac_sync_trainer.py +++ b/motrix_rl_builtin/tests/test_fastsac_sync_trainer.py @@ -20,7 +20,9 @@ def test_sync_train_closes_tensorboard_writer_when_training_fails(tmp_path, monk monkeypatch.setattr(Trainer, "_make_agent", Mock(return_value=SimpleNamespace(device="cpu", global_step=0))) def fail_after_logging(self, agent, env, training_log, **kwargs): - training_log.scalars({"train/qf_loss": 1.0}, 0, env_steps=1) # opens TensorBoard + training_log.advance(env_steps=1) + training_log.record({"train/qf_loss": 1.0}) + training_log.flush(force=True) # opens TensorBoard raise RuntimeError("training failed") monkeypatch.setattr(Trainer, "_run_loop", fail_after_logging) diff --git a/motrix_rl_builtin/tests/test_fastsac_worker_logging.py b/motrix_rl_builtin/tests/test_fastsac_worker_logging.py new file mode 100644 index 000000000..dd604bf08 --- /dev/null +++ b/motrix_rl_builtin/tests/test_fastsac_worker_logging.py @@ -0,0 +1,163 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import itertools +import queue +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +import torch +from motrix_rl_builtin.fastsac.async_impl import worker + + +@pytest.mark.parametrize("resume_step", [0, 10]) +@pytest.mark.parametrize("update_total", [2.0, None]) +def test_learner_reports_initial_and_first_update_without_shifting_aligned_windows( + tmp_path, monkeypatch, resume_step, update_total +): + control = SimpleNamespace(collector_steps=resume_step, stop=False) + control.set_stop = lambda: setattr(control, "stop", True) + agent = SimpleNamespace( + cfg=SimpleNamespace(learning_starts=0), + rb=SimpleNamespace(num_stored=1, buffer_size=8), + num_envs=1, + window_metrics=SimpleNamespace(stats_and_reset=lambda: {"loss": 1.0}), + state_dict=lambda: {}, + _last_update_timing_ms={}, + ) + observed_steps = [] + + class Learner: + def __init__(self, agent, cfg, endpoints, control, ddp_rank): + self.agent = agent + self.update_idx = 0 + self._last_publish_ms = 3.0 + + def publish_weights(self): + pass + + def drain(self): + control.collector_steps += 1 + return int(control.collector_steps % 2 == 0) + + def maybe_train(self, step): + if step < resume_step + 2: + return False + self.update_idx += 1 + self.agent._last_update_timing_ms = {} if update_total is None else {"total": update_total} + if step % 2 == 0: + self.agent._last_update_timing_ms["actor"] = 8.0 + return True + + def wait_ingest(self): + pass + + class PayloadQueue(queue.Queue): + def put_nowait(self, payload): + # Progress increments during drain; the payload describes the loop's input step. + observed_steps.append(control.collector_steps - 1) + super().put_nowait(payload) + + monkeypatch.setattr(worker, "Learner", Learner) + monkeypatch.setattr(worker, "build_agent", lambda *args, **kwargs: agent) + monkeypatch.setattr(worker, "pin_worker_cpus", lambda *args: None) + monkeypatch.setattr(worker, "resolve_worker_cpus", lambda *args: None) + monkeypatch.setattr(worker, "_install_graceful_sigint", lambda control: None) + ticks = itertools.count() + monkeypatch.setattr( + worker, + "time", + SimpleNamespace( + perf_counter=lambda: next(ticks) / 1000, monotonic=lambda: next(ticks) / 1000, sleep=lambda _: None + ), + ) + monkeypatch.setattr(torch, "save", lambda *args: None) + monkeypatch.setattr(worker.checkpoints, "record_checkpoint_artifact", lambda *args, **kwargs: None) + handshake = SimpleNamespace(report_ready=lambda *args: None, wait_for_start=lambda control: None) + payloads = PayloadQueue() + worker.LearnerWorker( + cfg=SimpleNamespace( + device="cpu", trainer=SimpleNamespace(async_options=SimpleNamespace(learner_cpu_cores=None, idle_sleep_s=0)) + ), + num_envs=1, + dims=(1, 1, 1), + action_scale=torch.ones(1), + action_bias=torch.zeros(1), + rings=[], + weights=[], + control=control, + num_iterations=resume_step + 7, + logging_interval=5, + save_interval=0, + run_dir=str(tmp_path), + checkpoint_dir=str(tmp_path), + checkpoint_format="pt", + resume_from=None, + learner_device=torch.device("cpu"), + handshake=handshake, + all_rings=[SimpleNamespace(size=lambda: 0)], + weight_ipc=[], + collector_ids=[], + learner_data_queue=payloads, + ).run() + assert observed_steps == [resume_step, resume_step + 2, resume_step + 5, resume_step + 6] + first, first_update, aligned = [payloads.get_nowait() for _ in range(3)] + assert not first["training_started"] and first["learn_ms"] == 0.0 + assert first_update["training_started"] and first_update["metrics"] == {"loss": 1.0} + # Sparse actor timings count only actual actor samples, not every train/drain call. + timings = aligned["learner_timing"] + assert isinstance(timings, tuple) + assert [node.name for node in timings] == ["drain", "update"] + update = timings[-1] + assert update.duration_ms == (None if update_total is None else update_total + 3.0) + assert [node.name for node in update.children] == ["actor", "publish"] + assert [node.duration_ms for node in update.children] == pytest.approx([8.0, 3.0]) + assert aligned["learn_ms"] == pytest.approx(1.0) + final = payloads.get_nowait() + assert final["training_started"] + assert final["updates"] > aligned["updates"] + assert final["metrics"] == {"loss": 1.0} + + +@pytest.mark.parametrize("failure_point", ["startup", "collector_close"]) +def test_collector_failure_stops_peers_and_closes_environment(monkeypatch, failure_point): + env = Mock() + collector = Mock() + if failure_point == "startup": + collector.warmup_inference.side_effect = RuntimeError("startup failed") + else: + collector.close.side_effect = RuntimeError("collector_close failed") + control = Mock() + control.stop = True + monkeypatch.setattr(worker, "build_env", lambda *args, **kwargs: env) + monkeypatch.setattr(worker, "Collector", lambda *args, **kwargs: collector) + monkeypatch.setattr(worker, "weight_receiver_for", lambda *args: Mock()) + monkeypatch.setattr(worker, "pin_worker_cpus", lambda *args: None) + monkeypatch.setattr(worker, "resolve_worker_cpus", lambda *args: set()) + monkeypatch.setattr(worker, "_install_graceful_sigint", lambda control: None) + task = worker.CollectorWorker( + env_spec=Mock(), + cfg=SimpleNamespace(trainer=SimpleNamespace(async_options=SimpleNamespace(collector_cpu_cores=None))), + num_envs=1, + dims=(1, 1, 1), + action_scale=torch.ones(1), + action_bias=torch.zeros(1), + ring=Mock(), + weights=Mock(), + control=control, + collector_data_queue=queue.Queue(), + num_iterations=1, + logging_interval=1, + is_resume=False, + seed=7, + handshake=Mock(), + collector_device=torch.device("cpu"), + ) + + with pytest.raises(RuntimeError, match=failure_point): + task.run() + + control.set_stop.assert_called_once_with() + collector.close.assert_called_once_with() + env.close.assert_called_once_with() diff --git a/motrix_rl_supermimic/tests/test_trainer.py b/motrix_rl_supermimic/tests/test_trainer.py index 0fc09a7b2..e45462287 100644 --- a/motrix_rl_supermimic/tests/test_trainer.py +++ b/motrix_rl_supermimic/tests/test_trainer.py @@ -39,7 +39,7 @@ def _run_trainer(tmp_path, monkeypatch, pi_ema, *, cuda_overlap=False, cuda_ipc= from motrix_rl_supermimic.provider import SuperMimicProvider from motrix_rl.contracts import TrainerContext - from motrix_rl.metrics import MetricsLogger + from motrix_rl.log.live import MotrixLiveLogger cfg = SuperMimicCfg( device=learner_device if cuda_overlap or cuda_ipc else "cpu", @@ -90,7 +90,7 @@ def _run_trainer(tmp_path, monkeypatch, pi_ema, *, cuda_overlap=False, cuda_ipc= rl_cfg=cfg, logging=None, checkpoint=None, - metrics=MetricsLogger.disabled(), + metrics=MotrixLiveLogger.disabled(), ) import motrix_rl_supermimic.trainer as trainer_module @@ -214,7 +214,7 @@ def test_play_loads_policy_and_preserves_step_failure(tmp_path, monkeypatch, che from motrix_rl_supermimic.trainer import SuperMimicTrainer from motrix_rl.contracts import TrainerContext - from motrix_rl.metrics import MetricsLogger + from motrix_rl.log.live import MotrixLiveLogger cfg = SuperMimicCfg(device="cpu", agent=AgentCfg(hidden=16, pi_ref_skip=True)) monkeypatch.setattr(ToyEnvCfg, "reference_action", lambda self: _RandomReference()) @@ -261,7 +261,7 @@ def stop_step(action): rl_cfg=cfg, logging=None, checkpoint=None, - metrics=MetricsLogger.disabled(), + metrics=MotrixLiveLogger.disabled(), ) trainer = SuperMimicTrainer(context=context) if checkpoint_goal_frames != play_env.cfg.goal_frames: @@ -277,7 +277,7 @@ def test_resume_uses_checkpoint_root_before_nonpersistent_reference_factory(tmp_ from motrix_rl_supermimic.trainer import SuperMimicTrainer from motrix_rl.contracts import TrainerContext - from motrix_rl.metrics import MetricsLogger + from motrix_rl.log.live import MotrixLiveLogger register_toy() cfg = SuperMimicCfg(device="cpu", agent=AgentCfg(hidden=8, pi_ref_skip=True)) @@ -299,7 +299,7 @@ def test_resume_uses_checkpoint_root_before_nonpersistent_reference_factory(tmp_ rl_cfg=cfg, logging=None, checkpoint=None, - metrics=MetricsLogger.disabled(), + metrics=MotrixLiveLogger.disabled(), resume_from=checkpoint_path, ) import motrix_rl_supermimic.trainer as trainer_module diff --git a/wiki/design/appo.md b/wiki/design/appo.md index a80c63e2a..7a2f49aea 100644 --- a/wiki/design/appo.md +++ b/wiki/design/appo.md @@ -50,6 +50,10 @@ CUDA Graph 捕获固定形状单 minibatch 的 forward/backward、梯度裁剪 实际性能结果与端到端瓶颈见 [APPO性能评测](../research/appo-evaluation.md#4-learner执行优化)。性能验收必须分别记录初次 compile/capture 成本与同步计时的 steady-state 完整 update;用相同 Go2 batch/network/epoch 规格比较,不能只测单个 kernel 或把异步提交耗时当GPU执行耗时。CPU correctness、CUDA eager/compile/graph多步数值parity、随机排列更新与checkpoint跨模式恢复分别覆盖;实际GPU验证不以skip替代。 +## 训练终端 + +父进程 learner 接入共享终端的方案见 [通用训练终端与 APPO 接入设计](./training-console.md)。该设计定义 consumed-transition FPS、原始 episode 窗口、并发阶段计时、独立刷新与 collector 日志隔离,不改变现有 TensorBoard/live-metrics 输出语义。 + ## 验证和比较 低成本测试覆盖 off-policy 手算、terminal/timeout/endpoint、pooled variance、action/logp 对齐、ring wrap-around 所有权、target snapshot、checkpoint round-trip、Hydra/provider 安装与发现。真实进程/仿真测试归 integration。 diff --git a/wiki/design/fastsac-async-heterogeneous-trainer.md b/wiki/design/fastsac-async-heterogeneous-trainer.md index f1a29a806..896f77743 100644 --- a/wiki/design/fastsac-async-heterogeneous-trainer.md +++ b/wiki/design/fastsac-async-heterogeneous-trainer.md @@ -203,11 +203,11 @@ producer lifetime 和 compiled collector 固定参数地址,不能只把 H2D **三种模式(`utd_mode`)**: -1. `learner_bound`(**吞吐优先**):只要 buffer 就绪,每轮固定做 `num_updates` 次更新、GPU 打满;collector 满速采样,UTD 随两进程相对速度浮动 → 最高 wall-clock 吞吐。代价是 UTD 偏离同步版,样本效率曲线会偏移,故实际 UTD 作为 `async/utd` 一等指标输出。 +1. `learner_bound`(**吞吐优先**):只要 buffer 就绪,每轮固定做 `num_updates` 次更新、GPU 打满;collector 满速采样,UTD 随两进程相对速度浮动 → 最高 wall-clock 吞吐。代价是 UTD 偏离同步版,样本效率曲线会偏移,故实际 UTD 作为 `train/UTD` 一等指标输出。 2. `strict`(对比验证用):`n = ingested * num_updates`,严格维持 `UTD == num_updates`,只买「相位重叠」的加速、不改样本效率 → 与同步版最可比;无新数据时 `n=0`,learner 让出时间片等数据。 -**权重发布与 staleness**:learner 每 `weight_publish_interval` 次更新调用一次 `publish`。collector 用的是「上次拉取的权重版本」,滞后 ≈ 发布间隔 × learner 速度 + 环内在途 slots。`learner_bound` 下 staleness 比 `strict` 大,故 `async/policy_lag`(= `weights.version − collector 本地版本`)作为一等诊断指标输出,必要时缩短 `weight_publish_interval` 主动压低。 +**权重发布与 staleness**:learner 每 `weight_publish_interval` 次更新调用一次 `publish`。collector 用的是「上次拉取的权重版本」,滞后 ≈ 发布间隔 × learner 速度 + 环内在途 slots。`learner_bound` 下 staleness 比 `strict` 大,故 `collector/policy_lag`(= `weights.version − collector 本地版本`)作为一等诊断指标输出,必要时缩短 `weight_publish_interval` 主动压低。 --- @@ -224,7 +224,7 @@ producer lifetime 和 compiled collector 固定参数地址,不能只把 H2D episode return / length、reward 分项、env metrics、collector timing 都发生在 collector(它才有 reward/done)。collector 按根级 `logging.interval` 把一份紧凑 `snapshot_stats()` 放进 `StatsQueue`(先清掉旧快照,保证 learner 总见最新);learner 在日志相位 drain 出来,喂给与同步版**完全复用**的 rich 训练面板。 -TensorBoard scalar 与同步版同名(`rollout/mean_return`、`rollout/mean_ep_len`、`perf/env_steps_per_s` 等),并新增异构专属:`async/policy_lag`、`async/ring_fill`、`async/weight_version`、`async/utd`,以及 collector 细分 timing `perf/collector_{sample_actions,env_step,env_step.*,push,bookkeep,sync,sync.*}_ms`(嵌套阶段为点分路径,如 `collector_env_step.physics.read_ms`)、整体 `perf/collect_ms_per_batch`,learner 侧 `perf/learn_ms_per_update`、`perf/learn_pct`、`perf/updates_per_s`。 +TensorBoard scalar 与同步版同名(`rollout/mean_return`、`rollout/mean_ep_len`、`perf/env_steps_per_s` 等),并新增异构专属:`collector/policy_lag`、`collector/ring_fill`、`learner/weight_version`、`train/UTD`,以及 collector 细分 timing `perf/collector_{sample_actions,env_step,env_step.*,push,bookkeep,sync,sync.*}_ms`(嵌套阶段为点分路径,如 `collector_env_step.physics.read_ms`)、整体 `perf/collect_ms_per_batch`,learner 侧 `perf/learn_ms_per_update`、`perf/learn_pct`、`perf/updates_per_s`。 > 面板中 `collect_ms` / `learn_ms` / `learn_pct` 因两进程并发,**不像同步版那样相加为 100%**:`learn_pct` 表示 learner wall-clock 中真正用于更新(vs 空转/欠数据)的比例,≈100% 表示 GPU-bound,偏低表示 collector 喂不满 buffer。 @@ -290,11 +290,11 @@ class FastSacCfg: **拓扑扩展**: - **每 collector 一条独立 SPSC ring**(不做共享 MPSC 环):ring 的 slot 形状为 `(capacity, num_envs/N, dim)`,所有无锁原语(单写方游标、seqlock)原样保留。满环背压按 ring 独立——快的 collector 阻塞在自己的满环上,不拖住别人。 -- **每 collector 一份独立 `WeightSnapshot`**:learner 逐份非阻塞 `publish`,某份正在被读(seqlock odd)不影响其他份;staleness 以 `async/policy_lag`(聚合 max)与 `async/policy_lag_collector{i}`(多 collector 时分列)监控,不做版本对齐屏障。 +- **每 collector 一份独立 `WeightSnapshot`**:learner 逐份非阻塞 `publish`,某份正在被读(seqlock odd)不影响其他份;staleness 以 `collector/policy_lag`(聚合 max)与 `collector/{i}/policy_lag`(多 collector 时分列)监控,不做版本对齐屏障。 - **learner 轮询多路 ring 并按「代」合并**:`drain()` 对每条 ring 至多消费 `max_ingest_per_iter` 个 slot;第 k 代(各 collector 的第 k 个 slot)拼成完整 `num_envs` 批(env 按 collector 连续分块映射,保证 n-step 的时间相邻性)。一个循环内所有完整批次先各自 `.to(device)`,再在 GPU 侧沿时间轴 stack,最后用 `SimpleReplayBuffer.extend_batch` 每字段一次连续列写入(H2D 次数与 GPU kernel 数不随批量增长——RTX 3090 + 双 CUDA collector 实测,逐批 `extend` 的阻塞式 CPU 源拷贝在多 CUDA context 争用下显著变慢)。未集齐的「代」以 CPU slot 视图挂起——慢 collector 自己的 ring 会先填满并背压它自己,不拖住别人;所有 ring 的读游标只在合并批到达 GPU 后推进,保持 ring 的 no-clobber 保证。`strict` 模式的 UTD 记账因此无需按 collector 数缩放(合并批就是完整 `num_envs` 批),任意 collector 数下长期 UTD 精确等于 `num_updates`;`learner_bound` 下 ring 全空时 learner 不等待,在已有 buffer 上继续 `num_updates`。 - **数据顺序无关**:off-policy + i.i.d. 采样,多 collector 的 transition 入 buffer 顺序无关,不引入全局序号。 - **seed 按 collector 划分**(`seed + collector_id`),保证可复现且样本不重复。 -- **进度与日志**:`Control.collector_steps` 是 per-collector 计数器数组(单写方不变),聚合求和后除以 collector 数得到「完整 num_envs 批等价步」,作为训练进度 / 日志 / checkpoint / resume 的统一基准——任意 collector 数下 `num_learning_iterations`、`learning_starts`、TensorBoard x 轴与同步版语义一致;每 collector 有独立 `StatsQueue`(快照携带 `collector_id`)、每个 learner rank 每 log 窗口发一份轻量 payload,全部汇到**父进程**——worker 完全对等,父进程聚合(return/ep_len/timing 取均值、episodes 求和、policy_lag 取 max)后渲染面板并写 TensorBoard。面板/系统采样由未绑定的父进程执行,CPU 视图是全机(所有 core)而非某个 node;多 collector 时额外输出 `async/policy_lag_collector{i}`、`async/ring_fill_collector{i}`,单 collector 的标量键保持不变。 +- **进度与日志**:`Control.collector_steps` 是 per-collector 计数器数组(单写方不变),聚合求和后除以 collector 数得到「完整 num_envs 批等价步」,作为训练进度 / 日志 / checkpoint / resume 的统一基准——任意 collector 数下 `num_learning_iterations`、`learning_starts`、TensorBoard x 轴与同步版语义一致;每 collector 有独立 `StatsQueue`(快照携带 `collector_id`)、每个 learner rank 每 log 窗口发一份轻量 payload,全部汇到**父进程**——worker 完全对等,父进程聚合(return/ep_len/timing 取均值、episodes 求和、policy_lag 取 max)后渲染面板并写 TensorBoard。面板/系统采样由未绑定的父进程执行,CPU 视图是全机(所有 core)而非某个 node;多 collector 时额外输出 `collector/{i}/policy_lag`、`collector/{i}/ring_fill`,单 collector 的标量键保持不变。 - **resume 语义**:多 collector 下 resume 与单 collector 相同——learner 从 checkpoint 恢复网络与优化器,所有 collector 重新 reset env 后从 checkpointed iteration 继续采样;ring / 在途 transition 不跨进程恢复。 **NUMA 绑定**(FastSAC 拓扑决策在 `async_impl/topology.py`,collector CPU 分片策略在 `async_impl/numa.py`;通用节点发现、GPU locality 查询、spawn 预绑定与绑定原语统一在 `motrix_rl.numa`,等价 `numactl --cpunodebind= --membind=`,best-effort,**自动分配**): diff --git a/wiki/design/index.md b/wiki/design/index.md index 450ac8f49..9d8da795b 100644 --- a/wiki/design/index.md +++ b/wiki/design/index.md @@ -25,8 +25,10 @@ 定义 IMPACT/V-trace 目标、chunk/endpoint/timeout 契约、插件集成与 Go2 RSLRL 基准比较。 - [训练随机性与 Seed 所有权](./randomness-and-seeding.md) 定义 `ctx.rand` 的默认 Torch 流、训练根 seed 职责、SuperMimic 模型初始化/探索隔离,以及异步训练与 warm resume 的可复现性边界。 +- [通用训练终端与 APPO 接入设计](./training-console.md) + 共享 console 的恢复计时、缺失值、刷新与终端生命周期契约,以及 APPO 指标映射、worker 日志隔离和分层验收方案;与 TensorBoard/live metrics 保持独立。 - [训练实时指标(Live Metrics)设计](./live-metrics.md) - 设置 `MOTRIX_METRICS_URL` 后训练进程把 `motrix.metrics/v1` 记录同时写入 `run_dir/metrics.jsonl` 并批量推送给兼容的 ingest 服务:公开协议(环境变量、记录格式、状态机、幂等、重试规则)、规范 key 与 FastSAC/SKRL/RSLRL 映射、控制平面 `MetricsLogger` 与生命周期接入、失败语义与测试策略。 + 设置 `MOTRIX_METRICS_URL` 后训练进程把 `motrix.metrics/v1` 记录同时写入 `run_dir/metrics.jsonl` 并批量推送给兼容的 ingest 服务:公开协议(环境变量、记录格式、状态机、幂等、重试规则)、规范 key 与 FastSAC/SKRL/RSLRL 映射、控制平面 `MotrixLiveLogger` 与生命周期接入、失败语义与测试策略。 - [Framework / Task 配置分离设计](./framework-task-split.md) 训练入口通过 Hydra task group 直接组合环境、算法与运行配置;外部应用使用自己的 Hydra config root,不维护 Python task registry 或额外 config-root 状态。 - [ConfigClass 配置装饰器设计](./configclass.md) diff --git a/wiki/design/live-metrics.md b/wiki/design/live-metrics.md index 418b6df06..6d1eabd5a 100644 --- a/wiki/design/live-metrics.md +++ b/wiki/design/live-metrics.md @@ -9,7 +9,7 @@ 不变)与 live metrics。终端面板保持原样。 范围:公开协议 `motrix.metrics/v1`(环境变量、记录格式、请求体、状态机、幂等、重试规则)、规范 key 与各 -provider 的映射、控制平面中的 `MetricsLogger` 与 `TrainingLogger`、FastSAC sync/async 的接入点、失败语义与测试 +provider 的映射、控制平面中的 `MotrixLiveLogger` 与 `TrainingLogger`、FastSAC sync/async 的接入点、失败语义与测试 策略。非目标:SKRL / RSLRL 接入(见 §5.4)、wandb sink、media 上传、pod sidecar 采集、新增 `logging.backend` 取值、 服务端实现。 @@ -168,16 +168,16 @@ FastSAC async 只是近似:训练按 learner 的迭代数停止,而 `env_ste `num_envs` 不能被 `num_collectors` 整除时也会少计,所以进度可能略超或略低于 100%。看板按进度展示时应截断到 `[0, 1]`,不能把它当作结束判据(结束以 `run` 状态为准)。 -## 4. 组件:`motrix_rl/src/motrix_rl/metrics.py` +## 4. 组件:`motrix_rl/src/motrix_rl/log/live.py` 控制平面只新增这一个模块,只用标准库(json、gzip、urllib.request、threading、queue、socket)。 ```python -class MetricsLogger: +class MotrixLiveLogger: @classmethod - def from_env(cls, run_dir: Path, *, role: str = "trainer") -> MetricsLogger: ... + def from_env(cls, run_dir: Path, *, role: str = "trainer") -> MotrixLiveLogger: ... @classmethod - def disabled(cls) -> MetricsLogger: ... + def disabled(cls) -> MotrixLiveLogger: ... enabled: bool run_id: str def run(self, state: str, **data) -> None: ... @@ -194,7 +194,7 @@ class MetricsLogger: 退出。序列化或 IO 异常吞掉并告警,不打断训练。 - **`HttpSink`**:daemon 线程 + 单一有界队列;入队一律 `put_nowait`,满了丢最旧的 scalars 并计数告警(run / event 记录不丢);每 2 s 或攒满 500 条发一批,请求超时 5 s,重试规则见 §2.3;空闲时补发 heartbeat。 -- 两个 sink 都是具体类,不建基类或注册表。`MetricsLogger._emit` 在训练线程只做数据清洗、分配 seq 与入队;scalars +- 两个 sink 都是具体类,不建基类或注册表。`MotrixLiveLogger._emit` 在训练线程只做数据清洗、分配 seq 与入队;scalars 在 `scalars()` 中已转成 float,不再二次清洗。 - **关闭是异步的**:`close()` 只表示没有后续数据,立即返回。每个 sink 按自己的节奏收尾:jsonl 写完队列后退出;http 发完 队列后退出,失败按 §2.3 重试,最多重试 `flush_budget`(60 s)后丢弃剩余。训练结束不等待任何 sink;下一个训练任务用 @@ -204,11 +204,11 @@ class MetricsLogger: 只需毫秒。 - logger 带线程与锁,不可 pickle;FastSAC async 只有父进程持有 logger,worker 子进程不接触。 -### 4.1 统一日志接口:`motrix_rl/src/motrix_rl/training_logger.py` +### 4.1 统一日志接口:`motrix_rl/src/motrix_rl/log/training_logger.py` ```python class TrainingLogger: - def __init__(self, log_dir: Path, live: MetricsLogger) -> None: ... + def __init__(self, log_dir: Path, live: MotrixLiveLogger) -> None: ... def scalars(self, values: Mapping[str, float], step: int, *, env_steps: int, live_extra: Callable[[], Mapping[str, float]] | None = None, placeholders: Collection[str] = ()) -> None: ... @@ -229,7 +229,7 @@ class TrainingLogger: ### 5.1 控制平面 -- **构造**:只在 `runner.create_training_handle` 中用 `MetricsLogger.from_env(run.run_dir)` 构造,经 `metrics=` 参数传给 +- **构造**:只在 `runner.create_training_handle` 中用 `MotrixLiveLogger.from_env(run.run_dir)` 构造,经 `metrics=` 参数传给 `create_trainer_context`。play 路径(`create_run_handle`)一律使用 disabled,避免设置了环境变量时 play 也起线程或 改写原训练 run 的 `metadata.json`。 - **契约字段**:`TrainerContext.metrics` 与 `TrainerHandle.metrics`,均有 disabled 默认值,第三方 provider 不接入也能 diff --git a/wiki/design/training-console.md b/wiki/design/training-console.md new file mode 100644 index 000000000..601951a90 --- /dev/null +++ b/wiki/design/training-console.md @@ -0,0 +1,214 @@ +# 通用训练终端与 APPO 接入设计 + +## 摘要 + +为 [issue #199](https://github.com/Motphys/MotrixLab/issues/199) 提供共享训练终端方案:复用 `motrix_rl.console` 的会话、三视图与聚合工具,在框架层补齐恢复训练计时、缺失值、存储单位、刷新前节流、启动状态及 worker 日志隔离;APPO 只负责自身指标映射和主循环接入。 + +本文描述已实现的首版方案。第一期支持单 collector、父进程 learner,不引入监控线程,不改变算法、transport 协议、训练预算、checkpoint 格式或 TensorBoard/live-metrics 输出语义。算法及数据所有权见 [APPO 设计](./appo.md),外部指标协议见 [Live Metrics 设计](./live-metrics.md)。 + +## 1. 结构与所有权 + +```text +APPO collector ── 现有 chunk + CollectorMetrics ──> APPO trainer(父进程 learner) + │ + APPO 指标映射与显示窗口 + │ + TrainingPanelStats + │ + motrix_rl.console.TrainingPanelSession + ├─ TTY:Overview / Timing / System + └─ 非 TTY:节流纯文本快照 + +APPO trainer ── 原有 logging.interval 分支 ──> TensorBoard / live metrics +worker stdout / stderr / logging / warnings ──> run_dir/logs/collector.log +worker failure ── 原有 error pipe ──> 父进程异常与日志路径 +``` + +- `motrix_rl.console` 拥有渲染、刷新策略、终端输入和恢复,不认识 learner、chunk、Torch tensor 或算法配置。 +- `EpisodeWindow`、`RateTracker`、`TimingWindow` 保持普通 Python 数据工具;算法侧决定计数和观测边界。 +- APPO trainer 持有显示窗口和最后一份 learner metrics,每个已消费 chunk 只登记一次。共享 sampler 在显示到期时调用,不在每个 update 调用。 +- worker 输出隔离属于 `motrix_rl` 的进程运行机制,不属于 console,也不要求 worker 依赖 Rich。 +- APPO 不导入 builtin。启动状态表与日志尾部归共享 console;FastSAC 的 stats source/aggregator、启动 barrier、readiness gate 和监控循环仍归算法实现。 + +## 2. 共享 console 的最小补齐 + +### 2.1 数据契约 + +扩展现有 `TrainingPanelStats`,不另建平行 snapshot/event 协议: + +| 数据 | 契约 | +| --- | --- | +| `iteration` / `total_iterations` | 累计进度;APPO 分别为 learner update count 与 max iterations | +| `initial_iteration` | 本次调用恢复后的起始进度,fresh run 为 0;供累计平均速率与 ETA 使用 | +| throughput 标签 | 速率单位固定显示 `env-steps/s`;consumed 口径由 steps 行的 `env-steps (consumed)` 标注表达,不把 learner consumed 描述为 collector sampled | +| episode mean | 接受 `None` 并渲染为 `n/a`;已有调用方使用的非有限占位值也渲染为不可用,而不是有效的 0 | +| `episodes` | 明确累计范围;APPO 为本次调用中随已消费 chunk 收到的完成 episode 数;TTY 与纯文本都显示 | +| timing group total | 允许对分组显式给出分母或无分母,避免只靠 collector/learner 字符串前缀推断比例 | + +总环境步数与 episode 数要出现在概览和纯文本中,不能只放在隐藏的 timing diagnostics 中。非 TTY 同样显示最后成功的 checkpoint 路径。 + +恢复后的平均更新速率与 ETA: + +```text +updates_this_invocation = iteration - initial_iteration +average_update_rate = updates_this_invocation / training_elapsed +ETA = max(total_iterations - iteration, 0) / average_update_rate +``` + +没有正的可用速率时显示 `n/a`,训练完成时 ETA 为 0。滚动 FPS 与滚动 updates/s 使用 `RateTracker`,不以恢复前的历史计数除以本次耗时。共享 renderer 的迭代速率 fallback 也必须使用本次调用增量。 + +不把 APPO 数据硬塞成 replay buffer。共享 renderer 必须在两种输出模式中尊重标签和单位;没有 storage 的算法可以不显示该行,但本期不增加 storage registry。 + +### 2.2 刷新策略 + +在 `TrainingPanelSession` 增加公开的到期判断(例如 `due()`),由 `TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。 统一管理 monotonic deadline。只有到期时,算法侧才生成快照、计算显示窗口、采样系统信息并 `submit()`;不能先做昂贵采样,再依赖 `submit()` 丢弃输出。 + +- 默认沿用秒级刷新;不新增算法专属的刷新配置体系。 +- update 完成、等待 ring 数据的轮询、启动等待的轮询都是协作式刷新机会,和 `logging.interval` 无关。 +- 每次刷新推进 deadline,不因训练较慢而补发一串历史帧。 +- 周期 checkpoint 成功、最终保存成功和退出允许强制刷新;强制刷新可复用最近系统样本,不必额外探测 GPU。 +- 无后台刷新线程时,单次长 learner update、compile/capture 或阻塞第三方调用期间无法保证秒级重绘。调用前显示阶段消息,返回后立即检查刷新;不为 UI 插入 CUDA 同步或拆分算法执行。 +- 等待期间可重新观测当前计数,使 rate 窗口反映停顿;不得再次登记 episode 或 timing 样本。 + +### 2.3 启动状态与生命周期 + +`BootWorker` 只携带 spawn 时固定的事实:`name` 和可选 `log_path`。共享 `BootPanel` 是纯渲染器,负责状态表、日志尾部和固定尺寸布局,不创建 Console/Live,不判断进程健康或启动完成。 + +`TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。输入按类别划分:构造参数是 spawn 固定的结构(worker 身份与日志路径);`mark_ready(*names)` 与 `start()` 是单调状态事件(就绪集合、barrier 释放);`message(text)` 覆盖式更新阶段行;`refresh()` 按会话节奏重绘使日志尾部滚动。行内状态由渲染器从记录的事实派生。同一个 session/Live 展示启动画面;TTY 事件立即重绘,非 TTY 仅打印事件本身。创建 `metrics_panel()` 切换为训练阶段并让启动句柄退役,session 统一关闭终端资源。启动不构造假的 TrainingPanelStats,也不把算法的 barrier、超时或启动阶段枚举放进框架。保存成功经 `checkpoint(path)` 在训练帧显示;收尾阶段不提供独立消息 API,最终帧定格于 close。 + +FastSAC 与 APPO 各自生成 worker 快照并控制启动到训练的切换;FastSAC 保留 ready barrier 和首份统计 gate。APPO 在现有等待轮询中刷新 collector 日志,阻塞 learner 构造期间不引入刷新线程。 + +APPO 的父进程就是 learner 进程:trainer 使用框架 `scoped_file_logging` 将 `motrix_rl_appo` 命名空间及其正常传播的子 logger 写入 `run_dir/logs/learner.log`,不向父终端重复传播;这只路由 Python logging,不拦截 stdout/native 输出。作用域退出恢复 handler/level/propagate,借用 handler 不关闭。异常写入文件后继续向外传播,ExitStack 保证即使 worker 清理失败仍关闭日志和面板。boot panel 展示 learner 状态行和日志窗格;最终训练统计强制刷新后才报告保存通知。 + +APPO boot 阶段负责启动 collector/等待环境信息、构造并恢复 learner、发布初始权重和建立 transport。发送 CollectorConnection 后即创建 MetricsPanel/TrainingMetrics 并 start,然后进入训练循环;等待首个及后续 chunk、第一次 update 的编译/捕获均属于训练阶段,循环不再调用 boot API 或延迟创建指标对象。训练预算已满足的恢复调用也使用同一指标阶段完成最终保存,不走可空 logger 特例。 + +`TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。 在启动 collector 前打开,由上下文管理器或 ExitStack 保证覆盖正常结束、异常、启动失败及 Ctrl+C。清理 worker、writer、pipe、queue 的单项失败不能跳过终端恢复;不吞掉原始训练错误。退出阶段显示停止状态,最终关闭 Live 后再向外传播异常与 traceback。不为 console 安装全局信号处理器。 + +`checkpoint(path)` 仅在文件保存和 manifest 登记均成功后调用;保留现有会话记住最近 checkpoint 的行为。保存失败不得显示成功通知;没有有效训练帧时也应能显示保存消息。 + +### 2.4 统一指标入口 + +`session.metrics_panel(total_iterations=..., initial_iteration=..., initial_env_steps=..., reductions=..., default_reduction=...)` 创建独立 MetricsPanel 阶段;`TrainingMetrics(sinks, initial_iteration=..., initial_env_steps=...)` 借用任意实现 MetricsSink Protocol 的对象,提供唯一 record(mapping)/advance/flush 入口。协议包含 record、advance、flush、start(now=...)、event(name, iteration=..., data=...),无需继承或注册。dispatcher 自己拥有权威进度,sinks 从同一恢复基线创建,不读取特定 logger 的进度;dispatcher 不查询任一 sink 的 due,也不指定主输出端;flush 只提供输出机会,各 sink 内部独立决定是否到期。设备→host 观测发布节拍由生产方明确控制,不由新增高频sink改变;系统采样使用独立 system_interval_seconds wall-clock间隔。一次 record 将相同样本送进两个独立的 MetricAccumulator,generator 只物化一次;日志按 iteration interval 输出,面板按 wall-clock cadence 输出,互不 drain。算法不再手工构造 TrainingPanelStats,APPO 私有 AppoConsole 删除。 + +MetricsPanel 阶段对象使用与 logger 对齐的 record/advance/flush,以及 start/due/checkpoint;session 不承载训练数据API,仅管理终端、boot_panel/metrics_panel阶段工厂与关闭。新phase激活后旧handle的事件、指标、采样、绘制均失效,关闭后也不输出。普通指标区完全由完整 key 自动分组:第一个 / 前为组名,剩余完整相对路径为组内label,无 / 归 ungrouped;不特判 train/reward/env 或合并 diagnostics,所有非空组动态生成,所有组使用相同数值格式规则。快照只保留 canonical metrics mapping,不再存专用字段或额外 metric_groups 缓存。episode/timing/system 的顶部摘要与专页只是额外投影。ThroughputSummary 是显式摘要配置,默认绑定 throughput/env_steps_per_s 和 throughput/iterations_per_s,面板只读共享观测,不重新计算速率。仅已显示的精确key从普通分组隐藏,throughput/custom等仍动态显示;配置为None时移除顶部吞吐卡且普通分组完整显示。EpisodeSummary 同理默认绑定 episode/recent_return_mean 和 episode/recent_length_mean,仅这两项投影顶部并隐藏普通行;episode/custom保留自动分组,episode_summary=None时无顶部episode卡且普通分组完整显示。canonical mapping始终保留全部keys。TimingView(prefix="timing/", overview=False) 显式将计时命名空间路由至专页,默认不在overview普通指标区生成timing组;overview=True可保留平铺。canonical映射和日志不变,顶部Collect/Learn摘要保留。非_s或不能构成树的同namespace指标在Timing专页附加区及纯文本detail区可见,不静默丢弃。timing 使用秒值、斜线层级和 _s 后缀;total_s 显式定义所在父路径总时长,不猜测子项总和,渲染时转毫秒。结构化系统硬件观测仍由框架采样,boot/checkpoint 保持事件接口。 + +计时报告携带 root/total_s 时定义该 root 的完整当前阶段集合:删除 latest/pending 中缺席旧阶段,共同阶段保留各自窗口 mean 样本;没有新 root 时保留整树,不拼入过期子阶段。多 learner 概览对 learner[N]/total_s 有效时长取均值,不相加并发时长。 + +TrainingMetrics 统一根据进度生成 throughput/env_steps_per_s 与 throughput/iterations_per_s,记录到两端而非只在面板生成;等待期间flush按秒级重新观测当前计数,使停顿速率能衰减至零,面板和日志消费同源数值。start() 在 boot/handoff 完成后按当前观测计数重锚定训练 elapsed 和速率,保留恢复累计计数与缓冲指标,排除 spawn/compile/barrier 时间。 + +TrainingMetrics checkpoint(path, iteration=...) 生成统一 checkpoint_saved 事件并分发所有sink;logger写事件,MetricsPanel显示提示,其余sink可明确忽略。事件默认dispatcher当前iteration,保留延迟历史iteration;关闭资源仍由 trainer 所有。TrainingPanelStats 是框架渲染快照,不再公开 submit;MetricsPanel 内部提交渲染结果给 session 的私有终端入口。session.close 强制输出当前 metrics 阶段未刷新的数据,当前若为 boot 不生成假训练帧。 + +## 3. APPO 指标映射 + +APPO 增加一个小型的显示状态组件,建议放在实现包的 `console.py`。它仅接受明确类型的 counters、CollectorMetrics、Python learner metrics 和 phase durations,复用公共窗口并构造 TrainingPanelStats;不持有 learner、writer 或 worker,不发送 IPC,不重建一套通用 trainer abstraction。 + +| 显示项 | 来源及含义 | +| --- | --- | +| updates | `learner.update_count` / `cfg.max_iterations`,累计更新次数 | +| consumed env steps | `learner.global_step`,每次 update 消费 T×N;不乘 epochs/minibatches | +| FPS | rolling delta(global_step)/delta(monotonic time),标明 consumed | +| updates/s | rolling delta(update_count)/delta(time) | +| elapsed / ETA | 进入可训练主循环后本次调用的时间;启动状态单独报告启动等待 | +| recent return / length | `record.returns` / `record.lengths` 输入独立 EpisodeWindow,最近 100 个已完成回合 | +| recent episode window | 内部维护本次调用完成数与最近窗口,不发布累计完成数指标;不假装恢复 checkpoint 中不存在的 episode 历史 | +| learner scalars | 显式映射现有 policy/value loss、entropy、KL、learning rate、policy std、grad norm;保留生产者的原有聚合语义 | +| queue | `ring.size()` / `cfg.queue_chunks` 为瞬时 chunks 快照,仅在纯文本 diagnostics/timing 场景按需显示;面板不再有通用 buffer 行 | +| weight lag | 现有 `record.published_version - record.weight_version`,标明 collector chunk 的版本观测,不称为父进程实时最新滞后 | +| transport / device | 已解析的 transition transport、weight transport 与 learner/collector device 记录在训练启动日志,不占面板 diagnostics;面板 diagnostics 只保留随训练变化的 weight lag | +| collector timing | `record.latency_s`,一整个 rollout chunk 的采集 host wall duration,不含之后的 publication/backpressure | +| learner timings | 现有 ingest、optimize、weight publish host wall duration;明确单位与样本边界 | + +每个 record 在 learner 成功完成该 batch 后登记一次。原始 episode return 已在 collector 中维护,不从经过 timeout bootstrap 的 batch reward 重算。 + +### 3.1 时间窗口与并发语义 + +- EpisodeWindow 独立于日志分支;首次完成 episode 前显示 `n/a`,已有回合后在新回合未完成期间保留最近窗口均值。 +- TimingWindow 按显示间隔累计、生成均值后 reset。没有新 timing 样本时显示上一份有效结果并保留样本边界说明,不用 0 假装测量结果。 +- learner 的现有 update duration 包含 optimize 与 publish,但不含 ingest。若显示父进程 ingest+optimize+publish 之和,应明确命名为 learner processing host wall,不把它混同为完整 loop wall。 +- collector 与 learner 分组并列,绝不把两者相加解释为串行 update 时间,不显示跨进程总 share 或伪造 learn_percent。 +- 面板通过 `timings: tuple[TimingNode, ...]` 接收计时森林。每个节点包含 `name`、`duration_ms: float | None` 和 `children`;节点耗时由生产方显式提供,不默认对子节点求和。collector 与各 learner 是独立根节点,不创建跨并发进程的合计。 +- SHARE 使用直接父节点的耗时作为分母;父节点耗时缺失或为零时不显示子节点占比。纯组织节点的耗时为 `None`,不借用祖先分母。明细可以不完整或重叠,不强制占比合计为 100%。 +- 计时树只在面板刷新时由计时窗口快照构造;训练热路径继续累计原有数值,不重建展示对象。普通文本与 Rich 面板均递归渲染同一结构。 +- 所有计时都是现有 host wall/enqueue 边界,不能声称为 GPU kernel 精确执行时间;不增加 CUDA events 或同步用于面板。 + +### 3.2 日志窗口完全独立 + +APPO 的日志输出经共享 `TrainingLogger`(TensorBoard + live,与 FastSAC 同一入口),TensorBoard 不可用时降级为 live-only。TrainingLogger 直接拥有 host 聚合窗口,创建时通过 `reductions` 定义各 key 的聚合方式,未列出的动态 key 使用 `default_reduction="last"`。`record(metrics)` 统一接收 mapping,标量为单个样本、iterable 为多个样本,不提供单 key 重载或 record_many;只累积、不输出,不重复指定策略;mean 按样本累计 sum/count,last 保留最新值。空样本不产生输出;策略在构造时复制并校验,不随窗口清空而改变。进程日志工具统一位于 `motrix_rl.log.process_logging`。创建时 initial_iteration/initial_env_steps 定义恢复基线;`advance(iterations=1, env_steps=...)` 只累加非负增量,不自动输出。同一轮所有输出共享只读 iteration/env_steps 上下文;异步父进程按真实观测减当前 logger 计数推进,重复 poll 的增量为零。`flush(force=False)` 按内部 iteration 跨阈值判断 interval(非正 interval 沿用每步输出),强制输出由调用方决定,不依赖算法 max_iterations;成功输出后清空窗口,空窗口不重复发送。后端 `_emit()` 为私有实现,所有标量都通过 record/flush。统一执行顺序为完成本轮工作 → record普通观测 → advance → due时补充昂贵窗口观测 → flush → checkpoint事件。每个sink拥有自己的输出节拍;FastSAC设备/collector昂贵观测用独立observation_schedule按发布interval或最终边界drain,输出端只消费最近观测。FastSAC sync允许先advance,再按观测发布节拍record该边界观测;不为形式顺序增加逐步 GPU→host 同步或空 record。常规 flush 不 force,最终输出才 force。FastSAC 已聚合 payload 按 last 记录,禁止对 worker 窗口均值再平均。系统指标按构造时 live_only_prefixes=("sys/",) 路由,不在 flush 传后端参数;缺失指标不记录,真实 NaN/Inf 保留,取消占位NaN和名单协议。event 默认当前 iteration,也可显式覆盖历史事件 iteration(例如延迟到达的 checkpoint 通知)。close 仅关闭后端,不猜测最终 step,不隐式输出尚未 flush 的样本。 + +APPO 仅保留接收 learner_metrics、CollectorMetrics、StageTimings 与 queue_depth 的无状态 metric_values 映射,不构造中间 observation/state/snapshot 包装。TrainingMetrics.record_episodes(returns,lengths) 一次消费新增完成回合,在共享的 EpisodeWindow 维护最近100回合与累计完成数,随后把同一快照送入日志/显示窗口;该最近回合窗口不因任一输出 flush 清空,恢复进度也不伪造历史回合。learner/env/diagnostics 直接通过 record(mapping) 分发,不另存算法侧 latest 缓存。episode/recent_return_mean、episode/recent_length_mean 是最近回合均值(不足100按实际数,未完成回合不纳入),累计完成数仅内部维护,不再发布 episode/completed 或在面板重复显示;删除旧 Train/mean_* 区间均值语义。train/*、env/*、collector/weight_lag、collector/queue_depth 两端覆盖和命名一致,不再显示侧过滤 learner 白名单。 + +统一 timing/* 秒值映射定义 rollout、ingest、optimize、weight_publish、update、processing;update 包含 optimize 与 publish 的完整实测范围,processing=ingest+update。日志与显示均求各自输出窗口内均值,console 仅转毫秒并渲染树(processing 的 children 为 ingest/update,update 的 children 为 optimize/publish)。两个窗口不互相清空,窗口边界不同时数值可不同但定义相同。logger 对 latest/recent snapshot 采用 last,只有 timing keys 采用 mean,不对 recent mean 再求均值。最终迭代强制输出。使用 TrainingLogger 的 provider 同步迁移至单一 mapping record/flush 入口,不保留公开即时输出兼容方法。 + +异步轮询可能跳过 step 的整数倍。通用 `IterationLogSchedule` 从 initial_iteration 后的下一个区间开始,达到或跨过阈值输出一次,再将阈值推进至当前 step 之后;重复观测同一步不补发历史窗口。TrainingLogger 的 host 窗口复用该节拍,只有成功输出后推进;FastSAC 父进程 aggregator 只生成当前观测,不拥有日志 schedule 或 TrainingLogRecord;重复快照按 last 记录,不增量平均。worker 的观测发布节拍独立于父日志节拍,保留初始、首update和最终报告。FastSAC 面板使用共享 RateTracker 和 monotonic 时间,首秒按真实采样跨度计算速率而非人为限制分母为一秒。 + +系统采样由 `motrix_rl.system_metrics.SystemSampler` 生成 UI 无关的 `SystemStats`;面板和 `motrix_rl.log.system_metrics.system_scalars` 各自映射同一观测,不以 TrainingPanelStats 作为日志输入。TrainingMetrics(system_sink=logger) 显式启用并只向该已连接sink发送系统采样,不再广播给面板;省略system_sink即关闭系统日志采样,无额外system_logging布尔。MetricsPanel自身采样只负责System Health结构化卡片,避免普通sys组重复;用户显式record的sys/custom等仍正常广播、动态分组,不由渲染器隐藏。保持 provider 的输出范围:FastSAC 的 sys/* 仅发 live,APPO 不自动新增系统日志指标。 + +设备侧 `TensorMetricWindow` 在创建时确定 mean/range 策略,在原设备累计 sum/count/min/max,drain 才转换 Python 标量;不得用每 update 的 float()/item() 替换而引入逐步 GPU 同步。FastSAC worker 的阶段时长使用共享 TimingWindow,输出节拍使用 IterationLogSchedule,首份/首 update 完成通知显式强制发送。 + +FastSAC 指标按角色分组:collector/policy_lag(max)、collector/ring_fill(slots总和)、collector/{i}/policy_lag与ring_fill(多collector)、learner/weight_version、learner/weight_publishes_per_iteration、learner/updates_per_s、learner/replay_warming;后者是replay预热而非进程启动/编译。统一吞吐只由TrainingMetrics生成throughput/*,不再重复生成diagnostics/collector/env_steps_per_s。同步即时平均reward使用collector/reward_mean;取消async/runtime/diagnostics这三种顶层用途分类。ring slots与APPO queue chunks单位不同,不做同名合并。 + +FastSAC sync 的 step 统一为完成采集批次数,env_steps=step*num_envs,interval 与最终输出使用完成批次语义,不保留旧零基日志偏移。恢复和 warmup/refill 的策略仍由算法决定。 + +### 3.3 Collector 快照契约 + +`motrix_rl.log.collector_stats.CollectorStats` 是可重复读取的最新观测快照,不是 APPO 每 chunk 消费一次的增量记录。`episodes` 是本次 collector 调用的累计完成数,mean_return/mean_episode_length 来自生产方最近回合窗口,不能用累计数作为均值权重;无回合样本用 None,真实非有限观测保留。reward_terms/timings 为报告窗口,env_metrics/diagnostics 为最新值。生产方创建独立映射副本,跨进程发送完整 dataclass 与 TimingNode 树。 + +`CollectorStatsTracker` 维护最近 N 个完成回合与累计计数,reward terms 按报告窗口求均值,timing 每次 `record_timings` 表示一个成功采集批次(未执行阶段显式记零)。snapshot 清空 reward/timing 窗口但保留最近回合、累计计数与最新 env/diagnostics;绑定的 PerfTimingWindow 将原生 profiler 子树合入快照,不二次平均、不经过路径字典覆盖参数。collector 提供普通数值及明确的 core Perf 对象,core 不读取算法私有字段。 + +`CollectorStatsTracker` 构造时绑定 collector_id、num_envs/device 与最近回合窗口长度;record_step 接收原始 rewards、显式 episode_done、reward_terms 和环境 metrics,统一维护逐环境 return/length、完成回合窗口及报告窗口。完成行向量化导出后清零;reset(env_ids) 只丢弃指定未完成轨迹,不改变累计完成数/最近窗口,不 reset 环境、不 bootstrap、不读取具体 env。snapshot 不清逐环境未完成轨迹。FastSAC 负责从结果中提取 terminated|truncated 和原始 reward,再提交观测。 + +启用 `collect_episode_deltas=True` 后,tracker 独立积累完成回合原始样本,`take_episodes()` 消费一次;snapshot/reset 均不消费此增量。APPO 使用增量构造 chunk sideband,在父进程共享状态维护最近100完成回合;环境 metrics 仍在 chunk 末尾归约一次;每步 reward_terms 在原设备 FP32 累积本 chunk 的逐环境均值,chunk 末尾才转 Python 标量并清空。CollectorMetrics 同时携带 env_metrics 与 reward_terms,父侧统一映射 env/* 与 reward/*,两种输出均可见,不额外增加逐步设备同步。reward 分项为环境已加权贡献,不承诺与 bootstrap 后 batch reward 或 episode return 相同。默认快照模式不保存无限增长的增量历史。 + +FastSAC 保留等权 collector 均值、episodes 求和、policy_lag 取最大值的现有策略;policy_lag 位于 diagnostics,不成为 core 的算法专属字段。缺失均值保持 None,日志不输出对应 key;面板显示 n/a,真实非有限值不作为缺失占位处理。快照重复读取不得重复累积 episode 或进入增量 mean 日志窗口。 + +### 3.4 统一环境 profiler 采样 + +ArrayEnv 在基类中无条件拥有 core Perf,RL 适配器使用明确 ArrayEnv 类型和直接 perf 属性。`PerfTimingWindow` 借用 Perf 并独占其报告窗口:显式 start 清空历史并 enable,采样 snapshot 的 step 根后 reset,close 恢复原 enabled 状态;不在活动 scope 内操作。该窗口不与其他 reset 消费者共享同一 Perf。 + +PerfNode 直接递归转 TimingNode,ns 转 ms,保留所有层级与显式父耗时。环境 step 子阶段挂入 collector 自测 env_step 下,保持外层 wall duration 为该父节点分母,不将各子阶段相加或丢弃深层节点。无 step 样本时不伪造子节点。learner IPC 直接传 TimingNode tuple,取消嵌套字典 total 保留键和算法私有树转换。 + +## 4. Worker 输出隔离 + +FastSAC 已有 spawn 继承 stdout/stderr 文件描述符、child 内 logging 配置的两段机制。提取真正通用的文件输出能力到 `motrix_rl`,由 Worker 启动路径复用;FastSAC 原调用方同步切换到定义模块,不保留同一 PR 中间版本的 wrapper。 + +建议在 `WorkerRuntime` 增加可选日志文件路径,并由 Worker.start/bootstrap 协同处理: + +1. 父进程建立日志目录,在 Process.start 的短作用域内让子进程继承日志 fd,覆盖 spawn 重导入 Torch/simulator 时的 Python 和 native 输出。 +2. 重定向前后 flush 父进程 Python 输出流,finally 中立即恢复父进程 fd;此机制修改进程全局 fd,必须串行启动,不能声称线程局部重定向。spawn guard 内不渲染 UI;其他父进程线程在该极短区间的输出也可能进入 worker 日志,这一限制需文档化。 +3. child bootstrap 在 placement/runtime 初始化前配置 logging 及 fd 1/2,后续 stdout、stderr、warnings、traceback 与 native 输出都留在文件。所有自有 fd 都有明确关闭路径。 +4. APPO 给 collector 传入固定日志路径;错误通道由 Worker.start 创建和管理,bootstrap 捕获初始化/run 异常,发送有界 UTF-8 摘要后重新抛出,完整 traceback 留在进程日志。WorkerHandle.check 非阻塞并缓存报告,未收到报告时仍依据非零 exitcode 报 WorkerError;正常退出由算法判断是否提前结束。WorkerHandle.close 在退出后释放进程与接收端,start 失败关闭两端;startup/metrics/stop 的算法协议不混入错误通道。 +5. FastSAC async 的 CollectorWorker/LearnerWorker 同样继承框架 Worker;父侧为各 rank/collector 传 WorkerPlacement 和 WorkerRuntime,bootstrap 统一日志隔离、NUMA 和派生 seed。父侧通过 handle.check 消费错误并发送 worker_crashed 事件,错误日志路径指向已有 logs 文件,不另设 error_queue 或重复 async_errors 文件。startup barrier、DDP、ring/weight slots 与全组停止策略仍归 FastSAC。正常结束/启动失败均回收已启动 handles;启动一半失败也必须释放 barrier 和停止同组。 + +6. 父进程使用同一个 console 的受控输出显示重要 warning/status。关闭 Live 后正常输出最终异常。不引入日志转发队列或日志尾部线程。 + +警告不再散落到终端,但仍完整可查:启动阶段显示 collector 日志位置,失败时再次给出位置和 error pipe traceback。非 TTY 也保留日志文件和失败摘要,不静默丢弃诊断。`logging.captureWarnings` 不作为必要条件,默认 warnings stderr 本身已写入文件;是否使用它只影响日志格式。 + +## 5. 实施边界与顺序 + +1. 补齐共享 panel 的 resume ETA、None/nonfinite 显示、env steps/episodes、storage labels、timing 分母控制、due/status 和纯文本 checkpoint。 +2. 提取 worker 文件日志机制,接入 WorkerRuntime;同步迁移 FastSAC 对通用 helper 的调用,保留其私有 startup UI。 +3. 实现 APPO 显示状态与父进程 hooks:启动状态、等待轮询、update 后登记、到期采样、保存成功通知和全生命周期清理。 +4. 在 APPO 使用说明中描述视图切换、consumed FPS、日志位置与非 TTY 行为;APPO 算法设计链接本文,不重复定义共享契约。 +5. 按下节验证后再考虑让其他 provider 采用同样入口。本期不强制改造 SKRL/RSLRL/SuperMimic,也不搬迁 FastSAC 的私有聚合架构。 + +本方案不新增事件总线、provider registry、监控 daemon、worker-grid、日志 tail、通用 collector 协议或 UI 专用 transport 字段。设计确认后再建立带 TODO 的实施计划,随后进入编码。 + +## 6. 验证 + +### 快速契约测试 + +- panel:fresh/resume 的 ETA 与速率 fallback、完成时 ETA、缺失回合、env steps 与 episode count、queue labels/units、并发 timing 无跨进程 share、纯文本 checkpoint。 +- cadence:假 monotonic clock 验证日志 interval 不影响显示、未到期不调用 system sampler、等待轮询可更新状态、强制通知不改变日志窗口。 +- APPO 映射:使用 CollectorMetrics 与 Python scalars 验证 consumed counter、resume baseline、raw episode、窗口重置、无重复 episode 登记与现有 learner key 映射。 +- lifecycle:正常、启动失败、learner 异常、保存失败、KeyboardInterrupt 均恢复 terminal;成功保存才更新 checkpoint,重复 close 安全。 +- 日志不变量:同一固定输入和 logging.interval 下,是否刷新面板不改变 writer/context.metrics 收到的 records、tags、step 与 env_steps。 + +### 进程集成与人工验收 + +- spawn 子进程在 import 阶段和 run 阶段分别产生 Python print、stderr、warning、logging、native fd 输出及异常,验证进入日志文件,父终端恢复,错误信息仍可诊断;此项属于 integration。 +- CPU CartPole 短训练覆盖首次启动、正常退出、checkpoint、warm resume;记录实际命令与结果。 +- 非 TTY 重定向验证节流和无 ANSI redraw 控制序列,并检查 worker 日志与最终失败摘要。 +- 真实 TTY 人工切换 1/2/3,分别在启动等待和训练期间 Ctrl+C,确认回显、光标和输入模式恢复。 +- CUDA 仅在真实硬件执行后报告支持证据,记录设备、执行模式、transport、命令及结果;不能以静态检查、CPU 冒烟或 skip 代替。 + +训练日志公开 API 使用 iteration 表达算法主进度,env_steps 表达 transition 数。TensorBoard/live 的底层 step 字段由后端适配保留,checkpoint/IPC 原有 step 字段不受此命名迁移影响。 From 799d2552d6c9e1e18940235187f9fa84e2f63165 Mon Sep 17 00:00:00 2001 From: zilch <147668916@qq.com> Date: Wed, 2 Dec 2026 15:33:24 +0800 Subject: [PATCH 2/2] refactor(rl): simplify FastSAC metrics and document current contracts --- motrix_rl/src/motrix_rl/console/panel.py | 14 +- motrix_rl/src/motrix_rl/console/timing.py | 21 +- motrix_rl/tests/test_console.py | 56 ++- motrix_rl/tests/test_timing.py | 42 ++- .../fastsac/async_impl/learner_stats.py | 135 ++++++++ .../fastsac/async_impl/stats.py | 221 +++++------- .../fastsac/async_impl/worker.py | 165 +++------ .../motrix_rl_builtin/fastsac/sync/metrics.py | 44 +++ .../motrix_rl_builtin/fastsac/sync/train.py | 48 ++- .../tests/test_fastsac_async_multi.py | 5 +- .../tests/test_fastsac_learner.py | 20 +- .../tests/test_fastsac_learner_stats.py | 100 ++++++ .../tests/test_fastsac_live_metrics.py | 20 +- .../tests/test_fastsac_sync_metrics.py | 103 ++++++ .../tests/test_fastsac_worker_logging.py | 6 +- wiki/design/index.md | 4 +- wiki/design/training-console.md | 319 ++++++++++-------- 17 files changed, 841 insertions(+), 482 deletions(-) create mode 100644 motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner_stats.py create mode 100644 motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/metrics.py create mode 100644 motrix_rl_builtin/tests/test_fastsac_learner_stats.py create mode 100644 motrix_rl_builtin/tests/test_fastsac_sync_metrics.py diff --git a/motrix_rl/src/motrix_rl/console/panel.py b/motrix_rl/src/motrix_rl/console/panel.py index 1823bcabd..be43c357a 100644 --- a/motrix_rl/src/motrix_rl/console/panel.py +++ b/motrix_rl/src/motrix_rl/console/panel.py @@ -509,6 +509,8 @@ def si(n: float) -> str: _append_timing_node_lines(lines, root) for name, values in _group_metrics(stats.timing_extras).items(): lines.append(f" {name}(detail) " + " ".join(_format_metric_items(values))) + if stats.checkpoint_path: + lines.append(f" saved checkpoint {stats.checkpoint_path}") lines.append("-" * width) return "\n".join(lines) @@ -528,7 +530,7 @@ def _append_timing_node_lines(lines: list[str], root: TimingNode) -> None: """Render the same timing forest as Rich, with direct-parent shares.""" def label(node: TimingNode) -> str: - name = _strip_markup(node.name) + name = node.name return f"{name} {_format_value(node.duration_ms)} ms" if node.duration_ms is not None else name lines.append(" " + label(root)) @@ -646,7 +648,7 @@ def append(parent: TimingNode, prefix: str = "") -> None: last = index == len(parent.children) - 1 branch = "└─ " if last else "├─ " cells = [ - Text(prefix + branch + _strip_markup(child.name), style="white"), + Text(prefix + branch + child.name, style="white"), f"{_format_value(child.duration_ms)} ms" if child.duration_ms is not None else "", ] if show_shares: @@ -1005,9 +1007,11 @@ def memory_style(memory: MemoryUsage | None) -> str: row.append( Panel( _rich_timing_grid(root), - title=f"{_strip_markup(root.name)} {_format_value(root.duration_ms)} ms" - if root.duration_ms is not None - else _strip_markup(root.name), + title=Text( + f"{root.name} {_format_value(root.duration_ms)} ms" + if root.duration_ms is not None + else root.name + ), border_style="grey37", padding=(0, 1), ) diff --git a/motrix_rl/src/motrix_rl/console/timing.py b/motrix_rl/src/motrix_rl/console/timing.py index 3c2c74a3b..9fb0091aa 100644 --- a/motrix_rl/src/motrix_rl/console/timing.py +++ b/motrix_rl/src/motrix_rl/console/timing.py @@ -1,11 +1,11 @@ # Copyright Motphys Technology Co., Ltd. 2025, 2026 # SPDX-License-Identifier: Apache-2.0 -"""Build console timing scopes from dotted paths.""" +"""Build console timing scopes and project their durations into canonical metrics.""" from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from motrix_env_core.perf import Perf, PerfNode @@ -42,6 +42,23 @@ def timing_nodes_from_paths(values: Mapping[str, float]) -> tuple[TimingNode, .. return tuple(child.to_node(name) for name, child in root.children.items()) +def timing_metrics(nodes: Sequence[TimingNode], *, prefix: str) -> dict[str, float]: + """Project explicit millisecond durations into slash-separated seconds metrics. + + Every timed node emits ``prefix/name_s``, including parents with children. + Organizational nodes retain their path without emitting a duration. Names + are literal path segments (dots are preserved), and ``total`` is ordinary; + callers supply any root total metric themselves. + """ + metrics: dict[str, float] = {} + for node in nodes: + path = f"{prefix}/{node.name}" + if node.duration_ms is not None: + metrics[f"{path}_s"] = node.duration_ms / 1000.0 + metrics.update(timing_metrics(node.children, prefix=path)) + return metrics + + def timing_node_from_perf(node: PerfNode) -> TimingNode: """Preserve every profiler scope and its own per-call mean, converting ns to ms.""" return TimingNode(node.name, node.mean_ns / 1e6, tuple(timing_node_from_perf(child) for child in node.children)) diff --git a/motrix_rl/tests/test_console.py b/motrix_rl/tests/test_console.py index 6f6b85fd4..6e52c16df 100644 --- a/motrix_rl/tests/test_console.py +++ b/motrix_rl/tests/test_console.py @@ -123,27 +123,17 @@ def test_format_training_panel_renders_nested_timing_nodes_as_tree() -> None: assert " └─ actor 1.000 ms 33%" in panel -def test_format_training_panel_strips_markup_from_group_titles() -> None: - stats = TrainingPanelStats( - iteration=1, - total_iterations=10, - steps_per_second=100.0, - elapsed_seconds=1.0, - mean_return=0.0, - mean_episode_length=0.0, - buffer_size=0, - buffer_capacity=1, - collect_ms=2.0, - learn_ms=3.0, - learn_percent=0.0, - timings=(TimingNode("learner [magenta]3.0[/]ms", None, (TimingNode("drain", 0.5),)),), +@pytest.mark.parametrize("rich", [False, True]) +def test_timing_names_preserve_rank_and_literal_brackets(rich: bool) -> None: + stats = _panel_stats( + timings=( + TimingNode("learner[0]", 1.0, (TimingNode("update[0]", 0.5),)), + TimingNode("learner[1]", 2.0, (TimingNode("[magenta]literal[/]", 1.0),)), + ) ) - - panel = format_training_panel(stats) - - assert "[magenta]" not in panel - assert "learner 3.0ms" in panel - assert "drain 0.500" in panel + text = _render_panel(stats, view="timing") if rich else format_training_panel(stats) + for name in ("learner[0]", "learner[1]", "update[0]", "[magenta]literal[/]"): + assert name in text def test_format_training_panel_shows_cpu_load_with_explicit_topology() -> None: @@ -528,20 +518,22 @@ def test_format_training_panel_hides_buffer_row_without_storage() -> None: assert " buffer 3/8" in format_training_panel(_panel_stats(buffer_size=3, buffer_capacity=8)) -def test_plain_text_fallback_shows_checkpoint_path() -> None: - rendered = [] - monkeypatch = pytest.MonkeyPatch() +@pytest.mark.parametrize("existing_frame", [False, True]) +def test_plain_text_checkpoint_event_shows_path_and_keeps_latest_notice(monkeypatch, capsys, existing_frame) -> None: monkeypatch.setattr(console_module, "open_training_live", lambda: (None, None)) - monkeypatch.setattr(console_module, "emit_training_panel", lambda live, stats, **k: rendered.append(stats)) - try: - session = TrainingPanelSession.open(title="test", interval_seconds=60.0) + with TrainingPanelSession.open(title="test", interval_seconds=60.0) as session: phase = session.metrics_panel(total_iterations=100) - phase.event("checkpoint_saved", iteration=0, data={"path": "/tmp/ckpt.pt"}) - stats = _panel_stats(checkpoint_path="/tmp/ckpt.pt") - phase._emit(stats) - finally: - monkeypatch.undo() - assert phase._last_checkpoint == "/tmp/ckpt.pt" + if existing_frame: + phase.record({"train/loss": 1.0}) + phase.flush() + capsys.readouterr() + phase.event("checkpoint_saved", iteration=1, data={"path": "/tmp/first.pt"}) + assert "saved checkpoint" in capsys.readouterr().out + phase.event("checkpoint_saved", iteration=2, data={"path": "/tmp/final.pt"}) + assert "/tmp/final.pt" in capsys.readouterr().out + phase.flush(force=True) + text = capsys.readouterr().out + assert "/tmp/final.pt" in text and "/tmp/first.pt" not in text def test_due_gates_refresh_until_first_submitted_frame(monkeypatch) -> None: diff --git a/motrix_rl/tests/test_timing.py b/motrix_rl/tests/test_timing.py index f7f5267dd..f28921f99 100644 --- a/motrix_rl/tests/test_timing.py +++ b/motrix_rl/tests/test_timing.py @@ -1,13 +1,14 @@ # Copyright Motphys Technology Co., Ltd. 2025, 2026 # SPDX-License-Identifier: Apache-2.0 +from copy import deepcopy from types import MappingProxyType import pytest from motrix_env_core.perf import Perf from motrix_rl.console.panel import TimingNode -from motrix_rl.console.timing import PerfTimingWindow, timing_nodes_from_paths +from motrix_rl.console.timing import PerfTimingWindow, timing_metrics, timing_nodes_from_paths def test_empty_timing_paths() -> None: @@ -68,6 +69,45 @@ def test_total_is_an_ordinary_path_segment() -> None: ) +def test_timing_metrics_preserves_parent_and_nested_durations() -> None: + nodes = [ + TimingNode( + "update", + 12.0, + (TimingNode("critic", 5.0, (TimingNode("backward", 2.0),)), TimingNode("actor", 0.0)), + ), + TimingNode("drain", 1.5), + ] + original = deepcopy(nodes) + + assert timing_metrics(nodes, prefix="timing/learner") == { + "timing/learner/update_s": 0.012, + "timing/learner/update/critic_s": 0.005, + "timing/learner/update/critic/backward_s": 0.002, + "timing/learner/update/actor_s": 0.0, + "timing/learner/drain_s": 0.0015, + } + assert nodes == original + + +def test_timing_metrics_keeps_organizational_paths_and_literal_names() -> None: + nodes = ( + TimingNode( + "step", + None, + (TimingNode("physics.solve", 4.0), TimingNode("total", 2.0), TimingNode("empty", None)), + ), + TimingNode("total", 8.0), + ) + + assert timing_metrics(nodes, prefix="timing/collector") == { + "timing/collector/step/physics.solve_s": 0.004, + "timing/collector/step/total_s": 0.002, + "timing/collector/total_s": 0.008, + } + assert timing_metrics((), prefix="timing/collector") == {} + + @pytest.mark.parametrize("enabled", [False, True]) def test_perf_window_preserves_nested_scopes_and_restores_enabled_state(enabled) -> None: perf = Perf(enabled=enabled, clock=iter((0, 1_000_000, 2_000_000, 4_000_000, 6_000_000, 9_000_000)).__next__) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner_stats.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner_stats.py new file mode 100644 index 000000000..3de337880 --- /dev/null +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/learner_stats.py @@ -0,0 +1,135 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Algorithm-private learner log windows; no model or transport ownership.""" + +from collections.abc import Mapping +from multiprocessing.queues import Queue +from queue import Full + +from motrix_rl.console.data import TimingWindow +from motrix_rl.console.panel import TimingNode +from motrix_rl.log.schedule import IterationLogSchedule +from motrix_rl.log.tensor_window import TensorMetricWindow +from motrix_rl_builtin.fastsac.async_impl.stats import LearnerPayload + + +class LearnerStatsPublisher: + """Aggregate independent timing samples and send nonblocking log windows. + + The caller samples rings and supplies model observations only at publication + boundaries. Metric tensors remain on device until that boundary. A full + consumer queue drops the completed window, including its diagnostics, rather + than carrying stale observations into the next window. + """ + + def __init__(self, queue: Queue, *, rank: int, interval: int, resume_step: int, now: float) -> None: + self._queue = queue + self._rank = rank + self._schedule = IterationLogSchedule(interval, initial_iteration=resume_step) + self._timing = TimingWindow() + self._phase_keys: set[str] = set() + self._breakdown_keys: set[str] = set() + self._window_start = now + self._record_anchored = False + self._training_started = False + self._first_payload = True + self._first_update = False + + def anchor_record(self, now: float) -> None: + """Anchor utilization to first ingestion, excluding concurrent startup wait. + + Call before recording the first successful drain. Earlier idle samples + remain visible, as before; only the utilization wall-clock origin moves. + """ + if not self._record_anchored: + self._window_start = now + self._record_anchored = True + + def record_drain(self, seconds: float) -> None: + self._timing.add("drain", seconds) + self._phase_keys.add("drain") + + def record_train(self, seconds: float, *, breakdown_ms: Mapping[str, float], publish_ms: float) -> None: + self._first_update = self._first_update or not self._training_started + self._training_started = True + self._timing.add("train", seconds) + # Each stage retains its own sample denominator, including sparse actor + # updates. The agent total is a call cost, not a per-gradient-step cost. + for key, value in breakdown_ms.items(): + self._timing.add(f"update.{key}", value / 1000.0) + self._breakdown_keys.add(key) + self._timing.add("update.publish", publish_ms / 1000.0) + self._breakdown_keys.add("publish") + + def record_idle(self, seconds: float, *, ring_empty: bool) -> None: + phase = "ring wait" if ring_empty else "gate wait" + self._timing.add(phase, seconds) + self._phase_keys.add(phase) + + def due(self, step: int) -> bool: + return self._first_payload or self._first_update or self._schedule.due(step) + + def publish( + self, + step: int, + *, + now: float, + warming: bool, + updates: int, + buffer_size: int, + buffer_capacity: int, + ring_fill: list[float | None], + weight_version: int | None, + metrics_window: TensorMetricWindow, + ) -> None: + """Send and reset a completed window, including a final partial window.""" + metrics = metrics_window.stats_and_reset() if self._training_started and not warming else None + timing = self._timing + items = [ + TimingNode(key, timing.mean_ms(key)) + for key in ("drain", "ring wait", "gate wait") + if key in self._phase_keys + ] + if self._breakdown_keys: + # Never synthesize an unmeasured total by summing child stages. + update_ms = ( + timing.mean_ms("update.total") + timing.mean_ms("update.publish") + if "total" in self._breakdown_keys + else None + ) + items.append( + TimingNode( + "update", + update_ms, + tuple( + TimingNode(key, timing.mean_ms(f"update.{key}")) + for key in sorted(self._breakdown_keys) + if key != "total" + ), + ) + ) + payload: LearnerPayload = { + "rank": self._rank, + "updates": updates, + "training_started": self._training_started, + "metrics": metrics, + "learn_ms": timing.mean_ms("train"), + "learn_pct": 100.0 * timing.total_seconds("train") / max(now - self._window_start, 1e-9), + "learner_timing": tuple(items), + "buffer_size": buffer_size, + "buffer_capacity": buffer_capacity, + "ring_fill": ring_fill, + "weight_version": weight_version, + } + try: + self._queue.put_nowait(payload) + except Full: + pass + self._window_start = now + self._first_payload = False + self._first_update = False + timing.reset() + self._phase_keys.clear() + self._breakdown_keys.clear() + self._schedule.mark_logged(step) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py index 171e1c7db..1aa397fba 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/stats.py @@ -14,33 +14,18 @@ from motrix_rl.console.data import RateTracker from motrix_rl.console.panel import TimingNode +from motrix_rl.console.timing import timing_metrics from motrix_rl.log.collector_stats import CollectorStats -def timing_mean(values: list[float]) -> float: - """Mean of a non-empty timing sample list.""" - return sum(values) / len(values) - - @dataclass(frozen=True) class AggregatedCollectorStats: mean_return: float | None mean_episode_length: float | None - episodes: int reward_terms: dict[str, float] env_metrics: dict[str, float] policy_lag: float - timing_ms: dict[str, float] - - -def _timing_values(nodes: tuple[TimingNode, ...], prefix: str = "") -> dict[str, float]: - values: dict[str, float] = {} - for node in nodes: - path = f"{prefix}.{node.name}" if prefix else node.name - if node.duration_ms is not None: - values[path] = node.duration_ms - values.update(_timing_values(node.children, path)) - return values + timings: dict[str, float] def aggregate_collector_stats(per_collector: Mapping[int, CollectorStats | None]) -> AggregatedCollectorStats: @@ -61,11 +46,10 @@ def mean_dicts(values: list[Mapping[str, float]]) -> dict[str, float]: return AggregatedCollectorStats( mean_return=mean([stats.mean_return for stats in snapshots]), mean_episode_length=mean([stats.mean_episode_length for stats in snapshots]), - episodes=sum(stats.episodes for stats in snapshots), reward_terms=mean_dicts([stats.reward_terms for stats in snapshots]), env_metrics=mean_dicts([stats.env_metrics for stats in snapshots]), policy_lag=max((stats.diagnostics["policy_lag"] for stats in snapshots), default=0.0), - timing_ms=mean_dicts([_timing_values(stats.timings) for stats in snapshots]), + timings=mean_dicts([timing_metrics(stats.timings, prefix="timing/collector") for stats in snapshots]), ) @@ -84,8 +68,7 @@ class LearnerPayload(TypedDict, total=False): buffer_capacity: float metrics: dict[str, float] | None ring_fill: list[float | None] - weight_version: int - checkpoint_path: str | None + weight_version: int | None class CheckpointNotice(TypedDict): @@ -161,137 +144,111 @@ class AsyncTrainingStats: step: int env_steps: int warmup_done: bool - updates: int scalars: Mapping[str, float] checkpoint_notices: tuple[CheckpointNotice, ...] = () +def metric_values( + source: AsyncTrainingStatsSource, + *, + iteration: int, + warming: bool, + updates: int, + updates_per_second: float | None, + publishes_per_iteration: float | None, +) -> dict[str, float]: + """Pure FastSAC aggregation and canonical naming; no cadence or mutable baselines.""" + collectors = aggregate_collector_stats(source.per_collector_stats) + payloads = [payload for payload in source.learner_payloads.values() if payload is not None] + primary = payloads[0] if payloads else None + values: dict[str, float] = { + "collector/policy_lag": collectors.policy_lag, + "train/UTD": updates / max(iteration, 1), + "learner/replay_warming": float(warming), + "learner/learn_percent": sum(payload["learn_pct"] for payload in payloads) / len(payloads) if payloads else 0.0, + **{f"env/{key}": value for key, value in collectors.env_metrics.items()}, + **{f"reward/{key}": value for key, value in collectors.reward_terms.items()}, + } + if collectors.mean_return is not None: + values["episode/recent_return_mean"] = collectors.mean_return + if collectors.mean_episode_length is not None: + values["episode/recent_length_mean"] = collectors.mean_episode_length + if updates_per_second is not None: + values["learner/updates_per_s"] = updates_per_second + if publishes_per_iteration is not None: + values["learner/weight_publishes_per_iteration"] = publishes_per_iteration + for key, value in collectors.timings.items(): + values["timing/collector/total_s" if key == "timing/collector/collect_s" else key] = value + for payload in payloads: + root = "learner" if source.num_learners == 1 else f"learner[{payload['rank']}]" + prefix = f"timing/{root}" + if payload["learn_ms"] is not None: + values[f"{prefix}/total_s"] = payload["learn_ms"] / 1000.0 + values.update(timing_metrics(payload["learner_timing"], prefix=prefix)) + if primary is not None: + fills = primary.get("ring_fill") or [] + values["collector/ring_fill"] = sum(fill for fill in fills if fill is not None) + if primary.get("weight_version") is not None: + values["learner/weight_version"] = primary["weight_version"] + values["learner/buffer_size"] = primary["buffer_size"] + values["learner/buffer_capacity"] = primary["buffer_capacity"] + if primary["metrics"] is not None: + values.update({f"train/{key}": value for key, value in primary["metrics"].items()}) + if source.num_collectors > 1: + for index, snapshot in source.per_collector_stats.items(): + if snapshot is not None: + values[f"collector/{index}/policy_lag"] = snapshot.diagnostics["policy_lag"] + if primary is not None: + fills = primary.get("ring_fill") or [] + fill = fills[index] if index < len(fills) else None + if fill is not None: + values[f"collector/{index}/ring_fill"] = fill + return values + + class AsyncTrainingStatsAggregator: - """Aggregate source payloads into normalized training statistics.""" + """Own only successive observation baselines, not source configuration or logging.""" def __init__(self, *, learning_starts: int) -> None: self._learning_starts = learning_starts - self._num_envs = 0 - self._num_collectors = 0 - self._num_learners = 0 self._update_rate = RateTracker() - self._last_observed_step: int | None = None - self._last_updates = 0 + self._last_iteration: int | None = None self._last_weight_version = 0 - self._was_warming = learning_starts > 0 + self._was_warming: bool | None = None def collect(self, source: AsyncTrainingStatsSource) -> AsyncTrainingStats | None: checkpoint_notices = source.drain() if not source.data_ready(): return None - self._num_envs = source.num_envs - self._num_collectors = source.num_collectors - self._num_learners = source.num_learners - if self._last_observed_step is None: - self._last_observed_step = source.resume_step - self._was_warming = source.resume_step < self._learning_starts - - collector_steps = source.control.collector_steps - step = collector_steps // self._num_collectors - now = time.monotonic() - last_stats = aggregate_collector_stats(source.per_collector_stats) - payloads = [payload for payload in source.learner_payloads.values() if payload] + iteration = source.control.collector_steps // source.num_collectors + payloads = [payload for payload in source.learner_payloads.values() if payload is not None] primary = payloads[0] if payloads else None - warming = step < self._learning_starts - learn_percent = timing_mean([payload["learn_pct"] for payload in payloads]) if payloads else 0.0 - updates = primary["updates"] if primary else self._last_updates - utd = updates / max(step, 1) - scalars = self._scalars( - last_stats, - primary, - payloads, - source.per_collector_stats, - step, - now, - updates, - utd, - learn_percent, + updates = primary["updates"] if primary is not None else 0 + updates_per_second = self._update_rate.update(updates, now=time.monotonic()) + warming = iteration < self._learning_starts + was_warming = source.resume_step < self._learning_starts if self._was_warming is None else self._was_warming + publishes_per_iteration = None + if primary is not None and primary.get("weight_version") is not None: + previous_iteration = source.resume_step if self._last_iteration is None else self._last_iteration + publishes_per_iteration = (primary["weight_version"] - self._last_weight_version) / max( + iteration - previous_iteration, 1 + ) + values = metric_values( + source, + iteration=iteration, + warming=warming, + updates=updates, + updates_per_second=updates_per_second, + publishes_per_iteration=publishes_per_iteration, ) - warmup_done = self._was_warming and not warming + self._last_iteration = iteration self._was_warming = warming - self._last_observed_step = step - self._last_updates = updates if primary is not None and primary.get("weight_version") is not None: self._last_weight_version = primary["weight_version"] return AsyncTrainingStats( - step=step, - env_steps=collector_steps * (self._num_envs // self._num_collectors), - warmup_done=warmup_done, - updates=updates, - scalars=scalars, + step=iteration, + env_steps=source.control.collector_steps * (source.num_envs // source.num_collectors), + warmup_done=was_warming and not warming, + scalars=values, checkpoint_notices=tuple(checkpoint_notices), ) - - def _scalars( - self, - last_stats: AggregatedCollectorStats, - primary: LearnerPayload | None, - payloads: list[LearnerPayload], - per_collector_stats: Mapping[int, CollectorStats | None], - step: int, - now: float, - updates: int, - utd: float, - learn_percent: float, - ) -> dict[str, float]: - scalars: dict[str, float] = {} - if last_stats.mean_return is not None: - scalars["episode/recent_return_mean"] = last_stats.mean_return - if last_stats.mean_episode_length is not None: - scalars["episode/recent_length_mean"] = last_stats.mean_episode_length - updates_per_second = self._update_rate.update(updates, now=now) - if updates_per_second is not None: - scalars["learner/updates_per_s"] = updates_per_second - scalars["collector/policy_lag"] = last_stats.policy_lag - if primary and primary.get("weight_version") is not None: - scalars["learner/weight_publishes_per_iteration"] = ( - primary["weight_version"] - self._last_weight_version - ) / max(step - self._last_observed_step, 1) - if primary: - fills = primary.get("ring_fill") or [] - scalars["collector/ring_fill"] = sum(fill for fill in fills if fill is not None) - if primary.get("weight_version") is not None: - scalars["learner/weight_version"] = primary["weight_version"] - scalars["train/UTD"] = utd - if self._num_collectors > 1: - for index in range(self._num_collectors): - stats = per_collector_stats.get(index) - if stats: - scalars[f"collector/{index}/policy_lag"] = stats.diagnostics["policy_lag"] - if primary: - fill = (primary.get("ring_fill") or [None] * self._num_collectors)[index] - if fill is not None: - scalars[f"collector/{index}/ring_fill"] = fill - scalars["learner/replay_warming"] = float(step < self._learning_starts) - scalars["learner/learn_percent"] = learn_percent - scalars["timing/collector/total_s"] = last_stats.timing_ms.get("collect", 0.0) / 1000.0 - scalars.update( - { - f"timing/collector/{key.replace('.', '/')}_s": value / 1000.0 - for key, value in last_stats.timing_ms.items() - if key != "collect" - } - ) - for payload in payloads: - root = "learner" if self._num_learners == 1 else f"learner[{payload['rank']}]" - if payload["learn_ms"] is not None: - scalars[f"timing/{root}/total_s"] = payload["learn_ms"] / 1000.0 - scalars.update( - { - f"timing/{root}/{key.replace('.', '/')}_s": value / 1000.0 - for key, value in _timing_values(payload["learner_timing"]).items() - } - ) - if primary: - scalars["learner/buffer_size"] = primary["buffer_size"] - scalars["learner/buffer_capacity"] = primary["buffer_capacity"] - scalars.update({f"env/{key}": value for key, value in last_stats.env_metrics.items()}) - scalars.update({f"reward/{key}": value for key, value in last_stats.reward_terms.items()}) - if primary and primary["metrics"] is not None: - scalars.update({f"train/{key}": value for key, value in primary["metrics"].items()}) - return scalars diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py index 06b34e6c1..25121f301 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/async_impl/worker.py @@ -30,14 +30,12 @@ from motrix_env_core.registry import EnvBuildSpec from motrix_env_core.renderer import RenderConfig from motrix_rl import checkpoints -from motrix_rl.console.data import TimingWindow -from motrix_rl.console.panel import TimingNode -from motrix_rl.log.schedule import IterationLogSchedule from motrix_rl.numa import pin_worker_cpus, resolve_worker_cpus from motrix_rl.worker import Worker from motrix_rl_builtin.fastsac.agent import FastSacAgent from motrix_rl_builtin.fastsac.async_impl.collector import Collector from motrix_rl_builtin.fastsac.async_impl.learner import CollectorEndpoint, Learner +from motrix_rl_builtin.fastsac.async_impl.learner_stats import LearnerStatsPublisher from motrix_rl_builtin.fastsac.async_impl.transport import ( Control, FinalObsStorage, @@ -452,25 +450,14 @@ def run(self) -> None: learner._last_train_gstep = resume_step # lockstep basis continues from the checkpoint learner.publish_weights() # give every collector an initial policy before it warms up - # Elapsed/ETA anchor. The collector's env build (scene compile, kernel - # compile) runs concurrently with the learner build and can outlast it by - # tens of seconds; timing from this point would bill that startup wait - # to elapsed and the first window's rates. The anchor moves to the - # first ingested collector batch below. - start_time = time.monotonic() - start_anchored = False - last_log_time = start_time - train_started = False - first_payload = True - log_schedule = IterationLogSchedule(self.logging_interval, initial_iteration=resume_step) + stats = LearnerStatsPublisher( + self.learner_data_queue, + rank=self.rank, + interval=self.logging_interval, + resume_step=resume_step, + now=time.monotonic(), + ) next_save = ((resume_step // self.save_interval) + 1) * self.save_interval if self.save_interval > 0 else 0 - timing = TimingWindow() - phase_keys: set[str] = set() - breakdown_keys: set[str] = set() - last_checkpoint_path: str | None = None - # The parent process renders the panel and writes TensorBoard: this - # worker ships one compact payload per log window (all learner ranks - # send — workers are peers, the parent is the recorder). # Startup barrier: report readiness and hold until every worker booted # (see CollectorWorker). Weight slots were already shipped and @@ -481,73 +468,6 @@ def run(self) -> None: if self.control.stop: return - def publish_stats(step: int) -> None: - nonlocal last_log_time, first_payload - now = time.monotonic() - warming = step < agent.cfg.learning_starts - metrics_log = None - if train_started and not warming: - # Window-aggregated diagnostics only (means + extremes - # since the last log window): single-update events between - # log points stay visible, mirroring holosoma's averaged - # meter logging. train_started just gates "training - # started". - metrics_log = learner.agent.window_metrics.stats_and_reset() - learn_pct = 100.0 * timing.total_seconds("train") / max(now - last_log_time, 1e-9) - learner_items = [ - TimingNode(key, timing.mean_ms(key)) - for key in ("drain", "ring wait", "gate wait") - if key in phase_keys - ] - if breakdown_keys: - # The measured agent total excludes publication; keep the - # parent unknown when no total was sampled, never sum stages. - update_ms = ( - timing.mean_ms("update.total") + timing.mean_ms("update.publish") - if "total" in breakdown_keys - else None - ) - learner_items.append( - TimingNode( - "update", - update_ms, - tuple( - TimingNode(key, timing.mean_ms(f"update.{key}")) - for key in sorted(breakdown_keys) - if key != "total" - ), - ) - ) - payload = { - "rank": self.rank, - "updates": learner.update_idx, - "training_started": train_started, - "metrics": metrics_log, - "learn_ms": timing.mean_ms("train"), - "learn_pct": learn_pct, - "learner_timing": tuple(learner_items), - "buffer_size": agent.rb.num_stored * agent.num_envs, - "buffer_capacity": agent.rb.buffer_size * agent.num_envs, - # bare RingCursors (IPC transport) carry no size; the - # wrapped GpuIpcTransitionRing lives in this worker. - "ring_fill": [None if isinstance(ring, RingCursors) else ring.size() for ring in self.all_rings], - "weight_version": max((tx.version for tx in weight_txs), default=None), - "checkpoint_path": last_checkpoint_path, - } - # Never block the training loop on a slow panel consumer: - # drop the window's payload if the queue is full (the next - # window's numbers supersede it anyway). - try: - self.learner_data_queue.put_nowait(payload) - except Full: - pass - last_log_time = now - first_payload = False - timing.reset() - phase_keys.clear() - breakdown_keys.clear() - log_schedule.mark_logged(step) - # Each collector runs until its own counter reaches num_iterations; the # aggregate (sum) therefore reaches num_iterations * num_collectors. total_collector_steps = self.num_iterations * num_collectors @@ -563,49 +483,28 @@ def publish_stats(step: int) -> None: t_drain = time.perf_counter() ingested = learner.drain() if ingested: - if not start_anchored: - start_time = time.monotonic() - last_log_time = start_time - start_anchored = True - timing.add("drain", time.perf_counter() - t_drain) - phase_keys.add("drain") + stats.anchor_record(time.monotonic()) + stats.record_drain(time.perf_counter() - t_drain) t_l = time.perf_counter() # One decision path for both topologies: updates are gated on the # global progress basis (identical on every DDP rank; the single # learner's own position when num_collectors == 1). trained = learner.maybe_train(step) - first_update = trained and not train_started if trained: - train_started = True - elapsed_learn_s = time.perf_counter() - t_l - timing.add("train", elapsed_learn_s) - # Keep the raw total cost of one agent.update(n) call. The - # timing tree uses total-cost semantics, not per-gradient-step - # normalization. - for key, value in learner.agent._last_update_timing_ms.items(): - timing.add(f"update.{key}", value / 1000.0) - breakdown_keys.add(key) - timing.add("update.publish", learner._last_publish_ms / 1000.0) - breakdown_keys.add("publish") + stats.record_train( + time.perf_counter() - t_l, + breakdown_ms=agent._last_update_timing_ms, + publish_ms=learner._last_publish_ms, + ) else: # warmup or starved: avoid a hot spin. t_idle = time.perf_counter() time.sleep(opts.idle_sleep_s) - idle_ms = (time.perf_counter() - t_idle) * 1000.0 - if ingested == 0: - # No ring slot was available: learner is waiting for collector data. - timing.add("ring wait", idle_ms / 1000.0) - phase_keys.add("ring wait") - else: - # Data arrived, but replay/batch readiness still gated training. - timing.add("gate wait", idle_ms / 1000.0) - phase_keys.add("gate wait") - if first_payload or log_schedule.due(step) or first_update: - # Publish first-update completion immediately: the startup - # handoff must not wait an entire user logging interval. - # One compact payload per log window to the parent (panel + - # TensorBoard live there; see train.py). All ranks send. - publish_stats(step) + stats.record_idle(time.perf_counter() - t_idle, ring_empty=ingested == 0) + if stats.due(step): + # First payload/update bypass the interval; ring sampling and + # metric host conversion happen only at publication boundaries. + self._publish_stats(stats, learner, weight_txs, step) if is_primary and self.save_interval > 0 and step >= next_save and step > 0: agent.global_step = step @@ -619,7 +518,6 @@ def publish_stats(step: int) -> None: checkpoints.TRAINING_STATE, checkpoint_format=self.checkpoint_format, ) - last_checkpoint_path = str(path) logger.info("saved checkpoint %s", path) # A notice per save for live metrics, separate from the log-window # payload: this step's payload already went out above, and a save @@ -635,7 +533,7 @@ def publish_stats(step: int) -> None: next_save += self.save_interval # A short or partial last window must reach the parent too. - publish_stats(self.control.collector_steps // num_collectors) + self._publish_stats(stats, learner, weight_txs, self.control.collector_steps // num_collectors) if self.num_learners > 1: # All ranks have consumed the identical global step count, so the @@ -669,3 +567,24 @@ def publish_stats(step: int) -> None: self.control.set_stop() # tell the collectors to exit, including failed DDP startup if self.num_learners > 1 and dist.is_initialized(): dist.destroy_process_group() + + def _publish_stats( + self, + stats: LearnerStatsPublisher, + learner: Learner, + weight_txs: list[GpuIpcWeightSender | HostWeightSender], + step: int, + ) -> None: + agent = learner.agent + stats.publish( + step, + now=time.monotonic(), + warming=step < agent.cfg.learning_starts, + updates=learner.update_idx, + buffer_size=agent.rb.num_stored * agent.num_envs, + buffer_capacity=agent.rb.buffer_size * agent.num_envs, + # Bare IPC cursors have no size; wrapped rings live in this worker. + ring_fill=[None if isinstance(ring, RingCursors) else ring.size() for ring in self.all_rings], + weight_version=max((tx.version for tx in weight_txs), default=None), + metrics_window=agent.window_metrics, + ) diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/metrics.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/metrics.py new file mode 100644 index 000000000..23efe00f0 --- /dev/null +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/metrics.py @@ -0,0 +1,44 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Stateless projection of synchronous FastSAC observations to canonical metrics.""" + +from collections.abc import Mapping + +from motrix_rl.log.collector_stats import CollectorStats + + +def metric_values( + *, + warming: bool, + collector: CollectorStats, + reward_mean: float, + buffer_size: int, + buffer_capacity: int, + collect_s: float, + learn_s: float, + train: Mapping[str, float] | None, +) -> dict[str, float]: + """Project one observation window; phase seconds are means per completed batch. + + Reward mean is the latest batch's raw reward, buffer counts are transitions, + and episode means retain the collector's recent completed-episode semantics. + Missing episode/train observations are omitted, not filled with zero. + """ + values = { + "learner/replay_warming": float(warming), + "collector/reward_mean": reward_mean, + "learner/buffer_size": buffer_size, + "learner/buffer_capacity": buffer_capacity, + "learner/learn_percent": 100.0 * learn_s / max(collect_s + learn_s, 1e-9), + "timing/collector/total_s": collect_s, + "timing/learner/total_s": learn_s, + **{f"env/{key}": value for key, value in collector.env_metrics.items()}, + **{f"reward/{key}": value for key, value in collector.reward_terms.items()}, + **{f"train/{key}": value for key, value in (train or {}).items()}, + } + if collector.mean_return is not None: + values["episode/recent_return_mean"] = collector.mean_return + if collector.mean_episode_length is not None: + values["episode/recent_length_mean"] = collector.mean_episode_length + return values diff --git a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py index bbafd7c70..a947f81d9 100644 --- a/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py +++ b/motrix_rl_builtin/src/motrix_rl_builtin/fastsac/sync/train.py @@ -12,6 +12,7 @@ from motrix_env_core.renderer import RenderConfig from motrix_rl import checkpoints from motrix_rl.console import TrainingPanelSession +from motrix_rl.console.data import TimingWindow from motrix_rl.contracts import TrainerBase, TrainerContext from motrix_rl.device import resolve_default_device from motrix_rl.log.collector_stats import CollectorStatsTracker @@ -20,6 +21,7 @@ from motrix_rl.log.training_metrics import TrainingMetrics from motrix_rl_builtin.fastsac.agent import FastSacAgent from motrix_rl_builtin.fastsac.config import FastSacCfg +from motrix_rl_builtin.fastsac.sync.metrics import metric_values from motrix_rl_builtin.fastsac.wrap import FastSacEnvWrap # Enable TF32 matmul on Ampere+ GPUs. SAC training has no precision concern with @@ -213,13 +215,10 @@ def _run_loop( obs, critic_obs = env.reset() tracker = CollectorStatsTracker(0, num_envs=agent.num_envs, device=device) - last_log_step = agent.global_step # Reuse the logging interval as the default observation publication cadence. # This schedule only drains device observations; sinks own output cadence. observation_schedule = IterationLogSchedule(self._context.logging.interval, initial_iteration=agent.global_step) - # Per-iteration phase timings are accumulated until the device drain. - t_collect = 0.0 - t_learn = 0.0 + timing = TimingWindow() session = TrainingPanelSession.open(title=f"{self._env_name}/motrix.fastsac") panel = session.metrics_panel( total_iterations=num_iterations, @@ -279,41 +278,36 @@ def _run_loop( ) obs = next_obs critic_obs = next_critic_obs - t_collect += time.perf_counter() - t0 + collect_s = time.perf_counter() - t0 # ---------------- learner phase: num_updates gradient steps on a sampled batch + learn_s = 0.0 if not warming: t1 = time.perf_counter() agent.update(cfg.num_updates) - t_learn += time.perf_counter() - t1 + learn_s = time.perf_counter() - t1 + # Both phases use completed batches as their denominator, including + # explicit zero learner time for warmup batches. + timing.add("collect", collect_s) + timing.add("learn", learn_s) local += 1 agent.global_step += 1 metrics.advance(env_steps=agent.num_envs) final_step = agent.global_step >= num_iterations scalars = {"learner/replay_warming": float(warming)} if observation_schedule.due(agent.global_step) or final_step: - metrics_log = agent.window_metrics.stats_and_reset() if not warming else None - episode_stats = tracker.snapshot() - n_iter_win = max(agent.global_step - last_log_step, 1) - phase_total = t_collect + t_learn - scalars |= { - "collector/reward_mean": float(rewards.mean()), - "learner/buffer_size": agent.rb.num_stored * agent.num_envs, - "learner/buffer_capacity": agent.rb.buffer_size * agent.num_envs, - "learner/learn_percent": 100.0 * t_learn / max(phase_total, 1e-9), - "timing/collector/total_s": t_collect / n_iter_win, - "timing/learner/total_s": t_learn / n_iter_win, - **{f"env/{key}": value for key, value in episode_stats.env_metrics.items()}, - **{f"reward/{key}": value for key, value in episode_stats.reward_terms.items()}, - **{f"train/{key}": value for key, value in (metrics_log or {}).items()}, - } - if episode_stats.mean_return is not None: - scalars["episode/recent_return_mean"] = episode_stats.mean_return - if episode_stats.mean_episode_length is not None: - scalars["episode/recent_length_mean"] = episode_stats.mean_episode_length - last_log_step = agent.global_step - t_collect, t_learn = 0.0, 0.0 + scalars = metric_values( + warming=warming, + collector=tracker.snapshot(), + reward_mean=float(rewards.mean()), + buffer_size=agent.rb.num_stored * agent.num_envs, + buffer_capacity=agent.rb.buffer_size * agent.num_envs, + collect_s=timing.mean_ms("collect") / 1000.0, + learn_s=timing.mean_ms("learn") / 1000.0, + train=agent.window_metrics.stats_and_reset() if not warming else None, + ) + timing.reset() observation_schedule.mark_logged(agent.global_step) metrics.record(scalars) if warmup_done: diff --git a/motrix_rl_builtin/tests/test_fastsac_async_multi.py b/motrix_rl_builtin/tests/test_fastsac_async_multi.py index 9b2b78ac3..e025004f7 100644 --- a/motrix_rl_builtin/tests/test_fastsac_async_multi.py +++ b/motrix_rl_builtin/tests/test_fastsac_async_multi.py @@ -148,23 +148,20 @@ def test_aggregate_collector_stats_merges_snapshots() -> None: stats = aggregate_collector_stats(per_collector) assert stats.mean_return == pytest.approx(15.0) - assert stats.episodes == 10 assert stats.policy_lag == 3 - assert stats.timing_ms["collect"] == pytest.approx(10.0) + assert stats.timings["timing/collector/collect_s"] == pytest.approx(0.010) def test_aggregate_collector_stats_skips_missing_collectors() -> None: stats = aggregate_collector_stats({0: _snapshot(0, 10.0, 4, 1, 8.0), 1: None}) assert stats.mean_return == pytest.approx(10.0) - assert stats.episodes == 4 def test_aggregate_collector_stats_defaults_without_snapshots() -> None: stats = aggregate_collector_stats({0: None, 1: None}) assert stats.mean_return is None - assert stats.episodes == 0 assert stats.policy_lag == 0 diff --git a/motrix_rl_builtin/tests/test_fastsac_learner.py b/motrix_rl_builtin/tests/test_fastsac_learner.py index 683f53228..a809f6e6b 100644 --- a/motrix_rl_builtin/tests/test_fastsac_learner.py +++ b/motrix_rl_builtin/tests/test_fastsac_learner.py @@ -89,7 +89,11 @@ def test_policy_frequency_gating_spans_update_calls() -> None: def test_learner_timing_payload_preserves_explicit_and_unknown_parent_durations() -> None: from queue import Queue - from motrix_rl_builtin.fastsac.async_impl.stats import AsyncTrainingStatsAggregator, AsyncTrainingStatsSource + from motrix_rl_builtin.fastsac.async_impl.stats import ( + AsyncTrainingStatsAggregator, + AsyncTrainingStatsSource, + metric_values, + ) from motrix_rl.console.panel import TimingNode from motrix_rl.log.collector_stats import CollectorStats @@ -136,11 +140,23 @@ def test_learner_timing_payload_preserves_explicit_and_unknown_parent_durations( "buffer_size": 1, "buffer_capacity": 2, "metrics": None, - "checkpoint_path": None, } }, ) + import copy + + before = copy.deepcopy(source.learner_payloads) + expected = metric_values( + source, iteration=1, warming=False, updates=1, updates_per_second=None, publishes_per_iteration=None + ) + assert ( + metric_values( + source, iteration=1, warming=False, updates=1, updates_per_second=None, publishes_per_iteration=None + ) + == expected + ) + assert source.learner_payloads == before sample = AsyncTrainingStatsAggregator(learning_starts=0).collect(source) assert sample is not None diff --git a/motrix_rl_builtin/tests/test_fastsac_learner_stats.py b/motrix_rl_builtin/tests/test_fastsac_learner_stats.py new file mode 100644 index 000000000..a423e6d44 --- /dev/null +++ b/motrix_rl_builtin/tests/test_fastsac_learner_stats.py @@ -0,0 +1,100 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +import queue + +import pytest +import torch +from motrix_rl_builtin.fastsac.async_impl.learner_stats import LearnerStatsPublisher + +from motrix_rl.log.tensor_window import TensorMetricWindow + + +def publish(stats, metrics, *, step, now=10.0, updates=0, warming=False): + stats.publish( + step, + now=now, + warming=warming, + updates=updates, + buffer_size=12, + buffer_capacity=24, + ring_fill=[None, 2], + weight_version=7, + metrics_window=metrics, + ) + + +@pytest.mark.parametrize("resume_step", [0, 12]) +def test_initial_first_update_and_resume_keep_aligned_schedule(resume_step): + output = queue.Queue() + metrics = TensorMetricWindow({"loss": "range"}) + stats = LearnerStatsPublisher(output, rank=2, interval=10, resume_step=resume_step, now=0) + assert stats.due(resume_step) + publish(stats, metrics, step=resume_step, warming=True) + initial = output.get_nowait() + assert initial["rank"] == 2 + assert initial["metrics"] is None + assert not initial["training_started"] + assert not stats.due(resume_step + 1) + metrics.record("loss", torch.tensor(4.0)) + stats.record_train(0.2, breakdown_ms={"total": 150}, publish_ms=2) + assert stats.due(resume_step + 1) + publish(stats, metrics, step=resume_step + 1, now=11, updates=1) + first_update = output.get_nowait() + assert first_update["training_started"] + assert first_update["metrics"] == {"loss": 4, "loss_min": 4, "loss_max": 4} + boundary = (resume_step // 10 + 1) * 10 + assert not stats.due(boundary - 1) + assert stats.due(boundary) + + +@pytest.mark.parametrize("sample_total", [False, True]) +def test_sparse_timings_publish_total_and_utilization_anchor(sample_total): + output = queue.Queue() + metrics = TensorMetricWindow({}) + stats = LearnerStatsPublisher(output, rank=0, interval=100, resume_step=0, now=0) + stats.anchor_record(100) + stats.anchor_record(101) # Later drains must not move the measurement origin. + stats.record_drain(0.01) + stats.record_drain(0.03) + stats.record_idle(0.04, ring_empty=True) + stats.record_idle(0.06, ring_empty=False) + first = {"actor": 8.0, **({"total": 20.0} if sample_total else {})} + second = {"critic": 4.0, **({"total": 40.0} if sample_total else {})} + stats.record_train(0.1, breakdown_ms=first, publish_ms=2) + stats.record_train(0.3, breakdown_ms=second, publish_ms=6) + publish(stats, metrics, step=3, now=102, updates=8) + payload = output.get_nowait() + assert payload["learn_pct"] == pytest.approx(20) + assert payload["learn_ms"] == pytest.approx(200) + drain, ring_wait, gate_wait, update = payload["learner_timing"] + assert [node.duration_ms for node in (drain, ring_wait, gate_wait)] == pytest.approx([20, 40, 60]) + assert update.duration_ms == (34 if sample_total else None) + assert {node.name: node.duration_ms for node in update.children} == {"actor": 8, "critic": 4, "publish": 4} + assert payload["buffer_size"] == 12 + assert payload["buffer_capacity"] == 24 + assert payload["ring_fill"] == [None, 2] + assert payload["weight_version"] == 7 + + +def test_full_queue_drops_and_resets_window_then_final_partial_reports_new_samples(): + output = queue.Queue(maxsize=1) + output.put_nowait("busy") + metrics = TensorMetricWindow({"loss": "mean"}) + stats = LearnerStatsPublisher(output, rank=0, interval=10, resume_step=0, now=0) + metrics.record("loss", torch.tensor(99.0)) + stats.record_train(0.9, breakdown_ms={"actor": 99}, publish_ms=9) + publish(stats, metrics, step=2, now=1, updates=1) + assert not stats.due(2) + assert output.get_nowait() == "busy" + metrics.record("loss", torch.tensor(3.0)) + stats.record_train(0.1, breakdown_ms={"critic": 4}, publish_ms=1) + assert not stats.due(3) + # Explicit final publication flushes a short window even before the next boundary. + publish(stats, metrics, step=3, now=2, updates=2) + final = output.get_nowait() + assert final["metrics"] == {"loss": 3} + assert final["learn_ms"] == pytest.approx(100) + assert final["learn_pct"] == pytest.approx(10) + update = final["learner_timing"][-1] + assert {node.name for node in update.children} == {"critic", "publish"} diff --git a/motrix_rl_builtin/tests/test_fastsac_live_metrics.py b/motrix_rl_builtin/tests/test_fastsac_live_metrics.py index 1fa57d919..f51b21238 100644 --- a/motrix_rl_builtin/tests/test_fastsac_live_metrics.py +++ b/motrix_rl_builtin/tests/test_fastsac_live_metrics.py @@ -451,7 +451,7 @@ def _snapshot(collector_id: int, stage: _Stage) -> CollectorStats: ) -def _payload(step: int, checkpoint_path: str | None) -> dict: +def _payload(step: int) -> dict: warming = step < LEARNING_STARTS return { "rank": 0, @@ -465,7 +465,6 @@ def _payload(step: int, checkpoint_path: str | None) -> dict: "buffer_capacity": 12, "ring_fill": [1, 2], "weight_version": step, - "checkpoint_path": checkpoint_path, } @@ -524,7 +523,6 @@ def learner(self, process) -> int: collectors = [p.arguments for p in self.ctx.processes if p is not process] logged = self.sink.count("scalars") expected_logs = logged - checkpoint_path = None for stage in self.stages: for collector_id, target in enumerate(stage.steps): while control.collector_steps_at(collector_id) < target: @@ -532,7 +530,7 @@ def learner(self, process) -> int: for collector in collectors: collector["collector_data_queue"].put(_snapshot(collector["collector_id"], stage)) if stage.payload: - payload = _payload(control.collector_steps // NUM_COLLECTORS, checkpoint_path) + payload = _payload(control.collector_steps // NUM_COLLECTORS) if stage.updates is not None: payload["updates"] = stage.updates payload["training_started"] = stage.updates > 0 @@ -686,7 +684,7 @@ def test_async_learner_updates_rate_reports_zero_after_training_stalls(monkeypat collector_queue = queue.Queue() learner_queue = queue.Queue() collector_queue.put(_snapshot(0, _Stage((20, 20)))) - learner_queue.put(_payload(20, None)) + learner_queue.put(_payload(20)) source = AsyncTrainingStatsSource( collector_data_queues=[collector_queue], learner_data_queue=learner_queue, @@ -773,7 +771,7 @@ def test_async_logging_progress_tracks_repeated_and_skipped_polls(tmp_path): num_iterations=50, resume_step=10, per_collector_stats={0: _snapshot(0, _Stage((11, 11))), 1: _snapshot(1, _Stage((11, 11)))}, - learner_payloads={0: _payload(11, None)}, + learner_payloads={0: _payload(11)}, ) aggregator = AsyncTrainingStatsAggregator(learning_starts=0) try: @@ -803,7 +801,7 @@ def test_async_weight_publish_rate_uses_observation_baseline(monkeypatch): collector_queue = queue.Queue() learner_queue = queue.Queue() collector_queue.put(_snapshot(0, _Stage((10, 10)))) - learner_queue.put(_payload(10, None)) + learner_queue.put(_payload(10)) source = AsyncTrainingStatsSource( collector_data_queues=[collector_queue], learner_data_queue=learner_queue, @@ -822,12 +820,12 @@ def test_async_weight_publish_rate_uses_observation_baseline(monkeypatch): assert first is not None and first.scalars control.collector_steps = 15 - source.learner_payloads[0] = _payload(15, None) + source.learner_payloads[0] = _payload(15) middle = aggregator.collect(source) assert middle is not None and middle.scalars control.collector_steps = 20 - source.learner_payloads[0] = _payload(20, None) + source.learner_payloads[0] = _payload(20) final = aggregator.collect(source) assert final is not None and final.scalars assert final.scalars["learner/weight_publishes_per_iteration"] == 1.0 @@ -965,13 +963,13 @@ def test_async_update_rate_baselines_first_observation_not_historical_updates(mo num_iterations=step + 20, resume_step=resume_step, per_collector_stats={0: _snapshot(0, _Stage((step, step)))}, - learner_payloads={0: _payload(step, None)}, + learner_payloads={0: _payload(step)}, ) aggregator = AsyncTrainingStatsAggregator(learning_starts=0) first = aggregator.collect(source) assert first.scalars assert "learner/updates_per_s" not in first.scalars control.collector_steps += 10 - source.learner_payloads[0] = _payload(step + 10, None) + source.learner_payloads[0] = _payload(step + 10) second = aggregator.collect(source) assert second.scalars["learner/updates_per_s"] == 10.0 diff --git a/motrix_rl_builtin/tests/test_fastsac_sync_metrics.py b/motrix_rl_builtin/tests/test_fastsac_sync_metrics.py new file mode 100644 index 000000000..f9b31ae96 --- /dev/null +++ b/motrix_rl_builtin/tests/test_fastsac_sync_metrics.py @@ -0,0 +1,103 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Sync metric naming, optional observations and completed-batch timing semantics.""" + +from types import SimpleNamespace + +import pytest +from motrix_rl_builtin.fastsac.sync.metrics import metric_values +from test_fastsac_live_metrics import _train_sync + +from motrix_rl.log.collector_stats import CollectorStats + + +def _collector(*, mean_return=None, mean_length=None): + return CollectorStats( + collector_id=0, + episodes=0 if mean_return is None else 5, + mean_return=mean_return, + mean_episode_length=mean_length, + env_metrics={"height": 0.75}, + reward_terms={"alive": 0.5}, + diagnostics={}, + timings=(), + ) + + +@pytest.mark.parametrize("collect_s", [0.0, 0.125]) +def test_warmup_metrics_preserve_zero_timings_and_omit_missing_observations(collect_s): + values = metric_values( + warming=True, + collector=_collector(), + reward_mean=0.0, + buffer_size=6, + buffer_capacity=24, + collect_s=collect_s, + learn_s=0.0, + train=None, + ) + + assert values == { + "learner/replay_warming": 1.0, + "collector/reward_mean": 0.0, + "learner/buffer_size": 6, + "learner/buffer_capacity": 24, + "learner/learn_percent": 0.0, + "timing/collector/total_s": collect_s, + "timing/learner/total_s": 0.0, + "env/height": 0.75, + "reward/alive": 0.5, + } + + +def test_metric_labels_keep_recent_episode_means_and_phase_percent_semantics(): + values = metric_values( + warming=False, + collector=_collector(mean_return=10.0, mean_length=8.0), + reward_mean=2.0, + buffer_size=12, + buffer_capacity=24, + collect_s=0.25, + learn_s=0.75, + train={"qf_loss": 0.125, "actor_loss": -1.5}, + ) + + assert values["episode/recent_return_mean"] == 10.0 + assert values["episode/recent_length_mean"] == 8.0 + assert values["collector/reward_mean"] == 2.0 + assert values["learner/learn_percent"] == 75.0 + assert values["train/qf_loss"] == 0.125 + assert values["train/actor_loss"] == -1.5 + assert values["learner/replay_warming"] == 0.0 + + +def test_sync_timing_means_include_warmup_batches_and_reset_at_observation(tmp_path, monkeypatch): + from motrix_rl_builtin.fastsac.sync import train + + # First window: three warmup batches (collect=1, learn=0), then one + # training batch (collect=1, learn=4). Second window is all training. + ticks = iter([0, 1, 1, 2, 2, 3, 3, 4, 4, 8] + [8, 9, 9, 13, 13, 14, 14, 18, 18, 19, 19, 23, 23, 24, 24, 28]) + monkeypatch.setattr(train, "time", SimpleNamespace(perf_counter=lambda: next(ticks))) + sink, _ = _train_sync(tmp_path, monkeypatch, logging_interval=4) + records = {record["step"]: record["data"] for record in sink.records if record["kind"] == "scalars"} + + assert records[4]["timing/collector/total_s"] == 1.0 + assert records[4]["timing/learner/total_s"] == 1.0 + assert records[4]["learner/learn_percent"] == 50.0 + assert records[8]["timing/collector/total_s"] == 1.0 + assert records[8]["timing/learner/total_s"] == 4.0 + assert records[8]["learner/learn_percent"] == 80.0 + + +def test_sync_warmup_window_reports_zero_learner_time(tmp_path, monkeypatch): + from motrix_rl_builtin.fastsac.sync import train + + ticks = iter(range(100)) + monkeypatch.setattr(train, "time", SimpleNamespace(perf_counter=lambda: next(ticks))) + sink, _ = _train_sync(tmp_path, monkeypatch, logging_interval=2) + first = next(record["data"] for record in sink.records if record["kind"] == "scalars") + + assert first["timing/collector/total_s"] == 1.0 + assert first["timing/learner/total_s"] == 0.0 + assert first["learner/learn_percent"] == 0.0 diff --git a/motrix_rl_builtin/tests/test_fastsac_worker_logging.py b/motrix_rl_builtin/tests/test_fastsac_worker_logging.py index dd604bf08..a0ac5c458 100644 --- a/motrix_rl_builtin/tests/test_fastsac_worker_logging.py +++ b/motrix_rl_builtin/tests/test_fastsac_worker_logging.py @@ -76,6 +76,8 @@ def put_nowait(self, payload): monkeypatch.setattr(worker.checkpoints, "record_checkpoint_artifact", lambda *args, **kwargs: None) handshake = SimpleNamespace(report_ready=lambda *args: None, wait_for_start=lambda control: None) payloads = PayloadQueue() + ring = Mock() + ring.size.return_value = 0 worker.LearnerWorker( cfg=SimpleNamespace( device="cpu", trainer=SimpleNamespace(async_options=SimpleNamespace(learner_cpu_cores=None, idle_sleep_s=0)) @@ -96,12 +98,14 @@ def put_nowait(self, payload): resume_from=None, learner_device=torch.device("cpu"), handshake=handshake, - all_rings=[SimpleNamespace(size=lambda: 0)], + all_rings=[ring], weight_ipc=[], collector_ids=[], learner_data_queue=payloads, ).run() assert observed_steps == [resume_step, resume_step + 2, resume_step + 5, resume_step + 6] + # Sampling shared cursors is restricted to emitted windows, never every loop. + assert ring.size.call_count == len(observed_steps) first, first_update, aligned = [payloads.get_nowait() for _ in range(3)] assert not first["training_started"] and first["learn_ms"] == 0.0 assert first_update["training_started"] and first_update["metrics"] == {"loss": 1.0} diff --git a/wiki/design/index.md b/wiki/design/index.md index 9d8da795b..6315bb6a9 100644 --- a/wiki/design/index.md +++ b/wiki/design/index.md @@ -25,8 +25,8 @@ 定义 IMPACT/V-trace 目标、chunk/endpoint/timeout 契约、插件集成与 Go2 RSLRL 基准比较。 - [训练随机性与 Seed 所有权](./randomness-and-seeding.md) 定义 `ctx.rand` 的默认 Torch 流、训练根 seed 职责、SuperMimic 模型初始化/探索隔离,以及异步训练与 warm resume 的可复现性边界。 -- [通用训练终端与 APPO 接入设计](./training-console.md) - 共享 console 的恢复计时、缺失值、刷新与终端生命周期契约,以及 APPO 指标映射、worker 日志隔离和分层验收方案;与 TensorBoard/live metrics 保持独立。 +- [训练指标、日志与终端展示](./training-console.md) + 统一指标入口与 MetricsSink 协议、独立输出窗口、动态分组和摘要投影、阶段生命周期、计时与系统观测、worker 日志及 APPO/FastSAC 接入边界。 - [训练实时指标(Live Metrics)设计](./live-metrics.md) 设置 `MOTRIX_METRICS_URL` 后训练进程把 `motrix.metrics/v1` 记录同时写入 `run_dir/metrics.jsonl` 并批量推送给兼容的 ingest 服务:公开协议(环境变量、记录格式、状态机、幂等、重试规则)、规范 key 与 FastSAC/SKRL/RSLRL 映射、控制平面 `MotrixLiveLogger` 与生命周期接入、失败语义与测试策略。 - [Framework / Task 配置分离设计](./framework-task-split.md) diff --git a/wiki/design/training-console.md b/wiki/design/training-console.md index 601951a90..c4e70954e 100644 --- a/wiki/design/training-console.md +++ b/wiki/design/training-console.md @@ -1,214 +1,253 @@ -# 通用训练终端与 APPO 接入设计 +# 训练指标、日志与终端展示 ## 摘要 -为 [issue #199](https://github.com/Motphys/MotrixLab/issues/199) 提供共享训练终端方案:复用 `motrix_rl.console` 的会话、三视图与聚合工具,在框架层补齐恢复训练计时、缺失值、存储单位、刷新前节流、启动状态及 worker 日志隔离;APPO 只负责自身指标映射和主循环接入。 +训练观测通过 `TrainingMetrics` 一次记录,分发给持久化日志、终端面板或外部输出对象。各输出端独立聚合和调度;普通指标按名称自动分组,摘要和专用视图只改变展示,不改变日志中的指标身份。 -本文描述已实现的首版方案。第一期支持单 collector、父进程 learner,不引入监控线程,不改变算法、transport 协议、训练预算、checkpoint 格式或 TensorBoard/live-metrics 输出语义。算法及数据所有权见 [APPO 设计](./appo.md),外部指标协议见 [Live Metrics 设计](./live-metrics.md)。 +本文说明共享框架契约及 APPO、FastSAC 的接入边界。算法与数据所有权分别见 [APPO 设计](./appo.md)和 [FastSAC 异步训练设计](./fastsac-async-heterogeneous-trainer.md);HTTP/JSONL 记录格式、环境变量和交付语义以 [Live Metrics 设计](./live-metrics.md)为准。 -## 1. 结构与所有权 +## 1. 数据流与职责 ```text -APPO collector ── 现有 chunk + CollectorMetrics ──> APPO trainer(父进程 learner) - │ - APPO 指标映射与显示窗口 - │ - TrainingPanelStats - │ - motrix_rl.console.TrainingPanelSession - ├─ TTY:Overview / Timing / System - └─ 非 TTY:节流纯文本快照 - -APPO trainer ── 原有 logging.interval 分支 ──> TensorBoard / live metrics -worker stdout / stderr / logging / warnings ──> run_dir/logs/collector.log -worker failure ── 原有 error pipe ──> 父进程异常与日志路径 +环境 / collector / learner + │ 原始观测、完成回合、阶段计时 + ▼ +provider 指标映射与必要的跨 worker 聚合 + │ canonical key/value + ▼ +TrainingMetrics + ├─ 统一进度、最近回合统计、吞吐量 + ├─ TrainingLogger ── TensorBoard + MotrixLiveLogger + ├─ MetricsPanel ──── Overview / Timing / System 或纯文本 + └─ 外部 MetricsSink ``` -- `motrix_rl.console` 拥有渲染、刷新策略、终端输入和恢复,不认识 learner、chunk、Torch tensor 或算法配置。 -- `EpisodeWindow`、`RateTracker`、`TimingWindow` 保持普通 Python 数据工具;算法侧决定计数和观测边界。 -- APPO trainer 持有显示窗口和最后一份 learner metrics,每个已消费 chunk 只登记一次。共享 sampler 在显示到期时调用,不在每个 update 调用。 -- worker 输出隔离属于 `motrix_rl` 的进程运行机制,不属于 console,也不要求 worker 依赖 Rich。 -- APPO 不导入 builtin。启动状态表与日志尾部归共享 console;FastSAC 的 stats source/aggregator、启动 barrier、readiness gate 和监控循环仍归算法实现。 +| 组件 | 负责 | 不负责 | +| --- | --- | --- | +| `TrainingMetrics` | 统一进度、观测分发、共享 episode/throughput、事件分发 | 选择主输出端、关闭借用的 sinks | +| `MetricsSink` | 定义结构化接入协议 | 注册、继承框架基类或统一输出频率 | +| `TrainingLogger` | host 指标窗口、iteration 输出节拍、后端分发 | 设备热路径统计、终端布局 | +| `MetricsPanel` | 显示窗口、前缀分组、摘要投影、终端刷新 | 重新定义算法指标或另算吞吐量 | +| `TrainingPanelSession` | Console/Live、阶段切换、键盘与终端恢复 | 训练指标聚合和算法流程 | +| `CollectorStatsTracker` | 环境统计、最近回合、报告窗口和快照 | 环境 reset、timeout bootstrap、算法决策 | +| provider | 生产数值、定义 iteration、计时边界、指标命名及多 worker 聚合策略 | 重复实现上述通用机制 | + +日志模块位于 `motrix_rl.log`,终端渲染位于 `motrix_rl.console`。provider 不直接构造用于渲染的 `TrainingPanelStats`。 + +## 2. 统一记录 API + +### 2.1 进度与记录顺序 + +```python +metrics_logger = TrainingMetrics( + sinks=[training_log, panel], + initial_iteration=resume_iteration, + initial_env_steps=resume_env_steps, +) + +# 完成本轮采集 / 更新后: +metrics_logger.record(values) +metrics_logger.advance(iterations=1, env_steps=batch_transitions) +metrics_logger.flush(force=is_final) +``` -## 2. 共享 console 的最小补齐 +- `iteration` 是算法定义的主进度:APPO 为 learner update count,FastSAC 为完成采集批次或全批环境等价进度;不保证等于梯度更新次数。 +- `env_steps` 是累计环境 transition 数。APPO 使用 learner 已消费量,FastSAC 使用已采集量。 +- `advance()` 接收非负增量,不自动输出。异步父进程用真实观测减当前进度,重复 poll 的增量为零。 +- `record()` 只接受 mapping;标量是一个样本,iterable 是多个样本。generator 在分发前只物化一次,所有 sinks 得到相同样本。 +- `flush()` 是输出机会,不保证所有端都写出;每个 sink 自行判断是否到期。 +- 最终输出使用 `force=True`。`close()` 不猜测最终进度,也不代替日志的最终 flush。 -### 2.1 数据契约 +底层 TensorBoard/live 协议仍使用 `step` 字段,由适配器将 `iteration` 写入;checkpoint 和 IPC 已有字段不因此改名。 -扩展现有 `TrainingPanelStats`,不另建平行 snapshot/event 协议: +### 2.2 外部输出端 -| 数据 | 契约 | -| --- | --- | -| `iteration` / `total_iterations` | 累计进度;APPO 分别为 learner update count 与 max iterations | -| `initial_iteration` | 本次调用恢复后的起始进度,fresh run 为 0;供累计平均速率与 ETA 使用 | -| throughput 标签 | 速率单位固定显示 `env-steps/s`;consumed 口径由 steps 行的 `env-steps (consumed)` 标注表达,不把 learner consumed 描述为 collector sampled | -| episode mean | 接受 `None` 并渲染为 `n/a`;已有调用方使用的非有限占位值也渲染为不可用,而不是有效的 0 | -| `episodes` | 明确累计范围;APPO 为本次调用中随已消费 chunk 收到的完成 episode 数;TTY 与纯文本都显示 | -| timing group total | 允许对分组显式给出分母或无分母,避免只靠 collector/learner 字符串前缀推断比例 | +满足 `MetricsSink` Protocol 的对象即可接入,无需继承或注册: -总环境步数与 episode 数要出现在概览和纯文本中,不能只放在隐藏的 timing diagnostics 中。非 TTY 同样显示最后成功的 checkpoint 路径。 +```python +record(metrics) +advance(*, iterations=1, env_steps) +flush(*, force=False) +start(*, now) +event(name, *, iteration, data) +``` -恢复后的平均更新速率与 ETA: +sinks 应以相同恢复基线创建,各自配置聚合策略。dispatcher 自己持有权威进度,不从 logger 或 panel 反读。`start()` 或不关心的事件可由 sink 明确实现为空操作。 -```text -updates_this_invocation = iteration - initial_iteration -average_update_rate = updates_this_invocation / training_elapsed -ETA = max(total_iterations - iteration, 0) / average_update_rate -``` +`TrainingMetrics.event()` 默认使用当前 iteration;延迟收到的 checkpoint 通知可指定保存时的 iteration。`checkpoint(path, iteration=...)` 生成一次 `checkpoint_saved` 事件:logger 记录,面板显示提示,其他 sink 按自己的事件策略处理。只有文件保存及产物登记成功后才能发送该事件。 + +### 2.3 输出周期与采样周期 + +三种周期互相独立: + +| 周期 | 所有者 | 示例 | +| --- | --- | --- | +| 观测发布 | 数据生产方 | 设备指标窗口 drain、worker payload 发布 | +| 持久化输出 | `TrainingLogger` | 每 N iteration 写出 | +| 终端刷新 | `MetricsPanel` | 秒级 wall-clock 刷新 | + +不能用某个 sink 的 `due()` 决定所有观测的生产频率。FastSAC 的设备统计由明确的 `observation_schedule` 或 worker 发布节拍控制,只在边界转换为 host 数值;面板可以更频繁地刷新进度和最近观测,不因此增加 GPU 同步。 + +对于 FastSAC sync,昂贵标量只能在完成本轮、判断观测发布边界后提取,因此允许 `advance → 边界取值/record → flush`,不为形式顺序增加逐步 `.item()` 或空记录。 -没有正的可用速率时显示 `n/a`,训练完成时 ETA 为 0。滚动 FPS 与滚动 updates/s 使用 `RateTracker`,不以恢复前的历史计数除以本次耗时。共享 renderer 的迭代速率 fallback 也必须使用本次调用增量。 +刷新是协作式的:等待数据、更新完成和保存成功都是刷新机会。长时间编译、GPU update 或第三方阻塞期间不保证重绘;框架不为 UI 增加线程或 CUDA 同步,也不补发一串过期帧。 -不把 APPO 数据硬塞成 replay buffer。共享 renderer 必须在两种输出模式中尊重标签和单位;没有 storage 的算法可以不显示该行,但本期不增加 storage registry。 +## 3. 聚合、回合与速率 -### 2.2 刷新策略 +### 3.1 输出窗口 -在 `TrainingPanelSession` 增加公开的到期判断(例如 `due()`),由 `TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。 统一管理 monotonic deadline。只有到期时,算法侧才生成快照、计算显示窗口、采样系统信息并 `submit()`;不能先做昂贵采样,再依赖 `submit()` 丢弃输出。 +`TrainingLogger` 与 `MetricsPanel` 使用独立的 `MetricAccumulator`: -- 默认沿用秒级刷新;不新增算法专属的刷新配置体系。 -- update 完成、等待 ring 数据的轮询、启动等待的轮询都是协作式刷新机会,和 `logging.interval` 无关。 -- 每次刷新推进 deadline,不因训练较慢而补发一串历史帧。 -- 周期 checkpoint 成功、最终保存成功和退出允许强制刷新;强制刷新可复用最近系统样本,不必额外探测 GPU。 -- 无后台刷新线程时,单次长 learner update、compile/capture 或阻塞第三方调用期间无法保证秒级重绘。调用前显示阶段消息,返回后立即检查刷新;不为 UI 插入 CUDA 同步或拆分算法执行。 -- 等待期间可重新观测当前计数,使 rate 窗口反映停顿;不得再次登记 episode 或 timing 样本。 +- 创建时确定 key 的 `mean` / `last` 策略,未指定的动态 key 使用默认策略。 +- `mean` 按样本累计 sum/count,不是对每次调用的均值等权平均;`last` 保留最近样本。 +- 空 iterable 不产生观测。缺失值不伪造零或 NaN 占位,真实 NaN/Inf 由后端按其协议处理。 +- 一个输出端清空窗口,不影响另一个输出端。 -### 2.3 启动状态与生命周期 +`TrainingLogger` 的 `IterationLogSchedule` 支持跨阈值和恢复基线:异步观察从 19 跳到 23 仍可越过 interval=20 的边界;一次跳过多个区间只输出当前窗口,不补历史窗口。成功输出后清空并推进边界,空窗口不推进。 -`BootWorker` 只携带 spawn 时固定的事实:`name` 和可选 `log_path`。共享 `BootPanel` 是纯渲染器,负责状态表、日志尾部和固定尺寸布局,不创建 Console/Live,不判断进程健康或启动完成。 +多后端写入不是事务。某后端写入后另一后端失败,即使待输出样本保留,重试也可能重复已写入的数据。 -`TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。输入按类别划分:构造参数是 spawn 固定的结构(worker 身份与日志路径);`mark_ready(*names)` 与 `start()` 是单调状态事件(就绪集合、barrier 释放);`message(text)` 覆盖式更新阶段行;`refresh()` 按会话节奏重绘使日志尾部滚动。行内状态由渲染器从记录的事实派生。同一个 session/Live 展示启动画面;TTY 事件立即重绘,非 TTY 仅打印事件本身。创建 `metrics_panel()` 切换为训练阶段并让启动句柄退役,session 统一关闭终端资源。启动不构造假的 TrainingPanelStats,也不把算法的 barrier、超时或启动阶段枚举放进框架。保存成功经 `checkpoint(path)` 在训练帧显示;收尾阶段不提供独立消息 API,最终帧定格于 close。 +### 3.2 最近完成回合 -FastSAC 与 APPO 各自生成 worker 快照并控制启动到训练的切换;FastSAC 保留 ready barrier 和首份统计 gate。APPO 在现有等待轮询中刷新 collector 日志,阻塞 learner 构造期间不引入刷新线程。 +一个 episode 是某个环境行从开始到终止或截断的完整轨迹,不是 rollout chunk 或训练 iteration。未结束的轨迹可以跨越多个 chunk。 -APPO 的父进程就是 learner 进程:trainer 使用框架 `scoped_file_logging` 将 `motrix_rl_appo` 命名空间及其正常传播的子 logger 写入 `run_dir/logs/learner.log`,不向父终端重复传播;这只路由 Python logging,不拦截 stdout/native 输出。作用域退出恢复 handler/level/propagate,借用 handler 不关闭。异常写入文件后继续向外传播,ExitStack 保证即使 worker 清理失败仍关闭日志和面板。boot panel 展示 learner 状态行和日志窗格;最终训练统计强制刷新后才报告保存通知。 +`TrainingMetrics.record_episodes(returns, lengths)` 一次消费新增完成回合,维护所有并行环境最近 100 条记录;不足 100 条按实际数量计算,首次完成前不发布均值。输出: -APPO boot 阶段负责启动 collector/等待环境信息、构造并恢复 learner、发布初始权重和建立 transport。发送 CollectorConnection 后即创建 MetricsPanel/TrainingMetrics 并 start,然后进入训练循环;等待首个及后续 chunk、第一次 update 的编译/捕获均属于训练阶段,循环不再调用 boot API 或延迟创建指标对象。训练预算已满足的恢复调用也使用同一指标阶段完成最终保存,不走可空 logger 特例。 +- `episode/recent_return_mean` +- `episode/recent_length_mean` -`TrainingPanelSession.boot_panel(workers)` 绑定 worker 列表并返回 `BootPanelView` 阶段句柄。 在启动 collector 前打开,由上下文管理器或 ExitStack 保证覆盖正常结束、异常、启动失败及 Ctrl+C。清理 worker、writer、pipe、queue 的单项失败不能跳过终端恢复;不吞掉原始训练错误。退出阶段显示停止状态,最终关闭 Live 后再向外传播异常与 traceback。不为 console 安装全局信号处理器。 +最近回合窗口不会因日志或面板 flush 清空。累计完成数只在内部维护,不发布 `episode/completed`;恢复累计训练进度不会伪造未保存在 checkpoint 中的 episode 历史。 -`checkpoint(path)` 仅在文件保存和 manifest 登记均成功后调用;保留现有会话记住最近 checkpoint 的行为。保存失败不得显示成功通知;没有有效训练帧时也应能显示保存消息。 +return 必须来自原始环境 reward,不从 bootstrap 调整后的训练 batch 重算。原始性由 collector 的生产契约保证,输出层只统计收到的样本。 -### 2.4 统一指标入口 +### 3.3 吞吐量、训练起点与 ETA -`session.metrics_panel(total_iterations=..., initial_iteration=..., initial_env_steps=..., reductions=..., default_reduction=...)` 创建独立 MetricsPanel 阶段;`TrainingMetrics(sinks, initial_iteration=..., initial_env_steps=...)` 借用任意实现 MetricsSink Protocol 的对象,提供唯一 record(mapping)/advance/flush 入口。协议包含 record、advance、flush、start(now=...)、event(name, iteration=..., data=...),无需继承或注册。dispatcher 自己拥有权威进度,sinks 从同一恢复基线创建,不读取特定 logger 的进度;dispatcher 不查询任一 sink 的 due,也不指定主输出端;flush 只提供输出机会,各 sink 内部独立决定是否到期。设备→host 观测发布节拍由生产方明确控制,不由新增高频sink改变;系统采样使用独立 system_interval_seconds wall-clock间隔。一次 record 将相同样本送进两个独立的 MetricAccumulator,generator 只物化一次;日志按 iteration interval 输出,面板按 wall-clock cadence 输出,互不 drain。算法不再手工构造 TrainingPanelStats,APPO 私有 AppoConsole 删除。 +`TrainingMetrics` 是共享速率的唯一生产者: -MetricsPanel 阶段对象使用与 logger 对齐的 record/advance/flush,以及 start/due/checkpoint;session 不承载训练数据API,仅管理终端、boot_panel/metrics_panel阶段工厂与关闭。新phase激活后旧handle的事件、指标、采样、绘制均失效,关闭后也不输出。普通指标区完全由完整 key 自动分组:第一个 / 前为组名,剩余完整相对路径为组内label,无 / 归 ungrouped;不特判 train/reward/env 或合并 diagnostics,所有非空组动态生成,所有组使用相同数值格式规则。快照只保留 canonical metrics mapping,不再存专用字段或额外 metric_groups 缓存。episode/timing/system 的顶部摘要与专页只是额外投影。ThroughputSummary 是显式摘要配置,默认绑定 throughput/env_steps_per_s 和 throughput/iterations_per_s,面板只读共享观测,不重新计算速率。仅已显示的精确key从普通分组隐藏,throughput/custom等仍动态显示;配置为None时移除顶部吞吐卡且普通分组完整显示。EpisodeSummary 同理默认绑定 episode/recent_return_mean 和 episode/recent_length_mean,仅这两项投影顶部并隐藏普通行;episode/custom保留自动分组,episode_summary=None时无顶部episode卡且普通分组完整显示。canonical mapping始终保留全部keys。TimingView(prefix="timing/", overview=False) 显式将计时命名空间路由至专页,默认不在overview普通指标区生成timing组;overview=True可保留平铺。canonical映射和日志不变,顶部Collect/Learn摘要保留。非_s或不能构成树的同namespace指标在Timing专页附加区及纯文本detail区可见,不静默丢弃。timing 使用秒值、斜线层级和 _s 后缀;total_s 显式定义所在父路径总时长,不猜测子项总和,渲染时转毫秒。结构化系统硬件观测仍由框架采样,boot/checkpoint 保持事件接口。 +- `throughput/env_steps_per_s` +- `throughput/iterations_per_s` -计时报告携带 root/total_s 时定义该 root 的完整当前阶段集合:删除 latest/pending 中缺席旧阶段,共同阶段保留各自窗口 mean 样本;没有新 root 时保留整树,不拼入过期子阶段。多 learner 概览对 learner[N]/total_s 有效时长取均值,不相加并发时长。 +面板直接读取这些值,不维护第二套速率计算。等待期间,dispatcher 按秒级重新观测当前计数,使停顿反映到滚动速率;不重复登记 episode 或计时样本。 -TrainingMetrics 统一根据进度生成 throughput/env_steps_per_s 与 throughput/iterations_per_s,记录到两端而非只在面板生成;等待期间flush按秒级重新观测当前计数,使停顿速率能衰减至零,面板和日志消费同源数值。start() 在 boot/handoff 完成后按当前观测计数重锚定训练 elapsed 和速率,保留恢复累计计数与缓冲指标,排除 spawn/compile/barrier 时间。 +`start()` 按当前计数重锚定训练时钟和速率,排除 boot/compile/barrier 等启动等待,保留累计进度与待输出观测。ETA 优先使用有效迭代速率;fallback 只使用本次调用的 `iteration - initial_iteration` 和训练 elapsed。无正速率时 ETA 不可用,完成时为零。 -TrainingMetrics checkpoint(path, iteration=...) 生成统一 checkpoint_saved 事件并分发所有sink;logger写事件,MetricsPanel显示提示,其余sink可明确忽略。事件默认dispatcher当前iteration,保留延迟历史iteration;关闭资源仍由 trainer 所有。TrainingPanelStats 是框架渲染快照,不再公开 submit;MetricsPanel 内部提交渲染结果给 session 的私有终端入口。session.close 强制输出当前 metrics 阶段未刷新的数据,当前若为 boot 不生成假训练帧。 +## 4. 终端阶段与展示 -## 3. APPO 指标映射 +### 4.1 阶段对象与所有权 -APPO 增加一个小型的显示状态组件,建议放在实现包的 `console.py`。它仅接受明确类型的 counters、CollectorMetrics、Python learner metrics 和 phase durations,复用公共窗口并构造 TrainingPanelStats;不持有 learner、writer 或 worker,不发送 IPC,不重建一套通用 trainer abstraction。 +```python +with TrainingPanelSession.open(title=..., screen=True) as session: + boot = session.boot_panel(workers) + boot.message("starting workers") + boot.mark_ready("collector") -| 显示项 | 来源及含义 | -| --- | --- | -| updates | `learner.update_count` / `cfg.max_iterations`,累计更新次数 | -| consumed env steps | `learner.global_step`,每次 update 消费 T×N;不乘 epochs/minibatches | -| FPS | rolling delta(global_step)/delta(monotonic time),标明 consumed | -| updates/s | rolling delta(update_count)/delta(time) | -| elapsed / ETA | 进入可训练主循环后本次调用的时间;启动状态单独报告启动等待 | -| recent return / length | `record.returns` / `record.lengths` 输入独立 EpisodeWindow,最近 100 个已完成回合 | -| recent episode window | 内部维护本次调用完成数与最近窗口,不发布累计完成数指标;不假装恢复 checkpoint 中不存在的 episode 历史 | -| learner scalars | 显式映射现有 policy/value loss、entropy、KL、learning rate、policy std、grad norm;保留生产者的原有聚合语义 | -| queue | `ring.size()` / `cfg.queue_chunks` 为瞬时 chunks 快照,仅在纯文本 diagnostics/timing 场景按需显示;面板不再有通用 buffer 行 | -| weight lag | 现有 `record.published_version - record.weight_version`,标明 collector chunk 的版本观测,不称为父进程实时最新滞后 | -| transport / device | 已解析的 transition transport、weight transport 与 learner/collector device 记录在训练启动日志,不占面板 diagnostics;面板 diagnostics 只保留随训练变化的 weight lag | -| collector timing | `record.latency_s`,一整个 rollout chunk 的采集 host wall duration,不含之后的 publication/backpressure | -| learner timings | 现有 ingest、optimize、weight publish host wall duration;明确单位与样本边界 | + panel = session.metrics_panel( + total_iterations=max_iterations, + initial_iteration=training_log.iteration, + initial_env_steps=training_log.env_steps, + reductions=training_log.reductions, + default_reduction=training_log.default_reduction, + ) + # panel 作为 MetricsSink 接入 TrainingMetrics +``` + +session 仅拥有终端和当前阶段身份。创建新阶段后,旧 handle 不再更新、采样或绘制;关闭后也不输出。`session.close()` 强刷当前 metrics 阶段的待处理数据后停止 Live;当前若为 boot,不生成假的训练帧。日志最终 flush 仍由 trainer 负责。 + +`BootWorker` 只包含固定的显示名称和可选日志路径。`BootPanelView` 记录就绪集合、启动状态和阶段消息,`refresh()` 节流读取 worker 日志尾部;它不启动进程、不判断健康、不控制 barrier。底层 `BootPanel` 只渲染固定尺寸布局。 -每个 record 在 learner 成功完成该 batch 后登记一次。原始 episode return 已在 collector 中维护,不从经过 timeout bootstrap 的 batch reward 重算。 +TTY 中使用 1/2/3 切换 Overview、Timing、System;非 TTY 使用节流纯文本输出,不输出交互式 redraw。两种模式都显示最近成功保存的 checkpoint 路径。 -### 3.1 时间窗口与并发语义 +### 4.2 自动分组与显式投影 -- EpisodeWindow 独立于日志分支;首次完成 episode 前显示 `n/a`,已有回合后在新回合未完成期间保留最近窗口均值。 -- TimingWindow 按显示间隔累计、生成均值后 reset。没有新 timing 样本时显示上一份有效结果并保留样本边界说明,不用 0 假装测量结果。 -- learner 的现有 update duration 包含 optimize 与 publish,但不含 ingest。若显示父进程 ingest+optimize+publish 之和,应明确命名为 learner processing host wall,不把它混同为完整 loop wall。 -- collector 与 learner 分组并列,绝不把两者相加解释为串行 update 时间,不显示跨进程总 share 或伪造 learn_percent。 -- 面板通过 `timings: tuple[TimingNode, ...]` 接收计时森林。每个节点包含 `name`、`duration_ms: float | None` 和 `children`;节点耗时由生产方显式提供,不默认对子节点求和。collector 与各 learner 是独立根节点,不创建跨并发进程的合计。 -- SHARE 使用直接父节点的耗时作为分母;父节点耗时缺失或为零时不显示子节点占比。纯组织节点的耗时为 `None`,不借用祖先分母。明细可以不完整或重叠,不强制占比合计为 100%。 -- 计时树只在面板刷新时由计时窗口快照构造;训练热路径继续累计原有数值,不重建展示对象。普通文本与 Rich 面板均递归渲染同一结构。 -- 所有计时都是现有 host wall/enqueue 边界,不能声称为 GPU kernel 精确执行时间;不增加 CUDA events 或同步用于面板。 +普通指标只保存一份 canonical mapping,在渲染边界按名称分组: -### 3.2 日志窗口完全独立 +```text +train/policy/loss → train 组 / policy/loss 标签 +collector/0/ring_fill → collector 组 / 0/ring_fill 标签 +score → ungrouped 组 / score 标签 +``` -APPO 的日志输出经共享 `TrainingLogger`(TensorBoard + live,与 FastSAC 同一入口),TensorBoard 不可用时降级为 live-only。TrainingLogger 直接拥有 host 聚合窗口,创建时通过 `reductions` 定义各 key 的聚合方式,未列出的动态 key 使用 `default_reduction="last"`。`record(metrics)` 统一接收 mapping,标量为单个样本、iterable 为多个样本,不提供单 key 重载或 record_many;只累积、不输出,不重复指定策略;mean 按样本累计 sum/count,last 保留最新值。空样本不产生输出;策略在构造时复制并校验,不随窗口清空而改变。进程日志工具统一位于 `motrix_rl.log.process_logging`。创建时 initial_iteration/initial_env_steps 定义恢复基线;`advance(iterations=1, env_steps=...)` 只累加非负增量,不自动输出。同一轮所有输出共享只读 iteration/env_steps 上下文;异步父进程按真实观测减当前 logger 计数推进,重复 poll 的增量为零。`flush(force=False)` 按内部 iteration 跨阈值判断 interval(非正 interval 沿用每步输出),强制输出由调用方决定,不依赖算法 max_iterations;成功输出后清空窗口,空窗口不重复发送。后端 `_emit()` 为私有实现,所有标量都通过 record/flush。统一执行顺序为完成本轮工作 → record普通观测 → advance → due时补充昂贵窗口观测 → flush → checkpoint事件。每个sink拥有自己的输出节拍;FastSAC设备/collector昂贵观测用独立observation_schedule按发布interval或最终边界drain,输出端只消费最近观测。FastSAC sync允许先advance,再按观测发布节拍record该边界观测;不为形式顺序增加逐步 GPU→host 同步或空 record。常规 flush 不 force,最终输出才 force。FastSAC 已聚合 payload 按 last 记录,禁止对 worker 窗口均值再平均。系统指标按构造时 live_only_prefixes=("sys/",) 路由,不在 flush 传后端参数;缺失指标不记录,真实 NaN/Inf 保留,取消占位NaN和名单协议。event 默认当前 iteration,也可显式覆盖历史事件 iteration(例如延迟到达的 checkpoint 通知)。close 仅关闭后端,不猜测最终 step,不隐式输出尚未 flush 的样本。 +所有非空组自动生成,组名不决定颜色、精度或正负号;不固定合并 collector、learner 等角色。组名和 label 按 literal 文本显示。新增 group 无需修改 renderer。 -APPO 仅保留接收 learner_metrics、CollectorMetrics、StageTimings 与 queue_depth 的无状态 metric_values 映射,不构造中间 observation/state/snapshot 包装。TrainingMetrics.record_episodes(returns,lengths) 一次消费新增完成回合,在共享的 EpisodeWindow 维护最近100回合与累计完成数,随后把同一快照送入日志/显示窗口;该最近回合窗口不因任一输出 flush 清空,恢复进度也不伪造历史回合。learner/env/diagnostics 直接通过 record(mapping) 分发,不另存算法侧 latest 缓存。episode/recent_return_mean、episode/recent_length_mean 是最近回合均值(不足100按实际数,未完成回合不纳入),累计完成数仅内部维护,不再发布 episode/completed 或在面板重复显示;删除旧 Train/mean_* 区间均值语义。train/*、env/*、collector/weight_lag、collector/queue_depth 两端覆盖和命名一致,不再显示侧过滤 learner 白名单。 +| 配置 | 默认行为 | 关闭或覆盖 | +| --- | --- | --- | +| `ThroughputSummary` | 顶部投影两个 `throughput/*` key | 可自定义 exact keys;`None` 关闭卡片 | +| `EpisodeSummary` | 顶部投影两个 recent episode 均值 | 可自定义 exact keys;`None` 关闭卡片 | +| `TimingView` | `timing/` 路由至 Timing 专页,Overview 不平铺 | 可改 prefix;`overview=True` 保留平铺 | -统一 timing/* 秒值映射定义 rollout、ingest、optimize、weight_publish、update、processing;update 包含 optimize 与 publish 的完整实测范围,processing=ingest+update。日志与显示均求各自输出窗口内均值,console 仅转毫秒并渲染树(processing 的 children 为 ingest/update,update 的 children 为 optimize/publish)。两个窗口不互相清空,窗口边界不同时数值可不同但定义相同。logger 对 latest/recent snapshot 采用 last,只有 timing keys 采用 mean,不对 recent mean 再求均值。最终迭代强制输出。使用 TrainingLogger 的 provider 同步迁移至单一 mapping record/flush 入口,不保留公开即时输出兼容方法。 +摘要只隐藏实际投影的精确 key,不隐藏整个 group:`throughput/custom_rate`、`episode/custom` 等仍正常展示。关闭摘要时对应普通组完整显示。canonical metrics 和日志内容不受这些配置影响。 -异步轮询可能跳过 step 的整数倍。通用 `IterationLogSchedule` 从 initial_iteration 后的下一个区间开始,达到或跨过阈值输出一次,再将阈值推进至当前 step 之后;重复观测同一步不补发历史窗口。TrainingLogger 的 host 窗口复用该节拍,只有成功输出后推进;FastSAC 父进程 aggregator 只生成当前观测,不拥有日志 schedule 或 TrainingLogRecord;重复快照按 last 记录,不增量平均。worker 的观测发布节拍独立于父日志节拍,保留初始、首update和最终报告。FastSAC 面板使用共享 RateTracker 和 monotonic 时间,首秒按真实采样跨度计算速率而非人为限制分母为一秒。 +Timing 专页显示完整树和直接父节点 SHARE;不能构成时长树的同 namespace 指标进入附加区,纯文本也保留 detail 输出。System 专页及 System Health 卡片使用结构化硬件观测。 -系统采样由 `motrix_rl.system_metrics.SystemSampler` 生成 UI 无关的 `SystemStats`;面板和 `motrix_rl.log.system_metrics.system_scalars` 各自映射同一观测,不以 TrainingPanelStats 作为日志输入。TrainingMetrics(system_sink=logger) 显式启用并只向该已连接sink发送系统采样,不再广播给面板;省略system_sink即关闭系统日志采样,无额外system_logging布尔。MetricsPanel自身采样只负责System Health结构化卡片,避免普通sys组重复;用户显式record的sys/custom等仍正常广播、动态分组,不由渲染器隐藏。保持 provider 的输出范围:FastSAC 的 sys/* 仅发 live,APPO 不自动新增系统日志指标。 +## 5. 计时契约 -设备侧 `TensorMetricWindow` 在创建时确定 mean/range 策略,在原设备累计 sum/count/min/max,drain 才转换 Python 标量;不得用每 update 的 float()/item() 替换而引入逐步 GPU 同步。FastSAC worker 的阶段时长使用共享 TimingWindow,输出节拍使用 IterationLogSchedule,首份/首 update 完成通知显式强制发送。 +### 5.1 指标路径与单位 + +计时指标使用秒值、斜线路径和 `_s` 后缀;面板渲染时转毫秒: + +```text +timing/learner/total_s → learner 的显式总时长 +timing/learner/update_s → update 的显式时长 +timing/learner/update/optimize_s → update 下的 optimize +``` -FastSAC 指标按角色分组:collector/policy_lag(max)、collector/ring_fill(slots总和)、collector/{i}/policy_lag与ring_fill(多collector)、learner/weight_version、learner/weight_publishes_per_iteration、learner/updates_per_s、learner/replay_warming;后者是replay预热而非进程启动/编译。统一吞吐只由TrainingMetrics生成throughput/*,不再重复生成diagnostics/collector/env_steps_per_s。同步即时平均reward使用collector/reward_mean;取消async/runtime/diagnostics这三种顶层用途分类。ring slots与APPO queue chunks单位不同,不做同名合并。 +`total_s` 定义所在父路径的耗时,不是子项名称。父时长必须显式提供,缺失时不对子节点求和;SHARE 使用直接父节点的正时长,父时长缺失或为零则不显示占比。 -FastSAC sync 的 step 统一为完成采集批次数,env_steps=step*num_envs,interval 与最终输出使用完成批次语义,不保留旧零基日志偏移。恢复和 warmup/refill 的策略仍由算法决定。 +collector 与各 learner 是独立并发根,不相加成串行总时长或跨进程占比。多 learner 概览对各显式有效 total 取均值,详细树保留 rank 名称。 -### 3.3 Collector 快照契约 +携带 root/total_s 的完整报告定义当前阶段集合:新报告缺席的旧阶段从 latest 和 pending 中移除,共同阶段保留当前显示窗口中的 mean 样本;没有新 root 报告时保留整树。 -`motrix_rl.log.collector_stats.CollectorStats` 是可重复读取的最新观测快照,不是 APPO 每 chunk 消费一次的增量记录。`episodes` 是本次 collector 调用的累计完成数,mean_return/mean_episode_length 来自生产方最近回合窗口,不能用累计数作为均值权重;无回合样本用 None,真实非有限观测保留。reward_terms/timings 为报告窗口,env_metrics/diagnostics 为最新值。生产方创建独立映射副本,跨进程发送完整 dataclass 与 TimingNode 树。 +所有计时反映已有 host wall/enqueue 边界,不是精确 GPU kernel 执行时长。显示不额外插入 CUDA events 或同步。 -`CollectorStatsTracker` 维护最近 N 个完成回合与累计计数,reward terms 按报告窗口求均值,timing 每次 `record_timings` 表示一个成功采集批次(未执行阶段显式记零)。snapshot 清空 reward/timing 窗口但保留最近回合、累计计数与最新 env/diagnostics;绑定的 PerfTimingWindow 将原生 profiler 子树合入快照,不二次平均、不经过路径字典覆盖参数。collector 提供普通数值及明确的 core Perf 对象,core 不读取算法私有字段。 +### 5.2 core Perf 与设备统计 -`CollectorStatsTracker` 构造时绑定 collector_id、num_envs/device 与最近回合窗口长度;record_step 接收原始 rewards、显式 episode_done、reward_terms 和环境 metrics,统一维护逐环境 return/length、完成回合窗口及报告窗口。完成行向量化导出后清零;reset(env_ids) 只丢弃指定未完成轨迹,不改变累计完成数/最近窗口,不 reset 环境、不 bootstrap、不读取具体 env。snapshot 不清逐环境未完成轨迹。FastSAC 负责从结果中提取 terminated|truncated 和原始 reward,再提交观测。 +`ArrayEnv` 基类拥有 `Perf`。`PerfTimingWindow` 明确借用并独占该 profiler 的报告窗口:start 清历史并 enable,snapshot 消费 step 子树后 reset,close 恢复原 enabled 状态;这些操作要求没有活动 scope,不能让多个消费者相互 reset。 -启用 `collect_episode_deltas=True` 后,tracker 独立积累完成回合原始样本,`take_episodes()` 消费一次;snapshot/reset 均不消费此增量。APPO 使用增量构造 chunk sideband,在父进程共享状态维护最近100完成回合;环境 metrics 仍在 chunk 末尾归约一次;每步 reward_terms 在原设备 FP32 累积本 chunk 的逐环境均值,chunk 末尾才转 Python 标量并清空。CollectorMetrics 同时携带 env_metrics 与 reward_terms,父侧统一映射 env/* 与 reward/*,两种输出均可见,不额外增加逐步设备同步。reward 分项为环境已加权贡献,不承诺与 bootstrap 后 batch reward 或 episode return 相同。默认快照模式不保存无限增长的增量历史。 +`PerfNode` 直接递归转 `TimingNode`,保留深层 scope 及各自均值;环境子阶段挂入 collector 自测 env_step 下,父分母仍是外层 wall 测量。`timing_metrics()` 再将树直接投影为 canonical 秒值,不经点分路径字典往返。 -FastSAC 保留等权 collector 均值、episodes 求和、policy_lag 取最大值的现有策略;policy_lag 位于 diagnostics,不成为 core 的算法专属字段。缺失均值保持 None,日志不输出对应 key;面板显示 n/a,真实非有限值不作为缺失占位处理。快照重复读取不得重复累积 episode 或进入增量 mean 日志窗口。 +`TensorMetricWindow` 在原设备 FP32 累积 detached 标量,创建时配置 mean/range 策略;动态 reward key 可显式配置默认 mean。只在 drain 边界转 Python 标量,不能用逐 update 的 `.item()` 代替。`TimingWindow` 则维护普通阶段时长的独立 sum/count。 -### 3.4 统一环境 profiler 采样 +## 6. 系统观测与进程日志 -ArrayEnv 在基类中无条件拥有 core Perf,RL 适配器使用明确 ArrayEnv 类型和直接 perf 属性。`PerfTimingWindow` 借用 Perf 并独占其报告窗口:显式 start 清空历史并 enable,采样 snapshot 的 step 根后 reset,close 恢复原 enabled 状态;不在活动 scope 内操作。该窗口不与其他 reset 消费者共享同一 Perf。 +### 6.1 系统指标路由 -PerfNode 直接递归转 TimingNode,ns 转 ms,保留所有层级与显式父耗时。环境 step 子阶段挂入 collector 自测 env_step 下,保持外层 wall duration 为该父节点分母,不将各子阶段相加或丢弃深层节点。无 step 样本时不伪造子节点。learner IPC 直接传 TimingNode tuple,取消嵌套字典 total 保留键和算法私有树转换。 +`SystemSampler` 生成 UI 无关的 `SystemStats`。面板使用自己的 sampler 生成硬件卡片;`TrainingMetrics(system_sink=training_log)` 另按 `system_interval_seconds` 采样,只把生成的 `sys/*` 发给该已连接 sink,不广播到普通 console 指标组。不指定 system_sink 即关闭系统日志采样。 -## 4. Worker 输出隔离 +FastSAC logger 将 `sys/` 配置为 live-only,APPO 不自动新增系统日志。用户显式 record 的 `sys/custom` 仍正常分发和展示,不由 renderer 隐式过滤。 -FastSAC 已有 spawn 继承 stdout/stderr 文件描述符、child 内 logging 配置的两段机制。提取真正通用的文件输出能力到 `motrix_rl`,由 Worker 启动路径复用;FastSAC 原调用方同步切换到定义模块,不保留同一 PR 中间版本的 wrapper。 +### 6.2 worker 输出与错误 -建议在 `WorkerRuntime` 增加可选日志文件路径,并由 Worker.start/bootstrap 协同处理: +`WorkerRuntime.log_path` 配合两阶段隔离:父侧在 spawn 的短作用域重定向 fd 1/2,覆盖子进程重导入输出;child bootstrap 在运行初始化前配置日志和 fd,捕获 Python print、stderr、warnings 及 native 输出。父侧作用域立即恢复自身 fd。 -1. 父进程建立日志目录,在 Process.start 的短作用域内让子进程继承日志 fd,覆盖 spawn 重导入 Torch/simulator 时的 Python 和 native 输出。 -2. 重定向前后 flush 父进程 Python 输出流,finally 中立即恢复父进程 fd;此机制修改进程全局 fd,必须串行启动,不能声称线程局部重定向。spawn guard 内不渲染 UI;其他父进程线程在该极短区间的输出也可能进入 worker 日志,这一限制需文档化。 -3. child bootstrap 在 placement/runtime 初始化前配置 logging 及 fd 1/2,后续 stdout、stderr、warnings、traceback 与 native 输出都留在文件。所有自有 fd 都有明确关闭路径。 -4. APPO 给 collector 传入固定日志路径;错误通道由 Worker.start 创建和管理,bootstrap 捕获初始化/run 异常,发送有界 UTF-8 摘要后重新抛出,完整 traceback 留在进程日志。WorkerHandle.check 非阻塞并缓存报告,未收到报告时仍依据非零 exitcode 报 WorkerError;正常退出由算法判断是否提前结束。WorkerHandle.close 在退出后释放进程与接收端,start 失败关闭两端;startup/metrics/stop 的算法协议不混入错误通道。 -5. FastSAC async 的 CollectorWorker/LearnerWorker 同样继承框架 Worker;父侧为各 rank/collector 传 WorkerPlacement 和 WorkerRuntime,bootstrap 统一日志隔离、NUMA 和派生 seed。父侧通过 handle.check 消费错误并发送 worker_crashed 事件,错误日志路径指向已有 logs 文件,不另设 error_queue 或重复 async_errors 文件。startup barrier、DDP、ring/weight slots 与全组停止策略仍归 FastSAC。正常结束/启动失败均回收已启动 handles;启动一半失败也必须释放 barrier 和停止同组。 +fd 重定向是进程全局行为,worker 必须串行启动;guard 中不绘制面板,其他父线程在该短区间的输出也可能进入 worker 文件。普通 worker 不依赖 Rich。 -6. 父进程使用同一个 console 的受控输出显示重要 warning/status。关闭 Live 后正常输出最终异常。不引入日志转发队列或日志尾部线程。 +错误通道由 `Worker.start()` 创建。bootstrap 捕获异常、发送有界摘要后重新抛出;完整 traceback 保留在进程日志。`WorkerHandle.check()` 非阻塞、缓存失败,无报告时仍按非零 exitcode 报错;正常退出是否提前由 provider 判断。退出后 `close()` 释放进程和接收端,启动失败清理两端。 -警告不再散落到终端,但仍完整可查:启动阶段显示 collector 日志位置,失败时再次给出位置和 error pipe traceback。非 TTY 也保留日志文件和失败摘要,不静默丢弃诊断。`logging.captureWarnings` 不作为必要条件,默认 warnings stderr 本身已写入文件;是否使用它只影响日志格式。 +父进程自身作为 learner 时使用 `scoped_file_logging` 路由明确的 Python logger namespace,作用域退出恢复 handlers、level、propagate;不拦截 stdout/native,也不关闭借用的 handlers。 -## 5. 实施边界与顺序 +## 7. Provider 接入 -1. 补齐共享 panel 的 resume ETA、None/nonfinite 显示、env steps/episodes、storage labels、timing 分母控制、due/status 和纯文本 checkpoint。 -2. 提取 worker 文件日志机制,接入 WorkerRuntime;同步迁移 FastSAC 对通用 helper 的调用,保留其私有 startup UI。 -3. 实现 APPO 显示状态与父进程 hooks:启动状态、等待轮询、update 后登记、到期采样、保存成功通知和全生命周期清理。 -4. 在 APPO 使用说明中描述视图切换、consumed FPS、日志位置与非 TTY 行为;APPO 算法设计链接本文,不重复定义共享契约。 -5. 按下节验证后再考虑让其他 provider 采用同样入口。本期不强制改造 SKRL/RSLRL/SuperMimic,也不搬迁 FastSAC 的私有聚合架构。 +### 7.1 APPO -本方案不新增事件总线、provider registry、监控 daemon、worker-grid、日志 tail、通用 collector 协议或 UI 专用 transport 字段。设计确认后再建立带 TODO 的实施计划,随后进入编码。 +- collector 子进程生成 transition chunk 和一次性 `CollectorMetrics`,父进程是 learner。 +- boot 完成边界是环境信息、learner、初始权重和 transport 已就绪;进入训练循环前创建指标阶段并 start。首个 chunk 等待和首次 update 都属于训练,不在循环内调用 boot API。 +- 每个成功消费并更新的 chunk 只登记一次 episode delta。reward terms 在设备上按 chunk 累积,末尾归约并清空;env metrics 使用 chunk 最后状态。sideband 先于 ring 发布,父进程按顺序一对一消费。 +- APPO 只保留 `metric_values()` 无状态映射:train/env/reward、weight lag、queue depth 与计时。共享框架拥有最近回合与双输出,不保留算法私有 state/snapshot 包装。 +- learner processing=ingest+update,update 是包含 optimize 和 weight publish 的实测范围。日志和显示各自对该范围求窗口 mean。 -## 6. 验证 +### 7.2 FastSAC -### 快速契约测试 +- sync 的无状态 `sync.metrics.metric_values()` 负责命名;collect/learn 通过 `TimingWindow` 每成功 batch 记录,warmup learn 显式为零。设备窗口仅在 observation 发布边界 drain。 +- async 的 `AsyncTrainingStatsSource` 拥有队列和 latest 快照;aggregator 只维护更新速率、版本差分和 warmup 转换;纯 `metric_values()` 执行算法聚合,不缓存 source 配置或承载日志节拍。 +- `LearnerStatsPublisher` 管观测窗口、首次/首 update/对齐/最终 partial 发布,不持有 agent/learner。队列满时按既有非阻塞策略丢弃完成窗口。checkpoint 走独立事件,不在统计 payload 重复传路径。 +- collector 使用可重复读取的 `CollectorStats`:最近回合均值与累计完成数不是同一窗口,不能用累计数加权最近均值;reward/timing 报告窗口在 snapshot 清空,latest 环境指标保留。APPO 的 chunk episode delta 不等同于这种快照。 +- 多 collector 聚合维持等权均值、policy lag 最大值等算法策略。计时在 canonical key 上聚合,已聚合的 worker 均值在父输出端使用 last,不二次平均。 +- collector/learner 任务继承 Worker;DDP、slot handshake、startup barrier、首份数据 gate 和同组停止仍归 FastSAC。handoff 后按当前计数 start,排除 worker 初始化时间。 -- panel:fresh/resume 的 ETA 与速率 fallback、完成时 ETA、缺失回合、env steps 与 episode count、queue labels/units、并发 timing 无跨进程 share、纯文本 checkpoint。 -- cadence:假 monotonic clock 验证日志 interval 不影响显示、未到期不调用 system sampler、等待轮询可更新状态、强制通知不改变日志窗口。 -- APPO 映射:使用 CollectorMetrics 与 Python scalars 验证 consumed counter、resume baseline、raw episode、窗口重置、无重复 episode 登记与现有 learner key 映射。 -- lifecycle:正常、启动失败、learner 异常、保存失败、KeyboardInterrupt 均恢复 terminal;成功保存才更新 checkpoint,重复 close 安全。 -- 日志不变量:同一固定输入和 logging.interval 下,是否刷新面板不改变 writer/context.metrics 收到的 records、tags、step 与 env_steps。 +普通指标按职责归组:`train/` 是优化指标,`collector/` 是采集状态,`learner/` 是更新、buffer、权重发布及 replay 预热状态;`reward/`、`env/` 保留环境观测。没有额外的 async/runtime/diagnostics 顶层分类。ring fill 的 slots 与 APPO queue depth 的 chunks 是不同单位,不以改名伪装成同一指标。 -### 进程集成与人工验收 +## 8. 验证边界 -- spawn 子进程在 import 阶段和 run 阶段分别产生 Python print、stderr、warning、logging、native fd 输出及异常,验证进入日志文件,父终端恢复,错误信息仍可诊断;此项属于 integration。 -- CPU CartPole 短训练覆盖首次启动、正常退出、checkpoint、warm resume;记录实际命令与结果。 -- 非 TTY 重定向验证节流和无 ANSI redraw 控制序列,并检查 worker 日志与最终失败摘要。 -- 真实 TTY 人工切换 1/2/3,分别在启动等待和训练期间 Ctrl+C,确认回显、光标和输入模式恢复。 -- CUDA 仅在真实硬件执行后报告支持证据,记录设备、执行模式、transport、命令及结果;不能以静态检查、CPU 冒烟或 skip 代替。 +低成本测试覆盖聚合权重与清空、独立 sink 节拍、恢复进度、空样本/真实非有限值、动态分组及 literal 名称、摘要精确隐藏、计时树与并发分母、阶段退役、非 TTY checkpoint 文本、资源失败时的清理。 -训练日志公开 API 使用 iteration 表达算法主进度,env_steps 表达 transition 数。TensorBoard/live 的底层 step 字段由后端适配保留,checkpoint/IPC 原有 step 字段不受此命名迁移影响。 +进程集成覆盖真实 spawn、原始 episode/timeout 分流、reward sideband、checkpoint 和 warm resume。真实 TTY 的键盘切换/Ctrl+C恢复、GPU/NCCL 多 learner、CUDA IPC、compile/capture 与训练性能需在相应环境单独验收;快速测试、静态检查或 skip 不能替代这些证据。