shakespeare_benchmark.py 11.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Copyright 2019 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.
# ==============================================================================
"""Executes Shakespeare (LSTM) benchmark and accuracy tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import time

from absl import flags
David Chen's avatar
David Chen committed
24
import tensorflow as tf  # pylint: disable=g-bad-import-order
25

26
from official.benchmark.models.shakespeare import shakespeare_main
27
28
from official.utils.flags import core as flags_core
from official.utils.misc import keras_utils
29
from official.benchmark import benchmark_wrappers
30
from official.benchmark.perfzero_benchmark import PerfZeroBenchmark
31

Hongkun Yu's avatar
Hongkun Yu committed
32
SHAKESPEARE_TRAIN_DATA = 'shakespeare/shakespeare.txt'
David Chen's avatar
David Chen committed
33
TMP_DIR = os.getenv('TMPDIR')
34
35
36
37
38
39
40
41
42
43
44
45
FLAGS = flags.FLAGS


class ShakespeareBenchmarkBase(PerfZeroBenchmark):
  """Base class for Shakespeare (LSTM) benchmark and accuracy tests."""

  def __init__(self, output_dir=None, default_flags=None, root_data_dir=None):
    super(ShakespeareBenchmarkBase, self).__init__(
        output_dir=output_dir,
        default_flags=default_flags,
        flag_methods=[shakespeare_main.define_flags])

46
  @benchmark_wrappers.enable_runtime_flags
47
  def _run_and_report_benchmark(self,
Toby Boyd's avatar
Toby Boyd committed
48
49
                                top_1_train_min=0.91,
                                top_1_train_max=0.94,
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
76
77
78
79
                                warmup=1,
                                log_steps=100):
    """Report benchmark results by writing to local protobuf file.

    Average epoch time is calculated by skipping the first epoch. This average
    ignores time spent between epoch and is recorded by begin and end epoch. To
    skip accuracy check set `top_1_train_min=None`.

    Args:
      top_1_train_min: lowest passing value.
      top_1_train_max: highest passing value.
      warmup: number of entries in `timestamp_log` to ignore.
      log_steps: How often the log was created for `timestamp_log`.
    """
    total_batch_size = FLAGS.batch_size
    metrics = []
    start_time_sec = time.time()
    stats = shakespeare_main.run(FLAGS)
    wall_time_sec = time.time() - start_time_sec

    if top_1_train_min:
      metrics.append({'name': 'accuracy_top_1_train',
                      'value': stats['history']['RecallAt1'][-1],
                      'min_value': top_1_train_min,
                      'max_value': top_1_train_max})

    # Look for the time history callback which was used during keras.fit
    for callback in stats['callbacks']:
      if isinstance(callback, keras_utils.TimeHistory):
        epoch_timings = callback.epoch_runtime_log
80
81
82
83
        if len(epoch_timings) > 1:
          average_time = sum(epoch_timings[1:]) / len(epoch_timings[1:])
          metrics.append({'name': 'avg_epoch_time',
                          'value': average_time})
84
85
86
87
88
89
90

      # First entry in timestamp_log is the start of step 1. The rest of the
      # entries are the end of each step recorded.
      time_log = callback.timestamp_log
      elapsed = time_log[-1].timestamp - time_log[warmup].timestamp
      num_examples = (
          total_batch_size * log_steps * (len(time_log) - warmup - 1))
Sai Ganesh Bandiatmakuri's avatar
Sai Ganesh Bandiatmakuri committed
91
92
93
94
      if elapsed > 0:
        examples_per_sec = num_examples / elapsed
        metrics.append({'name': 'exp_per_second',
                        'value': examples_per_sec})
95
96
97
98
99
100
101
102
103
104
105
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
145
146
147
148
149
150
151
152
153
154
155

    flags_str = flags_core.get_nondefault_flags_as_str()
    self.report_benchmark(iters=-1, wall_time=wall_time_sec,
                          metrics=metrics,
                          extras={'flags': flags_str})


class ShakespeareAccuracy(ShakespeareBenchmarkBase):
  """Shakespeare accuracy tests.

  This is not an ideal test. The best we can use for the accuracy check is to
  validate top_1 of the training set. At batch size 64 the top_1 training
  stabilizes to ~0.92 around 40-45 epochs.
  """

  def __init__(self, output_dir=None, root_data_dir=None, **kwargs):
    """Shakespeare accuracy tests.

    Args:
      output_dir: directory where to output e.g. log files
      root_data_dir: directory under which to look for dataset
      **kwargs: arbitrary named arguments. This is needed to make the
                constructor forward compatible in case PerfZero provides more
                named arguments before updating the constructor.
    """
    self.train_data = os.path.join(root_data_dir, SHAKESPEARE_TRAIN_DATA)
    super(ShakespeareAccuracy, self).__init__(
        output_dir=output_dir, root_data_dir=root_data_dir)

  def benchmark_cpu(self):
    """Benchmark cpu."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    self._run_and_report_benchmark()

  def benchmark_cpu_no_ds_run_eagerly(self):
    """Benchmark cpu without distribution strategies and run eagerly."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    FLAGS.run_eagerly = True
    FLAGS.distribution_strategy = 'off'
    self._run_and_report_benchmark()

  def benchmark_1_gpu(self):
    """Benchmark 1 gpu."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    self._run_and_report_benchmark()

Toby Boyd's avatar
Toby Boyd committed
156
  def benchmark_1_gpu_no_ds(self):
157
    """Benchmark 1 gpu without distribution strategies."""
158
159
160
161
162
163
164
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    FLAGS.distribution_strategy = 'off'
Toby Boyd's avatar
Toby Boyd committed
165
    self._run_and_report_benchmark()
166

Toby Boyd's avatar
Toby Boyd committed
167
168
169
170
171
172
173
174
175
176
  def benchmark_1_gpu_no_ds_run_eagerly(self):
    """Benchmark 1 gpu without distribution strategies and run eagerly."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    FLAGS.run_eagerly = True
    FLAGS.distribution_strategy = 'off'
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    self._run_and_report_benchmark()

  def benchmark_xla_1_gpu(self):
    """Benchmark 1 gpu w/xla."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    FLAGS.enable_xla = True
    self._run_and_report_benchmark()

  def benchmark_8_gpu(self):
    """Benchmark 8 gpu.

    This is test is for accuracy not scaling.  The batch-size is not scaled to
    the number of gpus.
    """
    self._setup()
    FLAGS.num_gpus = 8
    FLAGS.training_data = self.train_data
    FLAGS.batch_size = 64
    FLAGS.train_epochs = 43
    FLAGS.model_dir = ''
    self._run_and_report_benchmark()


class ShakespeareKerasBenchmarkReal(ShakespeareBenchmarkBase):
  """Benchmark accuracy tests."""

David Chen's avatar
David Chen committed
208
  def __init__(self, output_dir=None, root_data_dir=TMP_DIR, **kwargs):
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    """Benchmark tests w/Keras.

    Args:
      output_dir: directory where to output e.g. log files
      root_data_dir: directory under which to look for dataset
      **kwargs: arbitrary named arguments. This is needed to make the
                constructor forward compatible in case PerfZero provides more
                named arguments before updating the constructor.
    """
    self.train_data = os.path.join(root_data_dir, SHAKESPEARE_TRAIN_DATA)

    def_flags = {}
    def_flags['training_data'] = self.train_data
    def_flags['model_dir'] = ''
    def_flags['train_epochs'] = 4
224
    def_flags['log_steps'] = 50
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

    super(ShakespeareKerasBenchmarkReal, self).__init__(
        output_dir=output_dir,
        root_data_dir=root_data_dir,
        default_flags=def_flags)

  def benchmark_cpu(self):
    """Benchmark cpu."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.batch_size = 64
    self._run_and_report_benchmark()

  def benchmark_cpu_no_ds_run_eagerly(self):
    """Benchmark cpu without distribution strategy and run eagerly."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.batch_size = 64
    FLAGS.distribution_strategy = 'off'
    FLAGS.run_eagerly = True
    self._run_and_report_benchmark()

  def benchmark_cpu_no_ds(self):
    """Benchmark cpu without distribution strategy."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.batch_size = 64
    FLAGS.distribution_strategy = 'off'
    self._run_and_report_benchmark()

Toby Boyd's avatar
Toby Boyd committed
255
256
257
258
259
260
261
262
  def benchmark_cpu_no_ds_force_v2(self):
    """Benchmark cpu no ds, and force v2."""
    self._setup()
    FLAGS.num_gpus = 0
    FLAGS.batch_size = 64
    FLAGS.distribution_strategy = 'off'
    self._run_and_report_benchmark()

263
264
265
266
267
268
269
  def benchmark_1_gpu(self):
    """Benchmark 1 gpu."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    self._run_and_report_benchmark()

270
271
272
273
274
275
276
277
  def benchmark_1_gpu_no_cudnn(self):
    """Benchmark 1 gpu with CuDNN disabled."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    FLAGS.cudnn = False
    self._run_and_report_benchmark()

278
279
280
281
282
283
284
  def benchmark_1_gpu_no_ds(self):
    """Benchmark 1 gpu without distribution strategies."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    FLAGS.distribution_strategy = 'off'
    self._run_and_report_benchmark()
Toby Boyd's avatar
Toby Boyd committed
285

286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
  def benchmark_1_gpu_no_ds_run_eagerly(self):
    """Benchmark 1 gpu."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    FLAGS.run_eagerly = True
    FLAGS.distribution_strategy = 'off'
    self._run_and_report_benchmark()

  def benchmark_xla_1_gpu(self):
    """Benchmark 1 gpu."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    FLAGS.enable_xla = True
    self._run_and_report_benchmark()

303
304
305
306
307
308
309
310
311
  def benchmark_xla_1_gpu_no_cudnn(self):
    """Benchmark 1 gpu w/xla and CuDNN disabled."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64
    FLAGS.cudnn = False
    FLAGS.enable_xla = True
    self._run_and_report_benchmark()

312
313
314
315
316
  def benchmark_8_gpu(self):
    """Benchmark 8 gpu."""
    self._setup()
    FLAGS.num_gpus = 8
    FLAGS.batch_size = 64 * 8
317
    FLAGS.log_steps = 10
318
319
    self._run_and_report_benchmark()

320
321
322
323
324
  def benchmark_8_gpu_no_cudnn(self):
    """Benchmark 8 gpu with CuDNN disabled."""
    self._setup()
    FLAGS.num_gpus = 8
    FLAGS.batch_size = 64 * 8
325
    FLAGS.log_steps = 10
326
327
328
    FLAGS.cudnn = False
    self._run_and_report_benchmark()

329
330
331
332
333
  def benchmark_xla_8_gpu(self):
    """Benchmark 8 gpu w/xla."""
    self._setup()
    FLAGS.num_gpus = 1
    FLAGS.batch_size = 64 * 8
334
    FLAGS.log_steps = 10
335
336
337
    FLAGS.enable_xla = True
    self._run_and_report_benchmark()

338
339
340
341
342
  def benchmark_xla_8_gpu_no_cudnn(self):
    """Benchmark 8 gpu w/xla and CuDNN disabled."""
    self._setup()
    FLAGS.num_gpus = 8
    FLAGS.batch_size = 64 * 8
343
    FLAGS.log_steps = 10
344
345
346
347
    FLAGS.cudnn = False
    FLAGS.enable_xla = True
    self._run_and_report_benchmark()

348
349
350
  def _run_and_report_benchmark(self):
    """Run and report benchmark."""
    super(ShakespeareKerasBenchmarkReal, self)._run_and_report_benchmark(
351
        top_1_train_min=None, log_steps=FLAGS.log_steps)
David Chen's avatar
David Chen committed
352
353
354
355


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