bert_classifier.py 5.76 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

15
"""BERT cls-token classifier."""
16
# pylint: disable=g-classes-have-attributes
17
import collections
Hongkun Yu's avatar
Hongkun Yu committed
18
import tensorflow as tf
Hongkun Yu's avatar
Hongkun Yu committed
19

Hongkun Yu's avatar
Hongkun Yu committed
20
from official.nlp.modeling import layers
Hongkun Yu's avatar
Hongkun Yu committed
21
22
23
24
25
26
27
28
29
30
31
32


@tf.keras.utils.register_keras_serializable(package='Text')
class BertClassifier(tf.keras.Model):
  """Classifier model based on a BERT-style transformer-based encoder.

  This is an implementation of the network structure surrounding a transformer
  encoder as described in "BERT: Pre-training of Deep Bidirectional Transformers
  for Language Understanding" (https://arxiv.org/abs/1810.04805).

  The BertClassifier allows a user to pass in a transformer stack, and
  instantiates a classification network based on the passed `num_classes`
33
  argument. If `num_classes` is set to 1, a regression network is instantiated.
Hongkun Yu's avatar
Hongkun Yu committed
34

35
36
37
  *Note* that the model is constructed by
  [Keras Functional API](https://keras.io/guides/functional_api/).

38
  Args:
Hongkun Yu's avatar
Hongkun Yu committed
39
40
41
42
43
44
    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.
    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 Glorot uniform initializer.
Hongkun Yu's avatar
Hongkun Yu committed
45
    dropout_rate: The dropout probability of the cls head.
Hongkun Yu's avatar
Hongkun Yu committed
46
47
    use_encoder_pooler: Whether to use the pooler layer pre-defined inside the
      encoder.
Tianqi Liu's avatar
Tianqi Liu committed
48
    head_name: Name of the classification head.
49
50
    cls_head: (Optional) The layer instance to use for the classifier head.
      It should take in the output from network and produce the final logits.
51
      If set, the arguments ('num_classes', 'initializer', 'dropout_rate',
Tianqi Liu's avatar
Tianqi Liu committed
52
      'use_encoder_pooler', 'head_name') will be ignored.
Hongkun Yu's avatar
Hongkun Yu committed
53
54
55
56
57
58
59
  """

  def __init__(self,
               network,
               num_classes,
               initializer='glorot_uniform',
               dropout_rate=0.1,
Hongkun Yu's avatar
Hongkun Yu committed
60
               use_encoder_pooler=True,
Tianqi Liu's avatar
Tianqi Liu committed
61
               head_name='sentence_prediction',
62
               cls_head=None,
Hongkun Yu's avatar
Hongkun Yu committed
63
               **kwargs):
64
    self.num_classes = num_classes
Tianqi Liu's avatar
Tianqi Liu committed
65
    self.head_name = head_name
66
67
    self.initializer = initializer
    self.use_encoder_pooler = use_encoder_pooler
Hongkun Yu's avatar
Hongkun Yu committed
68
69
70
71
72
73

    # We want to use the inputs of the passed network as the inputs to this
    # Model. To do this, we need to keep a handle to the network inputs for use
    # when we construct the Model object at the end of init.
    inputs = network.inputs

Hongkun Yu's avatar
Hongkun Yu committed
74
75
76
    if use_encoder_pooler:
      # Because we have a copy of inputs to create this Model object, we can
      # invoke the Network object with its own input tensors to start the Model.
77
78
      outputs = network(inputs)
      if isinstance(outputs, list):
79
        cls_inputs = outputs[1]
80
      else:
81
82
        cls_inputs = outputs['pooled_output']
      cls_inputs = tf.keras.layers.Dropout(rate=dropout_rate)(cls_inputs)
Hongkun Yu's avatar
Hongkun Yu committed
83
    else:
84
85
      outputs = network(inputs)
      if isinstance(outputs, list):
86
        cls_inputs = outputs[0]
87
      else:
88
89
90
91
92
        cls_inputs = outputs['sequence_output']

    if cls_head:
      classifier = cls_head
    else:
93
      classifier = layers.ClassificationHead(
94
          inner_dim=0 if use_encoder_pooler else cls_inputs.shape[-1],
Hongkun Yu's avatar
Hongkun Yu committed
95
96
97
          num_classes=num_classes,
          initializer=initializer,
          dropout_rate=dropout_rate,
Tianqi Liu's avatar
Tianqi Liu committed
98
          name=head_name)
99
100

    predictions = classifier(cls_inputs)
101
102
103
104
105
106
107
108

    # b/164516224
    # Once we've created the network using the Functional API, we call
    # super().__init__ as though we were invoking the Functional API Model
    # constructor, resulting in this object having all the properties of a model
    # created using the Functional API. Once super().__init__ is called, we
    # can assign attributes to `self` - note that all `self` assignments are
    # below this line.
Hongkun Yu's avatar
Hongkun Yu committed
109
110
    super(BertClassifier, self).__init__(
        inputs=inputs, outputs=predictions, **kwargs)
111
    self._network = network
112
113
    self._cls_head = cls_head

114
    config_dict = self._make_config_dict()
115
116
117
118
119
120
121
122
    # We are storing the config dict as a namedtuple here to ensure checkpoint
    # compatibility with an earlier version of this model which did not track
    # the config dict attribute. TF does not track immutable attrs which
    # do not contain Trackables, so by creating a config namedtuple instead of
    # a dict we avoid tracking it.
    config_cls = collections.namedtuple('Config', config_dict.keys())
    self._config = config_cls(**config_dict)
    self.classifier = classifier
Hongkun Yu's avatar
Hongkun Yu committed
123

Hongkun Yu's avatar
Hongkun Yu committed
124
125
  @property
  def checkpoint_items(self):
Hongkun Yu's avatar
Hongkun Yu committed
126
127
128
129
130
    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
Hongkun Yu's avatar
Hongkun Yu committed
131

Hongkun Yu's avatar
Hongkun Yu committed
132
  def get_config(self):
133
    return dict(self._config._asdict())
Hongkun Yu's avatar
Hongkun Yu committed
134
135
136
137

  @classmethod
  def from_config(cls, config, custom_objects=None):
    return cls(**config)
138
139
140
141
142

  def _make_config_dict(self):
    return {
        'network': self._network,
        'num_classes': self.num_classes,
Tianqi Liu's avatar
Tianqi Liu committed
143
        'head_name': self.head_name,
144
145
        'initializer': self.initializer,
        'use_encoder_pooler': self.use_encoder_pooler,
146
        'cls_head': self._cls_head,
147
    }