Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

create_pretraining_data.py 16 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
87
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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Create masked LM/next sentence masked_lm TF examples for BERT."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import collections
  20. import random
  21. import tokenization
  22. import tensorflow as tf
  23. flags = tf.flags
  24. FLAGS = flags.FLAGS
  25. flags.DEFINE_string("input_file", None,
  26. "Input raw text file (or comma-separated list of files).")
  27. flags.DEFINE_string(
  28. "output_file", None,
  29. "Output TF example file (or comma-separated list of files).")
  30. flags.DEFINE_string("vocab_file", None,
  31. "The vocabulary file that the BERT model was trained on.")
  32. flags.DEFINE_bool(
  33. "do_lower_case", True,
  34. "Whether to lower case the input text. Should be True for uncased "
  35. "models and False for cased models.")
  36. flags.DEFINE_bool(
  37. "do_whole_word_mask", False,
  38. "Whether to use whole word masking rather than per-WordPiece masking.")
  39. flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.")
  40. flags.DEFINE_integer("max_predictions_per_seq", 20,
  41. "Maximum number of masked LM predictions per sequence.")
  42. flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.")
  43. flags.DEFINE_integer(
  44. "dupe_factor", 10,
  45. "Number of times to duplicate the input data (with different masks).")
  46. flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.")
  47. flags.DEFINE_float(
  48. "short_seq_prob", 0.1,
  49. "Probability of creating sequences which are shorter than the "
  50. "maximum length.")
  51. class TrainingInstance(object):
  52. """A single training instance (sentence pair)."""
  53. def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels,
  54. is_random_next):
  55. self.tokens = tokens
  56. self.segment_ids = segment_ids
  57. self.is_random_next = is_random_next
  58. self.masked_lm_positions = masked_lm_positions
  59. self.masked_lm_labels = masked_lm_labels
  60. def __str__(self):
  61. s = ""
  62. s += "tokens: %s\n" % (" ".join(
  63. [tokenization.printable_text(x) for x in self.tokens]))
  64. s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids]))
  65. s += "is_random_next: %s\n" % self.is_random_next
  66. s += "masked_lm_positions: %s\n" % (" ".join(
  67. [str(x) for x in self.masked_lm_positions]))
  68. s += "masked_lm_labels: %s\n" % (" ".join(
  69. [tokenization.printable_text(x) for x in self.masked_lm_labels]))
  70. s += "\n"
  71. return s
  72. def __repr__(self):
  73. return self.__str__()
  74. def write_instance_to_example_files(instances, tokenizer, max_seq_length,
  75. max_predictions_per_seq, output_files):
  76. """Create TF example files from `TrainingInstance`s."""
  77. writers = []
  78. for output_file in output_files:
  79. writers.append(tf.python_io.TFRecordWriter(output_file))
  80. writer_index = 0
  81. total_written = 0
  82. for (inst_index, instance) in enumerate(instances):
  83. input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
  84. input_mask = [1] * len(input_ids)
  85. segment_ids = list(instance.segment_ids)
  86. assert len(input_ids) <= max_seq_length
  87. while len(input_ids) < max_seq_length:
  88. input_ids.append(0)
  89. input_mask.append(0)
  90. segment_ids.append(0)
  91. assert len(input_ids) == max_seq_length
  92. assert len(input_mask) == max_seq_length
  93. assert len(segment_ids) == max_seq_length
  94. masked_lm_positions = list(instance.masked_lm_positions)
  95. masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels)
  96. masked_lm_weights = [1.0] * len(masked_lm_ids)
  97. while len(masked_lm_positions) < max_predictions_per_seq:
  98. masked_lm_positions.append(0)
  99. masked_lm_ids.append(0)
  100. masked_lm_weights.append(0.0)
  101. next_sentence_label = 1 if instance.is_random_next else 0
  102. features = collections.OrderedDict()
  103. features["input_ids"] = create_int_feature(input_ids)
  104. features["input_mask"] = create_int_feature(input_mask)
  105. features["segment_ids"] = create_int_feature(segment_ids)
  106. features["masked_lm_positions"] = create_int_feature(masked_lm_positions)
  107. features["masked_lm_ids"] = create_int_feature(masked_lm_ids)
  108. features["masked_lm_weights"] = create_float_feature(masked_lm_weights)
  109. features["next_sentence_labels"] = create_int_feature([next_sentence_label])
  110. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  111. writers[writer_index].write(tf_example.SerializeToString())
  112. writer_index = (writer_index + 1) % len(writers)
  113. total_written += 1
  114. if inst_index < 20:
  115. tf.logging.info("*** Example ***")
  116. tf.logging.info("tokens: %s" % " ".join(
  117. [tokenization.printable_text(x) for x in instance.tokens]))
  118. for feature_name in features.keys():
  119. feature = features[feature_name]
  120. values = []
  121. if feature.int64_list.value:
  122. values = feature.int64_list.value
  123. elif feature.float_list.value:
  124. values = feature.float_list.value
  125. tf.logging.info(
  126. "%s: %s" % (feature_name, " ".join([str(x) for x in values])))
  127. for writer in writers:
  128. writer.close()
  129. tf.logging.info("Wrote %d total instances", total_written)
  130. def create_int_feature(values):
  131. feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
  132. return feature
  133. def create_float_feature(values):
  134. feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
  135. return feature
  136. def create_training_instances(input_files, tokenizer, max_seq_length,
  137. dupe_factor, short_seq_prob, masked_lm_prob,
  138. max_predictions_per_seq, rng):
  139. """Create `TrainingInstance`s from raw text."""
  140. all_documents = [[]]
  141. # Input file format:
  142. # (1) One sentence per line. These should ideally be actual sentences, not
  143. # entire paragraphs or arbitrary spans of text. (Because we use the
  144. # sentence boundaries for the "next sentence prediction" task).
  145. # (2) Blank lines between documents. Document boundaries are needed so
  146. # that the "next sentence prediction" task doesn't span between documents.
  147. for input_file in input_files:
  148. with tf.gfile.GFile(input_file, "r") as reader:
  149. while True:
  150. line = tokenization.convert_to_unicode(reader.readline())
  151. if not line:
  152. break
  153. line = line.strip()
  154. # Empty lines are used as document delimiters
  155. if not line:
  156. all_documents.append([])
  157. tokens = tokenizer.tokenize(line)
  158. if tokens:
  159. all_documents[-1].append(tokens)
  160. # Remove empty documents
  161. all_documents = [x for x in all_documents if x]
  162. rng.shuffle(all_documents)
  163. vocab_words = list(tokenizer.vocab.keys())
  164. instances = []
  165. for _ in range(dupe_factor):
  166. for document_index in range(len(all_documents)):
  167. instances.extend(
  168. create_instances_from_document(
  169. all_documents, document_index, max_seq_length, short_seq_prob,
  170. masked_lm_prob, max_predictions_per_seq, vocab_words, rng))
  171. rng.shuffle(instances)
  172. return instances
  173. def create_instances_from_document(
  174. all_documents, document_index, max_seq_length, short_seq_prob,
  175. masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
  176. """Creates `TrainingInstance`s for a single document."""
  177. document = all_documents[document_index]
  178. # Account for [CLS], [SEP], [SEP]
  179. max_num_tokens = max_seq_length - 3
  180. # We *usually* want to fill up the entire sequence since we are padding
  181. # to `max_seq_length` anyways, so short sequences are generally wasted
  182. # computation. However, we *sometimes*
  183. # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
  184. # sequences to minimize the mismatch between pre-training and fine-tuning.
  185. # The `target_seq_length` is just a rough target however, whereas
  186. # `max_seq_length` is a hard limit.
  187. target_seq_length = max_num_tokens
  188. if rng.random() < short_seq_prob:
  189. target_seq_length = rng.randint(2, max_num_tokens)
  190. # We DON'T just concatenate all of the tokens from a document into a long
  191. # sequence and choose an arbitrary split point because this would make the
  192. # next sentence prediction task too easy. Instead, we split the input into
  193. # segments "A" and "B" based on the actual "sentences" provided by the user
  194. # input.
  195. instances = []
  196. current_chunk = []
  197. current_length = 0
  198. i = 0
  199. while i < len(document):
  200. segment = document[i]
  201. current_chunk.append(segment)
  202. current_length += len(segment)
  203. if i == len(document) - 1 or current_length >= target_seq_length:
  204. if current_chunk:
  205. # `a_end` is how many segments from `current_chunk` go into the `A`
  206. # (first) sentence.
  207. a_end = 1
  208. if len(current_chunk) >= 2:
  209. a_end = rng.randint(1, len(current_chunk) - 1)
  210. tokens_a = []
  211. for j in range(a_end):
  212. tokens_a.extend(current_chunk[j])
  213. tokens_b = []
  214. # Random next
  215. is_random_next = False
  216. if len(current_chunk) == 1 or rng.random() < 0.5:
  217. is_random_next = True
  218. target_b_length = target_seq_length - len(tokens_a)
  219. # This should rarely go for more than one iteration for large
  220. # corpora. However, just to be careful, we try to make sure that
  221. # the random document is not the same as the document
  222. # we're processing.
  223. for _ in range(10):
  224. random_document_index = rng.randint(0, len(all_documents) - 1)
  225. if random_document_index != document_index:
  226. break
  227. random_document = all_documents[random_document_index]
  228. random_start = rng.randint(0, len(random_document) - 1)
  229. for j in range(random_start, len(random_document)):
  230. tokens_b.extend(random_document[j])
  231. if len(tokens_b) >= target_b_length:
  232. break
  233. # We didn't actually use these segments so we "put them back" so
  234. # they don't go to waste.
  235. num_unused_segments = len(current_chunk) - a_end
  236. i -= num_unused_segments
  237. # Actual next
  238. else:
  239. is_random_next = False
  240. for j in range(a_end, len(current_chunk)):
  241. tokens_b.extend(current_chunk[j])
  242. truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)
  243. assert len(tokens_a) >= 1
  244. assert len(tokens_b) >= 1
  245. tokens = []
  246. segment_ids = []
  247. tokens.append("[CLS]")
  248. segment_ids.append(0)
  249. for token in tokens_a:
  250. tokens.append(token)
  251. segment_ids.append(0)
  252. tokens.append("[SEP]")
  253. segment_ids.append(0)
  254. for token in tokens_b:
  255. tokens.append(token)
  256. segment_ids.append(1)
  257. tokens.append("[SEP]")
  258. segment_ids.append(1)
  259. (tokens, masked_lm_positions,
  260. masked_lm_labels) = create_masked_lm_predictions(
  261. tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)
  262. instance = TrainingInstance(
  263. tokens=tokens,
  264. segment_ids=segment_ids,
  265. is_random_next=is_random_next,
  266. masked_lm_positions=masked_lm_positions,
  267. masked_lm_labels=masked_lm_labels)
  268. instances.append(instance)
  269. current_chunk = []
  270. current_length = 0
  271. i += 1
  272. return instances
  273. MaskedLmInstance = collections.namedtuple("MaskedLmInstance",
  274. ["index", "label"])
  275. def create_masked_lm_predictions(tokens, masked_lm_prob,
  276. max_predictions_per_seq, vocab_words, rng):
  277. """Creates the predictions for the masked LM objective."""
  278. cand_indexes = []
  279. for (i, token) in enumerate(tokens):
  280. if token == "[CLS]" or token == "[SEP]":
  281. continue
  282. # Whole Word Masking means that if we mask all of the wordpieces
  283. # corresponding to an original word. When a word has been split into
  284. # WordPieces, the first token does not have any marker and any subsequence
  285. # tokens are prefixed with ##. So whenever we see the ## token, we
  286. # append it to the previous set of word indexes.
  287. #
  288. # Note that Whole Word Masking does *not* change the training code
  289. # at all -- we still predict each WordPiece independently, softmaxed
  290. # over the entire vocabulary.
  291. if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and
  292. token.startswith("##")):
  293. cand_indexes[-1].append(i)
  294. else:
  295. cand_indexes.append([i])
  296. rng.shuffle(cand_indexes)
  297. output_tokens = list(tokens)
  298. num_to_predict = min(max_predictions_per_seq,
  299. max(1, int(round(len(tokens) * masked_lm_prob))))
  300. masked_lms = []
  301. covered_indexes = set()
  302. for index_set in cand_indexes:
  303. if len(masked_lms) >= num_to_predict:
  304. break
  305. # If adding a whole-word mask would exceed the maximum number of
  306. # predictions, then just skip this candidate.
  307. if len(masked_lms) + len(index_set) > num_to_predict:
  308. continue
  309. is_any_index_covered = False
  310. for index in index_set:
  311. if index in covered_indexes:
  312. is_any_index_covered = True
  313. break
  314. if is_any_index_covered:
  315. continue
  316. for index in index_set:
  317. covered_indexes.add(index)
  318. masked_token = None
  319. # 80% of the time, replace with [MASK]
  320. if rng.random() < 0.8:
  321. masked_token = "[MASK]"
  322. else:
  323. # 10% of the time, keep original
  324. if rng.random() < 0.5:
  325. masked_token = tokens[index]
  326. # 10% of the time, replace with random word
  327. else:
  328. masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
  329. output_tokens[index] = masked_token
  330. masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))
  331. assert len(masked_lms) <= num_to_predict
  332. masked_lms = sorted(masked_lms, key=lambda x: x.index)
  333. masked_lm_positions = []
  334. masked_lm_labels = []
  335. for p in masked_lms:
  336. masked_lm_positions.append(p.index)
  337. masked_lm_labels.append(p.label)
  338. return (output_tokens, masked_lm_positions, masked_lm_labels)
  339. def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
  340. """Truncates a pair of sequences to a maximum sequence length."""
  341. while True:
  342. total_length = len(tokens_a) + len(tokens_b)
  343. if total_length <= max_num_tokens:
  344. break
  345. trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
  346. assert len(trunc_tokens) >= 1
  347. # We want to sometimes truncate from the front and sometimes from the
  348. # back to add more randomness and avoid biases.
  349. if rng.random() < 0.5:
  350. del trunc_tokens[0]
  351. else:
  352. trunc_tokens.pop()
  353. def main(_):
  354. tf.logging.set_verbosity(tf.logging.INFO)
  355. tokenizer = tokenization.FullTokenizer(
  356. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  357. input_files = []
  358. for input_pattern in FLAGS.input_file.split(","):
  359. input_files.extend(tf.gfile.Glob(input_pattern))
  360. tf.logging.info("*** Reading from input files ***")
  361. for input_file in input_files:
  362. tf.logging.info(" %s", input_file)
  363. rng = random.Random(FLAGS.random_seed)
  364. instances = create_training_instances(
  365. input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,
  366. FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq,
  367. rng)
  368. output_files = FLAGS.output_file.split(",")
  369. tf.logging.info("*** Writing to output files ***")
  370. for output_file in output_files:
  371. tf.logging.info(" %s", output_file)
  372. write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,
  373. FLAGS.max_predictions_per_seq, output_files)
  374. if __name__ == "__main__":
  375. flags.mark_flag_as_required("input_file")
  376. flags.mark_flag_as_required("output_file")
  377. flags.mark_flag_as_required("vocab_file")
  378. tf.app.run()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...