data_download.py 14.9 KB
Newer Older
Frederick Liu's avatar
Frederick Liu committed
1
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Katherine Wu's avatar
Katherine Wu 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

Katherine Wu's avatar
Katherine Wu committed
15
16
17
18
19
20
21
"""Download and preprocess WMT17 ende training and evaluation datasets."""

import os
import random
import tarfile

# pylint: disable=g-bad-import-order
Hongkun Yu's avatar
Hongkun Yu committed
22

Hongkun Yu's avatar
Hongkun Yu committed
23
from absl import app
24
from absl import flags
25
from absl import logging
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
26
27
28
29
import six
from six.moves import range
from six.moves import urllib
from six.moves import zip
30
import tensorflow.compat.v1 as tf
Katherine Wu's avatar
Katherine Wu committed
31

32
from official.nlp.transformer.utils import tokenizer
33
from official.utils.flags import core as flags_core
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
34
# pylint: enable=g-bad-import-order
Katherine Wu's avatar
Katherine Wu committed
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

# Data sources for training/evaluating the transformer translation model.
# If any of the training sources are changed, then either:
#   1) use the flag `--search` to find the best min count or
#   2) update the _TRAIN_DATA_MIN_COUNT constant.
# min_count is the minimum number of times a token must appear in the data
# before it is added to the vocabulary. "Best min count" refers to the value
# that generates a vocabulary set that is closest in size to _TARGET_VOCAB_SIZE.
_TRAIN_DATA_SOURCES = [
    {
        "url": "http://data.statmt.org/wmt17/translation-task/"
               "training-parallel-nc-v12.tgz",
        "input": "news-commentary-v12.de-en.en",
        "target": "news-commentary-v12.de-en.de",
    },
    {
        "url": "http://www.statmt.org/wmt13/training-parallel-commoncrawl.tgz",
        "input": "commoncrawl.de-en.en",
        "target": "commoncrawl.de-en.de",
    },
    {
        "url": "http://www.statmt.org/wmt13/training-parallel-europarl-v7.tgz",
        "input": "europarl-v7.de-en.en",
        "target": "europarl-v7.de-en.de",
    },
]
# Use pre-defined minimum count to generate subtoken vocabulary.
_TRAIN_DATA_MIN_COUNT = 6

Hongkun Yu's avatar
Hongkun Yu committed
64
65
66
67
68
_EVAL_DATA_SOURCES = [{
    "url": "http://data.statmt.org/wmt17/translation-task/dev.tgz",
    "input": "newstest2013.en",
    "target": "newstest2013.de",
}]
Katherine Wu's avatar
Katherine Wu committed
69

Hongkun Yu's avatar
Hongkun Yu committed
70
_TEST_DATA_SOURCES = [{
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
71
72
    "url": ("https://storage.googleapis.com/cloud-tpu-test-datasets/"
            "transformer_data/newstest2014.tgz"),
Hongkun Yu's avatar
Hongkun Yu committed
73
74
75
    "input": "newstest2014.en",
    "target": "newstest2014.de",
}]
76

Katherine Wu's avatar
Katherine Wu committed
77
78
79
80
81
82
83
84
85
# Vocabulary constants
_TARGET_VOCAB_SIZE = 32768  # Number of subtokens in the vocabulary list.
_TARGET_THRESHOLD = 327  # Accept vocabulary if size is within this threshold
VOCAB_FILE = "vocab.ende.%d" % _TARGET_VOCAB_SIZE

# Strings to inclue in the generated files.
_PREFIX = "wmt32k"
_TRAIN_TAG = "train"
_EVAL_TAG = "dev"  # Following WMT and Tensor2Tensor conventions, in which the
86
# evaluation datasets are tagged as "dev" for development.
Katherine Wu's avatar
Katherine Wu committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

# Number of files to split train and evaluation data
_TRAIN_SHARDS = 100
_EVAL_SHARDS = 1


def find_file(path, filename, max_depth=5):
  """Returns full filepath if the file is in path or a subdirectory."""
  for root, dirs, files in os.walk(path):
    if filename in files:
      return os.path.join(root, filename)

    # Don't search past max_depth
    depth = root[len(path) + 1:].count(os.sep)
    if depth > max_depth:
      del dirs[:]  # Clear dirs
  return None


###############################################################################
# Download and extraction functions
###############################################################################
def get_raw_files(raw_dir, data_source):
Hongkun Yu's avatar
Hongkun Yu committed
110
111
112
  """Return raw files from source.

  Downloads/extracts if needed.
Katherine Wu's avatar
Katherine Wu committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

  Args:
    raw_dir: string directory to store raw files
    data_source: dictionary with
      {"url": url of compressed dataset containing input and target files
       "input": file with data in input language
       "target": file with data in target language}

  Returns:
    dictionary with
      {"inputs": list of files containing data in input language
       "targets": list of files containing corresponding data in target language
      }
  """
  raw_files = {
      "inputs": [],
      "targets": [],
  }  # keys
  for d in data_source:
Hongkun Yu's avatar
Hongkun Yu committed
132
133
    input_file, target_file = download_and_extract(raw_dir, d["url"],
                                                   d["input"], d["target"])
Katherine Wu's avatar
Katherine Wu committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    raw_files["inputs"].append(input_file)
    raw_files["targets"].append(target_file)
  return raw_files


def download_report_hook(count, block_size, total_size):
  """Report hook for download progress.

  Args:
    count: current block number
    block_size: block size
    total_size: total size
  """
  percent = int(count * block_size * 100 / total_size)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
148
  print(six.ensure_str("\r%d%%" % percent) + " completed", end="\r")
Katherine Wu's avatar
Katherine Wu committed
149
150
151
152
153
154
155
156
157
158
159
160


def download_from_url(path, url):
  """Download content from a url.

  Args:
    path: string directory where file will be downloaded
    url: string url

  Returns:
    Full path to downloaded file
  """
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
161
  filename = six.ensure_str(url).split("/")[-1]
Katherine Wu's avatar
Katherine Wu committed
162
163
164
  found_file = find_file(path, filename, max_depth=0)
  if found_file is None:
    filename = os.path.join(path, filename)
Hongkun Yu's avatar
Hongkun Yu committed
165
    logging.info("Downloading from %s to %s.", url, filename)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
166
    inprogress_filepath = six.ensure_str(filename) + ".incomplete"
167
    inprogress_filepath, _ = urllib.request.urlretrieve(
Katherine Wu's avatar
Katherine Wu committed
168
169
170
171
172
173
        url, inprogress_filepath, reporthook=download_report_hook)
    # Print newline to clear the carriage return from the download progress.
    print()
    tf.gfile.Rename(inprogress_filepath, filename)
    return filename
  else:
Hongkun Yu's avatar
Hongkun Yu committed
174
    logging.info("Already downloaded: %s (at %s).", url, found_file)
Katherine Wu's avatar
Katherine Wu committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    return found_file


def download_and_extract(path, url, input_filename, target_filename):
  """Extract files from downloaded compressed archive file.

  Args:
    path: string directory where the files will be downloaded
    url: url containing the compressed input and target files
    input_filename: name of file containing data in source language
    target_filename: name of file containing data in target language

  Returns:
    Full paths to extracted input and target files.

  Raises:
    OSError: if the the download/extraction fails.
  """
  # Check if extracted files already exist in path
  input_file = find_file(path, input_filename)
  target_file = find_file(path, target_filename)
  if input_file and target_file:
Hongkun Yu's avatar
Hongkun Yu committed
197
    logging.info("Already downloaded and extracted %s.", url)
Katherine Wu's avatar
Katherine Wu committed
198
199
200
201
202
203
    return input_file, target_file

  # Download archive file if it doesn't already exist.
  compressed_file = download_from_url(path, url)

  # Extract compressed files
Hongkun Yu's avatar
Hongkun Yu committed
204
  logging.info("Extracting %s.", compressed_file)
Katherine Wu's avatar
Katherine Wu committed
205
206
207
  with tarfile.open(compressed_file, "r:gz") as corpus_tar:
    corpus_tar.extractall(path)

208
  # Return file paths of the requested files.
Katherine Wu's avatar
Katherine Wu committed
209
210
211
212
213
214
215
216
217
218
219
220
  input_file = find_file(path, input_filename)
  target_file = find_file(path, target_filename)

  if input_file and target_file:
    return input_file, target_file

  raise OSError("Download/extraction failed for url %s to path %s" %
                (url, path))


def txt_line_iterator(path):
  """Iterate through lines of file."""
221
  with tf.io.gfile.GFile(path) as f:
Katherine Wu's avatar
Katherine Wu committed
222
223
224
225
226
227
228
229
230
231
232
233
    for line in f:
      yield line.strip()


def compile_files(raw_dir, raw_files, tag):
  """Compile raw files into a single file for each language.

  Args:
    raw_dir: Directory containing downloaded raw files.
    raw_files: Dict containing filenames of input and target data.
      {"inputs": list of files containing data in input language
       "targets": list of files containing corresponding data in target language
Hongkun Yu's avatar
Hongkun Yu committed
234
         }
Katherine Wu's avatar
Katherine Wu committed
235
236
237
238
239
    tag: String to append to the compiled filename.

  Returns:
    Full path of compiled input and target files.
  """
Hongkun Yu's avatar
Hongkun Yu committed
240
  logging.info("Compiling files with tag %s.", tag)
Katherine Wu's avatar
Katherine Wu committed
241
  filename = "%s-%s" % (_PREFIX, tag)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
242
243
244
245
  input_compiled_file = os.path.join(raw_dir,
                                     six.ensure_str(filename) + ".lang1")
  target_compiled_file = os.path.join(raw_dir,
                                      six.ensure_str(filename) + ".lang2")
Katherine Wu's avatar
Katherine Wu committed
246

247
248
  with tf.io.gfile.GFile(input_compiled_file, mode="w") as input_writer:
    with tf.io.gfile.GFile(target_compiled_file, mode="w") as target_writer:
Katherine Wu's avatar
Katherine Wu committed
249
250
251
252
      for i in range(len(raw_files["inputs"])):
        input_file = raw_files["inputs"][i]
        target_file = raw_files["targets"][i]

Hongkun Yu's avatar
Hongkun Yu committed
253
        logging.info("Reading files %s and %s.", input_file, target_file)
Katherine Wu's avatar
Katherine Wu committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        write_file(input_writer, input_file)
        write_file(target_writer, target_file)
  return input_compiled_file, target_compiled_file


def write_file(writer, filename):
  """Write all of lines from file using the writer."""
  for line in txt_line_iterator(filename):
    writer.write(line)
    writer.write("\n")


###############################################################################
# Data preprocessing
###############################################################################
Hongkun Yu's avatar
Hongkun Yu committed
269
def encode_and_save_files(subtokenizer, data_dir, raw_files, tag, total_shards):
Katherine Wu's avatar
Katherine Wu committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  """Save data from files as encoded Examples in TFrecord format.

  Args:
    subtokenizer: Subtokenizer object that will be used to encode the strings.
    data_dir: The directory in which to write the examples
    raw_files: A tuple of (input, target) data files. Each line in the input and
      the corresponding line in target file will be saved in a tf.Example.
    tag: String that will be added onto the file names.
    total_shards: Number of files to divide the data into.

  Returns:
    List of all files produced.
  """
  # Create a file for each shard.
Hongkun Yu's avatar
Hongkun Yu committed
284
285
286
287
  filepaths = [
      shard_filename(data_dir, tag, n + 1, total_shards)
      for n in range(total_shards)
  ]
Katherine Wu's avatar
Katherine Wu committed
288
289

  if all_exist(filepaths):
Hongkun Yu's avatar
Hongkun Yu committed
290
    logging.info("Files with tag %s already exist.", tag)
Katherine Wu's avatar
Katherine Wu committed
291
292
    return filepaths

Hongkun Yu's avatar
Hongkun Yu committed
293
  logging.info("Saving files with tag %s.", tag)
Katherine Wu's avatar
Katherine Wu committed
294
295
296
297
  input_file = raw_files[0]
  target_file = raw_files[1]

  # Write examples to each shard in round robin order.
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
298
  tmp_filepaths = [six.ensure_str(fname) + ".incomplete" for fname in filepaths]
Katherine Wu's avatar
Katherine Wu committed
299
300
  writers = [tf.python_io.TFRecordWriter(fname) for fname in tmp_filepaths]
  counter, shard = 0, 0
Hongkun Yu's avatar
Hongkun Yu committed
301
302
  for counter, (input_line, target_line) in enumerate(
      zip(txt_line_iterator(input_file), txt_line_iterator(target_file))):
Katherine Wu's avatar
Katherine Wu committed
303
    if counter > 0 and counter % 100000 == 0:
Hongkun Yu's avatar
Hongkun Yu committed
304
305
306
307
308
      logging.info("\tSaving case %d.", counter)
    example = dict_to_example({
        "inputs": subtokenizer.encode(input_line, add_eos=True),
        "targets": subtokenizer.encode(target_line, add_eos=True)
    })
Katherine Wu's avatar
Katherine Wu committed
309
310
311
312
313
314
315
316
    writers[shard].write(example.SerializeToString())
    shard = (shard + 1) % total_shards
  for writer in writers:
    writer.close()

  for tmp_name, final_name in zip(tmp_filepaths, filepaths):
    tf.gfile.Rename(tmp_name, final_name)

317
  logging.info("Saved %d Examples", counter + 1)
Katherine Wu's avatar
Katherine Wu committed
318
319
320
321
322
323
324
325
326
327
328
  return filepaths


def shard_filename(path, tag, shard_num, total_shards):
  """Create filename for data shard."""
  return os.path.join(
      path, "%s-%s-%.5d-of-%.5d" % (_PREFIX, tag, shard_num, total_shards))


def shuffle_records(fname):
  """Shuffle records in a single file."""
Hongkun Yu's avatar
Hongkun Yu committed
329
  logging.info("Shuffling records in file %s", fname)
Katherine Wu's avatar
Katherine Wu committed
330
331

  # Rename file prior to shuffling
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
332
  tmp_fname = six.ensure_str(fname) + ".unshuffled"
Katherine Wu's avatar
Katherine Wu committed
333
334
  tf.gfile.Rename(fname, tmp_fname)

Mirali Ahmadli's avatar
Mirali Ahmadli committed
335
  reader = tf.io.tf_record_iterator(tmp_fname)
Katherine Wu's avatar
Katherine Wu committed
336
337
338
339
  records = []
  for record in reader:
    records.append(record)
    if len(records) % 100000 == 0:
340
      logging.info("\tRead: %d", len(records))
Katherine Wu's avatar
Katherine Wu committed
341
342
343
344
345
346
347
348

  random.shuffle(records)

  # Write shuffled records to original file name
  with tf.python_io.TFRecordWriter(fname) as w:
    for count, record in enumerate(records):
      w.write(record)
      if count > 0 and count % 100000 == 0:
Hongkun Yu's avatar
Hongkun Yu committed
349
        logging.info("\tWriting record: %d", count)
Katherine Wu's avatar
Katherine Wu committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371

  tf.gfile.Remove(tmp_fname)


def dict_to_example(dictionary):
  """Converts a dictionary of string->int to a tf.Example."""
  features = {}
  for k, v in six.iteritems(dictionary):
    features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
  return tf.train.Example(features=tf.train.Features(feature=features))


def all_exist(filepaths):
  """Returns true if all files in the list exist."""
  for fname in filepaths:
    if not tf.gfile.Exists(fname):
      return False
  return True


def make_dir(path):
  if not tf.gfile.Exists(path):
Hongkun Yu's avatar
Hongkun Yu committed
372
    logging.info("Creating directory %s", path)
Katherine Wu's avatar
Katherine Wu committed
373
374
375
376
377
378
379
380
    tf.gfile.MakeDirs(path)


def main(unused_argv):
  """Obtain training and evaluation data for the Transformer model."""
  make_dir(FLAGS.raw_dir)
  make_dir(FLAGS.data_dir)

381
  # Download test_data
382
  logging.info("Step 1/5: Downloading test data")
383
  get_raw_files(FLAGS.data_dir, _TEST_DATA_SOURCES)
384

Katherine Wu's avatar
Katherine Wu committed
385
  # Get paths of download/extracted training and evaluation files.
386
  logging.info("Step 2/5: Downloading data from source")
Katherine Wu's avatar
Katherine Wu committed
387
388
389
390
  train_files = get_raw_files(FLAGS.raw_dir, _TRAIN_DATA_SOURCES)
  eval_files = get_raw_files(FLAGS.raw_dir, _EVAL_DATA_SOURCES)

  # Create subtokenizer based on the training files.
391
  logging.info("Step 3/5: Creating subtokenizer and building vocabulary")
Katherine Wu's avatar
Katherine Wu committed
392
393
394
  train_files_flat = train_files["inputs"] + train_files["targets"]
  vocab_file = os.path.join(FLAGS.data_dir, VOCAB_FILE)
  subtokenizer = tokenizer.Subtokenizer.init_from_files(
Hongkun Yu's avatar
Hongkun Yu committed
395
396
397
398
      vocab_file,
      train_files_flat,
      _TARGET_VOCAB_SIZE,
      _TARGET_THRESHOLD,
Katherine Wu's avatar
Katherine Wu committed
399
400
      min_count=None if FLAGS.search else _TRAIN_DATA_MIN_COUNT)

401
  logging.info("Step 4/5: Compiling training and evaluation data")
Katherine Wu's avatar
Katherine Wu committed
402
403
404
405
  compiled_train_files = compile_files(FLAGS.raw_dir, train_files, _TRAIN_TAG)
  compiled_eval_files = compile_files(FLAGS.raw_dir, eval_files, _EVAL_TAG)

  # Tokenize and save data as Examples in the TFRecord format.
406
  logging.info("Step 5/5: Preprocessing and saving data")
Hongkun Yu's avatar
Hongkun Yu committed
407
408
409
410
411
  train_tfrecord_files = encode_and_save_files(subtokenizer, FLAGS.data_dir,
                                               compiled_train_files, _TRAIN_TAG,
                                               _TRAIN_SHARDS)
  encode_and_save_files(subtokenizer, FLAGS.data_dir, compiled_eval_files,
                        _EVAL_TAG, _EVAL_SHARDS)
Katherine Wu's avatar
Katherine Wu committed
412
413
414
415
416

  for fname in train_tfrecord_files:
    shuffle_records(fname)


417
418
419
def define_data_download_flags():
  """Add flags specifying data download arguments."""
  flags.DEFINE_string(
Hongkun Yu's avatar
Hongkun Yu committed
420
421
422
      name="data_dir",
      short_name="dd",
      default="/tmp/translate_ende",
423
424
425
      help=flags_core.help_wrap(
          "Directory for where the translate_ende_wmt32k dataset is saved."))
  flags.DEFINE_string(
Hongkun Yu's avatar
Hongkun Yu committed
426
427
428
      name="raw_dir",
      short_name="rd",
      default="/tmp/translate_ende_raw",
429
430
431
      help=flags_core.help_wrap(
          "Path where the raw data will be downloaded and extracted."))
  flags.DEFINE_bool(
Hongkun Yu's avatar
Hongkun Yu committed
432
433
      name="search",
      default=False,
434
435
436
437
438
      help=flags_core.help_wrap(
          "If set, use binary search to find the vocabulary set with size"
          "closest to the target size (%d)." % _TARGET_VOCAB_SIZE))


Katherine Wu's avatar
Katherine Wu committed
439
if __name__ == "__main__":
440
  logging.set_verbosity(logging.INFO)
441
442
  define_data_download_flags()
  FLAGS = flags.FLAGS
Hongkun Yu's avatar
Hongkun Yu committed
443
  app.run(main)