"""Training metrics: a JSONL file on the VM, pushed to the run's Hub repo every few minutes, so the run can be watched from anywhere: tools/watch.py on this machine, or metrics/metrics.jsonl on huggingface.co (the repo is public). metrics = MetricsLogger(run_dir / "metrics.jsonl", store=hub) metrics.log("run", target_tokens=..., row_tokens=..., config=...) # once per start/resume metrics.log("train", step=..., tokens=..., loss=..., tok_s=..., lr=..., window=..., mem_gb=...) metrics.log("val", step=..., tokens=..., val_loss=...) metrics.log("checkpoint", step=..., tokens=..., name=...) metrics.close() # final push Writing a line costs microseconds. Pushes run in a background thread and never block training; one that fails is retried with the next log call. """ import json import threading import time from pathlib import Path REMOTE_PATH = "metrics/metrics.jsonl" class MetricsLogger: def __init__(self, path, store=None, push_every: float = 300.0): self.path = Path(path) self.path.parent.mkdir(parents=True, exist_ok=True) self.store, self.push_every = store, push_every self.push_errors = 0 self._last_push = 0.0 self._thread = None self._lock = threading.Lock() # the trainer and the checkpoint writer both log def log(self, kind: str, **fields): record = {"kind": kind, "time": round(time.time(), 1), **fields} with self._lock: with open(self.path, "a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n") if self.store is not None and time.time() - self._last_push >= self.push_every: self._push() def _push(self): if self._thread is not None and self._thread.is_alive(): return # the previous push is still running; the next log call tries again self._last_push = time.time() data = self.path.read_bytes() def run(): try: self.store.upload_file(data, REMOTE_PATH) except Exception: self.push_errors += 1 self._last_push = 0.0 # retry with the next log call self._thread = threading.Thread(target=run, name="metrics-push", daemon=True) self._thread.start() def close(self): """Pushes everything logged so far and waits for it.""" if self.store is None: return if self._thread is not None: self._thread.join() self._push() self._thread.join()