Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions bench/bench_live_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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.")
Expand Down
9 changes: 5 additions & 4 deletions motrix_rl/src/motrix_rl/console/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -23,14 +23,15 @@
)

__all__ = [
"BootPanel",
"BootWorker",
"EpisodeWindow",
"EpisodeWindowStats",
"PanelClock",
"PanelSystemSampler",
"PanelSystemStats",
"RateTracker",
"ScalarWindow",
"TimingWindow",
"TimingNode",
"TrainingPanelSession",
"TrainingPanelStats",
"emit_training_panel",
Expand Down
156 changes: 156 additions & 0 deletions motrix_rl/src/motrix_rl/console/boot.py
Original file line number Diff line number Diff line change
@@ -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)
41 changes: 1 addition & 40 deletions motrix_rl/src/motrix_rl/console/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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),
)
Loading