Caffe2 - Python API
A deep learning, cross platform ML framework
experiment_util.py
1 
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 
8 import datetime
9 import time
10 import logging
11 import socket
12 import abc
13 import six
14 
15 from collections import OrderedDict
16 
17 '''
18 Utilities for logging experiment run stats, such as accuracy
19 and loss over time for different runs. Runtime arguments are stored
20 in the log.
21 
22 Optionally, ModelTrainerLog calls out to an logger to log to
23 an external log destination.
24 '''
25 
26 
27 class ExternalLogger(object):
28  six.add_metaclass(abc.ABCMeta)
29 
30  @abc.abstractmethod
31  def set_runtime_args(self, runtime_args):
32  """
33  Set runtime arguments for the logger.
34  runtime_args: dict of runtime arguments.
35  """
36  raise NotImplementedError(
37  'Must define set_runtime_args function to use this base class'
38  )
39 
40  @abc.abstractmethod
41  def log(self, log_dict):
42  """
43  log a dict of key/values to an external destination
44  log_dict: input dict
45  """
46  raise NotImplementedError(
47  'Must define log function to use this base class'
48  )
49 
50 
52 
53  def __init__(self, expname, runtime_args, external_loggers=None):
54  now = datetime.datetime.fromtimestamp(time.time())
55  self.experiment_id = \
56  "{}_{}".format(expname, now.strftime('%Y%m%d_%H%M%S'))
57  self.filename = "{}.log".format(self.experiment_id)
58  self.logstr("# %s" % str(runtime_args))
59  self.headers = None
60  self.start_time = time.time()
61  self.last_time = self.start_time
62  self.last_input_count = 0
63  self.external_loggers = None
64 
65  if external_loggers is not None:
66  self.external_loggers = external_loggers
67  runtime_args = dict(vars(runtime_args))
68  runtime_args['experiment_id'] = self.experiment_id
69  runtime_args['hostname'] = socket.gethostname()
70  for logger in self.external_loggers:
71  logger.set_runtime_args(runtime_args)
72  else:
73  self.external_loggers = []
74 
75  def logstr(self, str):
76  with open(self.filename, "a") as f:
77  f.write(str + "\n")
78  f.close()
79  logging.getLogger("experiment_logger").info(str)
80 
81  def log(self, input_count, batch_count, additional_values):
82  logdict = OrderedDict()
83  delta_t = time.time() - self.last_time
84  delta_count = input_count - self.last_input_count
85  self.last_time = time.time()
86  self.last_input_count = input_count
87 
88  logdict['time_spent'] = delta_t
89  logdict['cumulative_time_spent'] = time.time() - self.start_time
90  logdict['input_count'] = delta_count
91  logdict['cumulative_input_count'] = input_count
92  logdict['cumulative_batch_count'] = batch_count
93  if delta_t > 0:
94  logdict['inputs_per_sec'] = delta_count / delta_t
95  else:
96  logdict['inputs_per_sec'] = 0.0
97 
98  for k in sorted(additional_values.keys()):
99  logdict[k] = additional_values[k]
100 
101  # Write the headers if they are not written yet
102  if self.headers is None:
103  self.headers = logdict.keys()[:]
104  self.logstr(",".join(self.headers))
105 
106  self.logstr(",".join([str(v) for v in logdict.values()]))
107 
108  for logger in self.external_loggers:
109  try:
110  logger.log(logdict)
111  except Exception as e:
112  logging.warn(
113  "Failed to call ExternalLogger: {}".format(e), e)
def set_runtime_args(self, runtime_args)