-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.py
122 lines (97 loc) · 3.37 KB
/
utils.py
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
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import logging
import datetime
import torch
import argparse
def str2bool(s):
if isinstance(s, bool):
return s
if s.lower() in ('yes', 'true'):
return True
elif s.lower() in ('no', 'false'):
return False
else:
raise argparse.ArgumentTypeError('bool value expected.')
def _create_if_not_exist(path):
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
def get_local_time():
cur = datetime.datetime.now()
cur = cur.strftime('%b-%d-%Y_%H-%M-%S')
return cur
def get_logger(config, name=None):
"""
Logger
Args:
config(ConfigParser): config
name: specified name
Returns:
Logger: logger
"""
log_dir = './log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_filename = '{}-{}-{}-{}.log'.format(config.exp_id, config.model, config.filename[:-4], get_local_time())
logfilepath = os.path.join(log_dir, log_filename)
logger = logging.getLogger(name)
log_level = config.get('log_level', 'INFO')
if log_level.lower() == 'info':
level = logging.INFO
elif log_level.lower() == 'debug':
level = logging.DEBUG
elif log_level.lower() == 'error':
level = logging.ERROR
elif log_level.lower() == 'warning':
level = logging.WARNING
elif log_level.lower() == 'critical':
level = logging.CRITICAL
else:
level = logging.INFO
logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler(logfilepath)
file_handler.setFormatter(formatter)
console_formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(console_formatter)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.info('Log directory: %s', log_dir)
return logger
def ensure_dir(dir_path):
"""Make sure the directory exists, if it does not exist, create it.
Args:
dir_path (str): directory path
"""
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def save_model(output_path,
model,
steps=None,
opt=None,
lr_scheduler=None,
max_ckpt=2, log=None):
if not os.path.exists(output_path):
os.makedirs(output_path)
output_dir = os.path.join(output_path, "model_%d.pt" % steps)
torch.save(model.state_dict(), output_dir)
def load_model(output_path, model, opt=None, lr_scheduler=None, log=None):
log.info("load model from %s" % output_path)
model_state = torch.load(output_path)
model.load_state_dict(model_state)