File size: 2,615 Bytes
a1fe2e2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | """Run logging: always a JSONL file, plus Weights & Biases when enabled."""
from __future__ import annotations
import json
import math
import os
from pathlib import Path
def _clean(metrics: dict) -> dict:
"""Drop NaN/inf so the JSONL stays valid and W&B charts stay readable."""
return {
k: v
for k, v in metrics.items()
if not (isinstance(v, float) and (math.isnan(v) or math.isinf(v)))
}
class RunLogger:
def __init__(self, run_dir: Path, cfg: dict, job_type: str = "train"):
self.run_dir = run_dir
run_dir.mkdir(parents=True, exist_ok=True)
self._file = (run_dir / f"{job_type}_log.jsonl").open("a", encoding="utf-8")
self.wandb = None
w = cfg["wandb"]
mode = os.environ.get("WANDB_MODE", w["mode"])
if not w["enabled"] or mode == "disabled":
return
try:
import wandb
except ImportError:
print("wandb is not installed; logging to JSONL only (pip install wandb)")
return
self.run = wandb.init(
project=w["project"],
entity=w["entity"] or None,
name=cfg["run_name"],
job_type=job_type,
tags=list(w["tags"]),
mode=mode,
dir=str(run_dir),
config=cfg,
)
self.wandb = wandb
def log(self, metrics: dict, step: int) -> None:
metrics = _clean(metrics)
self._file.write(json.dumps({"step": step, **metrics}) + "\n")
self._file.flush()
if self.wandb is not None:
self.wandb.log(metrics, step=step)
def summary(self, metrics: dict) -> None:
metrics = _clean(metrics)
(self.run_dir / "summary.json").write_text(json.dumps(metrics, indent=2))
if self.wandb is not None:
self.run.summary.update(metrics)
def table(self, name: str, columns: list[str], rows: list[list]) -> None:
if self.wandb is not None:
self.wandb.log({name: self.wandb.Table(columns=columns, data=rows)})
def image(self, name: str, path: Path) -> None:
if self.wandb is not None and path.exists():
self.wandb.log({name: self.wandb.Image(str(path))})
def artifact(self, name: str, path: Path, kind: str = "model") -> None:
if self.wandb is not None and path.exists():
art = self.wandb.Artifact(name, type=kind)
art.add_file(str(path))
self.run.log_artifact(art)
def close(self) -> None:
self._file.close()
if self.wandb is not None:
self.run.finish()
|