File size: 3,996 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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,
    )