Robotics
LeRobot
gr00t
act
pi05
training
bimanual
pl2m-training / scripts /tb_logger.py
minssuung's picture
Add PL-2 M training code
acba5e6 verified
Raw History Blame Contribute Delete
7.9 kB
#!/usr/bin/env python3
"""TensorBoard scalars for both trainers, without patching either one.
# attach to a run that is already going (no restart, no lost progress)
./scripts/tb_logger.py --policy act --log ~/caring/logs/act.log --out ~/caring/tb/act
tensorboard --logdir ~/caring/tb
WHY NOT PATCH THE TRAINER
-------------------------
lerobot ships only a wandb logger, and Isaac hardcodes
``report_to="wandb" if use_wandb else "none"``. The previous answer to that was
``tb_patch.py``: a script that rewrote five anchors inside
``lerobot_train.py`` in the installed checkout. It worked, and it was one more
piece of configuration living outside version control that a container rebuild
would silently take with it.
It is also unnecessary. Both trainers already print every scalar worth plotting,
and ``train.py`` already reads that stream line by line for early stopping. So
the numbers are parsed out of the log instead — no source edits, one code path
for both families, and it works equally well tailing the log of a run that is
already in flight.
STEP AXIS
---------
Neither log line carries an unambiguous global step: ACT prints ``step:54K``
(rounded) and GR00T prints no step at all. Both, however, log at a FIXED
interval — lerobot ``log_freq`` (200) and Isaac ``logging_steps`` (10) — so the
step is the count of log records times that interval. That is exact as long as
the interval matches the run, which is why it is passed in rather than guessed.
"""
from __future__ import annotations
import argparse
import ast
import logging
import re
import sys
import time
from pathlib import Path
logger = logging.getLogger(__name__)
ACT = "act"
GROOT = "groot"
#: Default log intervals, read from each trainer's own config default:
#: lerobot configs/train.py log_freq=200; Isaac training_config.py logging_steps=10.
DEFAULT_INTERVAL = {ACT: 200, GROOT: 10}
#: ACT prints flat ``key:value`` pairs. Keys may contain / and _ (``smp/s``,
#: ``l1_loss``); values may carry a K/M suffix (``smpl:435K``) or be
#: exponential (``lr:1.0e-05``).
_ACT_PAIR = re.compile(r"([A-Za-z][A-Za-z0-9_/]*):(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)([KM]?)\b")
_SUFFIX = {"": 1, "K": 1_000, "M": 1_000_000}
#: logging's "<file>.py:<lineno>" token, e.g. "ot_train.py:611".
#: Deliberately NOT anchored to the start of the line: lerobot's tqdm bar writes
#: with \r and no newline, so a log record routinely arrives with the whole
#: progress bar glued in front of it ("Training: 1%|...| 1800/300000 [...]INFO
#: 2026-07-27 ... ot_train.py:611 step:2K ..."). An anchored prefix strip matches
#: none of those, and every record then grows a "py" scalar holding the source
#: line number.
_LOG_PREFIX = re.compile(r"\S+\.py:\d+")
#: GR00T prints a Python dict literal, so it can be parsed as one.
_GROOT_DICT = re.compile(r"\{'loss':[^}]*\}")
def scalars_from_line(line: str, policy: str) -> dict:
"""Every numeric scalar on this line, or {} if it carries none."""
if policy == GROOT:
match = _GROOT_DICT.search(line)
if match is None:
return {}
try:
data = ast.literal_eval(match.group(0))
except (ValueError, SyntaxError):
return {}
return {k: float(v) for k, v in data.items() if isinstance(v, (int, float))}
if policy == ACT:
# Only lines that actually carry a loss are training records; the
# startup banner also has key:value shapes.
if "loss:" not in line:
return {}
# Drop logging's own "INFO <date> <time> <file>.py:<lineno>" prefix first.
# It is key:value shaped too, so without this every record grows a
# "py" scalar holding the source line number.
line = _LOG_PREFIX.sub(" ", line)
out = {}
for key, value, suffix in _ACT_PAIR.findall(line):
try:
out[key] = float(value) * _SUFFIX[suffix]
except (ValueError, KeyError):
continue
return out
return {}
class TensorBoardSink:
"""Writes parsed scalars, and stays out of the way when it cannot.
A missing tensorboard package must never take a multi-hour training run down
with it — logging is an observability nicety and the run is the deliverable.
So construction failure is a warning and every later call is a no-op.
"""
def __init__(self, out_dir, policy: str, interval: int | None = None):
self.policy = policy
self.interval = interval or DEFAULT_INTERVAL.get(policy, 1)
self.records = 0
self.writer = None
if out_dir is None:
return
try:
from torch.utils.tensorboard import SummaryWriter # noqa: PLC0415
except ImportError:
logger.warning(
"tensorboard is not installed in this interpreter — training will run "
"without it. Install it (uv pip install tensorboard) or attach later with "
"scripts/tb_logger.py against the log file.")
return
Path(out_dir).mkdir(parents=True, exist_ok=True)
self.writer = SummaryWriter(log_dir=str(out_dir))
logger.info("tensorboard events -> %s (step = record x %d)", out_dir, self.interval)
def observe(self, line: str) -> int:
"""Feed one log line. Returns how many scalars were written."""
if self.writer is None:
return 0
scalars = scalars_from_line(line, self.policy)
if not scalars:
return 0
self.records += 1
step = self.records * self.interval
for key, value in scalars.items():
self.writer.add_scalar(f"train/{key}", value, step)
if self.records % 50 == 0:
self.writer.flush()
return len(scalars)
def close(self) -> None:
if self.writer is not None:
self.writer.flush()
self.writer.close()
def tail(path: Path, *, from_start: bool = True, poll_s: float = 2.0):
"""Yield lines from a file that is still being written.
Starts at the beginning by default so attaching to a run already in progress
backfills everything it has logged so far.
"""
while not path.exists():
time.sleep(poll_s)
with path.open("r", errors="replace") as handle:
if not from_start:
handle.seek(0, 2)
while True:
line = handle.readline()
if line:
yield line
else:
time.sleep(poll_s)
def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--policy", required=True, choices=[ACT, GROOT])
parser.add_argument("--log", required=True, type=Path, help="training log to follow")
parser.add_argument("--out", required=True, type=Path, help="TensorBoard event directory")
parser.add_argument("--interval", type=int, default=None,
help="steps between log records (default: %s)" % DEFAULT_INTERVAL)
parser.add_argument("--once", action="store_true",
help="read what exists and exit, instead of following")
args = parser.parse_args()
sink = TensorBoardSink(args.out, args.policy, args.interval)
if sink.writer is None:
return 1
try:
if args.once:
for line in args.log.read_text(errors="replace").splitlines():
sink.observe(line)
else:
for line in tail(args.log):
sink.observe(line)
except KeyboardInterrupt:
pass
finally:
logger.info("wrote %d records", sink.records)
sink.close()
return 0
if __name__ == "__main__":
sys.exit(main())