logger.py 8.9 KB
Newer Older
Scott Zhu's avatar
Scott Zhu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Copyright 2018 The TensorFlow 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.
# ==============================================================================

16
17
18
"""Logging utilities for benchmark.

For collecting local environment metrics like CPU and memory, certain python
19
packages need be installed. See README for details.
20
"""
Scott Zhu's avatar
Scott Zhu committed
21
22
23
24
25
26
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime
import json
27
import multiprocessing
Scott Zhu's avatar
Scott Zhu committed
28
29
import numbers
import os
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
30
import threading
Scott Zhu's avatar
Scott Zhu committed
31
32

import tensorflow as tf
33
from tensorflow.python.client import device_lib
Scott Zhu's avatar
Scott Zhu committed
34

35
36
METRIC_LOG_FILE_NAME = "metric.log"
BENCHMARK_RUN_LOG_FILE_NAME = "benchmark_run.log"
Scott Zhu's avatar
Scott Zhu committed
37
38
39
_DATE_TIME_FORMAT_PATTERN = "%Y-%m-%dT%H:%M:%S.%fZ"


Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
40
41
42
# Don't use it directly. Use get_benchmark_logger to access a logger.
_benchmark_logger = None
_logger_lock = threading.Lock()
Scott Zhu's avatar
Scott Zhu committed
43
44


Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
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
def config_benchmark_logger(logging_dir):
  """Config the global benchmark logger"""
  _logger_lock.acquire()
  try:
    global _benchmark_logger
    if logging_dir:
      _benchmark_logger = BenchmarkFileLogger(logging_dir)
    else:
      _benchmark_logger = BaseBenchmarkLogger()
  finally:
    _logger_lock.release()
  return _benchmark_logger


def get_benchmark_logger():
  if not _benchmark_logger:
    config_benchmark_logger(None)

  return _benchmark_logger


class BaseBenchmarkLogger(object):
  """Class to log the benchmark information to STDOUT."""

  def log_evaluation_result(self, eval_results):
    """Log the evaluation result.
71

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
72
    The evaluate result is a dictionary that contains metrics defined in
73
74
75
76
    model_fn. It also contains a entry for global_step which contains the value
    of the global step when evaluation was performed.

    Args:
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
77
      eval_results: dict, the result of evaluate.
78
79
    """
    if not isinstance(eval_results, dict):
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
80
81
      tf.logging.warning("eval_results should be dictionary for logging. "
                         "Got %s", type(eval_results))
82
83
      return
    global_step = eval_results[tf.GraphKeys.GLOBAL_STEP]
84
    for key in sorted(eval_results):
85
86
87
      if key != tf.GraphKeys.GLOBAL_STEP:
        self.log_metric(key, eval_results[key], global_step=global_step)

Scott Zhu's avatar
Scott Zhu committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  def log_metric(self, name, value, unit=None, global_step=None, extras=None):
    """Log the benchmark metric information to local file.

    Currently the logging is done in a synchronized way. This should be updated
    to log asynchronously.

    Args:
      name: string, the name of the metric to log.
      value: number, the value of the metric. The value will not be logged if it
        is not a number type.
      unit: string, the unit of the metric, E.g "image per second".
      global_step: int, the global_step when the metric is logged.
      extras: map of string:string, the extra information about the metric.
    """
    if not isinstance(value, numbers.Number):
      tf.logging.warning(
Karmel Allison's avatar
Karmel Allison committed
104
          "Metric value to log should be a number. Got %s", type(value))
Scott Zhu's avatar
Scott Zhu committed
105
      return
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
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
    extras = _convert_to_json_dict(extras)

    tf.logging.info("Benchmark metric: "
                    "Name %s, value %d, unit %s, global_step %d, extras %s",
                    name, value, unit, global_step, extras)

  def log_run_info(self, model_name):
    tf.logging.info("Benchmark run: %s", _gather_run_info(model_name))


class BenchmarkFileLogger(BaseBenchmarkLogger):
  """Class to log the benchmark information to local disk."""

  def __init__(self, logging_dir):
    super(BenchmarkFileLogger, self).__init__()
    self._logging_dir = logging_dir
    if not tf.gfile.IsDirectory(self._logging_dir):
      tf.gfile.MakeDirs(self._logging_dir)

  def log_metric(self, name, value, unit=None, global_step=None, extras=None):
    """Log the benchmark metric information to local file.

    Currently the logging is done in a synchronized way. This should be updated
    to log asynchronously.

    Args:
      name: string, the name of the metric to log.
      value: number, the value of the metric. The value will not be logged if it
        is not a number type.
      unit: string, the unit of the metric, E.g "image per second".
      global_step: int, the global_step when the metric is logged.
      extras: map of string:string, the extra information about the metric.
    """
    if not isinstance(value, numbers.Number):
      tf.logging.warning(
          "Metric value to log should be a number. Got %s", type(value))
      return
    extras = _convert_to_json_dict(extras)

Scott Zhu's avatar
Scott Zhu committed
145
    with tf.gfile.GFile(
146
        os.path.join(self._logging_dir, METRIC_LOG_FILE_NAME), "a") as f:
Scott Zhu's avatar
Scott Zhu committed
147
148
      metric = {
          "name": name,
Scott Zhu's avatar
Scott Zhu committed
149
          "value": float(value),
Scott Zhu's avatar
Scott Zhu committed
150
151
152
153
154
          "unit": unit,
          "global_step": global_step,
          "timestamp": datetime.datetime.now().strftime(
              _DATE_TIME_FORMAT_PATTERN),
          "extras": extras}
Scott Zhu's avatar
Scott Zhu committed
155
156
157
158
      try:
        json.dump(metric, f)
        f.write("\n")
      except (TypeError, ValueError) as e:
Karmel Allison's avatar
Karmel Allison committed
159
160
        tf.logging.warning("Failed to dump metric to log file: "
                           "name %s, value %s, error %s", name, value, e)
161
162
163
164
165
166
167
168
169

  def log_run_info(self, model_name):
    """Collect most of the TF runtime information for the local env.

    The schema of the run info follows official/benchmark/datastore/schema.

    Args:
      model_name: string, the name of the model.
    """
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
170
    run_info = _gather_run_info(model_name)
171
172

    with tf.gfile.GFile(os.path.join(
173
        self._logging_dir, BENCHMARK_RUN_LOG_FILE_NAME), "w") as f:
174
175
176
177
178
179
180
181
      try:
        json.dump(run_info, f)
        f.write("\n")
      except (TypeError, ValueError) as e:
        tf.logging.warning("Failed to dump benchmark run info to log file: %s",
                           e)


Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def _gather_run_info(model_name):
  """Collect the benchmark run information for the local environment."""
  run_info = {
      "model_name": model_name,
      "machine_config": {},
      "run_date": datetime.datetime.now().strftime(_DATE_TIME_FORMAT_PATTERN)}
  _collect_tensorflow_info(run_info)
  _collect_tensorflow_environment_variables(run_info)
  _collect_cpu_info(run_info)
  _collect_gpu_info(run_info)
  _collect_memory_info(run_info)
  return run_info


196
197
198
199
200
201
def _collect_tensorflow_info(run_info):
  run_info["tensorflow_version"] = {
      "version": tf.VERSION, "git_hash": tf.GIT_VERSION}


def _collect_tensorflow_environment_variables(run_info):
202
203
204
  run_info["tensorflow_environment_variables"] = [
      {"name": k, "value": v}
      for k, v in sorted(os.environ.items()) if k.startswith("TF_")]
205
206
207
208
209
210
211
212
213
214


# The following code is mirrored from tensorflow/tools/test/system_info_lib
# which is not exposed for import.
def _collect_cpu_info(run_info):
  """Collect the CPU information for the local environment."""
  cpu_info = {}

  cpu_info["num_cores"] = multiprocessing.cpu_count()

215
216
217
218
  # Note: cpuinfo is not installed in the TensorFlow OSS tree.
  # It is installable via pip.
  import cpuinfo    # pylint: disable=g-import-not-at-top

219
220
221
222
  info = cpuinfo.get_cpu_info()
  cpu_info["cpu_info"] = info["brand"]
  cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6

223
  run_info["machine_config"]["cpu_info"] = cpu_info
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240


def _collect_gpu_info(run_info):
  """Collect local GPU information by TF device library."""
  gpu_info = {}
  local_device_protos = device_lib.list_local_devices()

  gpu_info["count"] = len([d for d in local_device_protos
                           if d.device_type == "GPU"])
  # The device description usually is a JSON string, which contains the GPU
  # model info, eg:
  # "device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0"
  for d in local_device_protos:
    if d.device_type == "GPU":
      gpu_info["model"] = _parse_gpu_model(d.physical_device_desc)
      # Assume all the GPU connected are same model
      break
241
  run_info["machine_config"]["gpu_info"] = gpu_info
242
243
244


def _collect_memory_info(run_info):
245
246
247
  # Note: psutil is not installed in the TensorFlow OSS tree.
  # It is installable via pip.
  import psutil   # pylint: disable=g-import-not-at-top
248
  vmem = psutil.virtual_memory()
249
250
  run_info["machine_config"]["memory_total"] = vmem.total
  run_info["machine_config"]["memory_available"] = vmem.available
251
252
253
254
255
256
257
258
259


def _parse_gpu_model(physical_device_desc):
  # Assume all the GPU connected are same model
  for kv in physical_device_desc.split(","):
    k, _, v = kv.partition(":")
    if k.strip() == "name":
      return v.strip()
  return None
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
260
261
262
263
264
265
266


def _convert_to_json_dict(input_dict):
  if input_dict:
    return [{"name": k, "value": v} for k, v in sorted(input_dict.items())]
  else:
    return []