/
ml_logger.py
2317 lines (1873 loc) · 86.7 KB
/
ml_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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from collections import defaultdict
from collections.abc import Sequence
from contextlib import contextmanager
from datetime import datetime
from functools import partial
from io import BytesIO
from math import ceil
from numbers import Number
from random import random
from time import perf_counter, sleep
from typing import Any, Union
import numpy as np
from ml_logger.helpers import load_from_pickle_file, load_from_jsonl_file
from termcolor import cprint
from .caches.key_value_cache import KeyValueCache
from .caches.summary_cache import SummaryCache
from .full_duplex import Duplex
from .helpers.color_helpers import Color
from .helpers.default_set import DefaultSet
from .helpers.print_utils import PrintHelper
from .log_client import LogClient
# environment defaults
CWD = os.environ["PWD"]
USER = os.environ.get("USER", None)
# template for the dashboard url
ML_DASH = "http://localhost:3001/{prefix}"
# ML_Logger defaults
ROOT = os.environ.get("ML_LOGGER_ROOT", CWD) or CWD
S3_ROOT = os.environ.get("ML_LOGGER_S3_ROOT", None)
LOGGER_USER = os.environ.get("ML_LOGGER_USER", USER)
ACCESS_TOKEN = os.environ.get("ML_LOGGER_ACCESS_TOKEN", None)
def pJoin(*args):
from os.path import join
args = [a for a in args if a]
if args:
return join(*args)
return None
def now(fmt=None):
"""
This is not idempotent--each call returns a new value. So it has to be a method
returns a datetime object if no format string is specified. Otherwise returns a
formated string.
Each call returns the current time in current timezone
:param fmt: formating string, i.e. "%Y-%m-%d-%H-%M-%S-%f"
:return: OneOf[datetime, string]
"""
now = datetime.now().astimezone()
return now.strftime(fmt) if fmt else now
def utcnow(fmt=None):
"""
This is not idempotent--each call returns a new value. So it has to be a method
returns a datetime object if no format string is specified. Otherwise returns a
formated string.
Each call returns the current time in UTC
:param fmt: formating string, i.e. "%Y-%m-%d-%H-%M-%S-%f"
:return: OneOf[datetime, string]
"""
now = datetime.utcnow()
return now.strftime(fmt) if fmt else now
def metrify(data):
"""Help convert non-json serializable objects, such as
:param data:
:return:
"""
if hasattr(data, 'shape') and len(data.shape) > 0:
return list(data)
elif isinstance(data, Sequence):
return data
elif isinstance(data, Number):
return data
elif data is None:
return data
elif type(data) in [dict, str, bool, str]:
return data
# todo: add datetime support
elif not hasattr(data, 'dtype'):
return str(data)
elif str(data.dtype).startswith('int'):
return int(data)
elif str(data.dtype).startswith('float'):
return float(data)
else:
return str(data)
@contextmanager
def _PrefixContext(logger, new_prefix=None, metrics=None, sep="/"):
old_metrics_prefix = logger.metrics_prefix
old_prefix = logger.prefix
if new_prefix:
logger.prefix = new_prefix
if metrics:
logger.metrics_prefix = metrics + (sep or "")
elif metrics is False:
logger.metrics_prefix = ""
try:
yield
finally:
logger.prefix = old_prefix
logger.metrics_prefix = old_metrics_prefix
# @contextmanager
# def _LocalContext(logger, new_prefix=None):
# old_client = logger.client
# logger.prefix = new_prefix
# try:
# yield
# finally:
# logger.prefix = old_prefix
def interpolate(path=None):
if path is None:
return None
path = str(path)
if path.startswith("$"):
return os.environ.get(path[1:], None)
return path
# noinspection PyPep8Naming
class ML_Logger:
"""
ML_Logger, a logging utility for ML training.
---
"""
client = None
root = None
prefix = "" # is okay b/c strings are immutable in python
metrics_prefix = ""
print_buffer = None # move initialization to init.
print_buffer_size = 2048
### Context Helpers
def Prefix(self, *praefixa, metrics=None, sep="/"):
"""
Returns a context in which the prefix of the logger is set to `prefix`
:param praefixa: the new prefix
:return: context object
"""
try:
path_prefix = os.path.normpath(pJoin(self.prefix, *praefixa))
return _PrefixContext(self, path_prefix, metrics, sep=sep)
except:
return _PrefixContext(self, metrics=metrics, sep=sep)
def Sync(self, clean=False, **kwargs):
"""
Returns a context in which the logger logs synchronously. The new
synchronous request pool is cached on the logging client, so this
context can happen repetitively without creating a run-away number
of parallel threads.
The context object can only be used once b/c it is create through
generator using the @contextmanager decorator.
:param clean: boolean flag for removing the thead pool after __exit__.
used to enforce single-use SyncContexts.
:param max_workers: `urllib3` session pool `max_workers` field
:return: context object
"""
return self.client.SyncContext(clean=clean, **kwargs)
def Async(self, clean=False, **kwargs):
"""
Returns a context in which the logger logs [a]synchronously. The new
asynchronous request pool is cached on the logging client, so this
context can happen repetitively without creating a run-away number
of parallel threads.
The context object can only be used once b/c it is create through
generator using the @contextmanager decorator.
:param clean: boolean flag for removing the thead pool after __exit__.
used to enforce single-use AsyncContexts.
:param max_workers: `future_sessions.Session` pool `max_workers` field
:return: context object
"""
return self.client.AsyncContext(clean=clean, **kwargs)
PrefixContext = Prefix
SyncContext = Sync
AsyncContext = Async
def __repr__(self):
return f'Logger(log_directory="{self.root}",' + "\n" + \
f' prefix="{self.prefix}")'
# noinspection PyInitNewSignature
# todo: use prefixes as opposed to prefix. (add *prefixae after prefix=None)
# todo: resolve path segment with $env variables.
def __init__(self, prefix="", *prefixae,
root=ROOT, user=LOGGER_USER, access_token=ACCESS_TOKEN,
buffer_size=2048, max_workers=None,
asynchronous=None, summary_cache_opts: dict = None):
""" logger constructor.
Assumes that you are starting from scratch.
| `log_directory` is overloaded to use either
| 1. file://some_abs_dir
| 2. http://19.2.34.3:8081
| 3. /tmp/some_dir
|
| `prefix` is the log directory relative to the root folder. Absolute path are resolved against the root.
| 1. prefix="causal_infogan" => logs to "/tmp/some_dir/causal_infogan"
| 2. prefix="" => logs to "/tmp/some_dir"
:param prefix: the prefix path
:param *prefixae: the rest of the prefix arguments
:param root: the server host and port number
:param user: environment $ML_LOGGER_USER
:param access_token: environment $ML_LOGGER_ACCESS_TOKEN
:param asynchronous: When this is not None, we create a http thread pool.
:param buffer_size: The string buffer size for the print buffer.
:param max_workers: the number of request-session workers for the async http requests.
"""
# self.summary_writer = tf.summary.FileWriter(log_directory)
self.step = None
self.duplex = None
self.timestamp = None
self.do_not_print = DefaultSet("__timestamp")
self.print_helper = PrintHelper()
# init print buffer
self.print_buffer_size = buffer_size
self.print_buffer = ""
self.timer_cache = defaultdict(None)
self.key_value_caches = defaultdict(KeyValueCache)
self.summary_caches = defaultdict(partial(SummaryCache, **(summary_cache_opts or {})))
# todo: add https support
self.root = interpolate(root) or ROOT
prefixae = [interpolate(p) for p in (prefix or "", *prefixae) if p is not None]
self.prefix = os.path.join(*prefixae) if prefixae else ""
self.client = LogClient(root=self.root, user=user, access_token=access_token,
asynchronous=asynchronous, max_workers=max_workers)
def configure(self,
prefix=None,
*prefixae,
root: str = None,
user=None,
access_token=None,
asynchronous=None,
max_workers=None,
buffer_size=None,
summary_cache_opts: dict = None,
register_experiment=None,
silent=False,
):
"""
Configure an existing logger with updated configurations.
# LogClient Behavior
The logger.client would be re-constructed if
- root_dir is changed
- max_workers is not None
- asynchronous is not None
Because the http LogClient contains http thread pools, one shouldn't call this
configure function in a loop. Instead, use the logger.(A)syncContext() contexts.
That context caches the pool so that you don't create new thread pools again and
again.
# Cache Behavior
Both key-value cache and the summary cache would be cleared if summary_cache_opts
is set to not None. A new summary cache would be created, whereas the old
key-value cache would be cleared.
# Print Buffer Behavior
If configure is called with a buffer_size not None, the old print buffer would
be cleared.
todo: I'm considering also clearing this buffer also when summary-cache is updated.
The use-case of changing print_buffer_size is pretty small. Should probaly
just deprecate this.
# Registering New Experiment
This is a convinient default for new users. It prints out a dashboard link to
the dashboard url.
todo: the table at the moment seems a bit verbose. I'm considering making this
just a single line print.
:param prefix: the first prefix
:param *prefixae: a list of prefix segments
:param root:
:param user:
:param access_token:
:param buffer_size:
:param summary_cache_opts:
:param asynchronous:
:param max_workers:
:param register_experiment:
:param silent: bool, True to turn off the print.
:return:
"""
# path logic
if prefix is not None:
prefixae = [interpolate(p) for p in (prefix, *prefixae) if p is not None]
if prefixae is not None:
self.prefix = os.path.join(*prefixae)
if buffer_size is not None:
self.print_buffer_size = buffer_size
self.print_buffer = ""
if summary_cache_opts is not None:
self.key_value_caches.clear()
self.summary_caches.clear()
self.summary_caches = defaultdict(partial(SummaryCache, **(summary_cache_opts or {})))
if root:
self.root = interpolate(root) or ROOT
if self.root or asynchronous is not None or max_workers is not None:
# note: logger.configure shouldn't be called too often. To quickly switch back
# and forth between synchronous and asynchronous calls, use the `SyncContext`
# and `AsyncContext` instead.
if not silent:
cprint('creating new logging client...', color='yellow', end='\r')
self.client.__init__(root=self.root, user=user, access_token=access_token,
asynchronous=asynchronous, max_workers=max_workers)
if not silent:
cprint('✓ created a new logging client', color="green")
if not silent:
if prefix:
from urllib.parse import quote
print(f"Dashboard: {ML_DASH.format(prefix=quote(self.prefix))}")
print(f"Log_directory: {self.root}")
# now register the experiment
if register_experiment:
raise DeprecationWarning("register_experiment is now set to None, and will be deprecated in the "
"next version. - Ge")
# with logger.SyncContext(clean=True): # single use SyncContext
# self.job_running(silent=silent)
@staticmethod
def fn_info(fn):
"""
logs information of the caller's stack (module, filename etc)
:param fn:
:return: info = dict(
name=_['__name__'],
doc=_['__doc__'],
module=_['__module__'],
file=_['__globals__']['__file__']
)
"""
from functools import partial
from inspect import getmembers
while True:
if hasattr(fn, "__wrapped__"):
fn = fn.__wrapped__
elif isinstance(fn, partial):
fn = fn.func
else:
break
_ = dict(getmembers(fn))
doc_string = _['__doc__']
if doc_string and len(doc_string) > 46:
doc_string = doc_string[:46] + " ..."
info = dict(name=_['__name__'], doc=doc_string, module=_['__module__'],
file=_['__globals__']['__file__'])
return info
def rev_info(self):
return dict(hash=self.__head__, branch=self.__current_branch__)
counter = defaultdict(lambda: 0)
def every(self, n=1, key="default", start_on=0):
"""
returns True every n counts. Use the key to count different intervals.
Example:
.. code:: python
for i in range(100):
if logger.every(10):
print('every tenth count!')
if logger.every(100, "hudred"):
print('every 100th count!')
if logger.every(10, "hudred", start_on=1):
print('every 10th count starting from the first call: i =', i)
:param n:
:param key:
:param start: start on this call. Use `start_on=1` for tail mode [0, 10, 20] instead of [9, 19, ...]
:return:
"""
self.counter[key] += 1
return (self.counter[key] - start_on) % n == 0 and self.counter[key] >= start_on
def count(self, key="default"):
self.counter[key] += 1
return self.counter[key]
def clear(self, key="default"):
try:
del self.counter[key]
except KeyError:
pass
def start(self, *keys):
"""
starts a timer, saved in float in seconds. The returned perf_counter does not have meaning
on its own. Only differences between two perf_counters make sense as time delta.
Automatically de-dupes the keys, but will return the same number of intervals. duplicates
will receive the same result.
.. code:: python
from ml_logger import logger
logger.start('loop', 'iter')
it = 0
for i in range(10):
it += logger.split('iter')
print('iteration', it / 10)
print('loop', logger.since('loop'))
:param *keys: position arguments are timed together.
:return: float (in seconds)
"""
keys = keys or ['default']
new_tic = perf_counter()
for key in set(keys):
self.timer_cache[key] = new_tic
return self.timer_cache[keys[0]] if len(keys) == 1 else [self.timer_cache[k] for k in keys]
def since(self, *keys):
"""
returns a float in seconds when 1 key is passed, or a list of floats when multiple
keys are passed in. The returned value are in seconds, measured by delta in perf_counter.
Automatically de-dupes the keys, but will return the same number of intervals. duplicates
will receive the same result.
Note: This *is* idempotent.
.. code:: python
from ml_logger import logger
logger.start('loop', 'iter')
it = 0
for i in range(10):
it += logger.split('iter')
print('iteration', it / 10)
print('loop', logger.since('loop'))
:param *keys: position arguments are timed together.
:return: float (in seconds)
"""
keys = keys or ['default']
results = {k: None for k in keys}
tick = perf_counter()
for key in set(keys):
try:
dt = tick - self.timer_cache[key]
results[key] = dt
except:
# not sure if setting an empty cache is good
self.timer_cache[key] = tick
results[key] = None
return results[keys[0]] \
if len(keys) == 1 else [results[k] for k in keys]
# timing functions
def split(self, *keys):
"""
returns a float in seconds when 1 key is passed, or a list of floats when multiple keys are
passed-in.
Automatically de-dupes the keys, but will return the same number of intervals. duplicates
will receive the same result.
Note: This is Not idempotent, which is why it is not a property.
.. code:: python
from ml_logger import logger
logger.split('loop', 'iter')
it = 0
for i in range(10):
it += logger.split('iter')
print('iteration', it / 10)
print('loop', logger.split('loop'))
:param *keys: position arguments are timed together.
:return: float (in seconds)
"""
keys = keys or ['default']
results = {k: None for k in keys}
new_tic = perf_counter()
for key in set(keys):
try:
results[key] = new_tic - self.timer_cache[key]
except KeyError as e:
pass
self.timer_cache[key] = new_tic
return results[keys[0]] if len(keys) == 1 else [results[k] for k in keys]
@contextmanager
def time(self, key="default", interval=1):
key, original = f"time.{key}", key
self.split(key)
yield
delta = self.split(key)
self.store(delta=delta, cache=key)
if self.every(interval, key=key):
logger.print(f"timing <{original}>:", end=" ")
data = self.summary_caches[key]['delta']
if interval > 1:
logger.print(f"{data.mean():0.3E}s", color="green", end=" ")
logger.print(f"±{data.std():0.1E}")
else:
logger.print(f"{data.mean():0.3E}s", color="green")
@staticmethod
def now(fmt=None):
return now(fmt)
@staticmethod
def utcnow(fmt=None):
return utcnow(fmt)
def truncate(self, path, depth=-1):
"""
truncates the path's parent directories w.r.t. given depth. By default, returns the filename
of the path.
.. code:: python
path = "/Users/geyang/some-proj/experiments/rope-cnn.py"
logger.truncate(path, -1)
::
"rope-cnn.py"
.. code:: python
logger.truncate(path, 4)
::
"experiments/rope-cnn.py"
This is useful for saving the *relative* path of your main script.
:param path: "learning-to-learn/experiments/run.py"
:param depth: 1, 2... when 1 it picks only the file name.
:return: "run"
"""
return "/".join(path.split('/')[depth:])
def stem(self, path):
"""
returns the stem of the filename in the path, removes the extension
.. code:: python
path = "/Users/geyang/some-proj/experiments/rope-cnn.py"
logger.stem(path)
returns:
::
"/Users/geyang/some-proj/experiments/rope-cnn"
You can use this in combination with the truncate function.
.. code:: python
_ = logger.truncate(path, 4)
_ = logger.stem(_)
::
"experiments/rope-cnn"
This is useful for saving the *relative* path of your main script.
:param path: "learning-to-learn/experiments/run.py"
:return: "run"
"""
return os.path.splitext(path)[0]
def diff(self, diff_directory=".", diff_filename="index.diff", ref="HEAD", verbose=False):
"""
example usage:
.. code:: python
from ml_logger import logger
logger.diff() # => this writes a diff file to the root of your logging directory.
:param ref: the ref w.r.t which you want to diff against. Default to HEAD
:param diff_directory: The root directory to call `git diff`, default to current directory.
:param diff_filename: The file key for saving the diff file.
:param verbose: if True, print out the command.
:return: string containing the content of the patch
"""
import subprocess
try:
cmd = f'cd "{os.path.realpath(diff_directory)}" && git diff {ref} --binary'
if verbose: self.log_line(cmd)
p = subprocess.check_output(cmd, shell=True) # Save git diff to experiment directory
patch = p.decode('utf-8').strip()
self.log_text(patch, diff_filename)
return patch
except subprocess.CalledProcessError as e:
self.log_line("not storing the git diff due to {}".format(e))
@property
def __status__(self):
"""
example usage:
--------------
.. code:: python
from ml_logger import logger
diff = logger.__status__ # => this writes a diff file to the root of your logging directory.
:return: the diff string for the current git repo.
"""
import subprocess
try:
cmd = f'cd "{os.path.getcwd()}" && git status -vv'
p = subprocess.check_output(cmd, shell=True) # Save git diff to experiment directory
return p.decode('utf-8').strip()
except subprocess.CalledProcessError as e:
return e
@property
def __current_branch__(self):
import subprocess
try:
cmd = f'git symbolic-ref HEAD'
p = subprocess.check_output(cmd, shell=True) # Save git diff to experiment directory
return p.decode('utf-8').strip()
except subprocess.CalledProcessError:
return None
@property
def __head__(self):
"""returns the git revision hash of the head if inside a git repository"""
return self.git_rev('HEAD')
def git_rev(self, branch):
"""
Helper function **used by `logger.__head__`** that returns the git revision hash of the
branch that you pass in.
full reference here: https://stackoverflow.com/a/949391
the `show-ref` and the `for-each-ref` commands both show a list of refs. We only need to get the
ref hash for the revision, not the entire branch of by tag.
"""
import subprocess
try:
cmd = ['git', 'rev-parse', branch]
p = subprocess.check_output(cmd)
return p.decode('utf-8').strip()
except subprocess.CalledProcessError:
return None
@property
def __tags__(self):
return self.git_tags()
def git_tags(self):
import subprocess
try:
cmd = ["git", "describe", "--tags"]
p = subprocess.check_output(cmd) # Save git diff to experiment directory
return p.decode('utf-8').strip()
except subprocess.CalledProcessError:
return None
def diff_file(self, path, silent=False):
raise NotImplementedError
# job host helper files
@property
def slurm_job_id(self):
import os
return os.getenv("SLURM_JOB_ID", None)
@property
def is_preempted(self):
import requests
return requests.get("http://169.254.169.254/latest/meta-data/spot/termination-time").status_code != 200
@property
def hostname(self):
import subprocess
cmd = 'hostname -f'
try:
p = subprocess.check_output(cmd, shell=True) # Save git diff to experiment directory
return p.decode('utf-8').strip()
except subprocess.CalledProcessError as e:
self.log_line(f"can not get obtain hostname via `{cmd}` due to exception: {e}")
return None
# job life-cycle methods
def job_created(self, job=None, **kwargs):
job = job or {}
job.update(status='created', createTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_requested(self, job=None, **kwargs):
job = job or {}
job.update(status='requested', requestTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_started(self, job=None, **kwargs):
job = job or {}
job.update(status='started', startTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_running(self, job=None, **kwargs):
# todo: this is called as a ping-home.
# todo: resolve race between multiple workers. Use hostname/job_id
job = job or {}
job.update(status='running', runTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_paused(self, job=None, **kwargs):
job = job or {}
job.update(status='paused', pauseTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_completed(self, job=None, **kwargs):
job = job or {}
job.update(status='completed', completionTime=self.utcnow())
self.log_params(job=job, **kwargs)
def job_errored(self, job=None, **kwargs):
job = job or {}
job.update(status='errored', errorTime=self.utcnow())
self.log_params(job=job, **kwargs)
def ping(self, status='running', interval=None):
"""
pings the instrumentation server to stay alive. Gets a control signal in return.
The background thread is responsible for making the call . This method just returns the buffered
signal synchronously.
:return: tuple signals
"""
if not self.duplex:
def thunk(*statuses):
nonlocal self
if len(statuses) > 0:
return self.client.ping(self.prefix, statuses[-1])
else:
return self.client.ping(self.prefix, "running")
self.duplex = Duplex(thunk, interval or 120) # default interval is two minutes
self.duplex.start()
if interval:
self.duplex.keep_alive_interval = interval
buffer = self.duplex.read_buffer()
self.duplex.send(status)
return buffer
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# todo: wait for logger to finish upload in async mode.
self.flush()
def remove(self, *paths):
"""
removes files and folders by path
:param path:
:return:
"""
found_paths = []
for path in paths:
found_paths += self.glob(path, wd=None) if "*" in path else [path]
for p in found_paths:
abs_path = pJoin(self.prefix, p)
self.client.delete(abs_path)
return found_paths
def glob_s3(self, *keys, path=None, max_keys=1000, **KWargs):
"""
Does not support wildcard or pagination, but we could add it in the future.
:param keys:
:param path:
:param max_keys: default is 1000 as in boto3
:return:
"""
import boto3
path = pJoin(*keys, path)
s3_client = boto3.client('s3')
# list_objects_v2 supports pagination. -- Ge
response = s3_client.list_objects(Bucket=path, MaxKeys=max_keys, **KWargs)
return [file['Key'] for file in response['Contents']]
def move(self, source, to):
abs_source = pJoin(self.prefix, source)
abs_target = pJoin(self.prefix, to)
self.client.move(abs_source, abs_target)
def duplicate(self, source, to, dirs_exist_ok=True):
abs_source = pJoin(self.prefix, source)
abs_target = pJoin(self.prefix, to)
self.client.duplicate(abs_source, abs_target, dirs_exist_ok=dirs_exist_ok)
def log_params(self, path="parameters.pkl", silent=False, **kwargs):
"""
Log namespaced parameters in a list.
Examples:
.. code:: python
logger.log_params(some_namespace=dict(layer=10, learning_rate=0.0001))
generates a table that looks like:
::
══════════════════════════════════════════
some_namespace
────────────────────┬─────────────────────
layer │ 10
learning_rate │ 0.0001
════════════════════╧═════════════════════
:param path: the file to which we save these parameters
:param silent: do not print out
:param kwargs: list of key/value pairs, each key representing the name of the namespace,
and the namespace itself.
:return: None
"""
from termcolor import colored as c
key_width = 20
value_width = 20
_kwargs = {}
table = []
for n, (title, section_data) in enumerate(kwargs.items()):
table.append('═' * (key_width) + ('═' if n == 0 else '╧') + '═' * (value_width + 1))
table.append(c('{:^{}}'.format(title, key_width), 'yellow') + "")
table.append('─' * (key_width) + "┬" + '─' * (value_width + 1))
if not hasattr(section_data, 'items'):
table.append(section_data)
_kwargs[title] = metrify(section_data)
else:
_param_dict = {}
for key, value in section_data.items():
_param_dict[key] = metrify(value.v if type(value) is Color else value)
value_string = str(value)
table.append('{:^{}}'.format(key, key_width) + "│ " + '{:<{}}'.format(value_string, value_width))
_kwargs[title] = _param_dict
if "n" in locals():
table.append('═' * (key_width) + '╧' + '═' * (value_width + 1))
# todo: add logging hook
# todo: add yml support
if table:
(self.log_line if silent else self.print)(*table, sep="\n")
self.log_data(path=path, data=_kwargs)
def save_pkl(self, data, path=None, append=False, use_dill=False):
"""Save data in pkl format
Note: We use dill so that we can save lambda functions but, but we use pure
pickle when saving nn.Modules
:param data: python data object to be saved
:param path: path for the object, relative to the root logging directory.
:param append: default to False -- overwrite by default
:return: None
"""
if use_dill:
import dill as pickle
else:
import pickle
path = path or "data.pkl"
abs_path = pJoin(self.prefix, path)
buf = BytesIO()
pickle.dump(data, buf)
buf.seek(0)
self.client.log_buffer(abs_path, buf=buf.read(), overwrite=not append)
return path
def log_data(self, data, path=None, overwrite=False):
"""
Append data to the file located at the path specified.
:param data: python data object to be saved
:param path: path for the object, relative to the root logging directory.
:param overwrite: boolean flag to switch between 'appending' mode and 'overwrite' mode.
:return: None
"""
return self.save_pkl(data, path, append=not overwrite)
def log_metrics(self, metrics=None, _prefix=None, silent=None,
cache: Union[str, None] = None, file: Union[str, None] = None,
flush=None, **_key_values) -> None:
"""
:param metrics: (mapping) key/values of metrics to be logged. Overwrites previous value if exist.
:param cache: optional KeyValueCache object to be passed in
:param flush:
:param _key_values:
:return:
"""
cache_key = cache
cache = self.key_value_caches[cache]
timestamp = np.datetime64(self.now())
metrics = metrics.copy() if metrics else {}
if _key_values:
metrics.update(_key_values)
with self.Prefix(metrics=_prefix):
if self.metrics_prefix:
metrics = {self.metrics_prefix + k: v for k, v in metrics.items()}
cache.update(metrics)
if flush:
self.flush_metrics(cache=cache_key, file=file, silent=silent)
def log_key_value(self, key: str, value: Any, cache=None) -> None:
cache = self.key_value_caches[cache]
timestamp = np.datetime64(self.now())
cache.update({key: value})
@property # get default cache
def summary_cache(self):
return self.summary_caches[None]
def store_key_value(self, key: str, value: Any, silent=None, cache: Union[str, None] = None) -> None:
"""
store the key: value awaiting future summary.
:param key: str, can be `/` separated.
:param value: numerical value