import json import logging import os import sys from argparse import Namespace from pathlib import Path from typing import Any, Optional, TextIO from omegaconf import OmegaConf _ORIGINAL_STDOUT = sys.__stdout__ _ORIGINAL_STDERR = sys.__stderr__ _SILENCED = False def is_global_rank_zero() -> bool: """True on the primary process in distributed training.""" try: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): return dist.get_rank() == 0 except Exception: pass rank = os.environ.get("RANK") if rank is not None: return int(rank) == 0 local_rank = os.environ.get("LOCAL_RANK") if local_rank is not None: return int(local_rank) == 0 return True def silence_non_rank_zero_output() -> None: """Drop stdout/stderr on non-primary ranks.""" global _SILENCED if is_global_rank_zero() or _SILENCED: return sys.stdout = open(os.devnull, "w") sys.stderr = open(os.devnull, "w") _SILENCED = True def rank_zero_print(*args, **kwargs) -> None: if is_global_rank_zero(): print(*args, **kwargs) def rank_zero_tqdm(*args, **kwargs): from tqdm import tqdm if not is_global_rank_zero(): kwargs["disable"] = True return tqdm(*args, **kwargs) class _Tee: """Mirror writes to the original stream and a log file.""" def __init__(self, stream, file: TextIO): self.stream = stream self.file = file def write(self, data): self.stream.write(data) self.file.write(data) def flush(self): self.stream.flush() self.file.flush() def isatty(self): return getattr(self.stream, "isatty", lambda: False)() def fileno(self): return self.stream.fileno() _CONSOLE_LOG_HANDLES: list[TextIO] = [] def setup_console_logging(log_path: str | Path) -> Optional[Path]: """ Tee stdout/stderr to a log file on global rank 0 only. Returns the log path when enabled, otherwise None. """ if not is_global_rank_zero(): silence_non_rank_zero_output() return None log_path = Path(log_path) log_path.parent.mkdir(parents=True, exist_ok=True) log_file = open(log_path, "a", encoding="utf-8", buffering=1) _CONSOLE_LOG_HANDLES.append(log_file) sys.stdout = _Tee(_ORIGINAL_STDOUT, log_file) sys.stderr = _Tee(_ORIGINAL_STDERR, log_file) return log_path def setup_logging(cfg, save_folder=None, console_log_file: str = "train.log"): silence_non_rank_zero_output() if save_folder is None: save_folder = "log" else: save_folder = save_folder + "/log" if is_global_rank_zero(): Path(save_folder).mkdir(parents=True, exist_ok=True) arg_dict = OmegaConf.to_container(cfg, resolve=True) args = Namespace(**arg_dict) with open(os.path.join(save_folder, "args.txt"), "w", encoding="utf-8") as f: json.dump(args.__dict__, f, indent=2) console_log_path = setup_console_logging(console_log_file) if console_log_path is not None: rank_zero_print(f"Console output is being logged to {console_log_path.resolve()}") if not is_global_rank_zero(): logging.basicConfig(level=logging.CRITICAL, handlers=[logging.NullHandler()], force=True) return log_handlers = [logging.StreamHandler(sys.stdout)] if console_log_path is not None: file_handler = logging.FileHandler(console_log_path, encoding="utf-8") file_handler.setFormatter( logging.Formatter( fmt="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", ) ) log_handlers.append(file_handler) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, handlers=log_handlers, force=True, )