Pradeep Kumar commited on
Commit
f724412
·
verified ·
1 Parent(s): 7a04101

Delete wmt_dataloader.py

Browse files
Files changed (1) hide show
  1. wmt_dataloader.py +0 -295
wmt_dataloader.py DELETED
@@ -1,295 +0,0 @@
1
- # Copyright 2024 The TensorFlow Authors. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- """Input pipeline for the transformer model to read, filter, and batch examples.
16
-
17
- Batching scheme
18
-
19
- Prior to batching, elements in the dataset are grouped by length (max between
20
- 'inputs' and 'targets' length). Each group is then batched such that:
21
- group_batch_size * length <= batch_size.
22
-
23
- Another way to view batch_size is the maximum number of tokens in each batch.
24
-
25
- Once batched, each element in the dataset will have the shape:
26
- {'inputs': [group_batch_size, padded_input_length],
27
- 'targets': [group_batch_size, padded_target_length]}
28
- Lengths are padded to the longest 'inputs' or 'targets' sequence in the batch
29
- (padded_input_length and padded_target_length can be different).
30
-
31
- This batching scheme decreases the fraction of padding tokens per training
32
- batch, thus improving the training speed significantly.
33
- """
34
- from typing import Dict, Optional
35
-
36
- import dataclasses
37
- import tensorflow as tf, tf_keras
38
- import tensorflow_text as tftxt
39
- from official.core import config_definitions as cfg
40
- from official.core import input_reader
41
- from official.nlp.data import data_loader
42
- from official.nlp.data import data_loader_factory
43
-
44
- # Example grouping constants. Defines length boundaries for each group.
45
- # These values are the defaults used in Tensor2Tensor.
46
- _MIN_BOUNDARY = 8
47
- _BOUNDARY_SCALE = 1.1
48
-
49
-
50
- def _get_example_length(example):
51
- """Returns the maximum length between the example inputs and targets."""
52
- length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0])
53
- return length
54
-
55
-
56
- def _create_min_max_boundaries(max_length,
57
- min_boundary=_MIN_BOUNDARY,
58
- boundary_scale=_BOUNDARY_SCALE):
59
- """Create min and max boundary lists up to max_length.
60
-
61
- For example, when max_length=24, min_boundary=4 and boundary_scale=2, the
62
- returned values will be:
63
- buckets_min = [0, 4, 8, 16]
64
- buckets_max = [4, 8, 16, 25]
65
-
66
- Args:
67
- max_length: The maximum length of example in dataset.
68
- min_boundary: Minimum length in boundary.
69
- boundary_scale: Amount to scale consecutive boundaries in the list.
70
-
71
- Returns:
72
- min and max boundary lists
73
-
74
- """
75
- # Create bucket boundaries list by scaling the previous boundary or adding 1
76
- # (to ensure increasing boundary sizes).
77
- bucket_boundaries = []
78
- x = min_boundary
79
- while x < max_length:
80
- bucket_boundaries.append(x)
81
- x = max(x + 1, int(x * boundary_scale))
82
-
83
- # Create min and max boundary lists from the initial list.
84
- buckets_min = [0] + bucket_boundaries
85
- buckets_max = bucket_boundaries + [max_length + 1]
86
- return buckets_min, buckets_max
87
-
88
-
89
- def _batch_examples(dataset, batch_size, max_length):
90
- """Group examples by similar lengths, and return batched dataset.
91
-
92
- Each batch of similar-length examples are padded to the same length, and may
93
- have different number of elements in each batch, such that:
94
- group_batch_size * padded_length <= batch_size.
95
-
96
- This decreases the number of padding tokens per batch, which improves the
97
- training speed.
98
-
99
- Args:
100
- dataset: Dataset of unbatched examples.
101
- batch_size: Max number of tokens per batch of examples.
102
- max_length: Max number of tokens in an example input or target sequence.
103
-
104
- Returns:
105
- Dataset of batched examples with similar lengths.
106
- """
107
- # Get min and max boundary lists for each example. These are used to calculate
108
- # the `bucket_id`, which is the index at which:
109
- # buckets_min[bucket_id] <= len(example) < buckets_max[bucket_id]
110
- # Note that using both min and max lists improves the performance.
111
- buckets_min, buckets_max = _create_min_max_boundaries(max_length)
112
-
113
- # Create list of batch sizes for each bucket_id, so that
114
- # bucket_batch_size[bucket_id] * buckets_max[bucket_id] <= batch_size
115
- bucket_batch_sizes = [int(batch_size) // x for x in buckets_max]
116
-
117
- # Validates bucket batch sizes.
118
- if any([batch_size <= 0 for batch_size in bucket_batch_sizes]):
119
- raise ValueError(
120
- 'The token budget, global batch size, is too small to yield 0 bucket '
121
- 'window: %s' % str(bucket_batch_sizes))
122
-
123
- # bucket_id will be a tensor, so convert this list to a tensor as well.
124
- bucket_batch_sizes = tf.constant(bucket_batch_sizes, dtype=tf.int64)
125
-
126
- def example_to_bucket_id(example):
127
- """Return int64 bucket id for this example, calculated based on length."""
128
- example_input = example['inputs']
129
- example_target = example['targets']
130
- seq_length = _get_example_length((example_input, example_target))
131
-
132
- conditions_c = tf.logical_and(
133
- tf.less_equal(buckets_min, seq_length), tf.less(seq_length,
134
- buckets_max))
135
- bucket_id = tf.reduce_min(tf.where(conditions_c))
136
- return bucket_id
137
-
138
- def window_size_fn(bucket_id):
139
- """Return number of examples to be grouped when given a bucket id."""
140
- return bucket_batch_sizes[bucket_id]
141
-
142
- def batching_fn(bucket_id, grouped_dataset):
143
- """Batch and add padding to a dataset of elements with similar lengths."""
144
- bucket_batch_size = window_size_fn(bucket_id)
145
-
146
- # Batch the dataset and add padding so that all input sequences in the
147
- # examples have the same length, and all target sequences have the same
148
- # lengths as well. Resulting lengths of inputs and targets can differ.
149
- padded_shapes = dict([
150
- (name, [None] * len(spec.shape))
151
- for name, spec in grouped_dataset.element_spec.items()
152
- ])
153
- return grouped_dataset.padded_batch(bucket_batch_size, padded_shapes)
154
-
155
- return dataset.apply(
156
- tf.data.experimental.group_by_window(
157
- key_func=example_to_bucket_id,
158
- reduce_func=batching_fn,
159
- window_size=None,
160
- window_size_func=window_size_fn))
161
-
162
-
163
- @dataclasses.dataclass
164
- class WMTDataConfig(cfg.DataConfig):
165
- """Data config for WMT translation."""
166
- max_seq_length: int = 64
167
- static_batch: bool = False
168
- sentencepiece_model_path: str = ''
169
- src_lang: str = ''
170
- tgt_lang: str = ''
171
- transform_and_batch: bool = True
172
- has_unique_id: bool = False
173
-
174
-
175
- @data_loader_factory.register_data_loader_cls(WMTDataConfig)
176
- class WMTDataLoader(data_loader.DataLoader):
177
- """A class to load dataset for WMT translation task."""
178
-
179
- def __init__(self, params: WMTDataConfig):
180
- self._params = params
181
- self._max_seq_length = params.max_seq_length
182
- self._static_batch = params.static_batch
183
- self._global_batch_size = params.global_batch_size
184
- if self._params.transform_and_batch:
185
- self._tokenizer = tftxt.SentencepieceTokenizer(
186
- model=tf.io.gfile.GFile(params.sentencepiece_model_path, 'rb').read(),
187
- add_eos=True)
188
-
189
- def _decode(self, record: tf.Tensor):
190
- """Decodes a serialized tf.Example."""
191
- name_to_features = {
192
- self._params.src_lang: tf.io.FixedLenFeature([], tf.string),
193
- self._params.tgt_lang: tf.io.FixedLenFeature([], tf.string),
194
- }
195
- if self._params.has_unique_id:
196
- name_to_features['unique_id'] = tf.io.FixedLenFeature([], tf.int64)
197
- example = tf.io.parse_single_example(record, name_to_features)
198
- # tf.Example only supports tf.int64, but the TPU only supports tf.int32.
199
- # So cast all int64 to int32.
200
- for name in example:
201
- t = example[name]
202
- if t.dtype == tf.int64:
203
- t = tf.cast(t, tf.int32)
204
- example[name] = t
205
- return example
206
-
207
- def _tokenize(self, inputs) -> Dict[str, tf.Tensor]:
208
- tokenized_inputs = {}
209
- for k, v in inputs.items():
210
- if k == self._params.src_lang:
211
- tokenized_inputs['inputs'] = self._tokenizer.tokenize(v)
212
- elif k == self._params.tgt_lang:
213
- tokenized_inputs['targets'] = self._tokenizer.tokenize(v)
214
- else:
215
- tokenized_inputs[k] = v
216
- print(tokenized_inputs)
217
- return tokenized_inputs
218
-
219
- def _filter_max_length(self, inputs):
220
- # return tf.constant(True)
221
- return tf.logical_and(
222
- tf.shape(inputs['inputs'])[0] <= self._max_seq_length,
223
- tf.shape(inputs['targets'])[0] <= self._max_seq_length)
224
-
225
- def _maybe_truncate(self, inputs):
226
- truncated_inputs = {}
227
- for k, v in inputs.items():
228
- if k == 'inputs' or k == 'targets':
229
- truncated_inputs[k] = tf.pad(
230
- v[:self._max_seq_length - 1], [[0, 1]],
231
- constant_values=1) if tf.shape(v)[0] > self._max_seq_length else v
232
- else:
233
- truncated_inputs[k] = v
234
- return truncated_inputs
235
-
236
- def _tokenize_bucketize_and_batch(
237
- self,
238
- dataset,
239
- input_context: Optional[tf.distribute.InputContext] = None):
240
- dataset = dataset.map(
241
- self._tokenize, num_parallel_calls=tf.data.experimental.AUTOTUNE)
242
-
243
- if self._params.is_training:
244
- dataset = dataset.filter(self._filter_max_length)
245
- else:
246
- dataset = dataset.map(
247
- self._maybe_truncate,
248
- num_parallel_calls=tf.data.experimental.AUTOTUNE)
249
-
250
- per_replica_batch_size = input_context.get_per_replica_batch_size(
251
- self._global_batch_size) if input_context else self._global_batch_size
252
- if self._static_batch:
253
- padded_shapes = {}
254
- for name, _ in dataset.element_spec.items():
255
- if name == 'unique_id':
256
- padded_shapes[name] = []
257
- else:
258
- padded_shapes[name] = [self._max_seq_length
259
- ] if self._static_batch else [None]
260
- batch_size = per_replica_batch_size
261
- if self._params.is_training:
262
- batch_size = int(batch_size // self._max_seq_length)
263
- dataset = dataset.padded_batch(
264
- batch_size,
265
- padded_shapes,
266
- drop_remainder=True)
267
- else:
268
- # Group and batch such that each batch has examples of similar length.
269
- dataset = _batch_examples(dataset, per_replica_batch_size,
270
- self._max_seq_length)
271
- # Prefetch the next element to improve speed of input pipeline.
272
- dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
273
- return dataset
274
-
275
- def load(self, input_context: Optional[tf.distribute.InputContext] = None):
276
- """Returns a tf.dataset.Dataset."""
277
- decoder_fn = None
278
- # Only decode for TFRecords.
279
- if self._params.input_path:
280
- decoder_fn = self._decode
281
-
282
- def _identity(
283
- dataset, input_context: Optional[tf.distribute.InputContext] = None):
284
- del input_context
285
- return dataset
286
-
287
- transform_and_batch_fn = _identity
288
- if self._params.transform_and_batch:
289
- transform_and_batch_fn = self._tokenize_bucketize_and_batch
290
-
291
- reader = input_reader.InputReader(
292
- params=self._params,
293
- decoder_fn=decoder_fn,
294
- transform_and_batch_fn=transform_and_batch_fn)
295
- return reader.read(input_context)