bert_squad_benchmark.py 21.1 KB
Newer Older
davidmochen's avatar
davidmochen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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 BERT SQuAD benchmarks and accuracy tests."""
import json
import os
import time

from absl import flags
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
21
from absl import logging
davidmochen's avatar
davidmochen committed
22
from absl.testing import flagsaver
23
import tensorflow as tf
davidmochen's avatar
davidmochen committed
24

25
from official.benchmark import benchmark_wrappers
26
from official.benchmark import bert_benchmark_utils as benchmark_utils
Jing Li's avatar
Jing Li committed
27
from official.benchmark import owner_utils
28
from official.common import distribute_utils
29
from official.nlp.bert import run_squad
30
from official.utils.misc import keras_utils
31

davidmochen's avatar
davidmochen committed
32
33

# pylint: disable=line-too-long
David Chen's avatar
David Chen committed
34
PRETRAINED_CHECKPOINT_PATH = 'gs://cloud-tpu-checkpoints/bert/keras_bert/uncased_L-24_H-1024_A-16/bert_model.ckpt'
davidmochen's avatar
davidmochen committed
35
36
SQUAD_TRAIN_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_train.tf_record'
SQUAD_PREDICT_FILE = 'gs://tf-perfzero-data/bert/squad/dev-v1.1.json'
David Chen's avatar
David Chen committed
37
SQUAD_VOCAB_FILE = 'gs://tf-perfzero-data/bert/squad/vocab.txt'
David Chen's avatar
David Chen committed
38
SQUAD_MEDIUM_INPUT_META_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_medium_meta_data'
Zongwei Zhou's avatar
Zongwei Zhou committed
39
SQUAD_LONG_INPUT_META_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_long_meta_data'
40
SQUAD_FULL_INPUT_META_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_full_meta_data'
David Chen's avatar
David Chen committed
41
MODEL_CONFIG_FILE_PATH = 'gs://cloud-tpu-checkpoints/bert/keras_bert/uncased_L-24_H-1024_A-16/bert_config.json'
davidmochen's avatar
davidmochen committed
42
43
# pylint: enable=line-too-long

David Chen's avatar
David Chen committed
44
TMP_DIR = os.getenv('TMPDIR')
davidmochen's avatar
davidmochen committed
45
46
47
48
49
50
FLAGS = flags.FLAGS


class BertSquadBenchmarkBase(benchmark_utils.BertBenchmarkBase):
  """Base class to hold methods common to test classes in the module."""

Zongwei Zhou's avatar
Zongwei Zhou committed
51
52
53
  def __init__(self, output_dir=None, tpu=None, **kwargs):
    super(BertSquadBenchmarkBase, self).__init__(
        output_dir=output_dir, tpu=tpu, **kwargs)
David Chen's avatar
David Chen committed
54

55
56
  def _read_training_summary_from_file(self):
    """Reads the training summary from a file."""
57
58
    summary_path = os.path.join(FLAGS.model_dir,
                                'summaries/training_summary.txt')
59
60
    with tf.io.gfile.GFile(summary_path, 'rb') as reader:
      return json.loads(reader.read().decode('utf-8'))
61

62
63
64
65
  def _read_input_meta_data_from_file(self):
    """Reads the input metadata from a file."""
    with tf.io.gfile.GFile(FLAGS.input_meta_data_path, 'rb') as reader:
      return json.loads(reader.read().decode('utf-8'))
66

67
68
69
70
71
  def _get_distribution_strategy(self, ds_type='mirrored'):
    """Gets the distribution strategy.

    Args:
      ds_type: String, the distribution strategy type to be used. Can be
Hongkun Yu's avatar
Hongkun Yu committed
72
        'mirrored', 'multi_worker_mirrored', 'tpu' and 'off'.
73
74
75
76

    Returns:
      A `tf.distribute.DistibutionStrategy` object.
    """
Sai Ganesh Bandiatmakuri's avatar
Sai Ganesh Bandiatmakuri committed
77
    if self.tpu or ds_type == 'tpu':
78
      return distribute_utils.get_distribution_strategy(
Sai Ganesh Bandiatmakuri's avatar
Sai Ganesh Bandiatmakuri committed
79
          distribution_strategy='tpu', tpu_address=self.tpu)
80
81
    elif ds_type == 'multi_worker_mirrored':
      # Configures cluster spec for multi-worker distribution strategy.
82
83
84
      _ = distribute_utils.configure_cluster(FLAGS.worker_hosts,
                                             FLAGS.task_index)
    return distribute_utils.get_distribution_strategy(
85
86
87
        distribution_strategy=ds_type,
        num_gpus=self.num_gpus,
        all_reduce_alg=FLAGS.all_reduce_alg)
88

89
90
91
92
93
94
95
96
97
  def _init_gpu_and_data_threads(self):
    """Set env variables before any TF calls."""
    if FLAGS.tf_gpu_thread_mode:
      keras_utils.set_gpu_thread_mode_and_count(
          per_gpu_thread_count=FLAGS.per_gpu_thread_count,
          gpu_thread_mode=FLAGS.tf_gpu_thread_mode,
          num_gpus=self.num_gpus,
          datasets_num_private_threads=FLAGS.datasets_num_private_threads)

davidmochen's avatar
davidmochen committed
98
  @flagsaver.flagsaver
99
100
  def _train_squad(self, run_eagerly=False, ds_type='mirrored'):
    """Runs BERT SQuAD training. Uses mirrored strategy by default."""
101
    self._init_gpu_and_data_threads()
102
    input_meta_data = self._read_input_meta_data_from_file()
103
    strategy = self._get_distribution_strategy(ds_type)
davidmochen's avatar
davidmochen committed
104
105
106
107

    run_squad.train_squad(
        strategy=strategy,
        input_meta_data=input_meta_data,
108
        run_eagerly=run_eagerly,
davidmochen's avatar
davidmochen committed
109
        custom_callbacks=[self.timer_callback])
110
111

  @flagsaver.flagsaver
112
113
  def _evaluate_squad(self, ds_type='mirrored'):
    """Runs BERT SQuAD evaluation. Uses mirrored strategy by default."""
114
    self._init_gpu_and_data_threads()
115
    input_meta_data = self._read_input_meta_data_from_file()
116
    strategy = self._get_distribution_strategy(ds_type)
117

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
118
119
    if input_meta_data.get('version_2_with_negative', False):
      logging.error('In memory evaluation result for SQuAD v2 is not accurate')
Hongkun Yu's avatar
Hongkun Yu committed
120
121
    eval_metrics = run_squad.eval_squad(
        strategy=strategy, input_meta_data=input_meta_data)
122
    # Use F1 score as reported evaluation metric.
Hongkun Yu's avatar
Hongkun Yu committed
123
    self.eval_metrics = eval_metrics['final_f1']
davidmochen's avatar
davidmochen committed
124
125


126
class BertSquadBenchmarkReal(BertSquadBenchmarkBase):
davidmochen's avatar
davidmochen committed
127
128
129
130
  """Short benchmark performance tests for BERT SQuAD model.

  Tests BERT SQuAD performance in different GPU configurations.
  The naming convention of below test cases follow
David Chen's avatar
David Chen committed
131
132
  `benchmark_(number of gpus)_gpu` format for GPUs and
  `benchmark_(topology)_tpu` format for TPUs.
davidmochen's avatar
davidmochen committed
133
134
  """

David Chen's avatar
David Chen committed
135
  def __init__(self, output_dir=TMP_DIR, tpu=None, **kwargs):
Zongwei Zhou's avatar
Zongwei Zhou committed
136
137
    super(BertSquadBenchmarkReal, self).__init__(
        output_dir=output_dir, tpu=tpu, **kwargs)
davidmochen's avatar
davidmochen committed
138
139

  def _setup(self):
140
141
    """Sets up the benchmark and SQuAD flags."""
    super(BertSquadBenchmarkReal, self)._setup()
davidmochen's avatar
davidmochen committed
142
143
144
145
146
    FLAGS.train_data_path = SQUAD_TRAIN_DATA_PATH
    FLAGS.predict_file = SQUAD_PREDICT_FILE
    FLAGS.vocab_file = SQUAD_VOCAB_FILE
    FLAGS.bert_config_file = MODEL_CONFIG_FILE_PATH
    FLAGS.num_train_epochs = 1
147
    FLAGS.steps_per_loop = 100
davidmochen's avatar
davidmochen committed
148

149
  @benchmark_wrappers.enable_runtime_flags
Hongkun Yu's avatar
Hongkun Yu committed
150
  def _run_and_report_benchmark(self, run_eagerly=False, ds_type='mirrored'):
151
    """Runs the benchmark and reports various metrics."""
152
    if FLAGS.train_batch_size <= 4 or run_eagerly:
153
154
155
      FLAGS.input_meta_data_path = SQUAD_MEDIUM_INPUT_META_DATA_PATH
    else:
      FLAGS.input_meta_data_path = SQUAD_LONG_INPUT_META_DATA_PATH
156
    start_time_sec = time.time()
157
    self._train_squad(run_eagerly=run_eagerly, ds_type=ds_type)
158
159
160
    wall_time_sec = time.time() - start_time_sec

    summary = self._read_training_summary_from_file()
David Chen's avatar
David Chen committed
161
    summary['start_time_sec'] = start_time_sec
162
163
164
165
166
167

    super(BertSquadBenchmarkReal, self)._report_benchmark(
        stats=summary,
        wall_time_sec=wall_time_sec,
        min_accuracy=0,
        max_accuracy=1)
davidmochen's avatar
davidmochen committed
168
169

  def benchmark_1_gpu(self):
170
    """Tests BERT SQuAD model performance with 1 GPU."""
davidmochen's avatar
davidmochen committed
171
172
173
174

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_squad')
175
    FLAGS.train_batch_size = 4
davidmochen's avatar
davidmochen committed
176

177
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
178

179
180
181
182
183
184
185
186
  def benchmark_1_gpu_eager(self):
    """Tests BERT SQuAD model performance with 1 GPU."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_squad_eager')
    FLAGS.train_batch_size = 2

Zongwei Zhou's avatar
Zongwei Zhou committed
187
    self._run_and_report_benchmark(run_eagerly=True)
188

189
190
191
192
193
194
  def benchmark_1_gpu_xla(self):
    """Tests BERT SQuAD model performance with 1 GPU with XLA."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_xla_squad')
195
196
    # XLA runs out of memory when running with batch size 4.
    FLAGS.train_batch_size = 3
197
    FLAGS.enable_xla = True
198

199
    self._run_and_report_benchmark()
200
201
202
203
204
205
206

  def benchmark_1_gpu_no_dist_strat(self):
    """Tests BERT SQuAD model performance with 1 GPU without DS."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_no_dist_strat_squad')
207
    FLAGS.train_batch_size = 4
208

209
    self._run_and_report_benchmark(ds_type='off')
210
211
212
213
214
215
216
217

  def benchmark_1_gpu_eager_no_dist_strat(self):
    """Tests BERT SQuAD model performance with 1 GPU with eager execution."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir(
        'benchmark_1_gpu_eager_no_dist_strat_squad')
218
    FLAGS.train_batch_size = 4
219

220
    self._run_and_report_benchmark(ds_type='off', run_eagerly=True)
221

Jing Li's avatar
Jing Li committed
222
  @owner_utils.Owner('tf-model-garden')
davidmochen's avatar
davidmochen committed
223
  def benchmark_8_gpu(self):
224
225
226
227
228
    """Tests BERT SQuAD model performance with 8 GPUs."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad')
Sai Ganesh Bandiatmakuri's avatar
Sai Ganesh Bandiatmakuri committed
229
    FLAGS.train_batch_size = 24
230
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
231

232
    self._run_and_report_benchmark()
233

234
235
236
237
238
239
240
241
242
243
  def benchmark_1_gpu_fp16_eager(self):
    """Tests BERT SQuAD model performance with 1 GPU and FP16."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_squad_fp16_eager')
    FLAGS.train_batch_size = 4
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'

Zongwei Zhou's avatar
Zongwei Zhou committed
244
    self._run_and_report_benchmark(run_eagerly=True)
245

246
247
248
249
250
251
252
253
254
255
256
257
  def benchmark_1_gpu_fp16(self):
    """Tests BERT SQuAD model performance with 1 GPU and FP16."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_squad_fp16')
    FLAGS.train_batch_size = 4
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'

    self._run_and_report_benchmark()

258
259
260
261
262
263
264
265
266
267
268
269
270
  def benchmark_1_gpu_xla_fp16(self):
    """Tests BERT SQuAD model performance with 1 GPU with XLA and FP16."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_xla_squad_fp16')
    FLAGS.train_batch_size = 4
    FLAGS.enable_xla = True
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'

    self._run_and_report_benchmark()

271
272
273
274
275
276
277
278
279
  def benchmark_8_gpu_fp16(self):
    """Tests BERT SQuAD model performance with 8 GPUs."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad_fp16')
    FLAGS.train_batch_size = 32
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'
280
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
281
282
283

    self._run_and_report_benchmark()

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
284
285
286
287
288
289
290
291
292
293
294
295
296
  def benchmark_8_gpu_xla_fp16(self):
    """Tests BERT SQuAD model performance with 8 GPUs with XLA."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad_fp16')
    FLAGS.train_batch_size = 32
    FLAGS.enable_xla = True
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'

    self._run_and_report_benchmark()

Pankaj Kanwar's avatar
Pankaj Kanwar committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
  def benchmark_8_gpu_xla_tf32(self):
    """Tests BERT SQuAD model performance with 8 GPUs with XLA using TF32."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_xla_tf32')
    FLAGS.train_batch_size = 32
    FLAGS.enable_xla = True
    FLAGS.loss_scale = 'dynamic'

    self._run_and_report_benchmark()

  def benchmark_8_gpu_xla_fp32_no_tf32(self):
    """Tests BERT SQuAD model performance with 8 GPUs with XLA using FP32."""

    self._setup()
    tf.config.experimental.enable_tensor_float_32_execution(False)
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_xla_fp32_no_tf32')
    FLAGS.train_batch_size = 32
    FLAGS.enable_xla = True
    FLAGS.loss_scale = 'dynamic'

    self._run_and_report_benchmark()

Jing Li's avatar
Jing Li committed
322
  @owner_utils.Owner('tf-model-garden')
David Chen's avatar
David Chen committed
323
324
325
326
327
328
  def benchmark_2x2_tpu(self):
    """Tests BERT SQuAD model performance with 2x2 TPU."""

    self._setup()
    FLAGS.model_dir = self._get_model_dir('benchmark_2x2_tpu')
    FLAGS.train_batch_size = 48
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
329
330
331
332
333
334
335
    FLAGS.predict_batch_size = 48
    FLAGS.mode = 'train'
    FLAGS.learning_rate = 8e-5
    FLAGS.num_train_epochs = 1
    FLAGS.steps_per_loop = 100
    FLAGS.do_lower_case = True
    FLAGS.init_checkpoint = PRETRAINED_CHECKPOINT_PATH
David Chen's avatar
David Chen committed
336
337
    self._run_and_report_benchmark()

338
339
340
341
342

class BertSquadAccuracy(BertSquadBenchmarkBase):
  """Short accuracy test for BERT SQuAD model.

  Tests BERT SQuAD accuracy. The naming convention of below test cases follow
David Chen's avatar
David Chen committed
343
344
  `benchmark_(number of gpus)_gpu` format for GPUs and
  `benchmark_(topology)_tpu` format for TPUs.
345
346
  """

David Chen's avatar
David Chen committed
347
  def __init__(self, output_dir=None, tpu=None, **kwargs):
Zongwei Zhou's avatar
Zongwei Zhou committed
348
349
    super(BertSquadAccuracy, self).__init__(
        output_dir=output_dir, tpu=tpu, **kwargs)
350
351
352
353
354
355
356
357
358
359
360

  def _setup(self):
    """Sets up the benchmark and SQuAD flags."""
    super(BertSquadAccuracy, self)._setup()
    FLAGS.train_data_path = SQUAD_TRAIN_DATA_PATH
    FLAGS.predict_file = SQUAD_PREDICT_FILE
    FLAGS.vocab_file = SQUAD_VOCAB_FILE
    FLAGS.input_meta_data_path = SQUAD_FULL_INPUT_META_DATA_PATH
    FLAGS.bert_config_file = MODEL_CONFIG_FILE_PATH
    FLAGS.init_checkpoint = PRETRAINED_CHECKPOINT_PATH
    FLAGS.num_train_epochs = 2
361
    FLAGS.steps_per_loop = 100
362

363
  @benchmark_wrappers.enable_runtime_flags
Hongkun Yu's avatar
Hongkun Yu committed
364
  def _run_and_report_benchmark(self, run_eagerly=False, ds_type='mirrored'):
365
    """Runs the benchmark and reports various metrics."""
366
    start_time_sec = time.time()
367
368
    self._train_squad(run_eagerly=run_eagerly, ds_type=ds_type)
    self._evaluate_squad(ds_type=ds_type)
369
370
371
372
    wall_time_sec = time.time() - start_time_sec

    summary = self._read_training_summary_from_file()
    summary['eval_metrics'] = self.eval_metrics
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
373
    summary['start_time_sec'] = start_time_sec
374
375
376
377

    super(BertSquadAccuracy, self)._report_benchmark(
        stats=summary,
        wall_time_sec=wall_time_sec,
378
        min_accuracy=0.900,
379
        max_accuracy=0.920)
380

381
382
383
384
385
386
387
388
  def benchmark_1_gpu_eager(self):
    """Tests BERT SQuAD model accuracy with 1 GPU with eager execution."""

    self._setup()
    self.num_gpus = 1
    FLAGS.model_dir = self._get_model_dir('benchmark_1_gpu_squad_eager')
    FLAGS.train_batch_size = 4

389
    self._run_and_report_benchmark(ds_type='off', run_eagerly=True)
390

Jing Li's avatar
Jing Li committed
391
  @owner_utils.Owner('tf-model-garden')
392
393
  def benchmark_8_gpu(self):
    """Tests BERT SQuAD model accuracy with 8 GPUs."""
davidmochen's avatar
davidmochen committed
394
395
396
397

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad')
398
    FLAGS.train_batch_size = 24
399
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
davidmochen's avatar
davidmochen committed
400

401
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
402

403
404
405
406
407
408
409
410
411
  def benchmark_8_gpu_fp16(self):
    """Tests BERT SQuAD model accuracy with 8 GPUs and FP16."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad_fp16')
    FLAGS.train_batch_size = 32
    FLAGS.dtype = 'fp16'
    FLAGS.loss_scale = 'dynamic'
412
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
413
414
415

    self._run_and_report_benchmark()

416
417
418
419
420
421
422
  def benchmark_8_gpu_xla(self):
    """Tests BERT SQuAD model accuracy with 8 GPUs."""

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad_xla')
    FLAGS.train_batch_size = 32
423
    FLAGS.enable_xla = True
424
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
425

426
    self._run_and_report_benchmark()
427

Jing Li's avatar
Jing Li committed
428
  @owner_utils.Owner('tf-model-garden')
David Chen's avatar
David Chen committed
429
430
431
432
433
434
435
436
437
  def benchmark_2x2_tpu(self):
    """Tests BERT SQuAD model accuracy with 2x2 TPU."""

    self._setup()
    FLAGS.model_dir = self._get_model_dir('benchmark_2x2_tpu')
    FLAGS.train_batch_size = 48

    self._run_and_report_benchmark()

davidmochen's avatar
davidmochen committed
438

439
440
441
442
443
class BertSquadMultiWorkerAccuracy(BertSquadBenchmarkBase):
  """BERT SQuAD distributed accuracy tests with multiple workers."""

  def __init__(self, output_dir=None, tpu=None, **kwargs):
    super(BertSquadMultiWorkerAccuracy, self).__init__(
Zongwei Zhou's avatar
Zongwei Zhou committed
444
        output_dir=output_dir, tpu=tpu, **kwargs)
445
446
447
448
449
450
451
452
453
454
455

  def _setup(self):
    """Sets up the benchmark and SQuAD flags."""
    super(BertSquadMultiWorkerAccuracy, self)._setup()
    FLAGS.train_data_path = SQUAD_TRAIN_DATA_PATH
    FLAGS.predict_file = SQUAD_PREDICT_FILE
    FLAGS.vocab_file = SQUAD_VOCAB_FILE
    FLAGS.input_meta_data_path = SQUAD_FULL_INPUT_META_DATA_PATH
    FLAGS.bert_config_file = MODEL_CONFIG_FILE_PATH
    FLAGS.init_checkpoint = PRETRAINED_CHECKPOINT_PATH
    FLAGS.num_train_epochs = 2
456
    FLAGS.steps_per_loop = 100
457
458

  @benchmark_wrappers.enable_runtime_flags
Hongkun Yu's avatar
Hongkun Yu committed
459
  def _run_and_report_benchmark(self, use_ds=True, run_eagerly=False):
460
461
    """Runs the benchmark and reports various metrics."""
    start_time_sec = time.time()
Hongkun Yu's avatar
Hongkun Yu committed
462
    self._train_squad(run_eagerly=run_eagerly, ds_type='multi_worker_mirrored')
463
    self._evaluate_squad(ds_type='multi_worker_mirrored')
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
    wall_time_sec = time.time() - start_time_sec

    summary = self._read_training_summary_from_file()
    summary['eval_metrics'] = self.eval_metrics

    super(BertSquadMultiWorkerAccuracy, self)._report_benchmark(
        stats=summary,
        wall_time_sec=wall_time_sec,
        min_accuracy=0.900,
        max_accuracy=0.920)

  def _benchmark_common(self, num_workers, all_reduce_alg):
    """Common to all benchmarks in this class."""
    self._setup()

    num_gpus = 8
    FLAGS.num_gpus = num_gpus
    FLAGS.dtype = 'fp16'
    FLAGS.enable_xla = False
    FLAGS.distribution_strategy = 'multi_worker_mirrored'
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
    FLAGS.datasets_num_private_threads = 32
    FLAGS.model_dir = self._get_model_dir(
        'benchmark_8_gpu_{}_worker_fp16_{}_tweaked'.format(
            num_workers, all_reduce_alg))
    FLAGS.train_batch_size = 4 * num_gpus * num_workers
    FLAGS.all_reduce_alg = all_reduce_alg

    self._run_and_report_benchmark()

Yanhui Liang's avatar
Yanhui Liang committed
494
495
496
497
498
499
500
501
  def benchmark_eager_8_gpu_2_workers_fp16_ring_tweaked(self):
    """8 GPUs per worker, 2 workers, fp16, ring all-reduce."""
    self._benchmark_common(num_workers=2, all_reduce_alg='ring')

  def benchmark_eager_8_gpu_2_workers_fp16_nccl_tweaked(self):
    """8 GPUs per worker, 2 workers, fp16, nccl all-reduce."""
    self._benchmark_common(num_workers=2, all_reduce_alg='nccl')

502
503
504
505
506
507
508
509
510
511
512
513
514
515
  def benchmark_8_gpu_8_workers_fp16_ring_tweaked(self):
    """8 GPUs per worker, 8 workers, fp16, ring all-reduce."""
    self._benchmark_common(num_workers=8, all_reduce_alg='ring')

  def benchmark_8_gpu_8_workers_fp16_nccl_tweaked(self):
    """8 GPUs per worker, 8 workers, fp16, nccl all-reduce."""
    self._benchmark_common(num_workers=8, all_reduce_alg='nccl')


class BertSquadMultiWorkerBenchmark(BertSquadBenchmarkBase):
  """BERT SQuAD distributed benchmark tests with multiple workers."""

  def __init__(self, output_dir=TMP_DIR, tpu=None, **kwargs):
    super(BertSquadMultiWorkerBenchmark, self).__init__(
Zongwei Zhou's avatar
Zongwei Zhou committed
516
        output_dir=output_dir, tpu=tpu, **kwargs)
517
518
519
520
521
522
523

  def _setup(self):
    """Sets up the benchmark and SQuAD flags."""
    super(BertSquadMultiWorkerBenchmark, self)._setup()
    FLAGS.train_data_path = SQUAD_TRAIN_DATA_PATH
    FLAGS.predict_file = SQUAD_PREDICT_FILE
    FLAGS.vocab_file = SQUAD_VOCAB_FILE
524
    FLAGS.input_meta_data_path = SQUAD_FULL_INPUT_META_DATA_PATH
525
526
    FLAGS.bert_config_file = MODEL_CONFIG_FILE_PATH
    FLAGS.num_train_epochs = 1
527
    FLAGS.steps_per_loop = 100
528
529

  @benchmark_wrappers.enable_runtime_flags
Hongkun Yu's avatar
Hongkun Yu committed
530
  def _run_and_report_benchmark(self, use_ds=True, run_eagerly=False):
531
    """Runs the benchmark and reports various metrics."""
532
533
534
535
    if FLAGS.train_batch_size <= 4 * 8:
      FLAGS.input_meta_data_path = SQUAD_LONG_INPUT_META_DATA_PATH
    else:
      FLAGS.input_meta_data_path = SQUAD_FULL_INPUT_META_DATA_PATH
536
    start_time_sec = time.time()
Hongkun Yu's avatar
Hongkun Yu committed
537
    self._train_squad(run_eagerly=run_eagerly, ds_type='multi_worker_mirrored')
538
539
540
541
542
543
544
545
546
547
548
    wall_time_sec = time.time() - start_time_sec

    summary = self._read_training_summary_from_file()
    summary['start_time_sec'] = start_time_sec

    super(BertSquadMultiWorkerBenchmark, self)._report_benchmark(
        stats=summary,
        wall_time_sec=wall_time_sec,
        min_accuracy=0,
        max_accuracy=1)

Hongkun Yu's avatar
Hongkun Yu committed
549
  def _benchmark_common(self, num_workers, all_reduce_alg):
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    """Common to all benchmarks in this class."""
    self._setup()

    num_gpus = 8
    FLAGS.num_gpus = num_gpus
    FLAGS.dtype = 'fp16'
    FLAGS.enable_xla = False
    FLAGS.distribution_strategy = 'multi_worker_mirrored'
    FLAGS.tf_gpu_thread_mode = 'gpu_private'
    FLAGS.datasets_num_private_threads = 32
    FLAGS.model_dir = self._get_model_dir(
        'benchmark_8_gpu_{}_worker_fp16_{}_tweaked'.format(
            num_workers, all_reduce_alg))
    FLAGS.train_batch_size = 4 * num_gpus * num_workers
    FLAGS.all_reduce_alg = all_reduce_alg

    self._run_and_report_benchmark()

  def benchmark_8_gpu_1_worker_fp16_ring_tweaked(self):
    """8 GPUs per worker, 1 worker, fp16, ring all-reduce."""
    self._benchmark_common(num_workers=1, all_reduce_alg='ring')

  def benchmark_8_gpu_1_worker_fp16_nccl_tweaked(self):
    """8 GPUs per worker, 1 worker, fp16, nccl all-reduce."""
    self._benchmark_common(num_workers=1, all_reduce_alg='nccl')

  def benchmark_8_gpu_2_workers_fp16_ring_tweaked(self):
    """8 GPUs per worker, 2 workers, fp16, ring all-reduce."""
Hongkun Yu's avatar
Hongkun Yu committed
578
    self._benchmark_common(num_workers=2, all_reduce_alg='ring')
579
580
581

  def benchmark_8_gpu_2_workers_fp16_nccl_tweaked(self):
    """8 GPUs per worker, 2 workers, fp16, nccl all-reduce."""
Hongkun Yu's avatar
Hongkun Yu committed
582
    self._benchmark_common(num_workers=2, all_reduce_alg='nccl')
583
584
585

  def benchmark_8_gpu_8_workers_fp16_ring_tweaked(self):
    """8 GPUs per worker, 8 workers, fp16, ring all-reduce."""
Hongkun Yu's avatar
Hongkun Yu committed
586
    self._benchmark_common(num_workers=8, all_reduce_alg='ring')
587
588
589

  def benchmark_8_gpu_8_workers_fp16_nccl_tweaked(self):
    """8 GPUs per worker, 8 workers, fp16, nccl all-reduce."""
Hongkun Yu's avatar
Hongkun Yu committed
590
    self._benchmark_common(num_workers=8, all_reduce_alg='nccl')
591
592


davidmochen's avatar
davidmochen committed
593
594
if __name__ == '__main__':
  tf.test.main()