sentence_prediction_test.py 6.27 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Lint as: python3
# Copyright 2020 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.
# ==============================================================================
"""Tests for official.nlp.tasks.sentence_prediction."""
17
import functools
18
import os
19
20

from absl.testing import parameterized
21
22
23
24
25
26
27
28
29
import tensorflow as tf

from official.nlp.bert import configs
from official.nlp.bert import export_tfhub
from official.nlp.configs import bert
from official.nlp.configs import encoders
from official.nlp.tasks import sentence_prediction


30
class SentencePredictionTaskTest(tf.test.TestCase, parameterized.TestCase):
31

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
32
33
  def setUp(self):
    super(SentencePredictionTaskTest, self).setUp()
34
35
36
    self._train_data_config = bert.SentencePredictionDataConfig(
        input_path="dummy", seq_length=128, global_batch_size=1)

Pengchong Jin's avatar
Pengchong Jin committed
37
  def get_model_config(self, num_classes):
38
    return bert.BertPretrainerConfig(
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
39
40
41
42
43
        encoder=encoders.TransformerEncoderConfig(
            vocab_size=30522, num_layers=1),
        num_masked_tokens=0,
        cls_heads=[
            bert.ClsHeadConfig(
44
45
46
                inner_dim=10,
                num_classes=num_classes,
                name="sentence_prediction")
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
47
48
        ])

49
50
51
52
53
54
  def _run_task(self, config):
    task = sentence_prediction.SentencePredictionTask(config)
    model = task.build_model()
    metrics = task.build_metrics()

    strategy = tf.distribute.get_strategy()
55
56
    dataset = strategy.experimental_distribute_datasets_from_function(
        functools.partial(task.build_inputs, config.train_data))
57
58
59
60
61
62
63
64

    iterator = iter(dataset)
    optimizer = tf.keras.optimizers.SGD(lr=0.1)
    task.train_step(next(iterator), model, optimizer, metrics=metrics)
    task.validation_step(next(iterator), model, metrics=metrics)

  def test_task(self):
    config = sentence_prediction.SentencePredictionConfig(
Hongkun Yu's avatar
Hongkun Yu committed
65
        init_checkpoint=self.get_temp_dir(),
Pengchong Jin's avatar
Pengchong Jin committed
66
        model=self.get_model_config(2),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
67
        train_data=self._train_data_config)
68
69
70
71
72
73
74
75
76
77
    task = sentence_prediction.SentencePredictionTask(config)
    model = task.build_model()
    metrics = task.build_metrics()
    dataset = task.build_inputs(config.train_data)

    iterator = iter(dataset)
    optimizer = tf.keras.optimizers.SGD(lr=0.1)
    task.train_step(next(iterator), model, optimizer, metrics=metrics)
    task.validation_step(next(iterator), model, metrics=metrics)

Hongkun Yu's avatar
Hongkun Yu committed
78
79
80
81
82
83
84
85
86
    # Saves a checkpoint.
    pretrain_cfg = bert.BertPretrainerConfig(
        encoder=encoders.TransformerEncoderConfig(
            vocab_size=30522, num_layers=1),
        num_masked_tokens=20,
        cls_heads=[
            bert.ClsHeadConfig(
                inner_dim=10, num_classes=3, name="next_sentence")
        ])
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
87
    pretrain_model = bert.instantiate_bertpretrainer_from_cfg(pretrain_cfg)
Hongkun Yu's avatar
Hongkun Yu committed
88
89
90
91
92
    ckpt = tf.train.Checkpoint(
        model=pretrain_model, **pretrain_model.checkpoint_items)
    ckpt.save(config.init_checkpoint)
    task.initialize(model)

93
94
95
  @parameterized.parameters(("matthews_corrcoef", 2),
                            ("pearson_spearman_corr", 1))
  def test_np_metrics(self, metric_type, num_classes):
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
96
    config = sentence_prediction.SentencePredictionConfig(
97
98
        metric_type=metric_type,
        init_checkpoint=self.get_temp_dir(),
Pengchong Jin's avatar
Pengchong Jin committed
99
        model=self.get_model_config(num_classes),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
100
101
102
        train_data=self._train_data_config)
    task = sentence_prediction.SentencePredictionTask(config)
    model = task.build_model()
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    dataset = task.build_inputs(config.train_data)

    iterator = iter(dataset)
    strategy = tf.distribute.get_strategy()
    distributed_outputs = strategy.run(
        functools.partial(task.validation_step, model=model),
        args=(next(iterator),))
    outputs = tf.nest.map_structure(strategy.experimental_local_results,
                                    distributed_outputs)
    aggregated = task.aggregate_logs(step_outputs=outputs)
    aggregated = task.aggregate_logs(state=aggregated, step_outputs=outputs)
    self.assertIn(metric_type, task.reduce_aggregated_logs(aggregated))

  def test_task_with_fit(self):
    config = sentence_prediction.SentencePredictionConfig(
Pengchong Jin's avatar
Pengchong Jin committed
118
        model=self.get_model_config(2), train_data=self._train_data_config)
119
120
    task = sentence_prediction.SentencePredictionTask(config)
    model = task.build_model()
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
121
122
123
124
125
126
127
128
129
    model = task.compile_model(
        model,
        optimizer=tf.keras.optimizers.SGD(lr=0.1),
        train_step=task.train_step,
        metrics=task.build_metrics())
    dataset = task.build_inputs(config.train_data)
    logs = model.fit(dataset, epochs=1, steps_per_epoch=2)
    self.assertIn("loss", logs.history)

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
  def _export_bert_tfhub(self):
    bert_config = configs.BertConfig(
        vocab_size=30522,
        hidden_size=16,
        intermediate_size=32,
        max_position_embeddings=128,
        num_attention_heads=2,
        num_hidden_layers=1)
    _, encoder = export_tfhub.create_bert_model(bert_config)
    model_checkpoint_dir = os.path.join(self.get_temp_dir(), "checkpoint")
    checkpoint = tf.train.Checkpoint(model=encoder)
    checkpoint.save(os.path.join(model_checkpoint_dir, "test"))
    model_checkpoint_path = tf.train.latest_checkpoint(model_checkpoint_dir)

    vocab_file = os.path.join(self.get_temp_dir(), "uncased_vocab.txt")
    with tf.io.gfile.GFile(vocab_file, "w") as f:
      f.write("dummy content")

    hub_destination = os.path.join(self.get_temp_dir(), "hub")
    export_tfhub.export_bert_tfhub(bert_config, model_checkpoint_path,
                                   hub_destination, vocab_file)
    return hub_destination

  def test_task_with_hub(self):
    hub_module_url = self._export_bert_tfhub()
    config = sentence_prediction.SentencePredictionConfig(
        hub_module_url=hub_module_url,
Pengchong Jin's avatar
Pengchong Jin committed
157
        model=self.get_model_config(2),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
158
        train_data=self._train_data_config)
159
160
161
162
163
    self._run_task(config)


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