run_classifier.py 6.79 KB
Newer Older
Frederick Liu's avatar
Frederick Liu committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Hongkun Yu's avatar
Hongkun Yu committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# 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.
Frederick Liu's avatar
Frederick Liu committed
14

Hongkun Yu's avatar
Hongkun Yu committed
15
16
17
"""XLNet classification finetuning runner in tf2.0."""

import functools
Hongkun Yu's avatar
Hongkun Yu committed
18
# Import libraries
Hongkun Yu's avatar
Hongkun Yu committed
19
20
21
22
23
24
25
from absl import app
from absl import flags
from absl import logging

import numpy as np
import tensorflow as tf
# pylint: disable=unused-import
26
from official.common import distribute_utils
Hongkun Yu's avatar
Hongkun Yu committed
27
28
29
30
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
31
32
from official.nlp.xlnet import xlnet_config
from official.nlp.xlnet import xlnet_modeling as modeling
Hongkun Yu's avatar
Hongkun Yu committed
33
34

flags.DEFINE_integer("n_class", default=2, help="Number of classes.")
Hongkun Yu's avatar
Hongkun Yu committed
35
36
37
38
flags.DEFINE_string(
    "summary_type",
    default="last",
    help="Method used to summarize a sequence into a vector.")
Hongkun Yu's avatar
Hongkun Yu committed
39
40
41
42

FLAGS = flags.FLAGS


Hongkun Yu's avatar
Hongkun Yu committed
43
44
45
46
def get_classificationxlnet_model(model_config,
                                  run_config,
                                  n_class,
                                  summary_type="last"):
Hongkun Yu's avatar
Hongkun Yu committed
47
  model = modeling.ClassificationXLNetModel(
Hongkun Yu's avatar
Hongkun Yu committed
48
      model_config, run_config, n_class, summary_type, name="model")
Hongkun Yu's avatar
Hongkun Yu committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  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
71

72
73
  Returns:
    A float metric, accuracy.
Hongkun Yu's avatar
Hongkun Yu committed
74
75
76
77
78
79
80
81
82
83
84
85
  """

  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
86
    logits, labels, masks = strategy.run(
Hongkun Yu's avatar
Hongkun Yu committed
87
88
89
        _test_step_fn, args=(next(test_iterator),))
    return logits, labels, masks

Hongkun Yu's avatar
Hongkun Yu committed
90
  test_iterator = data_utils.get_input_iterator(test_input_fn, strategy)
Hongkun Yu's avatar
Hongkun Yu committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
  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]
115
  accuracy = float(correct) / float(total)
Hongkun Yu's avatar
Hongkun Yu committed
116
  logging.info("Train step: %d  /  acc = %d/%d = %f", step, correct, total,
117
               accuracy)
Hongkun Yu's avatar
Hongkun Yu committed
118
119
120
121
  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()
122
  return accuracy
Hongkun Yu's avatar
Hongkun Yu committed
123
124
125
126
127
128
129
130
131
132


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
133
  strategy = distribute_utils.get_distribution_strategy(
Hongkun Yu's avatar
Hongkun Yu committed
134
135
      distribution_strategy=FLAGS.strategy_type,
      tpu_address=FLAGS.tpu)
Hongkun Yu's avatar
Hongkun Yu committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  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)
Allen Wang's avatar
Allen Wang committed
158
  model_fn = functools.partial(get_classificationxlnet_model, model_config,
Hongkun Yu's avatar
Hongkun Yu committed
159
                               run_config, FLAGS.n_class, FLAGS.summary_type)
Hongkun Yu's avatar
Hongkun Yu committed
160
161
162
163
164
165
166
167
168
  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

169
170
171
172
173
174
175
176
  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,
177
      init_from_transformerxl=FLAGS.init_from_transformerxl,
178
179
180
181
182
      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
183
      save_steps=FLAGS.save_steps)
Hongkun Yu's avatar
Hongkun Yu committed
184
185
186
187


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