data_mem / step_train /src /utils /tb_writer.py
dudulu66666's picture
Add files using upload-large-folder tool
4968ea3 verified
Raw
History Blame Contribute Delete
5.08 kB
"""TensorBoard logging wrapper (platform-aware, fail-soft, rank-0-only).
Platform contract (用户平台要求): when TensorBoard is enabled on the task-creation
page the platform injects $TENSORBOARD_LOG_PATH and expects logs written there:
log_dir = os.getenv('TENSORBOARD_LOG_PATH')
writer = SummaryWriter(log_dir=log_dir)
writer.add_scalar('Loss/train', train_loss, step)
This wrapper adds three robustness properties on top of the raw SummaryWriter:
1. fail-soft import — if `tensorboard` isn't installed (e.g. CPU dev box) every
call is a silent no-op, so training code never needs `try/except` around logging.
2. rank-aware — only the main process writes (avoids 8 ranks clobbering one event
file); non-main ranks get a no-op writer.
3. path resolution — $TENSORBOARD_LOG_PATH first, else a config/explicit dir, else
a sensible default under the run's output_dir; parent dirs are created.
Usage:
from src.utils.tb_writer import TBWriter
tb = TBWriter(fallback_dir=os.path.join(output_dir, "tb"))
tb.add_scalar("Loss/train", loss, step)
...
tb.close()
"""
import os
from typing import Dict, Optional
from src.utils.logging_utils import setup_logger
logger = setup_logger(__name__)
def resolve_log_dir(fallback_dir: Optional[str] = None) -> Optional[str]:
"""$TENSORBOARD_LOG_PATH (platform) > fallback_dir > None. (single-dir, legacy)."""
env = os.getenv("TENSORBOARD_LOG_PATH")
if env:
return env
return fallback_dir
def resolve_log_dirs(fallback_dir: Optional[str] = None) -> list:
"""Return ALL target dirs to write to (deduped, order-preserving).
🔴 DUAL-WRITE: we write to BOTH the platform-injected $TENSORBOARD_LOG_PATH (for the
live hosted dashboard) AND fallback_dir (a local, checkpoint-adjacent path) at once.
The platform path (e.g. /mnt/tensorboard_logs) is typically wiped after the job ends,
so the local copy under <output_dir>/tb survives for post-hoc 复盘. If only one is
available we just write that one; if they coincide we write once.
"""
dirs = []
env = os.getenv("TENSORBOARD_LOG_PATH")
if env:
dirs.append(env)
if fallback_dir and fallback_dir not in dirs:
dirs.append(fallback_dir)
return dirs
class TBWriter:
"""Thin SummaryWriter facade. No-op when disabled / tensorboard missing / non-main.
Fans every write out to one OR MORE SummaryWriters (dual-write: platform dir +
local persistent dir) — see resolve_log_dirs."""
def __init__(
self,
fallback_dir: Optional[str] = None,
enabled: bool = True,
is_main: bool = True,
):
self.writers = [] # list[SummaryWriter]
self.log_dirs = [] # list[str], parallel to writers
if not enabled or not is_main:
return
log_dirs = resolve_log_dirs(fallback_dir)
if not log_dirs:
logger.info("[TB] no $TENSORBOARD_LOG_PATH and no fallback dir → disabled")
return
try:
from torch.utils.tensorboard import SummaryWriter
except Exception as e: # tensorboard not installed
logger.warning(f"[TB] tensorboard unavailable ({type(e).__name__}) → logging disabled")
return
for d in log_dirs:
try:
os.makedirs(d, exist_ok=True)
self.writers.append(SummaryWriter(log_dir=d))
self.log_dirs.append(d)
except Exception as e: # a bad dir shouldn't kill the others / training
logger.warning(f"[TB] cannot open {d} ({type(e).__name__}: {e}) → skipped")
if self.log_dirs:
logger.info(f"[TB] logging to {len(self.log_dirs)} dir(s): {self.log_dirs}")
@property
def enabled(self) -> bool:
return bool(self.writers)
@property
def log_dir(self):
"""Back-compat: first (primary) dir, or None."""
return self.log_dirs[0] if self.log_dirs else None
def add_scalar(self, tag: str, value, step: int):
if not self.writers or value is None:
return
for w in self.writers:
try:
w.add_scalar(tag, float(value), step)
except Exception as e: # never let logging crash training
logger.debug(f"[TB] add_scalar({tag}) failed: {e}")
def add_scalars(self, prefix: str, values: Dict[str, float], step: int):
"""Log each value as a separate `{prefix}/{key}` scalar.
We deliberately avoid SummaryWriter.add_scalars (it spawns per-tag event
subdirs that are awkward on hosted dashboards); flat `prefix/key` tags render
cleanly and group under one section.
"""
if not self.writers:
return
for k, v in values.items():
self.add_scalar(f"{prefix}/{k}", v, step)
def flush(self):
for w in self.writers:
w.flush()
def close(self):
for w in self.writers:
w.flush()
w.close()
self.writers = []