sentence_prediction_dataloader.py 8.97 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.
# ==============================================================================
"""Loads dataset for the sentence prediction (classification) task."""
17
import functools
Chen Chen's avatar
Chen Chen committed
18
from typing import List, Mapping, Optional
Hongkun Yu's avatar
Hongkun Yu committed
19

Chen Chen's avatar
Chen Chen committed
20
import dataclasses
21
import tensorflow as tf
Chen Chen's avatar
Chen Chen committed
22
23
24
import tensorflow_hub as hub

from official.common import dataset_fn
25
from official.core import config_definitions as cfg
26
from official.core import input_reader
Chen Chen's avatar
Chen Chen committed
27
from official.nlp import modeling
28
from official.nlp.data import data_loader
Chen Chen's avatar
Chen Chen committed
29
from official.nlp.data import data_loader_factory
30

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
31
32
33
LABEL_TYPES_MAP = {'int': tf.int64, 'float': tf.float32}


Chen Chen's avatar
Chen Chen committed
34
35
36
37
38
39
40
@dataclasses.dataclass
class SentencePredictionDataConfig(cfg.DataConfig):
  """Data config for sentence prediction task (tasks/sentence_prediction)."""
  input_path: str = ''
  global_batch_size: int = 32
  is_training: bool = True
  seq_length: int = 128
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
41
  label_type: str = 'int'
Chen Chen's avatar
Chen Chen committed
42
43
  # Whether to include the example id number.
  include_example_id: bool = False
Chen Chen's avatar
Chen Chen committed
44
45
46


@data_loader_factory.register_data_loader_cls(SentencePredictionDataConfig)
47
class SentencePredictionDataLoader(data_loader.DataLoader):
48
49
50
51
52
  """A class to load dataset for sentence prediction (classification) task."""

  def __init__(self, params):
    self._params = params
    self._seq_length = params.seq_length
Chen Chen's avatar
Chen Chen committed
53
    self._include_example_id = params.include_example_id
54
55
56

  def _decode(self, record: tf.Tensor):
    """Decodes a serialized tf.Example."""
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
57
    label_type = LABEL_TYPES_MAP[self._params.label_type]
58
59
60
61
    name_to_features = {
        'input_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
        'input_mask': tf.io.FixedLenFeature([self._seq_length], tf.int64),
        'segment_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
62
        'label_ids': tf.io.FixedLenFeature([], label_type),
63
    }
Chen Chen's avatar
Chen Chen committed
64
65
66
    if self._include_example_id:
      name_to_features['example_id'] = tf.io.FixedLenFeature([], tf.int64)

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    example = tf.io.parse_single_example(record, name_to_features)

    # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
    # So cast all int64 to int32.
    for name in example:
      t = example[name]
      if t.dtype == tf.int64:
        t = tf.cast(t, tf.int32)
      example[name] = t

    return example

  def _parse(self, record: Mapping[str, tf.Tensor]):
    """Parses raw tensors into a dict of tensors to be consumed by the model."""
    x = {
        'input_word_ids': record['input_ids'],
        'input_mask': record['input_mask'],
        'input_type_ids': record['segment_ids']
    }
Chen Chen's avatar
Chen Chen committed
86
87
88
    if self._include_example_id:
      x['example_id'] = record['example_id']

89
90
91
92
93
94
95
96
    y = record['label_ids']
    return (x, y)

  def load(self, input_context: Optional[tf.distribute.InputContext] = None):
    """Returns a tf.dataset.Dataset."""
    reader = input_reader.InputReader(
        params=self._params, decoder_fn=self._decode, parser_fn=self._parse)
    return reader.read(input_context)
Chen Chen's avatar
Chen Chen committed
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


@dataclasses.dataclass
class SentencePredictionTextDataConfig(cfg.DataConfig):
  """Data config for sentence prediction task with raw text."""
  # Either set `input_path`...
  input_path: str = ''
  # Either `int` or `float`.
  label_type: str = 'int'
  # ...or `tfds_name` and `tfds_split` to specify input.
  tfds_name: str = ''
  tfds_split: str = ''
  # The name of the text feature fields. The text features will be
  # concatenated in order.
  text_fields: Optional[List[str]] = None
  label_field: str = 'label'
  global_batch_size: int = 32
  seq_length: int = 128
  is_training: bool = True
  # Either build preprocessing with Python code by specifying these values
  # for modeling.layers.BertTokenizer()/SentencepieceTokenizer()....
  tokenization: str = 'WordPiece'  # WordPiece or SentencePiece
  # Text vocab file if tokenization is WordPiece, or sentencepiece.ModelProto
  # file if tokenization is SentencePiece.
  vocab_file: str = ''
  lower_case: bool = True
  # ...or load preprocessing from a SavedModel at this location.
  preprocessing_hub_module_url: str = ''
  # Either tfrecord or sstsable or recordio.
  file_type: str = 'tfrecord'


class TextProcessor(tf.Module):
  """Text features processing for sentence prediction task."""

  def __init__(self,
               seq_length: int,
               vocab_file: Optional[str] = None,
               tokenization: Optional[str] = None,
               lower_case: Optional[bool] = True,
               preprocessing_hub_module_url: Optional[str] = None):
    if preprocessing_hub_module_url:
      self._preprocessing_hub_module = hub.load(preprocessing_hub_module_url)
      self._tokenizer = self._preprocessing_hub_module.tokenize
141
142
143
      self._pack_inputs = functools.partial(
          self._preprocessing_hub_module.bert_pack_inputs,
          seq_length=seq_length)
Chen Chen's avatar
Chen Chen committed
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
      return

    if tokenization == 'WordPiece':
      self._tokenizer = modeling.layers.BertTokenizer(
          vocab_file=vocab_file, lower_case=lower_case)
    elif tokenization == 'SentencePiece':
      self._tokenizer = modeling.layers.SentencepieceTokenizer(
          model_file_path=vocab_file, lower_case=lower_case,
          strip_diacritics=True)  # Strip diacritics to follow ALBERT model
    else:
      raise ValueError('Unsupported tokenization: %s' % tokenization)

    self._pack_inputs = modeling.layers.BertPackInputs(
        seq_length=seq_length,
        special_tokens_dict=self._tokenizer.get_special_tokens_dict())

  def __call__(self, segments):
    segments = [self._tokenizer(s) for s in segments]
    # BertTokenizer returns a RaggedTensor with shape [batch, word, subword],
    # and SentencepieceTokenizer returns a RaggedTensor with shape
    # [batch, sentencepiece],
    segments = [
        tf.cast(x.merge_dims(1, -1) if x.shape.rank > 2 else x, tf.int32)
        for x in segments
    ]
    return self._pack_inputs(segments)


@data_loader_factory.register_data_loader_cls(SentencePredictionTextDataConfig)
class SentencePredictionTextDataLoader(data_loader.DataLoader):
  """Loads dataset with raw text for sentence prediction task."""

  def __init__(self, params):
    if bool(params.tfds_name) != bool(params.tfds_split):
      raise ValueError('`tfds_name` and `tfds_split` should be specified or '
                       'unspecified at the same time.')
    if bool(params.tfds_name) == bool(params.input_path):
      raise ValueError('Must specify either `tfds_name` and `tfds_split` '
                       'or `input_path`.')
    if not params.text_fields:
      raise ValueError('Unexpected empty text fields.')
    if bool(params.vocab_file) == bool(params.preprocessing_hub_module_url):
      raise ValueError('Must specify exactly one of vocab_file (with matching '
                       'lower_case flag) or preprocessing_hub_module_url.')

    self._params = params
    self._text_fields = params.text_fields
    self._label_field = params.label_field
    self._label_type = params.label_type
    self._text_processor = TextProcessor(
        seq_length=params.seq_length,
        vocab_file=params.vocab_file,
        tokenization=params.tokenization,
        lower_case=params.lower_case,
        preprocessing_hub_module_url=params.preprocessing_hub_module_url)

  def _bert_preprocess(self, record: Mapping[str, tf.Tensor]):
    """Berts preprocess."""
    segments = [record[x] for x in self._text_fields]
    model_inputs = self._text_processor(segments)
    y = record[self._label_field]
    return model_inputs, y

  def _decode(self, record: tf.Tensor):
    """Decodes a serialized tf.Example."""
    name_to_features = {}
    for text_field in self._text_fields:
      name_to_features[text_field] = tf.io.FixedLenFeature([], tf.string)

    label_type = LABEL_TYPES_MAP[self._label_type]
    name_to_features[self._label_field] = tf.io.FixedLenFeature([], label_type)
    example = tf.io.parse_single_example(record, name_to_features)

    # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
    # So cast all int64 to int32.
    for name in example:
      t = example[name]
      if t.dtype == tf.int64:
        t = tf.cast(t, tf.int32)
      example[name] = t

    return example

  def load(self, input_context: Optional[tf.distribute.InputContext] = None):
    """Returns a tf.dataset.Dataset."""
    reader = input_reader.InputReader(
        dataset_fn=dataset_fn.pick_dataset_fn(self._params.file_type),
        decoder_fn=self._decode if self._params.input_path else None,
        params=self._params,
        postprocess_fn=self._bert_preprocess)
    return reader.read(input_context)