masked_lm.py 7.54 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
# 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.
# ==============================================================================
"""Masked language task."""
Hongkun Yu's avatar
Hongkun Yu committed
17

Hongkun Yu's avatar
Hongkun Yu committed
18
19
20
21
import dataclasses
import tensorflow as tf

from official.core import base_task
22
from official.core import config_definitions as cfg
Abdullah Rashwan's avatar
Abdullah Rashwan committed
23
from official.core import task_factory
Hongkun Yu's avatar
Hongkun Yu committed
24
from official.modeling import tf_utils
Hongkun Yu's avatar
Hongkun Yu committed
25
from official.nlp.configs import bert
Hongkun Yu's avatar
Hongkun Yu committed
26
from official.nlp.configs import encoders
Chen Chen's avatar
Chen Chen committed
27
from official.nlp.data import data_loader_factory
Hongkun Yu's avatar
Hongkun Yu committed
28
29
from official.nlp.modeling import layers
from official.nlp.modeling import models
Hongkun Yu's avatar
Hongkun Yu committed
30
31
32
33
34


@dataclasses.dataclass
class MaskedLMConfig(cfg.TaskConfig):
  """The model config."""
Hongkun Yu's avatar
Hongkun Yu committed
35
  model: bert.PretrainerConfig = bert.PretrainerConfig(cls_heads=[
Hongkun Yu's avatar
Hongkun Yu committed
36
37
38
      bert.ClsHeadConfig(
          inner_dim=768, num_classes=2, dropout_rate=0.1, name='next_sentence')
  ])
Le Hou's avatar
Le Hou committed
39
40
41
  # TODO(b/154564893): Mathematically, scale_loss should be True.
  # However, it works better with scale_loss being False.
  scale_loss: bool = False
Hongkun Yu's avatar
Hongkun Yu committed
42
43
44
45
  train_data: cfg.DataConfig = cfg.DataConfig()
  validation_data: cfg.DataConfig = cfg.DataConfig()


Abdullah Rashwan's avatar
Abdullah Rashwan committed
46
@task_factory.register_task_cls(MaskedLMConfig)
Hongkun Yu's avatar
Hongkun Yu committed
47
class MaskedLMTask(base_task.Task):
Hongkun Yu's avatar
Hongkun Yu committed
48
  """Task object for Mask language modeling."""
Hongkun Yu's avatar
Hongkun Yu committed
49

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
50
  def build_model(self, params=None):
Hongkun Yu's avatar
Hongkun Yu committed
51
52
53
54
55
56
57
58
59
60
61
62
    config = params or self.task_config.model
    encoder_cfg = config.encoder
    encoder_network = encoders.build_encoder(encoder_cfg)
    cls_heads = [
        layers.ClassificationHead(**cfg.as_dict()) for cfg in config.cls_heads
    ] if config.cls_heads else []
    return models.BertPretrainerV2(
        mlm_activation=tf_utils.get_activation(config.mlm_activation),
        mlm_initializer=tf.keras.initializers.TruncatedNormal(
            stddev=config.mlm_initializer_range),
        encoder_network=encoder_network,
        classification_heads=cls_heads)
Hongkun Yu's avatar
Hongkun Yu committed
63
64

  def build_losses(self,
65
                   labels,
Hongkun Yu's avatar
Hongkun Yu committed
66
67
68
                   model_outputs,
                   metrics,
                   aux_losses=None) -> tf.Tensor:
Terry Huang's avatar
Terry Huang committed
69
70
71
72
    with tf.name_scope('MaskedLMTask/losses'):
      metrics = dict([(metric.name, metric) for metric in metrics])
      lm_prediction_losses = tf.keras.losses.sparse_categorical_crossentropy(
          labels['masked_lm_ids'],
Chen Chen's avatar
Chen Chen committed
73
          tf.cast(model_outputs['mlm_logits'], tf.float32),
Terry Huang's avatar
Terry Huang committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
          from_logits=True)
      lm_label_weights = labels['masked_lm_weights']
      lm_numerator_loss = tf.reduce_sum(lm_prediction_losses *
                                        lm_label_weights)
      lm_denominator_loss = tf.reduce_sum(lm_label_weights)
      mlm_loss = tf.math.divide_no_nan(lm_numerator_loss, lm_denominator_loss)
      metrics['lm_example_loss'].update_state(mlm_loss)
      if 'next_sentence_labels' in labels:
        sentence_labels = labels['next_sentence_labels']
        sentence_outputs = tf.cast(
            model_outputs['next_sentence'], dtype=tf.float32)
        sentence_loss = tf.reduce_mean(
            tf.keras.losses.sparse_categorical_crossentropy(
                sentence_labels, sentence_outputs, from_logits=True))
        metrics['next_sentence_loss'].update_state(sentence_loss)
        total_loss = mlm_loss + sentence_loss
      else:
        total_loss = mlm_loss

      if aux_losses:
        total_loss += tf.add_n(aux_losses)
      return total_loss
Hongkun Yu's avatar
Hongkun Yu committed
96
97
98
99

  def build_inputs(self, params, input_context=None):
    """Returns tf.data.Dataset for pretraining."""
    if params.input_path == 'dummy':
100

Hongkun Yu's avatar
Hongkun Yu committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
      def dummy_data(_):
        dummy_ids = tf.zeros((1, params.seq_length), dtype=tf.int32)
        dummy_lm = tf.zeros((1, params.max_predictions_per_seq), dtype=tf.int32)
        return dict(
            input_word_ids=dummy_ids,
            input_mask=dummy_ids,
            input_type_ids=dummy_ids,
            masked_lm_positions=dummy_lm,
            masked_lm_ids=dummy_lm,
            masked_lm_weights=tf.cast(dummy_lm, dtype=tf.float32),
            next_sentence_labels=tf.zeros((1, 1), dtype=tf.int32))

      dataset = tf.data.Dataset.range(1)
      dataset = dataset.repeat()
      dataset = dataset.map(
          dummy_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
      return dataset

Chen Chen's avatar
Chen Chen committed
119
    return data_loader_factory.get_data_loader(params).load(input_context)
Hongkun Yu's avatar
Hongkun Yu committed
120
121
122
123

  def build_metrics(self, training=None):
    del training
    metrics = [
124
        tf.keras.metrics.SparseCategoricalAccuracy(name='masked_lm_accuracy'),
Hongkun Yu's avatar
Hongkun Yu committed
125
126
127
128
129
130
131
132
133
134
        tf.keras.metrics.Mean(name='lm_example_loss')
    ]
    # TODO(hongkuny): rethink how to manage metrics creation with heads.
    if self.task_config.train_data.use_next_sentence_label:
      metrics.append(
          tf.keras.metrics.SparseCategoricalAccuracy(
              name='next_sentence_accuracy'))
      metrics.append(tf.keras.metrics.Mean(name='next_sentence_loss'))
    return metrics

135
  def process_metrics(self, metrics, labels, model_outputs):
Terry Huang's avatar
Terry Huang committed
136
137
138
139
    with tf.name_scope('MaskedLMTask/process_metrics'):
      metrics = dict([(metric.name, metric) for metric in metrics])
      if 'masked_lm_accuracy' in metrics:
        metrics['masked_lm_accuracy'].update_state(
Chen Chen's avatar
Chen Chen committed
140
            labels['masked_lm_ids'], model_outputs['mlm_logits'],
Terry Huang's avatar
Terry Huang committed
141
142
143
144
            labels['masked_lm_weights'])
      if 'next_sentence_accuracy' in metrics:
        metrics['next_sentence_accuracy'].update_state(
            labels['next_sentence_labels'], model_outputs['next_sentence'])
Hongkun Yu's avatar
Hongkun Yu committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

  def train_step(self, inputs, model: tf.keras.Model,
                 optimizer: tf.keras.optimizers.Optimizer, metrics):
    """Does forward and backward.

    Args:
      inputs: a dictionary of input tensors.
      model: the model, forward pass definition.
      optimizer: the optimizer for this training step.
      metrics: a nested structure of metrics objects.

    Returns:
      A dictionary of logs.
    """
    with tf.GradientTape() as tape:
      outputs = model(inputs, training=True)
      # Computes per-replica loss.
      loss = self.build_losses(
163
          labels=inputs,
Hongkun Yu's avatar
Hongkun Yu committed
164
165
166
          model_outputs=outputs,
          metrics=metrics,
          aux_losses=model.losses)
Le Hou's avatar
Le Hou committed
167
168
169
170
      if self.task_config.scale_loss:
        # Scales loss as the default gradients allreduce performs sum inside the
        # optimizer.
        scaled_loss = loss / tf.distribute.get_strategy().num_replicas_in_sync
Hongkun Yu's avatar
Hongkun Yu committed
171
    tvars = model.trainable_variables
Le Hou's avatar
Le Hou committed
172
173
174
175
    if self.task_config.scale_loss:
      grads = tape.gradient(scaled_loss, tvars)
    else:
      grads = tape.gradient(loss, tvars)
Hongkun Yu's avatar
Hongkun Yu committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    optimizer.apply_gradients(list(zip(grads, tvars)))
    self.process_metrics(metrics, inputs, outputs)
    return {self.loss: loss}

  def validation_step(self, inputs, model: tf.keras.Model, metrics):
    """Validatation step.

    Args:
      inputs: a dictionary of input tensors.
      model: the keras.Model.
      metrics: a nested structure of metrics objects.

    Returns:
      A dictionary of logs.
    """
    outputs = self.inference_step(inputs, model)
    loss = self.build_losses(
193
        labels=inputs,
Hongkun Yu's avatar
Hongkun Yu committed
194
195
196
197
198
        model_outputs=outputs,
        metrics=metrics,
        aux_losses=model.losses)
    self.process_metrics(metrics, inputs, outputs)
    return {self.loss: loss}