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 15 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
  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_integer("max_seq_length", 128, "Maximum sequence length.")
  37. flags.DEFINE_integer("max_predictions_per_seq", 20,
  38. "Maximum number of masked LM predictions per sequence.")
  39. flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.")
  40. flags.DEFINE_integer(
  41. "dupe_factor", 10,
  42. "Number of times to duplicate the input data (with different masks).")
  43. flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.")
  44. flags.DEFINE_float(
  45. "short_seq_prob", 0.1,
  46. "Probability of creating sequences which are shorter than the "
  47. "maximum length.")
  48. class TrainingInstance(object):
  49. """A single training instance (sentence pair)."""
  50. def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels,
  51. is_random_next):
  52. self.tokens = tokens
  53. self.segment_ids = segment_ids
  54. self.is_random_next = is_random_next
  55. self.masked_lm_positions = masked_lm_positions
  56. self.masked_lm_labels = masked_lm_labels
  57. def __str__(self):
  58. s = ""
  59. s += "tokens: %s\n" % (" ".join(
  60. [tokenization.printable_text(x) for x in self.tokens]))
  61. s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids]))
  62. s += "is_random_next: %s\n" % self.is_random_next
  63. s += "masked_lm_positions: %s\n" % (" ".join(
  64. [str(x) for x in self.masked_lm_positions]))
  65. s += "masked_lm_labels: %s\n" % (" ".join(
  66. [tokenization.printable_text(x) for x in self.masked_lm_labels]))
  67. s += "\n"
  68. return s
  69. def __repr__(self):
  70. return self.__str__()
  71. def write_instance_to_example_files(instances, tokenizer, max_seq_length,
  72. max_predictions_per_seq, output_files):
  73. """Create TF example files from `TrainingInstance`s."""
  74. writers = []
  75. for output_file in output_files:
  76. writers.append(tf.python_io.TFRecordWriter(output_file))
  77. writer_index = 0
  78. total_written = 0
  79. for (inst_index, instance) in enumerate(instances):
  80. input_ids = tokenizer.convert_tokens_to_ids(instance.tokens)
  81. input_mask = [1] * len(input_ids)
  82. segment_ids = list(instance.segment_ids)
  83. assert len(input_ids) <= max_seq_length
  84. while len(input_ids) < max_seq_length:
  85. input_ids.append(0)
  86. input_mask.append(0)
  87. segment_ids.append(0)
  88. assert len(input_ids) == max_seq_length
  89. assert len(input_mask) == max_seq_length
  90. assert len(segment_ids) == max_seq_length
  91. masked_lm_positions = list(instance.masked_lm_positions)
  92. masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels)
  93. masked_lm_weights = [1.0] * len(masked_lm_ids)
  94. while len(masked_lm_positions) < max_predictions_per_seq:
  95. masked_lm_positions.append(0)
  96. masked_lm_ids.append(0)
  97. masked_lm_weights.append(0.0)
  98. next_sentence_label = 1 if instance.is_random_next else 0
  99. features = collections.OrderedDict()
  100. features["input_ids"] = create_int_feature(input_ids)
  101. features["input_mask"] = create_int_feature(input_mask)
  102. features["segment_ids"] = create_int_feature(segment_ids)
  103. features["masked_lm_positions"] = create_int_feature(masked_lm_positions)
  104. features["masked_lm_ids"] = create_int_feature(masked_lm_ids)
  105. features["masked_lm_weights"] = create_float_feature(masked_lm_weights)
  106. features["next_sentence_labels"] = create_int_feature([next_sentence_label])
  107. tf_example = tf.train.Example(features=tf.train.Features(feature=features))
  108. writers[writer_index].write(tf_example.SerializeToString())
  109. writer_index = (writer_index + 1) % len(writers)
  110. total_written += 1
  111. if inst_index < 20:
  112. tf.logging.info("*** Example ***")
  113. tf.logging.info("tokens: %s" % " ".join(
  114. [tokenization.printable_text(x) for x in instance.tokens]))
  115. for feature_name in features.keys():
  116. feature = features[feature_name]
  117. values = []
  118. if feature.int64_list.value:
  119. values = feature.int64_list.value
  120. elif feature.float_list.value:
  121. values = feature.float_list.value
  122. tf.logging.info(
  123. "%s: %s" % (feature_name, " ".join([str(x) for x in values])))
  124. for writer in writers:
  125. writer.close()
  126. tf.logging.info("Wrote %d total instances", total_written)
  127. def create_int_feature(values):
  128. feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
  129. return feature
  130. def create_float_feature(values):
  131. feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
  132. return feature
  133. def create_training_instances(input_files, tokenizer, max_seq_length,
  134. dupe_factor, short_seq_prob, masked_lm_prob,
  135. max_predictions_per_seq, rng):
  136. """Create `TrainingInstance`s from raw text."""
  137. all_documents = [[]]
  138. # Input file format:
  139. # (1) One sentence per line. These should ideally be actual sentences, not
  140. # entire paragraphs or arbitrary spans of text. (Because we use the
  141. # sentence boundaries for the "next sentence prediction" task).
  142. # (2) Blank lines between documents. Document boundaries are needed so
  143. # that the "next sentence prediction" task doesn't span between documents.
  144. for input_file in input_files:
  145. with tf.gfile.GFile(input_file, "r") as reader:
  146. while True:
  147. line = tokenization.convert_to_unicode(reader.readline())
  148. if not line:
  149. break
  150. line = line.strip()
  151. # Empty lines are used as document delimiters
  152. if not line:
  153. all_documents.append([])
  154. tokens = tokenizer.tokenize(line)
  155. if tokens:
  156. all_documents[-1].append(tokens)
  157. # Remove empty documents
  158. all_documents = [x for x in all_documents if x]
  159. rng.shuffle(all_documents)
  160. vocab_words = list(tokenizer.vocab.keys())
  161. instances = []
  162. for _ in range(dupe_factor):
  163. for document_index in range(len(all_documents)):
  164. instances.extend(
  165. create_instances_from_document(
  166. all_documents, document_index, max_seq_length, short_seq_prob,
  167. masked_lm_prob, max_predictions_per_seq, vocab_words, rng))
  168. rng.shuffle(instances)
  169. return instances
  170. def create_instances_from_document(
  171. all_documents, document_index, max_seq_length, short_seq_prob,
  172. masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
  173. """Creates `TrainingInstance`s for a single document."""
  174. document = all_documents[document_index]
  175. # Account for [CLS], [SEP], [SEP]
  176. max_num_tokens = max_seq_length - 3
  177. # We *usually* want to fill up the entire sequence since we are padding
  178. # to `max_seq_length` anyways, so short sequences are generally wasted
  179. # computation. However, we *sometimes*
  180. # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter
  181. # sequences to minimize the mismatch between pre-training and fine-tuning.
  182. # The `target_seq_length` is just a rough target however, whereas
  183. # `max_seq_length` is a hard limit.
  184. target_seq_length = max_num_tokens
  185. if rng.random() < short_seq_prob:
  186. target_seq_length = rng.randint(2, max_num_tokens)
  187. # We DON'T just concatenate all of the tokens from a document into a long
  188. # sequence and choose an arbitrary split point because this would make the
  189. # next sentence prediction task too easy. Instead, we split the input into
  190. # segments "A" and "B" based on the actual "sentences" provided by the user
  191. # input.
  192. instances = []
  193. current_chunk = []
  194. current_length = 0
  195. i = 0
  196. while i < len(document):
  197. segment = document[i]
  198. current_chunk.append(segment)
  199. current_length += len(segment)
  200. if i == len(document) - 1 or current_length >= target_seq_length:
  201. if current_chunk:
  202. # `a_end` is how many segments from `current_chunk` go into the `A`
  203. # (first) sentence.
  204. a_end = 1
  205. if len(current_chunk) >= 2:
  206. a_end = rng.randint(1, len(current_chunk) - 1)
  207. tokens_a = []
  208. for j in range(a_end):
  209. tokens_a.extend(current_chunk[j])
  210. tokens_b = []
  211. # Random next
  212. is_random_next = False
  213. if len(current_chunk) == 1 or rng.random() < 0.5:
  214. is_random_next = True
  215. target_b_length = target_seq_length - len(tokens_a)
  216. # This should rarely go for more than one iteration for large
  217. # corpora. However, just to be careful, we try to make sure that
  218. # the random document is not the same as the document
  219. # we're processing.
  220. for _ in range(10):
  221. random_document_index = rng.randint(0, len(all_documents) - 1)
  222. if random_document_index != document_index:
  223. break
  224. random_document = all_documents[random_document_index]
  225. random_start = rng.randint(0, len(random_document) - 1)
  226. for j in range(random_start, len(random_document)):
  227. tokens_b.extend(random_document[j])
  228. if len(tokens_b) >= target_b_length:
  229. break
  230. # We didn't actually use these segments so we "put them back" so
  231. # they don't go to waste.
  232. num_unused_segments = len(current_chunk) - a_end
  233. i -= num_unused_segments
  234. # Actual next
  235. else:
  236. is_random_next = False
  237. for j in range(a_end, len(current_chunk)):
  238. tokens_b.extend(current_chunk[j])
  239. truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng)
  240. assert len(tokens_a) >= 1
  241. assert len(tokens_b) >= 1
  242. tokens = []
  243. segment_ids = []
  244. tokens.append("[CLS]")
  245. segment_ids.append(0)
  246. for token in tokens_a:
  247. tokens.append(token)
  248. segment_ids.append(0)
  249. tokens.append("[SEP]")
  250. segment_ids.append(0)
  251. for token in tokens_b:
  252. tokens.append(token)
  253. segment_ids.append(1)
  254. tokens.append("[SEP]")
  255. segment_ids.append(1)
  256. (tokens, masked_lm_positions,
  257. masked_lm_labels) = create_masked_lm_predictions(
  258. tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)
  259. instance = TrainingInstance(
  260. tokens=tokens,
  261. segment_ids=segment_ids,
  262. is_random_next=is_random_next,
  263. masked_lm_positions=masked_lm_positions,
  264. masked_lm_labels=masked_lm_labels)
  265. instances.append(instance)
  266. current_chunk = []
  267. current_length = 0
  268. i += 1
  269. return instances
  270. MaskedLmInstance = collections.namedtuple("MaskedLmInstance",
  271. ["index", "label"])
  272. def create_masked_lm_predictions(tokens, masked_lm_prob,
  273. max_predictions_per_seq, vocab_words, rng):
  274. """Creates the predictions for the masked LM objective."""
  275. cand_indexes = []
  276. for (i, token) in enumerate(tokens):
  277. if token == "[CLS]" or token == "[SEP]":
  278. continue
  279. cand_indexes.append(i)
  280. rng.shuffle(cand_indexes)
  281. output_tokens = list(tokens)
  282. num_to_predict = min(max_predictions_per_seq,
  283. max(1, int(round(len(tokens) * masked_lm_prob))))
  284. masked_lms = []
  285. covered_indexes = set()
  286. for index in cand_indexes:
  287. if len(masked_lms) >= num_to_predict:
  288. break
  289. if index in covered_indexes:
  290. continue
  291. covered_indexes.add(index)
  292. masked_token = None
  293. # 80% of the time, replace with [MASK]
  294. if rng.random() < 0.8:
  295. masked_token = "[MASK]"
  296. else:
  297. # 10% of the time, keep original
  298. if rng.random() < 0.5:
  299. masked_token = tokens[index]
  300. # 10% of the time, replace with random word
  301. else:
  302. masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)]
  303. output_tokens[index] = masked_token
  304. masked_lms.append(MaskedLmInstance(index=index, label=tokens[index]))
  305. masked_lms = sorted(masked_lms, key=lambda x: x.index)
  306. masked_lm_positions = []
  307. masked_lm_labels = []
  308. for p in masked_lms:
  309. masked_lm_positions.append(p.index)
  310. masked_lm_labels.append(p.label)
  311. return (output_tokens, masked_lm_positions, masked_lm_labels)
  312. def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
  313. """Truncates a pair of sequences to a maximum sequence length."""
  314. while True:
  315. total_length = len(tokens_a) + len(tokens_b)
  316. if total_length <= max_num_tokens:
  317. break
  318. trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b
  319. assert len(trunc_tokens) >= 1
  320. # We want to sometimes truncate from the front and sometimes from the
  321. # back to add more randomness and avoid biases.
  322. if rng.random() < 0.5:
  323. del trunc_tokens[0]
  324. else:
  325. trunc_tokens.pop()
  326. def main(_):
  327. tf.logging.set_verbosity(tf.logging.INFO)
  328. tokenizer = tokenization.FullTokenizer(
  329. vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
  330. input_files = []
  331. for input_pattern in FLAGS.input_file.split(","):
  332. input_files.extend(tf.gfile.Glob(input_pattern))
  333. tf.logging.info("*** Reading from input files ***")
  334. for input_file in input_files:
  335. tf.logging.info(" %s", input_file)
  336. rng = random.Random(FLAGS.random_seed)
  337. instances = create_training_instances(
  338. input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor,
  339. FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq,
  340. rng)
  341. output_files = FLAGS.output_file.split(",")
  342. tf.logging.info("*** Writing to output files ***")
  343. for output_file in output_files:
  344. tf.logging.info(" %s", output_file)
  345. write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length,
  346. FLAGS.max_predictions_per_seq, output_files)
  347. if __name__ == "__main__":
  348. flags.mark_flag_as_required("input_file")
  349. flags.mark_flag_as_required("output_file")
  350. flags.mark_flag_as_required("vocab_file")
  351. tf.app.run()
Tip!

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

Comments

Loading...