-
Notifications
You must be signed in to change notification settings - Fork 0
/
saver.py
297 lines (244 loc) · 8.04 KB
/
saver.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
'''
inference.py
Pedro Sarmento, Adarsh Kumar, C J Carr, Zack Zukowski, Mathieu
Barthet, and Yi-Hsuan Yang. Dadagp: A dataset of tokenized guitarpro
songs for sequence models, 2021.
'''
import os
import time
import torch
import logging
import collections
import numpy as np
import matplotlib.pyplot as plt
class Saver(object):
def __init__(
self,
exp_dir,
mode='w'):
self.exp_dir = exp_dir
self.init_time = time.time()
self.global_step = 0
# makedirs
os.makedirs(exp_dir, exist_ok=True)
# logging config
path_logger = os.path.join(exp_dir, 'log.txt')
logging.basicConfig(
level=logging.DEBUG,
format='%(message)s',
filename=path_logger,
filemode=mode)
self.logger = logging.getLogger('training monitor')
def add_summary_msg(self, msg):
self.logger.debug(msg)
def add_summary(
self,
key,
val,
step=None,
cur_time=None):
if cur_time is None:
cur_time = time.time() - self.init_time
if step is None:
step = self.global_step
# write msg (key, val, step, time)
if isinstance(val, float):
msg_str = '{:10s} | {:.10f} | {:10d} | {}'.format(
key,
val,
step,
cur_time
)
else:
msg_str = '{:10s} | {} | {:10d} | {}'.format(
key,
val,
step,
cur_time
)
self.logger.debug(msg_str)
def save_model(
self,
model,
optimizer=None,
outdir=None,
name='model'):
if outdir is None:
outdir = self.exp_dir
print(' [*] saving model to {}, name: {}'.format(outdir, name))
torch.save(model, os.path.join(outdir, name+'.pt'))
torch.save(model.state_dict(), os.path.join(outdir, name+'_params.pt'))
if optimizer is not None:
torch.save(optimizer.state_dict(), os.path.join(outdir, name+'_opt.pt'))
def load_model(
self,
path_exp,
device='cpu',
name='model.pt'):
path_pt = os.path.join(path_exp, name)
print(' [*] restoring model from', path_pt)
model = torch.load(path_pt, map_location=torch.device(device))
return model
def global_step_increment(self):
self.global_step += 1
"""
file modes
'a':
Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
'w':
Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
"""
def make_loss_report(
path_log,
path_figure='loss.png',
dpi=100):
# load logfile
monitor_vals = collections.defaultdict(list)
with open(path_logfile, 'r') as f:
for line in f:
try:
line = line.strip()
key, val, step, acc_time = line.split(' | ')
monitor_vals[key].append((float(val), int(step), acc_time))
except:
continue
# collect
step_train = [item[1] for item in monitor_vals['train loss']]
vals_train = [item[0] for item in monitor_vals['train loss']]
step_valid = [item[1] for item in monitor_vals['valid loss']]
vals_valid = [item[0] for item in monitor_vals['valid loss']]
x_min = step_valid[np.argmin(vals_valid)]
y_min = min(vals_valid)
# plot
fig = plt.figure(dpi=dpi)
plt.title('training process')
plt.plot(step_train, vals_train, label='train')
plt.plot(step_valid, vals_valid, label='valid')
plt.yscale('log')
plt.plot([x_min], [y_min], 'ro')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig(path_figure)
'''
author: wayn391@mastertones
'''
import os
import time
import torch
import logging
import datetime
import collections
import numpy as np
import matplotlib.pyplot as plt
class Saver(object):
def __init__(
self,
exp_dir,
mode='w'):
self.exp_dir = exp_dir
self.init_time = time.time()
self.global_step = 0
# makedirs
os.makedirs(exp_dir, exist_ok=True)
# logging config
path_logger = os.path.join(exp_dir, 'log.txt')
logging.basicConfig(
level=logging.DEBUG,
format='%(message)s',
filename=path_logger,
filemode=mode)
self.logger = logging.getLogger('training monitor')
def add_summary_msg(self, msg):
self.logger.debug(msg)
def add_summary(
self,
key,
val,
step=None,
cur_time=None):
if cur_time is None:
cur_time = time.time() - self.init_time
if step is None:
step = self.global_step
# write msg (key, val, step, time)
if isinstance(val, float):
msg_str = '{:10s} | {:.10f} | {:10d} | {}'.format(
key,
val,
step,
cur_time
)
else:
msg_str = '{:10s} | {} | {:10d} | {}'.format(
key,
val,
step,
cur_time
)
self.logger.debug(msg_str)
def save_model(
self,
model,
optimizer=None,
outdir=None,
name='model'):
if outdir is None:
outdir = self.exp_dir
print(' [*] saving model to {}, name: {}'.format(outdir, name))
# torch.save(model, os.path.join(outdir, name+'.pt'))
torch.save(model.state_dict(), os.path.join(outdir, name+'_params.pt'))
if optimizer is not None:
torch.save(optimizer.state_dict(), os.path.join(outdir, name+'_opt.pt'))
def load_model(
self,
path_exp,
device='cpu',
name='model.pt'):
path_pt = os.path.join(path_exp, name)
print(' [*] restoring model from', path_pt)
model = torch.load(path_pt, map_location=torch.device(device))
return model
def global_step_increment(self):
self.global_step += 1
"""
file modes
'a':
Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
'w':
Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
"""
def make_loss_report(
path_log,
path_figure='loss.png',
dpi=100):
# load logfile
monitor_vals = collections.defaultdict(list)
with open(path_logfile, 'r') as f:
for line in f:
try:
line = line.strip()
key, val, step, acc_time = line.split(' | ')
monitor_vals[key].append((float(val), int(step), acc_time))
except:
continue
# collect
step_train = [item[1] for item in monitor_vals['train loss']]
vals_train = [item[0] for item in monitor_vals['train loss']]
step_valid = [item[1] for item in monitor_vals['valid loss']]
vals_valid = [item[0] for item in monitor_vals['valid loss']]
x_min = step_valid[np.argmin(vals_valid)]
y_min = min(vals_valid)
# plot
fig = plt.figure(dpi=dpi)
plt.title('training process')
plt.plot(step_train, vals_train, label='train')
plt.plot(step_valid, vals_valid, label='valid')
plt.yscale('log')
plt.plot([x_min], [y_min], 'ro')
plt.legend(loc='upper right')
plt.tight_layout()
plt.savefig(path_figure)