run_classifier.py 7.26 KB
Newer Older
Hongkun Yu's avatar
Hongkun Yu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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.
# ==============================================================================
"""XLNet classification finetuning runner in tf2.0."""

from __future__ import absolute_import
from __future__ import division
# from __future__ import google_type_annotations
from __future__ import print_function

import functools
Hongkun Yu's avatar
Hongkun Yu committed
23
# Import libraries
Hongkun Yu's avatar
Hongkun Yu committed
24
25
26
27
28
29
30
31
32
33
34
from absl import app
from absl import flags
from absl import logging

import numpy as np
import tensorflow as tf
# pylint: disable=unused-import
from official.nlp.xlnet import common_flags
from official.nlp.xlnet import data_utils
from official.nlp.xlnet import optimization
from official.nlp.xlnet import training_utils
35
36
from official.nlp.xlnet import xlnet_config
from official.nlp.xlnet import xlnet_modeling as modeling
Hongkun Yu's avatar
Hongkun Yu committed
37
from official.utils.misc import tpu_lib
Hongkun Yu's avatar
Hongkun Yu committed
38
39

flags.DEFINE_integer("n_class", default=2, help="Number of classes.")
Hongkun Yu's avatar
Hongkun Yu committed
40
41
42
43
flags.DEFINE_string(
    "summary_type",
    default="last",
    help="Method used to summarize a sequence into a vector.")
Hongkun Yu's avatar
Hongkun Yu committed
44
45
46
47

FLAGS = flags.FLAGS


Hongkun Yu's avatar
Hongkun Yu committed
48
49
50
51
def get_classificationxlnet_model(model_config,
                                  run_config,
                                  n_class,
                                  summary_type="last"):
Hongkun Yu's avatar
Hongkun Yu committed
52
  model = modeling.ClassificationXLNetModel(
Hongkun Yu's avatar
Hongkun Yu committed
53
      model_config, run_config, n_class, summary_type, name="model")
Hongkun Yu's avatar
Hongkun Yu committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  return model


def run_evaluation(strategy,
                   test_input_fn,
                   eval_steps,
                   model,
                   step,
                   eval_summary_writer=None):
  """Run evaluation for classification task.

  Args:
    strategy: distribution strategy.
    test_input_fn: input function for evaluation data.
    eval_steps: total number of evaluation steps.
    model: keras model object.
    step: current train step.
    eval_summary_writer: summary writer used to record evaluation metrics.  As
      there are fake data samples in validation set, we use mask to get rid of
      them when calculating the accuracy. For the reason that there will be
      dynamic-shape tensor, we first collect logits, labels and masks from TPU
      and calculate the accuracy via numpy locally.
Hongkun Yu's avatar
Hongkun Yu committed
76

77
78
  Returns:
    A float metric, accuracy.
Hongkun Yu's avatar
Hongkun Yu committed
79
80
81
82
83
84
85
86
87
88
89
90
  """

  def _test_step_fn(inputs):
    """Replicated validation step."""

    inputs["mems"] = None
    _, logits = model(inputs, training=False)
    return logits, inputs["label_ids"], inputs["is_real_example"]

  @tf.function
  def _run_evaluation(test_iterator):
    """Runs validation steps."""
Ken Franko's avatar
Ken Franko committed
91
    logits, labels, masks = strategy.run(
Hongkun Yu's avatar
Hongkun Yu committed
92
93
94
        _test_step_fn, args=(next(test_iterator),))
    return logits, labels, masks

Hongkun Yu's avatar
Hongkun Yu committed
95
  test_iterator = data_utils.get_input_iterator(test_input_fn, strategy)
Hongkun Yu's avatar
Hongkun Yu committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  correct = 0
  total = 0
  for _ in range(eval_steps):
    logits, labels, masks = _run_evaluation(test_iterator)
    logits = strategy.experimental_local_results(logits)
    labels = strategy.experimental_local_results(labels)
    masks = strategy.experimental_local_results(masks)
    merged_logits = []
    merged_labels = []
    merged_masks = []

    for i in range(strategy.num_replicas_in_sync):
      merged_logits.append(logits[i].numpy())
      merged_labels.append(labels[i].numpy())
      merged_masks.append(masks[i].numpy())
    merged_logits = np.vstack(np.array(merged_logits))
    merged_labels = np.hstack(np.array(merged_labels))
    merged_masks = np.hstack(np.array(merged_masks))
    real_index = np.where(np.equal(merged_masks, 1))
    correct += np.sum(
        np.equal(
            np.argmax(merged_logits[real_index], axis=-1),
            merged_labels[real_index]))
    total += np.shape(real_index)[-1]
120
  accuracy = float(correct) / float(total)
Hongkun Yu's avatar
Hongkun Yu committed
121
  logging.info("Train step: %d  /  acc = %d/%d = %f", step, correct, total,
122
               accuracy)
Hongkun Yu's avatar
Hongkun Yu committed
123
124
125
126
  if eval_summary_writer:
    with eval_summary_writer.as_default():
      tf.summary.scalar("eval_acc", float(correct) / float(total), step=step)
      eval_summary_writer.flush()
127
  return accuracy
Hongkun Yu's avatar
Hongkun Yu committed
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
157
158
159
160
161
162
163
164
165
166
167
168


def get_metric_fn():
  train_acc_metric = tf.keras.metrics.SparseCategoricalAccuracy(
      "acc", dtype=tf.float32)
  return train_acc_metric


def main(unused_argv):
  del unused_argv
  if FLAGS.strategy_type == "mirror":
    strategy = tf.distribute.MirroredStrategy()
  elif FLAGS.strategy_type == "tpu":
    cluster_resolver = tpu_lib.tpu_initialize(FLAGS.tpu)
    strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)
  else:
    raise ValueError("The distribution strategy type is not supported: %s" %
                     FLAGS.strategy_type)
  if strategy:
    logging.info("***** Number of cores used : %d",
                 strategy.num_replicas_in_sync)
  train_input_fn = functools.partial(data_utils.get_classification_input_data,
                                     FLAGS.train_batch_size, FLAGS.seq_len,
                                     strategy, True, FLAGS.train_tfrecord_path)
  test_input_fn = functools.partial(data_utils.get_classification_input_data,
                                    FLAGS.test_batch_size, FLAGS.seq_len,
                                    strategy, False, FLAGS.test_tfrecord_path)

  total_training_steps = FLAGS.train_steps
  steps_per_loop = FLAGS.iterations
  eval_steps = int(FLAGS.test_data_size / FLAGS.test_batch_size)
  eval_fn = functools.partial(run_evaluation, strategy, test_input_fn,
                              eval_steps)
  optimizer, learning_rate_fn = optimization.create_optimizer(
      FLAGS.learning_rate,
      total_training_steps,
      FLAGS.warmup_steps,
      adam_epsilon=FLAGS.adam_epsilon)
  model_config = xlnet_config.XLNetConfig(FLAGS)
  run_config = xlnet_config.create_run_config(True, False, FLAGS)
  model_fn = functools.partial(get_classificationxlnet_model, model_config,
Hongkun Yu's avatar
Hongkun Yu committed
169
                               run_config, FLAGS.n_class, FLAGS.summary_type)
Hongkun Yu's avatar
Hongkun Yu committed
170
171
172
173
174
175
176
177
178
  input_meta_data = {}
  input_meta_data["d_model"] = FLAGS.d_model
  input_meta_data["mem_len"] = FLAGS.mem_len
  input_meta_data["batch_size_per_core"] = int(FLAGS.train_batch_size /
                                               strategy.num_replicas_in_sync)
  input_meta_data["n_layer"] = FLAGS.n_layer
  input_meta_data["lr_layer_decay_rate"] = FLAGS.lr_layer_decay_rate
  input_meta_data["n_class"] = FLAGS.n_class

179
180
181
182
183
184
185
186
  training_utils.train(
      strategy=strategy,
      model_fn=model_fn,
      input_meta_data=input_meta_data,
      eval_fn=eval_fn,
      metric_fn=get_metric_fn,
      train_input_fn=train_input_fn,
      init_checkpoint=FLAGS.init_checkpoint,
187
      init_from_transformerxl=FLAGS.init_from_transformerxl,
188
189
190
191
192
      total_training_steps=total_training_steps,
      steps_per_loop=steps_per_loop,
      optimizer=optimizer,
      learning_rate_fn=learning_rate_fn,
      model_dir=FLAGS.model_dir,
Hongkun Yu's avatar
Hongkun Yu committed
193
      save_steps=FLAGS.save_steps)
Hongkun Yu's avatar
Hongkun Yu committed
194
195
196
197


if __name__ == "__main__":
  app.run(main)