base_benchmark.py 7.13 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
# 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
Brandon Jiang's avatar
Brandon Jiang committed
19
from typing import Optional
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
20
21
22
# Import libraries

from absl import logging
Le Hou's avatar
Le Hou committed
23
import gin
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
24
25
26
27
28
29
30
31
32
33
34
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
35
def _get_benchmark_params(benchmark_models, eval_tflite=False):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
36
37
38
39
  """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
40
41
42
43
44
      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
45
46
47
48
        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
49
            params.get('benchmark_function') or benchmark_lib.run_benchmark,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
50
51
52
53
54
55
            params['experiment_type'],
            execution_mode,
            params['platform'],
            params['precision'],
            params['metric_bounds'],
            params.get('config_files') or [],
Le Hou's avatar
Le Hou committed
56
57
            params.get('params_override') or None,
            params.get('gin_file') or [])
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        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
75
          benchmark_definitions.NLP_BENCHMARKS) + _get_benchmark_params(
76
77
78
              benchmark_definitions.QAT_BENCHMARKS,
              True) + _get_benchmark_params(
                  benchmark_definitions.TENSOR_TRACER_BENCHMARKS)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
79
80
81

  def __init__(self,
               output_dir=None,
Brandon Jiang's avatar
Brandon Jiang committed
82
83
               tpu=None,
               tensorflow_models_path: Optional[str] = None):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
84
85
86
87
88
    """Initialize class.

    Args:
      output_dir: Base directory to store all output for the test.
      tpu: (optional) TPU name to use in a TPU benchmark.
Brandon Jiang's avatar
Brandon Jiang committed
89
90
      tensorflow_models_path: Full path to tensorflow models directory. Needed
        to locate config files.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    """

    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

Brandon Jiang's avatar
Brandon Jiang committed
107
108
109
110
111
    if os.getenv('TENSORFLOW_MODELS_PATH'):
      self._tensorflow_models_path = os.getenv('TENSORFLOW_MODELS_PATH')
    elif tensorflow_models_path:
      self._tensorflow_models_path = tensorflow_models_path
    else:
Brandon Jiang's avatar
Brandon Jiang committed
112
      self._tensorflow_models_path = ''
Brandon Jiang's avatar
Brandon Jiang committed
113

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
114
115
116
117
118
119
  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
120
                benchmark_function,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
121
122
123
124
125
126
                experiment_type,
                execution_mode,
                platform,
                precision,
                metric_bounds,
                config_files,
Le Hou's avatar
Le Hou committed
127
128
129
130
                params_override,
                gin_file):

    with gin.unlock_config():
Brandon Jiang's avatar
Brandon Jiang committed
131
132
133
134
      gin.parse_config_files_and_bindings([
          config_utils.get_config_path(
              g, base_dir=self._tensorflow_models_path) for g in gin_file
      ], None)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
135
136
137
138

    params = exp_factory.get_exp_config(experiment_type)

    for config_file in config_files:
Brandon Jiang's avatar
Brandon Jiang committed
139
140
      file_path = config_utils.get_config_path(
          config_file, base_dir=self._tensorflow_models_path)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
      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
170
    benchmark_data = benchmark_function(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
171
172
173
        execution_mode, params, self._get_model_dir(benchmark_name))

    metrics = []
Jaehong Kim's avatar
Jaehong Kim committed
174
    if execution_mode in ['accuracy', 'tflite_accuracy']:
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
      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()