forked from aviralkumar2907/BEAR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.py
495 lines (424 loc) · 15.8 KB
/
logger.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
"""
Based on rllab's logger.
https://github.com/rll/rllab
"""
from enum import Enum
from contextlib import contextmanager
import numpy as np
import os
import os.path as osp
import sys
import datetime
import dateutil.tz
import csv
import json
import pickle
import errno
from collections import OrderedDict
from numbers import Number
import os
# We need rlkit for this
from rlkit.core.tabulate import tabulate
import dateutil.tz
import rlkit.pythonplusplus as ppp
import os.path as osp
def dict_to_safe_json(d):
"""
Convert each value in the dictionary into a JSON'able primitive.
:param d:
:return:
"""
new_d = {}
for key, item in d.items():
if safe_json(item):
new_d[key] = item
else:
if isinstance(item, dict):
new_d[key] = dict_to_safe_json(item)
else:
new_d[key] = str(item)
return new_d
def safe_json(data):
if data is None:
return True
elif isinstance(data, (bool, int, float)):
return True
elif isinstance(data, (tuple, list)):
return all(safe_json(x) for x in data)
elif isinstance(data, dict):
return all(isinstance(k, str) and safe_json(v) for k, v in data.items())
return False
def create_exp_name(exp_prefix, exp_id=0, seed=0):
"""
Create a semi-unique experiment name that has a timestamp
:param exp_prefix:
:param exp_id:
:return:
"""
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
return "%s_%s_%04d--s-%d" % (exp_prefix, timestamp, exp_id, seed)
def create_log_dir(
exp_prefix,
exp_id=0,
seed=0,
base_log_dir=None,
include_exp_prefix_sub_dir=True,
):
"""
Creates and returns a unique log directory.
:param exp_prefix: All experiments with this prefix will have log
directories be under this directory.
:param exp_id: The number of the specific experiment run within this
experiment.
:param base_log_dir: The directory where all log should be saved.
:return:
"""
exp_name = create_exp_name(exp_prefix, exp_id=exp_id,
seed=seed)
if base_log_dir is None:
base_log_dir = './data'
if include_exp_prefix_sub_dir:
log_dir = osp.join(base_log_dir, exp_prefix.replace("_", "-"), exp_name)
else:
log_dir = osp.join(base_log_dir, exp_name)
if osp.exists(log_dir):
print("WARNING: Log directory already exists {}".format(log_dir))
os.makedirs(log_dir, exist_ok=True)
return log_dir
def setup_logger(
exp_prefix="default",
variant=None,
text_log_file="debug.log",
variant_log_file="variant.json",
tabular_log_file="progress.csv",
snapshot_mode="last",
snapshot_gap=1,
log_tabular_only=False,
log_dir=None,
git_infos=None,
script_name=None,
**create_log_dir_kwargs
):
"""
Set up logger to have some reasonable default settings.
Will save log output to
based_log_dir/exp_prefix/exp_name.
exp_name will be auto-generated to be unique.
If log_dir is specified, then that directory is used as the output dir.
:param exp_prefix: The sub-directory for this specific experiment.
:param variant:
:param text_log_file:
:param variant_log_file:
:param tabular_log_file:
:param snapshot_mode:
:param log_tabular_only:
:param snapshot_gap:
:param log_dir:
:param git_infos:
:param script_name: If set, save the script name to this.
:return:
"""
first_time = log_dir is None
if first_time:
log_dir = create_log_dir(exp_prefix, **create_log_dir_kwargs)
if variant is not None:
logger.log("Variant:")
logger.log(json.dumps(dict_to_safe_json(variant), indent=2))
variant_log_path = osp.join(log_dir, variant_log_file)
logger.log_variant(variant_log_path, variant)
tabular_log_path = osp.join(log_dir, tabular_log_file)
text_log_path = osp.join(log_dir, text_log_file)
logger.add_text_output(text_log_path)
if first_time:
logger.add_tabular_output(tabular_log_path)
else:
logger._add_output(tabular_log_path, logger._tabular_outputs,
logger._tabular_fds, mode='a')
for tabular_fd in logger._tabular_fds:
logger._tabular_header_written.add(tabular_fd)
logger.set_snapshot_dir(log_dir)
logger.set_snapshot_mode(snapshot_mode)
logger.set_snapshot_gap(snapshot_gap)
logger.set_log_tabular_only(log_tabular_only)
exp_name = log_dir.split("/")[-1]
logger.push_prefix("[%s] " % exp_name)
if script_name is not None:
with open(osp.join(log_dir, "script_name.txt"), "w") as f:
f.write(script_name)
return log_dir
def create_stats_ordered_dict(
name,
data,
stat_prefix=None,
always_show_all_stats=True,
exclude_max_min=False,
):
if stat_prefix is not None:
name = "{}{}".format(stat_prefix, name)
if isinstance(data, Number):
return OrderedDict({name: data})
if len(data) == 0:
return OrderedDict()
if isinstance(data, tuple):
ordered_dict = OrderedDict()
for number, d in enumerate(data):
sub_dict = create_stats_ordered_dict(
"{0}_{1}".format(name, number),
d,
)
ordered_dict.update(sub_dict)
return ordered_dict
if isinstance(data, list):
try:
iter(data[0])
except TypeError:
pass
else:
data = np.concatenate(data)
if (isinstance(data, np.ndarray) and data.size == 1
and not always_show_all_stats):
return OrderedDict({name: float(data)})
stats = OrderedDict([
(name + ' Mean', np.mean(data)),
(name + ' Std', np.std(data)),
])
if not exclude_max_min:
stats[name + ' Max'] = np.max(data)
stats[name + ' Min'] = np.min(data)
return stats
class TerminalTablePrinter(object):
def __init__(self):
self.headers = None
self.tabulars = []
def print_tabular(self, new_tabular):
if self.headers is None:
self.headers = [x[0] for x in new_tabular]
else:
assert len(self.headers) == len(new_tabular)
self.tabulars.append([x[1] for x in new_tabular])
self.refresh()
def refresh(self):
import os
rows, columns = os.popen('stty size', 'r').read().split()
tabulars = self.tabulars[-(int(rows) - 3):]
sys.stdout.write("\x1b[2J\x1b[H")
sys.stdout.write(tabulate(tabulars, self.headers))
sys.stdout.write("\n")
class MyEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, type):
return {'$class': o.__module__ + "." + o.__name__}
elif isinstance(o, Enum):
return {
'$enum': o.__module__ + "." + o.__class__.__name__ + '.' + o.name
}
elif callable(o):
return {
'$function': o.__module__ + "." + o.__name__
}
return json.JSONEncoder.default(self, o)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
class Logger(object):
def __init__(self):
self._prefixes = []
self._prefix_str = ''
self._tabular_prefixes = []
self._tabular_prefix_str = ''
self._tabular = []
self._text_outputs = []
self._tabular_outputs = []
self._text_fds = {}
self._tabular_fds = {}
self._tabular_header_written = set()
self._snapshot_dir = None
self._snapshot_mode = 'all'
self._snapshot_gap = 1
self._log_tabular_only = False
self._header_printed = False
self.table_printer = TerminalTablePrinter()
def reset(self):
self.__init__()
def _add_output(self, file_name, arr, fds, mode='a'):
if file_name not in arr:
mkdir_p(os.path.dirname(file_name))
arr.append(file_name)
fds[file_name] = open(file_name, mode)
def _remove_output(self, file_name, arr, fds):
if file_name in arr:
fds[file_name].close()
del fds[file_name]
arr.remove(file_name)
def push_prefix(self, prefix):
self._prefixes.append(prefix)
self._prefix_str = ''.join(self._prefixes)
def add_text_output(self, file_name):
self._add_output(file_name, self._text_outputs, self._text_fds,
mode='a')
def remove_text_output(self, file_name):
self._remove_output(file_name, self._text_outputs, self._text_fds)
def add_tabular_output(self, file_name, relative_to_snapshot_dir=False):
if relative_to_snapshot_dir:
file_name = osp.join(self._snapshot_dir, file_name)
self._add_output(file_name, self._tabular_outputs, self._tabular_fds,
mode='w')
def remove_tabular_output(self, file_name, relative_to_snapshot_dir=False):
if relative_to_snapshot_dir:
file_name = osp.join(self._snapshot_dir, file_name)
if self._tabular_fds[file_name] in self._tabular_header_written:
self._tabular_header_written.remove(self._tabular_fds[file_name])
self._remove_output(file_name, self._tabular_outputs, self._tabular_fds)
def set_snapshot_dir(self, dir_name):
self._snapshot_dir = dir_name
def get_snapshot_dir(self, ):
return self._snapshot_dir
def get_snapshot_mode(self, ):
return self._snapshot_mode
def set_snapshot_mode(self, mode):
self._snapshot_mode = mode
def get_snapshot_gap(self, ):
return self._snapshot_gap
def set_snapshot_gap(self, gap):
self._snapshot_gap = gap
def set_log_tabular_only(self, log_tabular_only):
self._log_tabular_only = log_tabular_only
def get_log_tabular_only(self, ):
return self._log_tabular_only
def log(self, s, with_prefix=True, with_timestamp=True):
out = s
if with_prefix:
out = self._prefix_str + out
if with_timestamp:
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %Z')
out = "%s | %s" % (timestamp, out)
if not self._log_tabular_only:
# Also log to stdout
print(out)
for fd in list(self._text_fds.values()):
fd.write(out + '\n')
fd.flush()
sys.stdout.flush()
def record_tabular(self, key, val):
self._tabular.append((self._tabular_prefix_str + str(key), str(val)))
def record_dict(self, d, prefix=None):
if prefix is not None:
self.push_tabular_prefix(prefix)
for k, v in d.items():
self.record_tabular(k, v)
if prefix is not None:
self.pop_tabular_prefix()
def push_tabular_prefix(self, key):
self._tabular_prefixes.append(key)
self._tabular_prefix_str = ''.join(self._tabular_prefixes)
def pop_tabular_prefix(self, ):
del self._tabular_prefixes[-1]
self._tabular_prefix_str = ''.join(self._tabular_prefixes)
def save_extra_data(self, data, file_name='extra_data.pkl', mode='joblib'):
"""
Data saved here will always override the last entry
:param data: Something pickle'able.
"""
file_name = osp.join(self._snapshot_dir, file_name)
if mode == 'joblib':
import joblib
joblib.dump(data, file_name, compress=3)
elif mode == 'pickle':
pickle.dump(data, open(file_name, "wb"))
else:
raise ValueError("Invalid mode: {}".format(mode))
return file_name
def get_table_dict(self, ):
return dict(self._tabular)
def get_table_key_set(self, ):
return set(key for key, value in self._tabular)
@contextmanager
def prefix(self, key):
self.push_prefix(key)
try:
yield
finally:
self.pop_prefix()
@contextmanager
def tabular_prefix(self, key):
self.push_tabular_prefix(key)
yield
self.pop_tabular_prefix()
def log_variant(self, log_file, variant_data):
mkdir_p(os.path.dirname(log_file))
with open(log_file, "w") as f:
json.dump(variant_data, f, indent=2, sort_keys=True, cls=MyEncoder)
def record_tabular_misc_stat(self, key, values, placement='back'):
if placement == 'front':
prefix = ""
suffix = key
else:
prefix = key
suffix = ""
if len(values) > 0:
self.record_tabular(prefix + "Average" + suffix, np.average(values))
self.record_tabular(prefix + "Std" + suffix, np.std(values))
self.record_tabular(prefix + "Median" + suffix, np.median(values))
self.record_tabular(prefix + "Min" + suffix, np.min(values))
self.record_tabular(prefix + "Max" + suffix, np.max(values))
else:
self.record_tabular(prefix + "Average" + suffix, np.nan)
self.record_tabular(prefix + "Std" + suffix, np.nan)
self.record_tabular(prefix + "Median" + suffix, np.nan)
self.record_tabular(prefix + "Min" + suffix, np.nan)
self.record_tabular(prefix + "Max" + suffix, np.nan)
def dump_tabular(self, *args, **kwargs):
wh = kwargs.pop("write_header", None)
if len(self._tabular) > 0:
if self._log_tabular_only:
self.table_printer.print_tabular(self._tabular)
else:
for line in tabulate(self._tabular).split('\n'):
self.log(line, *args, **kwargs)
tabular_dict = dict(self._tabular)
# Also write to the csv files
# This assumes that the keys in each iteration won't change!
for tabular_fd in list(self._tabular_fds.values()):
writer = csv.DictWriter(tabular_fd,
fieldnames=list(tabular_dict.keys()))
if wh or (
wh is None and tabular_fd not in self._tabular_header_written):
writer.writeheader()
self._tabular_header_written.add(tabular_fd)
writer.writerow(tabular_dict)
tabular_fd.flush()
del self._tabular[:]
def pop_prefix(self, ):
del self._prefixes[-1]
self._prefix_str = ''.join(self._prefixes)
def save_itr_params(self, itr, params):
if self._snapshot_dir:
if self._snapshot_mode == 'all':
file_name = osp.join(self._snapshot_dir, 'itr_%d.pkl' % itr)
pickle.dump(params, open(file_name, "wb"))
elif self._snapshot_mode == 'last':
# override previous params
file_name = osp.join(self._snapshot_dir, 'params.pkl')
pickle.dump(params, open(file_name, "wb"))
elif self._snapshot_mode == "gap":
if itr % self._snapshot_gap == 0:
file_name = osp.join(self._snapshot_dir, 'itr_%d.pkl' % itr)
pickle.dump(params, open(file_name, "wb"))
elif self._snapshot_mode == "gap_and_last":
if itr % self._snapshot_gap == 0:
file_name = osp.join(self._snapshot_dir, 'itr_%d.pkl' % itr)
pickle.dump(params, open(file_name, "wb"))
file_name = osp.join(self._snapshot_dir, 'params.pkl')
pickle.dump(params, open(file_name, "wb"))
elif self._snapshot_mode == 'none':
pass
else:
raise NotImplementedError
logger = Logger()