base_benchmark.py 6.49 KB
Newer Older
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Lint as: python3
# Copyright 2020 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.
# ==============================================================================
"""Common benchmark class for model garden models."""

import os
import pprint

# Import libraries

from absl import logging
Le Hou's avatar
Le Hou committed
24
import gin
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
25
26
27
28
29
30
31
32
33
34
35
import tensorflow as tf

from tensorflow.python.platform import benchmark  # pylint: disable=unused-import
from official.common import registry_imports  # pylint: disable=unused-import
from official.benchmark import benchmark_lib
from official.benchmark import benchmark_definitions
from official.benchmark import config_utils
from official.core import exp_factory
from official.modeling import hyperparams


Jaehong Kim's avatar
Jaehong Kim committed
36
def _get_benchmark_params(benchmark_models, eval_tflite=False):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
37
38
39
40
  """Formats benchmark params into a list."""
  parameterized_benchmark_params = []
  for _, benchmarks in benchmark_models.items():
    for name, params in benchmarks.items():
Jaehong Kim's avatar
Jaehong Kim committed
41
42
43
44
45
      if eval_tflite:
        execution_modes = ['performance', 'tflite_accuracy']
      else:
        execution_modes = ['performance', 'accuracy']
      for execution_mode in execution_modes:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
46
47
48
49
        benchmark_name = '{}.{}'.format(name, execution_mode)
        benchmark_params = (
            benchmark_name,  # First arg is used by ParameterizedBenchmark.
            benchmark_name,
Le Hou's avatar
Le Hou committed
50
            params.get('benchmark_function') or benchmark_lib.run_benchmark,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
51
52
53
54
55
56
            params['experiment_type'],
            execution_mode,
            params['platform'],
            params['precision'],
            params['metric_bounds'],
            params.get('config_files') or [],
Le Hou's avatar
Le Hou committed
57
58
            params.get('params_override') or None,
            params.get('gin_file') or [])
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
        parameterized_benchmark_params.append(benchmark_params)
  return parameterized_benchmark_params


class BaseBenchmark(  # pylint: disable=undefined-variable
    tf.test.Benchmark, metaclass=benchmark.ParameterizedBenchmark):
  """Common Benchmark.

     benchmark.ParameterizedBenchmark is used to auto create benchmarks from
     benchmark method according to the benchmarks defined in
     benchmark_definitions. The name of the new benchmark methods is
     benchmark__{benchmark_name}. _get_benchmark_params is used to generate the
     benchmark name and args.
  """

  _benchmark_parameters = _get_benchmark_params(
      benchmark_definitions.VISION_BENCHMARKS) + _get_benchmark_params(
Jaehong Kim's avatar
Jaehong Kim committed
76
77
          benchmark_definitions.NLP_BENCHMARKS) + _get_benchmark_params(
              benchmark_definitions.QAT_BENCHMARKS, True)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
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

  def __init__(self,
               output_dir=None,
               tpu=None):
    """Initialize class.

    Args:
      output_dir: Base directory to store all output for the test.
      tpu: (optional) TPU name to use in a TPU benchmark.
    """

    if os.getenv('BENCHMARK_OUTPUT_DIR'):
      self.output_dir = os.getenv('BENCHMARK_OUTPUT_DIR')
    elif output_dir:
      self.output_dir = output_dir
    else:
      self.output_dir = '/tmp'

    if os.getenv('BENCHMARK_TPU'):
      self._resolved_tpu = os.getenv('BENCHMARK_TPU')
    elif tpu:
      self._resolved_tpu = tpu
    else:
      self._resolved_tpu = None

  def _get_model_dir(self, folder_name):
    """Returns directory to store info, e.g. saved model and event log."""
    return os.path.join(self.output_dir, folder_name)

  def benchmark(self,
                benchmark_name,
Le Hou's avatar
Le Hou committed
109
                benchmark_function,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
110
111
112
113
114
115
                experiment_type,
                execution_mode,
                platform,
                precision,
                metric_bounds,
                config_files,
Le Hou's avatar
Le Hou committed
116
117
118
119
120
121
                params_override,
                gin_file):

    with gin.unlock_config():
      gin.parse_config_files_and_bindings(
          [config_utils.get_config_path(g) for g in gin_file], None)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
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

    params = exp_factory.get_exp_config(experiment_type)

    for config_file in config_files:
      file_path = config_utils.get_config_path(config_file)
      params = hyperparams.override_params_dict(
          params, file_path, is_strict=True)

    if params_override:
      params = hyperparams.override_params_dict(
          params, params_override, is_strict=True)
    # platform in format tpu.[n]x[n] or gpu.[n]
    if 'tpu' in platform:
      params.runtime.distribution_strategy = 'tpu'
      params.runtime.tpu = self._resolved_tpu
    elif 'gpu' in platform:
      params.runtime.num_gpus = int(platform.split('.')[-1])
      params.runtime.distribution_strategy = 'mirrored'
    else:
      NotImplementedError('platform :{} is not supported'.format(platform))

    params.runtime.mixed_precision_dtype = precision

    params.validate()
    params.lock()

    tf.io.gfile.makedirs(self._get_model_dir(benchmark_name))
    hyperparams.save_params_dict_to_yaml(
        params,
        os.path.join(self._get_model_dir(benchmark_name), 'params.yaml'))

    pp = pprint.PrettyPrinter()
    logging.info('Final experiment parameters: %s',
                 pp.pformat(params.as_dict()))

Le Hou's avatar
Le Hou committed
157
    benchmark_data = benchmark_function(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
158
159
160
        execution_mode, params, self._get_model_dir(benchmark_name))

    metrics = []
Jaehong Kim's avatar
Jaehong Kim committed
161
    if execution_mode in ['accuracy', 'tflite_accuracy']:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
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
      for metric_bound in metric_bounds:
        metric = {
            'name': metric_bound['name'],
            'value': benchmark_data['metrics'][metric_bound['name']],
            'min_value': metric_bound['min_value'],
            'max_value': metric_bound['max_value']
        }
        metrics.append(metric)

    metrics.append({'name': 'startup_time',
                    'value': benchmark_data['startup_time']})
    metrics.append({'name': 'exp_per_second',
                    'value': benchmark_data['examples_per_second']})

    self.report_benchmark(
        iters=-1,
        wall_time=benchmark_data['wall_time'],
        metrics=metrics,
        extras={'model_name': benchmark_name.split('.')[0],
                'platform': platform,
                'implementation': 'orbit.ctl',
                'parameters': precision})


if __name__ == '__main__':
  tf.test.main()