xlnet.py 11.3 KB
Newer Older
Allen Wang's avatar
Allen Wang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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.
# ==============================================================================
Allen Wang's avatar
Allen Wang committed
15
"""XLNet models."""
Allen Wang's avatar
Allen Wang committed
16
17
18
19
20
21
22
# pylint: disable=g-classes-have-attributes

from typing import Any, Mapping, Union

import tensorflow as tf

from official.nlp.modeling import layers
Allen Wang's avatar
Allen Wang committed
23
from official.nlp.modeling import networks
Allen Wang's avatar
Allen Wang committed
24
25


Allen Wang's avatar
Allen Wang committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class XLNetMaskedLM(tf.keras.layers.Layer):
  """XLNet pretraining head."""

  def __init__(self,
               vocab_size: int,
               hidden_size: int,
               initializer: str = 'glorot_uniform',
               activation: str = 'gelu',
               name=None,
               **kwargs):
    super().__init__(name=name, **kwargs)
    self._vocab_size = vocab_size
    self._hidden_size = hidden_size
    self._initializer = initializer
    self._activation = activation

  def build(self, input_shape):
    self.dense = tf.keras.layers.Dense(
        units=self._hidden_size,
        activation=self._activation,
        kernel_initializer=self._initializer,
        name='transform/dense')
    self.layer_norm = tf.keras.layers.LayerNormalization(
        axis=-1, epsilon=1e-12, name='transform/LayerNorm')
    self.bias = self.add_weight(
        'output_bias/bias',
        shape=(self._vocab_size,),
        initializer='zeros',
        trainable=True)
    super().build(input_shape)

  def call(self,
           sequence_data: tf.Tensor,
           embedding_table: tf.Tensor):
    lm_data = self.dense(sequence_data)
    lm_data = self.layer_norm(lm_data)
    lm_data = tf.matmul(lm_data, embedding_table, transpose_b=True)
    logits = tf.nn.bias_add(lm_data, self.bias)
    return logits

  def get_config(self) -> Mapping[str, Any]:
    config = {
        'vocab_size':
            self._vocab_size,
        'hidden_size':
            self._hidden_size,
        'initializer':
            self._initializer
    }
    base_config = super(XLNetMaskedLM, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))


@tf.keras.utils.register_keras_serializable(package='Text')
class XLNetPretrainer(tf.keras.Model):
  """XLNet-based pretrainer.

  This is an implementation of the network structure surrounding a
  Transformer-XL encoder as described in "XLNet: Generalized Autoregressive
  Pretraining for Language Understanding" (https://arxiv.org/abs/1906.08237).

87
  Args:
Allen Wang's avatar
Allen Wang committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
    network: An XLNet/Transformer-XL based network. This network should output a
      sequence output and list of `state` tensors.
    mlm_activation: The activation (if any) to use in the Masked LM network. If
      None, then no activation will be used.
    mlm_initializer: The initializer (if any) to use in the masked LM. Defaults
      to a Glorot uniform initializer.

  """

  def __init__(
      self,
      network: Union[tf.keras.layers.Layer, tf.keras.Model],
      mlm_activation=None,
      mlm_initializer='glorot_uniform',
      name: str = None,
      **kwargs):
    super().__init__(name=name, **kwargs)
    self._config = {
        'network': network,
        'mlm_activation': mlm_activation,
        'mlm_initializer': mlm_initializer,
    }
    self._network = network
    self._hidden_size = network.get_config()['hidden_size']
    self._vocab_size = network.get_config()['vocab_size']
    self._activation = mlm_activation
    self._initializer = mlm_initializer
    self._masked_lm = XLNetMaskedLM(
        vocab_size=self._vocab_size,
        hidden_size=self._hidden_size,
        initializer=self._initializer)

  def call(self, inputs: Mapping[str, Any]):
    input_word_ids = inputs['input_word_ids']
    input_type_ids = inputs['input_type_ids']
    masked_tokens = inputs['masked_tokens']
    permutation_mask = inputs['permutation_mask']
    target_mapping = inputs['target_mapping']
    state = inputs.get('state', None)

    attention_output, state = self._network(
        input_ids=input_word_ids,
        segment_ids=input_type_ids,
        input_mask=None,
        state=state,
        permutation_mask=permutation_mask,
        target_mapping=target_mapping,
        masked_tokens=masked_tokens)

    embedding_table = self._network.get_embedding_lookup_table()
    mlm_outputs = self._masked_lm(
        sequence_data=attention_output,
        embedding_table=embedding_table)
    return mlm_outputs, state

  def get_config(self) -> Mapping[str, Any]:
    return self._config

  @classmethod
  def from_config(cls, config, custom_objects=None):
    return cls(**config)

  @property
  def checkpoint_items(self):
    return dict(encoder=self._network)


Allen Wang's avatar
Allen Wang committed
155
156
157
158
159
160
161
162
@tf.keras.utils.register_keras_serializable(package='Text')
class XLNetClassifier(tf.keras.Model):
  """Classifier model based on XLNet.

  This is an implementation of the network structure surrounding a
  Transformer-XL encoder as described in "XLNet: Generalized Autoregressive
  Pretraining for Language Understanding" (https://arxiv.org/abs/1906.08237).

Allen Wang's avatar
Allen Wang committed
163
164
165
  Note: This model does not use utilize the memory mechanism used in the
  original XLNet Classifier.

166
  Args:
Allen Wang's avatar
Allen Wang committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    network: An XLNet/Transformer-XL based network. This network should output a
      sequence output and list of `state` tensors.
    num_classes: Number of classes to predict from the classification network.
    initializer: The initializer (if any) to use in the classification networks.
      Defaults to a RandomNormal initializer.
    summary_type: Method used to summarize a sequence into a compact vector.
    dropout_rate: The dropout probability of the cls head.
  """

  def __init__(
      self,
      network: Union[tf.keras.layers.Layer, tf.keras.Model],
      num_classes: int,
      initializer: tf.keras.initializers.Initializer = 'random_normal',
      summary_type: str = 'last',
      dropout_rate: float = 0.1,
      **kwargs):
    super().__init__(**kwargs)
    self._network = network
    self._initializer = initializer
    self._summary_type = summary_type
    self._num_classes = num_classes
    self._config = {
        'network': network,
        'initializer': initializer,
        'num_classes': num_classes,
        'summary_type': summary_type,
        'dropout_rate': dropout_rate,
    }

    if summary_type == 'last':
      cls_token_idx = -1
    elif summary_type == 'first':
      cls_token_idx = 0
    else:
      raise ValueError('Invalid summary type provided: %s.' % summary_type)

    self.classifier = layers.ClassificationHead(
Allen Wang's avatar
Allen Wang committed
205
        inner_dim=network.get_config()['hidden_size'],
Allen Wang's avatar
Allen Wang committed
206
207
208
209
210
211
212
        num_classes=num_classes,
        initializer=initializer,
        dropout_rate=dropout_rate,
        cls_token_idx=cls_token_idx,
        name='sentence_prediction')

  def call(self, inputs: Mapping[str, Any]):
Allen Wang's avatar
Allen Wang committed
213
214
215
    input_ids = inputs['input_word_ids']
    segment_ids = inputs['input_type_ids']
    input_mask = tf.cast(inputs['input_mask'], tf.float32)
Allen Wang's avatar
Allen Wang committed
216
217
    state = inputs.get('mems', None)

Allen Wang's avatar
Allen Wang committed
218
    attention_output, _ = self._network(
Allen Wang's avatar
Allen Wang committed
219
220
221
222
223
224
225
        input_ids=input_ids,
        segment_ids=segment_ids,
        input_mask=input_mask,
        state=state)

    logits = self.classifier(attention_output)

Allen Wang's avatar
Allen Wang committed
226
    return logits
Allen Wang's avatar
Allen Wang committed
227
228
229
230
231
232
233

  def get_config(self):
    return self._config

  @classmethod
  def from_config(cls, config, custom_objects=None):
    return cls(**config)
Allen Wang's avatar
Allen Wang committed
234

Allen Wang's avatar
Allen Wang committed
235
236
237
238
239
240
241
242
  @property
  def checkpoint_items(self):
    items = dict(encoder=self._network)
    if hasattr(self.classifier, 'checkpoint_items'):
      for key, item in self.classifier.checkpoint_items.items():
        items['.'.join([self.classifier.name, key])] = item
    return items

Allen Wang's avatar
Allen Wang committed
243
244
245
246
247
248
249
250
251

@tf.keras.utils.register_keras_serializable(package='Text')
class XLNetSpanLabeler(tf.keras.Model):
  """Span labeler model based on XLNet.

  This is an implementation of the network structure surrounding a
  Transformer-XL encoder as described in "XLNet: Generalized Autoregressive
  Pretraining for Language Understanding" (https://arxiv.org/abs/1906.08237).

252
  Args:
Allen Wang's avatar
Allen Wang committed
253
254
255
256
257
258
    network: A transformer network. This network should output a sequence output
      and a classification output. Furthermore, it should expose its embedding
      table via a "get_embedding_table" method.
    start_n_top: Beam size for span start.
    end_n_top: Beam size for span end.
    dropout_rate: The dropout rate for the span labeling layer.
Allen Wang's avatar
Allen Wang committed
259
    span_labeling_activation: The activation for the span labeling head.
Allen Wang's avatar
Allen Wang committed
260
261
262
263
264
265
266
    initializer: The initializer (if any) to use in the span labeling network.
      Defaults to a Glorot uniform initializer.
  """

  def __init__(
      self,
      network: Union[tf.keras.layers.Layer, tf.keras.Model],
Allen Wang's avatar
Allen Wang committed
267
268
269
      start_n_top: int = 5,
      end_n_top: int = 5,
      dropout_rate: float = 0.1,
Allen Wang's avatar
Allen Wang committed
270
271
272
273
274
275
276
277
278
279
280
281
      span_labeling_activation: tf.keras.initializers.Initializer = 'tanh',
      initializer: tf.keras.initializers.Initializer = 'glorot_uniform',
      **kwargs):
    super().__init__(**kwargs)
    self._config = {
        'network': network,
        'start_n_top': start_n_top,
        'end_n_top': end_n_top,
        'dropout_rate': dropout_rate,
        'span_labeling_activation': span_labeling_activation,
        'initializer': initializer,
    }
Allen Wang's avatar
Allen Wang committed
282
283
284
285
286
287
288
289
290
    network_config = network.get_config()
    try:
      input_width = network_config['inner_size']
      self._xlnet_base = True
    except KeyError:
      # BertEncoder uses 'intermediate_size' due to legacy naming.
      input_width = network_config['intermediate_size']
      self._xlnet_base = False

Allen Wang's avatar
Allen Wang committed
291
292
293
294
295
296
297
    self._network = network
    self._initializer = initializer
    self._start_n_top = start_n_top
    self._end_n_top = end_n_top
    self._dropout_rate = dropout_rate
    self._activation = span_labeling_activation
    self.span_labeling = networks.XLNetSpanLabeling(
Allen Wang's avatar
Allen Wang committed
298
        input_width=input_width,
Allen Wang's avatar
Allen Wang committed
299
300
301
302
303
304
305
        start_n_top=self._start_n_top,
        end_n_top=self._end_n_top,
        activation=self._activation,
        dropout_rate=self._dropout_rate,
        initializer=self._initializer)

  def call(self, inputs: Mapping[str, Any]):
Allen Wang's avatar
Allen Wang committed
306
307
    input_word_ids = inputs['input_word_ids']
    input_type_ids = inputs['input_type_ids']
Allen Wang's avatar
Allen Wang committed
308
    input_mask = inputs['input_mask']
Allen Wang's avatar
Allen Wang committed
309
310
311
    class_index = inputs['class_index']
    paragraph_mask = inputs['paragraph_mask']
    start_positions = inputs.get('start_positions', None)
Allen Wang's avatar
Allen Wang committed
312

Allen Wang's avatar
Allen Wang committed
313
314
315
316
317
318
319
320
321
322
323
324
    if self._xlnet_base:
      attention_output, _ = self._network(
          input_ids=input_word_ids,
          segment_ids=input_type_ids,
          input_mask=input_mask)
    else:
      network_output_dict = self._network(dict(
          input_word_ids=input_word_ids,
          input_type_ids=input_type_ids,
          input_mask=input_mask))
      attention_output = network_output_dict['sequence_output']

Allen Wang's avatar
Allen Wang committed
325
326
327
    outputs = self.span_labeling(
        sequence_data=attention_output,
        class_index=class_index,
Allen Wang's avatar
Allen Wang committed
328
        paragraph_mask=paragraph_mask,
Allen Wang's avatar
Allen Wang committed
329
        start_positions=start_positions)
Allen Wang's avatar
Allen Wang committed
330
331
332
333
334
    return outputs

  @property
  def checkpoint_items(self):
    return dict(encoder=self._network)
Allen Wang's avatar
Allen Wang committed
335
336
337
338
339
340
341
342

  def get_config(self):
    return self._config

  @classmethod
  def from_config(cls, config, custom_objects=None):
    return cls(**config)