File size: 2,623 Bytes
cf29045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
"""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}"