-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathloggers.py
More file actions
99 lines (74 loc) · 2.67 KB
/
Copy pathloggers.py
File metadata and controls
99 lines (74 loc) · 2.67 KB
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
import logging
import os
from torch.utils.tensorboard import SummaryWriter
import torch
import wandb
local_rank = os.environ.get("LOCAL_RANK", -1)
logging.basicConfig(
level=logging.INFO,
format=f'[rank {local_rank}]' + '[\033[34m%(asctime)s\033[0m][%(name)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
class WrappedLogger():
def __init__(self, name: str):
"""A warpped logger that allows rank 0 print control
Args:
name (str): name of the logger
"""
self.logger = logging.getLogger(name)
@staticmethod
def maybe_not_rank0(kwargs):
if kwargs.get("on_rank0", None) is not None:
is_rank0_log = kwargs.pop("on_rank0")
if is_rank0_log:
return int(local_rank) in [0, -1]
return True
def log(self, *args, **kwargs):
if self.maybe_not_rank0(kwargs):
self.logger.log(*args, **kwargs)
def info(self, *args, **kwargs):
if self.maybe_not_rank0(kwargs):
self.logger.info(*args, **kwargs)
def warning(self, *args, **kwargs):
if self.maybe_not_rank0(kwargs):
self.logger.warning(*args, **kwargs)
def error(self, *args, **kwargs):
if self.maybe_not_rank0(kwargs):
self.logger.error(*args, **kwargs)
class TensorBoardLogger():
def __init__(
self,
logdir
):
self.writer = SummaryWriter(logdir)
def log(self, item: dict, step: int, prefix: str):
for k, v in item.items():
if isinstance(v, torch.Tensor):
item[k] = v.item()
k = prefix + "/" + k
if isinstance(v, (int, float)):
self.writer.add_scalar(k, v, step)
elif isinstance(v, str):
self.writer.add_text(k, v, step)
self.writer.flush()
def shutdown(self):
self.writer.close()
class WandbLogger():
def __init__(
self,
workdir: str,
):
self._wandb = wandb
self._wandb.init(
project=os.getenv("WANDB_PROJECT", "Default"),
name=os.path.split(workdir)[-1],
resume="auto"
)
def log(self, item: dict, step: int, prefix: str):
logterm = {}
for k, v in item.items():
if isinstance(v, torch.Tensor):
item[k] = v.item()
k = prefix + "/" + k
logterm[k] = v
self._wandb.log({**logterm, "train/global_step": step})