logger_test.py 7.75 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
16
17
18
19
20
21
22
23
24
# 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.
# ==============================================================================

"""Tests for benchmark logger."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import os
import tempfile
25
import unittest
Scott Zhu's avatar
Scott Zhu committed
26

Karmel Allison's avatar
Karmel Allison committed
27
import tensorflow as tf  # pylint: disable=g-bad-import-order
Scott Zhu's avatar
Scott Zhu committed
28

29
from official.utils.logs import logger
Scott Zhu's avatar
Scott Zhu committed
30
31
32
33


class BenchmarkLoggerTest(tf.test.TestCase):

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
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
  def test_get_default_benchmark_logger(self):
    self.assertIsInstance(logger.get_benchmark_logger(),
                          logger.BaseBenchmarkLogger)

  def test_config_base_benchmark_logger(self):
    logger.config_benchmark_logger("")
    self.assertIsInstance(logger.get_benchmark_logger(),
                          logger.BaseBenchmarkLogger)

  def test_config_benchmark_file_logger(self):
    logger.config_benchmark_logger("/tmp/abc")
    self.assertIsInstance(logger.get_benchmark_logger(),
                          logger.BenchmarkFileLogger)


class BaseBenchmarkLoggerTest(tf.test.TestCase):

  def setUp(self):
    super(BaseBenchmarkLoggerTest, self).setUp()
    self._actual_log = tf.logging.info
    self.logged_message = None

    def mock_log(*args, **kwargs):
      self.logged_message = args
      self._actual_log(*args, **kwargs)

    tf.logging.info = mock_log

  def tearDown(self):
    super(BaseBenchmarkLoggerTest, self).tearDown()
    tf.logging.info = self._actual_log

  def test_log_metric(self):
    log = logger.BaseBenchmarkLogger()
    log.log_metric("accuracy", 0.999, global_step=1e4, extras={"name": "value"})

    expected_log_prefix = "Benchmark metric:"
    self.assertRegexpMatches(str(self.logged_message), expected_log_prefix)


class BenchmarkFileLoggerTest(tf.test.TestCase):

76
  def setUp(self):
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
77
    super(BenchmarkFileLoggerTest, self).setUp()
78
79
80
81
82
83
    # Avoid pulling extra env vars from test environment which affects the test
    # result, eg. Kokoro test has a TF_PKG env which affect the test case
    # test_collect_tensorflow_environment_variables()
    self.original_environ = dict(os.environ)
    os.environ.clear()

Scott Zhu's avatar
Scott Zhu committed
84
  def tearDown(self):
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
85
    super(BenchmarkFileLoggerTest, self).tearDown()
Scott Zhu's avatar
Scott Zhu committed
86
    tf.gfile.DeleteRecursively(self.get_temp_dir())
87
88
    os.environ.clear()
    os.environ.update(self.original_environ)
Scott Zhu's avatar
Scott Zhu committed
89
90
91
92
93

  def test_create_logging_dir(self):
    non_exist_temp_dir = os.path.join(self.get_temp_dir(), "unknown_dir")
    self.assertFalse(tf.gfile.IsDirectory(non_exist_temp_dir))

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
94
    logger.BenchmarkFileLogger(non_exist_temp_dir)
Scott Zhu's avatar
Scott Zhu committed
95
96
97
98
    self.assertTrue(tf.gfile.IsDirectory(non_exist_temp_dir))

  def test_log_metric(self):
    log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
99
    log = logger.BenchmarkFileLogger(log_dir)
Scott Zhu's avatar
Scott Zhu committed
100
101
102
103
104
105
106
107
108
109
    log.log_metric("accuracy", 0.999, global_step=1e4, extras={"name": "value"})

    metric_log = os.path.join(log_dir, "metric.log")
    self.assertTrue(tf.gfile.Exists(metric_log))
    with tf.gfile.GFile(metric_log) as f:
      metric = json.loads(f.readline())
      self.assertEqual(metric["name"], "accuracy")
      self.assertEqual(metric["value"], 0.999)
      self.assertEqual(metric["unit"], None)
      self.assertEqual(metric["global_step"], 1e4)
110
      self.assertEqual(metric["extras"], [{"name": "name", "value": "value"}])
Scott Zhu's avatar
Scott Zhu committed
111
112
113

  def test_log_multiple_metrics(self):
    log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
114
    log = logger.BenchmarkFileLogger(log_dir)
Scott Zhu's avatar
Scott Zhu committed
115
116
117
118
119
120
121
122
123
124
125
    log.log_metric("accuracy", 0.999, global_step=1e4, extras={"name": "value"})
    log.log_metric("loss", 0.02, global_step=1e4)

    metric_log = os.path.join(log_dir, "metric.log")
    self.assertTrue(tf.gfile.Exists(metric_log))
    with tf.gfile.GFile(metric_log) as f:
      accuracy = json.loads(f.readline())
      self.assertEqual(accuracy["name"], "accuracy")
      self.assertEqual(accuracy["value"], 0.999)
      self.assertEqual(accuracy["unit"], None)
      self.assertEqual(accuracy["global_step"], 1e4)
126
      self.assertEqual(accuracy["extras"], [{"name": "name", "value": "value"}])
Scott Zhu's avatar
Scott Zhu committed
127
128
129
130
131
132

      loss = json.loads(f.readline())
      self.assertEqual(loss["name"], "loss")
      self.assertEqual(loss["value"], 0.02)
      self.assertEqual(loss["unit"], None)
      self.assertEqual(loss["global_step"], 1e4)
133
      self.assertEqual(loss["extras"], [])
Scott Zhu's avatar
Scott Zhu committed
134

Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
135
  def test_log_non_number_value(self):
Scott Zhu's avatar
Scott Zhu committed
136
    log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
137
    log = logger.BenchmarkFileLogger(log_dir)
Scott Zhu's avatar
Scott Zhu committed
138
139
140
141
142
143
    const = tf.constant(1)
    log.log_metric("accuracy", const)

    metric_log = os.path.join(log_dir, "metric.log")
    self.assertFalse(tf.gfile.Exists(metric_log))

144
  def test_log_evaluation_result(self):
145
146
147
    eval_result = {"loss": 0.46237424,
                   "global_step": 207082,
                   "accuracy": 0.9285}
148
    log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
149
150
    log = logger.BenchmarkFileLogger(log_dir)
    log.log_evaluation_result(eval_result)
151
152
153
154
155
156
157
158
159
160

    metric_log = os.path.join(log_dir, "metric.log")
    self.assertTrue(tf.gfile.Exists(metric_log))
    with tf.gfile.GFile(metric_log) as f:
      accuracy = json.loads(f.readline())
      self.assertEqual(accuracy["name"], "accuracy")
      self.assertEqual(accuracy["value"], 0.9285)
      self.assertEqual(accuracy["unit"], None)
      self.assertEqual(accuracy["global_step"], 207082)

161
162
163
164
165
166
      loss = json.loads(f.readline())
      self.assertEqual(loss["name"], "loss")
      self.assertEqual(loss["value"], 0.46237424)
      self.assertEqual(loss["unit"], None)
      self.assertEqual(loss["global_step"], 207082)

167
168
169
  def test_log_evaluation_result_with_invalid_type(self):
    eval_result = "{'loss': 0.46237424, 'global_step': 207082}"
    log_dir = tempfile.mkdtemp(dir=self.get_temp_dir())
Qianli Scott Zhu's avatar
Qianli Scott Zhu committed
170
171
    log = logger.BenchmarkFileLogger(log_dir)
    log.log_evaluation_result(eval_result)
172
173
174
175

    metric_log = os.path.join(log_dir, "metric.log")
    self.assertFalse(tf.gfile.Exists(metric_log))

176
177
178
179
180
181
182
183
184
  def test_collect_tensorflow_info(self):
    run_info = {}
    logger._collect_tensorflow_info(run_info)
    self.assertNotEqual(run_info["tensorflow_version"], {})
    self.assertEqual(run_info["tensorflow_version"]["version"], tf.VERSION)
    self.assertEqual(run_info["tensorflow_version"]["git_hash"], tf.GIT_VERSION)

  def test_collect_tensorflow_environment_variables(self):
    os.environ["TF_ENABLE_WINOGRAD_NONFUSED"] = "1"
185
186
    os.environ["TF_OTHER"] = "2"
    os.environ["OTHER"] = "3"
187
188
189
190

    run_info = {}
    logger._collect_tensorflow_environment_variables(run_info)
    self.assertIsNotNone(run_info["tensorflow_environment_variables"])
191
192
193
194
195
196
    expected_tf_envs = [
        {"name": "TF_ENABLE_WINOGRAD_NONFUSED", "value": "1"},
        {"name": "TF_OTHER", "value": "2"},
    ]
    self.assertEqual(run_info["tensorflow_environment_variables"],
                     expected_tf_envs)
197
198
199

  @unittest.skipUnless(tf.test.is_built_with_cuda(), "requires GPU")
  def test_collect_gpu_info(self):
200
    run_info = {"machine_config": {}}
201
    logger._collect_gpu_info(run_info)
202
    self.assertNotEqual(run_info["machine_config"]["gpu_info"], {})
203
204

  def test_collect_memory_info(self):
205
    run_info = {"machine_config": {}}
206
    logger._collect_memory_info(run_info)
207
208
    self.assertIsNotNone(run_info["machine_config"]["memory_total"])
    self.assertIsNotNone(run_info["machine_config"]["memory_available"])
209

Scott Zhu's avatar
Scott Zhu committed
210
211
if __name__ == "__main__":
  tf.test.main()