Download code/vitakws/logging_utils.py from thucdangvan020999/aurora-wake-model: direct link, hf CLI and curl.
- Browser
- Download file 2.62 kB
-
https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/vitakws/logging_utils.py
- Command line
-
hf download hf://thucdangvan020999/aurora-wake-model/code/vitakws/logging_utils.py
-
curl -L -o logging_utils.py https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/vitakws/logging_utils.py
2.62 kB
| """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() | |