logger.py 16.2 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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

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

34
35
from six.moves import _thread as thread
from absl import flags
Scott Zhu's avatar
Scott Zhu committed
36
import tensorflow as tf
37
from tensorflow.python.client import device_lib
Scott Zhu's avatar
Scott Zhu committed
38

39
40
from official.utils.logs import cloud_lib

41
42
METRIC_LOG_FILE_NAME = "metric.log"
BENCHMARK_RUN_LOG_FILE_NAME = "benchmark_run.log"
Scott Zhu's avatar
Scott Zhu committed
43
_DATE_TIME_FORMAT_PATTERN = "%Y-%m-%dT%H:%M:%S.%fZ"
44
GCP_TEST_ENV = "GCP"
45
46
47
RUN_STATUS_SUCCESS = "success"
RUN_STATUS_FAILURE = "failure"
RUN_STATUS_RUNNING = "running"
Scott Zhu's avatar
Scott Zhu committed
48

49

50
FLAGS = flags.FLAGS
Scott Zhu's avatar
Scott Zhu committed
51

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
52
53
54
# 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
55
56


57
def config_benchmark_logger(flag_obj=None):
Karmel Allison's avatar
Karmel Allison committed
58
  """Config the global benchmark logger."""
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
59
60
61
  _logger_lock.acquire()
  try:
    global _benchmark_logger
62
63
64
    if not flag_obj:
      flag_obj = FLAGS

Karmel Allison's avatar
Karmel Allison committed
65
66
    if (not hasattr(flag_obj, "benchmark_logger_type") or
        flag_obj.benchmark_logger_type == "BaseBenchmarkLogger"):
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
67
      _benchmark_logger = BaseBenchmarkLogger()
Karmel Allison's avatar
Karmel Allison committed
68
    elif flag_obj.benchmark_logger_type == "BenchmarkFileLogger":
69
      _benchmark_logger = BenchmarkFileLogger(flag_obj.benchmark_log_dir)
Karmel Allison's avatar
Karmel Allison committed
70
71
    elif flag_obj.benchmark_logger_type == "BenchmarkBigQueryLogger":
      from official.benchmark import benchmark_uploader as bu  # pylint: disable=g-import-not-at-top
72
73
74
75
76
      bq_uploader = bu.BigQueryUploader(gcp_project=flag_obj.gcp_project)
      _benchmark_logger = BenchmarkBigQueryLogger(
          bigquery_uploader=bq_uploader,
          bigquery_data_set=flag_obj.bigquery_data_set,
          bigquery_run_table=flag_obj.bigquery_run_table,
77
          bigquery_run_status_table=flag_obj.bigquery_run_status_table,
78
79
80
          bigquery_metric_table=flag_obj.bigquery_metric_table,
          run_id=str(uuid.uuid4()))
    else:
Karmel Allison's avatar
Karmel Allison committed
81
82
      raise ValueError("Unrecognized benchmark_logger_type: %s"
                       % flag_obj.benchmark_logger_type)
83

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
84
85
86
87
88
89
90
  finally:
    _logger_lock.release()
  return _benchmark_logger


def get_benchmark_logger():
  if not _benchmark_logger:
91
    config_benchmark_logger()
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
92
93
94
  return _benchmark_logger


95
96
97
98
99
100
101
102
103
104
105
106
107
@contextlib.contextmanager
def benchmark_context(flag_obj):
  """Context of benchmark, which will update status of the run accordingly."""
  benchmark_logger = config_benchmark_logger(flag_obj)
  try:
    yield
    benchmark_logger.on_finish(RUN_STATUS_SUCCESS)
  except Exception:  # pylint: disable=broad-except
    # Catch all the exception, update the run status to be failure, and re-raise
    benchmark_logger.on_finish(RUN_STATUS_FAILURE)
    raise


Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
108
109
110
111
112
class BaseBenchmarkLogger(object):
  """Class to log the benchmark information to STDOUT."""

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

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
114
    The evaluate result is a dictionary that contains metrics defined in
115
116
117
118
    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
119
      eval_results: dict, the result of evaluate.
120
121
    """
    if not isinstance(eval_results, dict):
122
123
124
      tf.compat.v1.logging.warning(
          "eval_results should be dictionary for logging. Got %s",
          type(eval_results))
125
      return
126
    global_step = eval_results[tf.compat.v1.GraphKeys.GLOBAL_STEP]
127
    for key in sorted(eval_results):
128
      if key != tf.compat.v1.GraphKeys.GLOBAL_STEP:
129
130
        self.log_metric(key, eval_results[key], global_step=global_step)

Scott Zhu's avatar
Scott Zhu committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
  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.
    """
145
146
    metric = _process_metric_to_json(name, value, unit, global_step, extras)
    if metric:
147
      tf.compat.v1.logging.info("Benchmark metric: %s", metric)
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
148

149
  def log_run_info(self, model_name, dataset_name, run_params, test_id=None):
150
151
152
    tf.compat.v1.logging.info(
        "Benchmark run: %s", _gather_run_info(model_name, dataset_name,
                                              run_params, test_id))
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
153

154
155
156
  def on_finish(self, status):
    pass

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
157
158
159
160
161
162
163

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
164
165
166
    if not tf.io.gfile.isdir(self._logging_dir):
      tf.io.gfile.makedirs(self._logging_dir)
    self._metric_file_handler = tf.io.gfile.GFile(
167
        os.path.join(self._logging_dir, METRIC_LOG_FILE_NAME), "a")
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

  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.
    """
183
184
    metric = _process_metric_to_json(name, value, unit, global_step, extras)
    if metric:
185
186
187
188
189
      try:
        json.dump(metric, self._metric_file_handler)
        self._metric_file_handler.write("\n")
        self._metric_file_handler.flush()
      except (TypeError, ValueError) as e:
190
191
192
        tf.compat.v1.logging.warning(
            "Failed to dump metric to log file: name %s, value %s, error %s",
            name, value, e)
193

194
  def log_run_info(self, model_name, dataset_name, run_params, test_id=None):
195
196
197
198
199
200
    """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.
201
202
203
      dataset_name: string, the name of dataset for training and evaluation.
      run_params: dict, the dictionary of parameters for the run, it could
        include hyperparameters or other params that are important for the run.
204
205
      test_id: string, the unique name of the test run by the combination of key
        parameters, eg batch size, num of GPU. It is hardware independent.
206
    """
207
    run_info = _gather_run_info(model_name, dataset_name, run_params, test_id)
208

209
    with tf.io.gfile.GFile(os.path.join(
210
        self._logging_dir, BENCHMARK_RUN_LOG_FILE_NAME), "w") as f:
211
212
213
214
      try:
        json.dump(run_info, f)
        f.write("\n")
      except (TypeError, ValueError) as e:
215
216
        tf.compat.v1.logging.warning(
            "Failed to dump benchmark run info to log file: %s", e)
217

218
  def on_finish(self, status):
219
220
    self._metric_file_handler.flush()
    self._metric_file_handler.close()
221

222

223
224
225
226
227
228
229
class BenchmarkBigQueryLogger(BaseBenchmarkLogger):
  """Class to log the benchmark information to BigQuery data store."""

  def __init__(self,
               bigquery_uploader,
               bigquery_data_set,
               bigquery_run_table,
230
               bigquery_run_status_table,
231
232
233
234
235
236
               bigquery_metric_table,
               run_id):
    super(BenchmarkBigQueryLogger, self).__init__()
    self._bigquery_uploader = bigquery_uploader
    self._bigquery_data_set = bigquery_data_set
    self._bigquery_run_table = bigquery_run_table
237
    self._bigquery_run_status_table = bigquery_run_status_table
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
    self._bigquery_metric_table = bigquery_metric_table
    self._run_id = run_id

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

    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.
    """
    metric = _process_metric_to_json(name, value, unit, global_step, extras)
    if metric:
      # Starting new thread for bigquery upload in case it might take long time
      # and impact the benchmark and performance measurement. Starting a new
      # thread might have potential performance impact for model that run on
      # CPU.
      thread.start_new_thread(
          self._bigquery_uploader.upload_benchmark_metric_json,
          (self._bigquery_data_set,
           self._bigquery_metric_table,
           self._run_id,
           [metric]))

265
  def log_run_info(self, model_name, dataset_name, run_params, test_id=None):
266
267
268
269
270
271
272
273
274
    """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.
      dataset_name: string, the name of dataset for training and evaluation.
      run_params: dict, the dictionary of parameters for the run, it could
        include hyperparameters or other params that are important for the run.
275
276
      test_id: string, the unique name of the test run by the combination of key
        parameters, eg batch size, num of GPU. It is hardware independent.
277
    """
278
    run_info = _gather_run_info(model_name, dataset_name, run_params, test_id)
279
280
281
282
283
284
285
286
287
    # Starting new thread for bigquery upload in case it might take long time
    # and impact the benchmark and performance measurement. Starting a new
    # thread might have potential performance impact for model that run on CPU.
    thread.start_new_thread(
        self._bigquery_uploader.upload_benchmark_run_json,
        (self._bigquery_data_set,
         self._bigquery_run_table,
         self._run_id,
         run_info))
288
289
290
291
292
293
294
295
    thread.start_new_thread(
        self._bigquery_uploader.insert_run_status,
        (self._bigquery_data_set,
         self._bigquery_run_status_table,
         self._run_id,
         RUN_STATUS_RUNNING))

  def on_finish(self, status):
296
297
298
299
300
    self._bigquery_uploader.update_run_status(
        self._bigquery_data_set,
        self._bigquery_run_status_table,
        self._run_id,
        status)
301

Karmel Allison's avatar
Karmel Allison committed
302

303
def _gather_run_info(model_name, dataset_name, run_params, test_id):
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
304
305
306
  """Collect the benchmark run information for the local environment."""
  run_info = {
      "model_name": model_name,
307
      "dataset": {"name": dataset_name},
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
308
      "machine_config": {},
309
      "test_id": test_id,
310
311
      "run_date": datetime.datetime.utcnow().strftime(
          _DATE_TIME_FORMAT_PATTERN)}
Sami Kama's avatar
Sami Kama committed
312
  session_config = None
313
  if "session_config" in run_params:
Sami Kama's avatar
Sami Kama committed
314
    session_config = run_params["session_config"]
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
315
316
  _collect_tensorflow_info(run_info)
  _collect_tensorflow_environment_variables(run_info)
317
  _collect_run_params(run_info, run_params)
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
318
  _collect_cpu_info(run_info)
Sami Kama's avatar
Sami Kama committed
319
  _collect_gpu_info(run_info, session_config)
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
320
  _collect_memory_info(run_info)
321
  _collect_test_environment(run_info)
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
322
323
324
  return run_info


325
326
327
328
def _process_metric_to_json(
    name, value, unit=None, global_step=None, extras=None):
  """Validate the metric data and generate JSON for insert."""
  if not isinstance(value, numbers.Number):
329
    tf.compat.v1.logging.warning(
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        "Metric value to log should be a number. Got %s", type(value))
    return None

  extras = _convert_to_json_dict(extras)
  return {
      "name": name,
      "value": float(value),
      "unit": unit,
      "global_step": global_step,
      "timestamp": datetime.datetime.utcnow().strftime(
          _DATE_TIME_FORMAT_PATTERN),
      "extras": extras}


344
345
def _collect_tensorflow_info(run_info):
  run_info["tensorflow_version"] = {
346
      "version": tf.version.VERSION, "git_hash": tf.version.GIT_VERSION}
347
348


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def _collect_run_params(run_info, run_params):
  """Log the parameter information for the benchmark run."""
  def process_param(name, value):
    type_check = {
        str: {"name": name, "string_value": value},
        int: {"name": name, "long_value": value},
        bool: {"name": name, "bool_value": str(value)},
        float: {"name": name, "float_value": value},
    }
    return type_check.get(type(value),
                          {"name": name, "string_value": str(value)})
  if run_params:
    run_info["run_parameters"] = [
        process_param(k, v) for k, v in sorted(run_params.items())]

Karmel Allison's avatar
Karmel Allison committed
364

365
def _collect_tensorflow_environment_variables(run_info):
366
367
368
  run_info["tensorflow_environment_variables"] = [
      {"name": k, "value": v}
      for k, v in sorted(os.environ.items()) if k.startswith("TF_")]
369
370
371
372
373
374
375
376
377
378


# 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()

379
380
381
382
  try:
    # Note: cpuinfo is not installed in the TensorFlow OSS tree.
    # It is installable via pip.
    import cpuinfo    # pylint: disable=g-import-not-at-top
383

384
385
386
    info = cpuinfo.get_cpu_info()
    cpu_info["cpu_info"] = info["brand"]
    cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6
387

388
389
    run_info["machine_config"]["cpu_info"] = cpu_info
  except ImportError:
390
391
    tf.compat.v1.logging.warn(
        "'cpuinfo' not imported. CPU info will not be logged.")
392
393


Sami Kama's avatar
Sami Kama committed
394
def _collect_gpu_info(run_info, session_config=None):
395
396
  """Collect local GPU information by TF device library."""
  gpu_info = {}
397
  local_device_protos = device_lib.list_local_devices(session_config)
398
399
400
401
402
403
404
405
406
407
408

  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
409
  run_info["machine_config"]["gpu_info"] = gpu_info
410
411
412


def _collect_memory_info(run_info):
413
414
415
416
417
418
419
420
  try:
    # Note: psutil is not installed in the TensorFlow OSS tree.
    # It is installable via pip.
    import psutil   # pylint: disable=g-import-not-at-top
    vmem = psutil.virtual_memory()
    run_info["machine_config"]["memory_total"] = vmem.total
    run_info["machine_config"]["memory_available"] = vmem.available
  except ImportError:
421
422
    tf.compat.v1.logging.warn(
        "'psutil' not imported. Memory info will not be logged.")
423
424


425
426
427
428
429
430
431
def _collect_test_environment(run_info):
  """Detect the local environment, eg GCE, AWS or DGX, etc."""
  if cloud_lib.on_gcp():
    run_info["test_environment"] = GCP_TEST_ENV
  # TODO(scottzhu): Add more testing env detection for other platform


432
433
434
435
436
437
438
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
439
440
441
442
443
444
445


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 []