bert_squad_benchmark.py 10.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
21
22
23
24
25
26
27
28
29
30
31
32
# 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."""

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

import json
import os
import time

# pylint: disable=g-bad-import-order
from absl import flags
from absl.testing import flagsaver
import tensorflow as tf
# pylint: enable=g-bad-import-order

from official.bert import run_squad
from official.bert.benchmark import benchmark_utils
33
from official.bert.benchmark import squad_evaluate_v1_1
davidmochen's avatar
davidmochen committed
34
from official.utils.misc import distribution_utils
35
from official.utils.misc import keras_utils
davidmochen's avatar
davidmochen committed
36
37

# pylint: disable=line-too-long
38
PRETRAINED_CHECKPOINT_PATH = 'gs://cloud-tpu-checkpoints/bert/tf_20/uncased_L-24_H-1024_A-16/bert_model.ckpt'
davidmochen's avatar
davidmochen committed
39
40
41
42
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'
SQUAD_VOCAB_FILE = 'gs://tf-perfzero-data/bert/squad/vocab.txt'
SQUAD_SMALL_INPUT_META_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_small_meta_data'
43
SQUAD_FULL_INPUT_META_DATA_PATH = 'gs://tf-perfzero-data/bert/squad/squad_full_meta_data'
davidmochen's avatar
davidmochen committed
44
45
46
47
48
49
50
51
52
MODEL_CONFIG_FILE_PATH = 'gs://cloud-tpu-checkpoints/bert/tf_20/uncased_L-24_H-1024_A-16/bert_config'
# pylint: enable=line-too-long

FLAGS = flags.FLAGS


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

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

59
60
61
62
  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'))
63

64
65
  def _read_predictions_dataset_from_file(self):
    """Reads the predictions dataset from a file."""
66
67
    with tf.io.gfile.GFile(SQUAD_PREDICT_FILE, 'r') as reader:
      dataset_json = json.load(reader)
68
      return dataset_json['data']
69

70
71
72
  def _read_predictions_from_file(self):
    """Reads the predictions from a file."""
    predictions_file = os.path.join(FLAGS.model_dir, 'predictions.json')
73
    with tf.io.gfile.GFile(predictions_file, 'r') as reader:
74
      return json.load(reader)
75

76
  def _get_distribution_strategy(self, use_ds=True):
77
78
    """Gets the distribution strategy."""
    return distribution_utils.get_distribution_strategy(
79
80
        distribution_strategy='mirrored' if use_ds else 'off',
        num_gpus=self.num_gpus)
81

davidmochen's avatar
davidmochen committed
82
  @flagsaver.flagsaver
83
  def _train_squad(self, use_ds=True, run_eagerly=False):
84
85
    """Runs BERT SQuAD training."""
    input_meta_data = self._read_input_meta_data_from_file()
86
    strategy = self._get_distribution_strategy(use_ds)
davidmochen's avatar
davidmochen committed
87
88
89
90

    run_squad.train_squad(
        strategy=strategy,
        input_meta_data=input_meta_data,
91
        run_eagerly=run_eagerly,
davidmochen's avatar
davidmochen committed
92
        custom_callbacks=[self.timer_callback])
93
94

  @flagsaver.flagsaver
95
  def _evaluate_squad(self, use_ds=True):
96
97
    """Runs BERT SQuAD evaluation."""
    input_meta_data = self._read_input_meta_data_from_file()
98
    strategy = self._get_distribution_strategy(use_ds)
99

100
    run_squad.predict_squad(strategy=strategy, input_meta_data=input_meta_data)
101
102
103
104
105

    dataset = self._read_predictions_dataset_from_file()
    predictions = self._read_predictions_from_file()

    eval_metrics = squad_evaluate_v1_1.evaluate(dataset, predictions)
106
107
    # Use F1 score as reported evaluation metric.
    self.eval_metrics = eval_metrics['f1']
davidmochen's avatar
davidmochen committed
108
109


110
class BertSquadBenchmarkReal(BertSquadBenchmarkBase):
davidmochen's avatar
davidmochen committed
111
112
113
114
115
116
117
118
  """Short benchmark performance tests for BERT SQuAD model.

  Tests BERT SQuAD performance in different GPU configurations.
  The naming convention of below test cases follow
  `benchmark_(number of gpus)_gpu` format.
  """

  def __init__(self, output_dir=None, **kwargs):
119
    super(BertSquadBenchmarkReal, self).__init__(output_dir=output_dir)
davidmochen's avatar
davidmochen committed
120
121

  def _setup(self):
122
123
    """Sets up the benchmark and SQuAD flags."""
    super(BertSquadBenchmarkReal, self)._setup()
davidmochen's avatar
davidmochen committed
124
125
126
127
128
129
    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_SMALL_INPUT_META_DATA_PATH
    FLAGS.bert_config_file = MODEL_CONFIG_FILE_PATH
    FLAGS.num_train_epochs = 1
130
    FLAGS.steps_per_loop = 1
davidmochen's avatar
davidmochen committed
131

132
133
134
135
  def _run_and_report_benchmark(self,
                                use_ds=True,
                                enable_xla=False,
                                run_eagerly=False):
136
    """Runs the benchmark and reports various metrics."""
137
    keras_utils.set_config_v2(enable_xla)
138
    start_time_sec = time.time()
139
    self._train_squad(use_ds=use_ds, run_eagerly=run_eagerly)
140
141
142
143
144
145
146
147
148
    wall_time_sec = time.time() - start_time_sec

    summary = self._read_training_summary_from_file()

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

  def benchmark_1_gpu(self):
151
    """Tests BERT SQuAD model performance with 1 GPU."""
davidmochen's avatar
davidmochen committed
152
153
154
155
156
157

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

158
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
159

160
161
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
188
189
190
  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')
    FLAGS.train_batch_size = 4

    self._run_and_report_benchmark(enable_xla=True)

  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')
    FLAGS.train_batch_size = 4

    self._run_and_report_benchmark(use_ds=False)

  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')
    FLAGS.train_batch_size = 4

    self._run_and_report_benchmark(use_ds=False, run_eagerly=True)

davidmochen's avatar
davidmochen committed
191
  def benchmark_2_gpu(self):
192
    """Tests BERT SQuAD model performance with 2 GPUs."""
davidmochen's avatar
davidmochen committed
193
194
195
196
197
198

    self._setup()
    self.num_gpus = 2
    FLAGS.model_dir = self._get_model_dir('benchmark_2_gpu_squad')
    FLAGS.train_batch_size = 8

199
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
200
201

  def benchmark_4_gpu(self):
202
    """Tests BERT SQuAD model performance with 4 GPUs."""
davidmochen's avatar
davidmochen committed
203
204
205
206
207
208

    self._setup()
    self.num_gpus = 4
    FLAGS.model_dir = self._get_model_dir('benchmark_4_gpu_squad')
    FLAGS.train_batch_size = 16

209
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
210
211

  def benchmark_8_gpu(self):
212
213
214
215
216
217
218
    """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')
    FLAGS.train_batch_size = 32

219
    self._run_and_report_benchmark()
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241


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

  Tests BERT SQuAD accuracy. The naming convention of below test cases follow
  `benchmark_(number of gpus)_gpu` format.
  """

  def __init__(self, output_dir=None, **kwargs):
    super(BertSquadAccuracy, self).__init__(output_dir=output_dir)

  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
242
    FLAGS.steps_per_loop = 1
243

244
245
246
247
  def _run_and_report_benchmark(self,
                                use_ds=True,
                                enable_xla=False,
                                run_eagerly=False):
248
    """Runs the benchmark and reports various metrics."""
249
    keras_utils.set_config_v2(enable_xla)
250
    start_time_sec = time.time()
251
    self._train_squad(use_ds=use_ds, run_eagerly=run_eagerly)
252
253
254
255
256
257
258
259
260
    self._evaluate_squad()
    wall_time_sec = time.time() - start_time_sec

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

    super(BertSquadAccuracy, self)._report_benchmark(
        stats=summary,
        wall_time_sec=wall_time_sec,
261
262
        min_accuracy=0.900,
        max_accuracy=0.908)
263

264
265
266
267
268
269
270
271
272
273
  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

    self._run_and_report_benchmark(use_ds=False, run_eagerly=True)

274
275
  def benchmark_8_gpu(self):
    """Tests BERT SQuAD model accuracy with 8 GPUs."""
davidmochen's avatar
davidmochen committed
276
277
278
279
280
281

    self._setup()
    self.num_gpus = 8
    FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_squad')
    FLAGS.train_batch_size = 32

282
    self._run_and_report_benchmark()
davidmochen's avatar
davidmochen committed
283

284
285
286
287
288
289
290
291
292
293
  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

    self._run_and_report_benchmark(enable_xla=True)

davidmochen's avatar
davidmochen committed
294
295
296

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