Download src/common/logging_utils.py from khiemdztv/civic-backup: direct link, hf CLI and curl.
- Browser
- Download file 2.62 kB
-
https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/common/logging_utils.py
- Command line
-
hf download hf://khiemdztv/civic-backup/src/common/logging_utils.py
-
curl -L -o logging_utils.py https://huggingface.co/khiemdztv/civic-backup/resolve/main/src/common/logging_utils.py
2.62 kB
| """Logger dùng chung + đo thời gian + theo dõi GPU/RAM.""" | |
| from __future__ import annotations | |
| import logging | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import Optional | |
| _FMT = "%(asctime)s | %(levelname)-7s | %(name)-22s | %(message)s" | |
| _DATEFMT = "%H:%M:%S" | |
| _CONFIGURED = set() | |
| def get_logger(name: str, log_dir: Optional[str] = None) -> logging.Logger: | |
| logger = logging.getLogger(name) | |
| if name in _CONFIGURED: | |
| return logger | |
| logger.setLevel(logging.INFO) | |
| logger.propagate = False | |
| # Log đi STDERR, không đi stdout: `--json-only` phải cho ra JSON sạch để | |
| # máy đọc được. Trước đây một WARNING lọt vào stdout là hỏng cả đầu ra. | |
| sh = logging.StreamHandler(sys.stderr) | |
| sh.setFormatter(logging.Formatter(_FMT, _DATEFMT)) | |
| logger.addHandler(sh) | |
| if log_dir: | |
| Path(log_dir).mkdir(parents=True, exist_ok=True) | |
| fh = logging.FileHandler(Path(log_dir) / f"{name}.log", encoding="utf-8") | |
| fh.setFormatter(logging.Formatter(_FMT, _DATEFMT)) | |
| logger.addHandler(fh) | |
| _CONFIGURED.add(name) | |
| return logger | |
| def gpu_mem_str() -> str: | |
| try: | |
| import torch | |
| if not torch.cuda.is_available(): | |
| return "GPU n/a" | |
| alloc = torch.cuda.memory_allocated() / 2 ** 30 | |
| peak = torch.cuda.max_memory_allocated() / 2 ** 30 | |
| return f"VRAM {alloc:.1f}/{peak:.1f} GB" | |
| except Exception: | |
| return "GPU n/a" | |
| def ram_gb() -> float: | |
| try: | |
| with open("/proc/self/status", "r") as f: | |
| for line in f: | |
| if line.startswith("VmRSS:"): | |
| return int(line.split()[1]) / 1024 / 1024 | |
| except OSError: | |
| pass | |
| return 0.0 | |
| def log_resources(logger: logging.Logger, prefix: str = "") -> None: | |
| logger.info("%s%s | RAM %.1f GB", prefix, gpu_mem_str(), ram_gb()) | |
| class Timer: | |
| """with Timer(logger, 'dựng index'): ...""" | |
| def __init__(self, logger: Optional[logging.Logger] = None, label: str = ""): | |
| self.logger = logger | |
| self.label = label | |
| self.elapsed = 0.0 | |
| def __enter__(self) -> "Timer": | |
| self._t0 = time.time() | |
| return self | |
| def __exit__(self, *exc) -> None: | |
| self.elapsed = time.time() - self._t0 | |
| if self.logger: | |
| self.logger.info("[%s] xong sau %.1f s (%.2f phút)", self.label, | |
| self.elapsed, self.elapsed / 60) | |
| def fmt_hms(seconds: float) -> str: | |
| seconds = int(max(0, seconds)) | |
| h, rem = divmod(seconds, 3600) | |
| m, s = divmod(rem, 60) | |
| return f"{h:02d}:{m:02d}:{s:02d}" | |