Pradeep Kumar commited on
Commit
3dad389
·
verified ·
1 Parent(s): 9dcd3ec

Delete squad_lib_sp.py

Browse files
Files changed (1) hide show
  1. squad_lib_sp.py +0 -976
squad_lib_sp.py DELETED
@@ -1,976 +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
- """Run ALBERT on SQuAD 1.1 and SQuAD 2.0 using sentence piece tokenization.
16
-
17
- The file is forked from:
18
-
19
- https://github.com/google-research/ALBERT/blob/master/run_squad_sp.py
20
- """
21
- import collections
22
- import copy
23
- import json
24
- import math
25
- import os
26
-
27
- from absl import logging
28
- import numpy as np
29
- import tensorflow as tf, tf_keras
30
-
31
- from official.nlp.tools import tokenization
32
-
33
-
34
- class SquadExample(object):
35
- """A single training/test example for simple sequence classification.
36
-
37
- For examples without an answer, the start and end position are -1.
38
- """
39
-
40
- def __init__(self,
41
- qas_id,
42
- question_text,
43
- paragraph_text,
44
- orig_answer_text=None,
45
- start_position=None,
46
- end_position=None,
47
- is_impossible=False):
48
- self.qas_id = qas_id
49
- self.question_text = question_text
50
- self.paragraph_text = paragraph_text
51
- self.orig_answer_text = orig_answer_text
52
- self.start_position = start_position
53
- self.end_position = end_position
54
- self.is_impossible = is_impossible
55
-
56
- def __str__(self):
57
- return self.__repr__()
58
-
59
- def __repr__(self):
60
- s = ""
61
- s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
62
- s += ", question_text: %s" % (
63
- tokenization.printable_text(self.question_text))
64
- s += ", paragraph_text: [%s]" % (" ".join(self.paragraph_text))
65
- if self.start_position:
66
- s += ", start_position: %d" % (self.start_position,)
67
- if self.start_position:
68
- s += ", end_position: %d" % (self.end_position)
69
- if self.start_position:
70
- s += ", is_impossible: %r" % (self.is_impossible)
71
- return s
72
-
73
-
74
- class InputFeatures(object):
75
- """A single set of features of data."""
76
-
77
- def __init__(self,
78
- unique_id,
79
- example_index,
80
- doc_span_index,
81
- tok_start_to_orig_index,
82
- tok_end_to_orig_index,
83
- token_is_max_context,
84
- tokens,
85
- input_ids,
86
- input_mask,
87
- segment_ids,
88
- paragraph_len,
89
- class_index=None,
90
- paragraph_mask=None,
91
- start_position=None,
92
- end_position=None,
93
- is_impossible=None):
94
- self.unique_id = unique_id
95
- self.example_index = example_index
96
- self.doc_span_index = doc_span_index
97
- self.tok_start_to_orig_index = tok_start_to_orig_index
98
- self.tok_end_to_orig_index = tok_end_to_orig_index
99
- self.token_is_max_context = token_is_max_context
100
- self.tokens = tokens
101
- self.input_ids = input_ids
102
- self.input_mask = input_mask
103
- self.paragraph_mask = paragraph_mask
104
- self.segment_ids = segment_ids
105
- self.paragraph_len = paragraph_len
106
- self.class_index = class_index
107
- self.start_position = start_position
108
- self.end_position = end_position
109
- self.is_impossible = is_impossible
110
-
111
-
112
- def read_squad_examples(input_file,
113
- is_training,
114
- version_2_with_negative,
115
- translated_input_folder=None):
116
- """Read a SQuAD json file into a list of SquadExample."""
117
- del version_2_with_negative
118
- with tf.io.gfile.GFile(input_file, "r") as reader:
119
- input_data = json.load(reader)["data"]
120
-
121
- if translated_input_folder is not None:
122
- translated_files = tf.io.gfile.glob(
123
- os.path.join(translated_input_folder, "*.json"))
124
- for file in translated_files:
125
- with tf.io.gfile.GFile(file, "r") as reader:
126
- input_data.extend(json.load(reader)["data"])
127
-
128
- examples = []
129
- for entry in input_data:
130
- for paragraph in entry["paragraphs"]:
131
- paragraph_text = paragraph["context"]
132
-
133
- for qa in paragraph["qas"]:
134
- qas_id = qa["id"]
135
- question_text = qa["question"]
136
- start_position = None
137
- orig_answer_text = None
138
- is_impossible = False
139
-
140
- if is_training:
141
- is_impossible = qa.get("is_impossible", False)
142
- if (len(qa["answers"]) != 1) and (not is_impossible):
143
- raise ValueError(
144
- "For training, each question should have exactly 1 answer.")
145
- if not is_impossible:
146
- answer = qa["answers"][0]
147
- orig_answer_text = answer["text"]
148
- start_position = answer["answer_start"]
149
- else:
150
- start_position = -1
151
- orig_answer_text = ""
152
-
153
- example = SquadExample(
154
- qas_id=qas_id,
155
- question_text=question_text,
156
- paragraph_text=paragraph_text,
157
- orig_answer_text=orig_answer_text,
158
- start_position=start_position,
159
- is_impossible=is_impossible)
160
- examples.append(example)
161
-
162
- return examples
163
-
164
-
165
- def _convert_index(index, pos, m=None, is_start=True):
166
- """Converts index."""
167
- if index[pos] is not None:
168
- return index[pos]
169
- n = len(index)
170
- rear = pos
171
- while rear < n - 1 and index[rear] is None:
172
- rear += 1
173
- front = pos
174
- while front > 0 and index[front] is None:
175
- front -= 1
176
- assert index[front] is not None or index[rear] is not None
177
- if index[front] is None:
178
- if index[rear] >= 1: # pytype: disable=unsupported-operands
179
- if is_start:
180
- return 0
181
- else:
182
- return index[rear] - 1
183
- return index[rear]
184
- if index[rear] is None:
185
- if m is not None and index[front] < m - 1:
186
- if is_start:
187
- return index[front] + 1
188
- else:
189
- return m - 1
190
- return index[front]
191
- if is_start:
192
- if index[rear] > index[front] + 1:
193
- return index[front] + 1
194
- else:
195
- return index[rear]
196
- else:
197
- if index[rear] > index[front] + 1:
198
- return index[rear] - 1
199
- else:
200
- return index[front]
201
-
202
-
203
- def convert_examples_to_features(examples,
204
- tokenizer,
205
- max_seq_length,
206
- doc_stride,
207
- max_query_length,
208
- is_training,
209
- output_fn,
210
- do_lower_case,
211
- xlnet_format=False,
212
- batch_size=None):
213
- """Loads a data file into a list of `InputBatch`s."""
214
- cnt_pos, cnt_neg = 0, 0
215
- base_id = 1000000000
216
- unique_id = base_id
217
- max_n, max_m = 1024, 1024
218
- f = np.zeros((max_n, max_m), dtype=np.float32)
219
-
220
- for (example_index, example) in enumerate(examples):
221
-
222
- if example_index % 100 == 0:
223
- logging.info("Converting %d/%d pos %d neg %d", example_index,
224
- len(examples), cnt_pos, cnt_neg)
225
-
226
- query_tokens = tokenization.encode_ids(
227
- tokenizer.sp_model,
228
- tokenization.preprocess_text(
229
- example.question_text, lower=do_lower_case))
230
-
231
- if len(query_tokens) > max_query_length:
232
- query_tokens = query_tokens[0:max_query_length]
233
-
234
- paragraph_text = example.paragraph_text
235
- para_tokens = tokenization.encode_pieces(
236
- tokenizer.sp_model,
237
- tokenization.preprocess_text(
238
- example.paragraph_text, lower=do_lower_case))
239
-
240
- chartok_to_tok_index = []
241
- tok_start_to_chartok_index = []
242
- tok_end_to_chartok_index = []
243
- char_cnt = 0
244
- for i, token in enumerate(para_tokens):
245
- new_token = token.replace(tokenization.SPIECE_UNDERLINE, " ")
246
- chartok_to_tok_index.extend([i] * len(new_token))
247
- tok_start_to_chartok_index.append(char_cnt)
248
- char_cnt += len(new_token)
249
- tok_end_to_chartok_index.append(char_cnt - 1)
250
-
251
- tok_cat_text = "".join(para_tokens).replace(tokenization.SPIECE_UNDERLINE,
252
- " ")
253
- n, m = len(paragraph_text), len(tok_cat_text)
254
-
255
- if n > max_n or m > max_m:
256
- max_n = max(n, max_n)
257
- max_m = max(m, max_m)
258
- f = np.zeros((max_n, max_m), dtype=np.float32)
259
-
260
- g = {}
261
-
262
- # pylint: disable=cell-var-from-loop
263
- def _lcs_match(max_dist, n=n, m=m):
264
- """Longest-common-substring algorithm."""
265
- f.fill(0)
266
- g.clear()
267
-
268
- ### longest common sub sequence
269
- # f[i, j] = max(f[i - 1, j], f[i, j - 1], f[i - 1, j - 1] + match(i, j))
270
- for i in range(n):
271
-
272
- # unlike standard LCS, this is specifically optimized for the setting
273
- # because the mismatch between sentence pieces and original text will
274
- # be small
275
- for j in range(i - max_dist, i + max_dist):
276
- if j >= m or j < 0:
277
- continue
278
-
279
- if i > 0:
280
- g[(i, j)] = 0
281
- f[i, j] = f[i - 1, j]
282
-
283
- if j > 0 and f[i, j - 1] > f[i, j]:
284
- g[(i, j)] = 1
285
- f[i, j] = f[i, j - 1]
286
-
287
- f_prev = f[i - 1, j - 1] if i > 0 and j > 0 else 0
288
- if (tokenization.preprocess_text(
289
- paragraph_text[i], lower=do_lower_case,
290
- remove_space=False) == tok_cat_text[j] and f_prev + 1 > f[i, j]):
291
- g[(i, j)] = 2
292
- f[i, j] = f_prev + 1
293
-
294
- # pylint: enable=cell-var-from-loop
295
-
296
- max_dist = abs(n - m) + 5
297
- for _ in range(2):
298
- _lcs_match(max_dist)
299
- if f[n - 1, m - 1] > 0.8 * n:
300
- break
301
- max_dist *= 2
302
-
303
- orig_to_chartok_index = [None] * n
304
- chartok_to_orig_index = [None] * m
305
- i, j = n - 1, m - 1
306
- while i >= 0 and j >= 0:
307
- if (i, j) not in g:
308
- break
309
- if g[(i, j)] == 2:
310
- orig_to_chartok_index[i] = j
311
- chartok_to_orig_index[j] = i
312
- i, j = i - 1, j - 1
313
- elif g[(i, j)] == 1:
314
- j = j - 1
315
- else:
316
- i = i - 1
317
-
318
- if (all(v is None for v in orig_to_chartok_index) or
319
- f[n - 1, m - 1] < 0.8 * n):
320
- logging.info("MISMATCH DETECTED!")
321
- continue
322
-
323
- tok_start_to_orig_index = []
324
- tok_end_to_orig_index = []
325
- for i in range(len(para_tokens)):
326
- start_chartok_pos = tok_start_to_chartok_index[i]
327
- end_chartok_pos = tok_end_to_chartok_index[i]
328
- start_orig_pos = _convert_index(
329
- chartok_to_orig_index, start_chartok_pos, n, is_start=True)
330
- end_orig_pos = _convert_index(
331
- chartok_to_orig_index, end_chartok_pos, n, is_start=False)
332
-
333
- tok_start_to_orig_index.append(start_orig_pos)
334
- tok_end_to_orig_index.append(end_orig_pos)
335
-
336
- if not is_training:
337
- tok_start_position = tok_end_position = None
338
-
339
- if is_training and example.is_impossible:
340
- tok_start_position = 0
341
- tok_end_position = 0
342
-
343
- if is_training and not example.is_impossible:
344
- start_position = example.start_position
345
- end_position = start_position + len(example.orig_answer_text) - 1
346
-
347
- start_chartok_pos = _convert_index(
348
- orig_to_chartok_index, start_position, is_start=True)
349
- tok_start_position = chartok_to_tok_index[start_chartok_pos]
350
-
351
- end_chartok_pos = _convert_index(
352
- orig_to_chartok_index, end_position, is_start=False)
353
- tok_end_position = chartok_to_tok_index[end_chartok_pos]
354
- assert tok_start_position <= tok_end_position
355
-
356
- def _piece_to_id(x):
357
- return tokenizer.sp_model.PieceToId(x)
358
-
359
- all_doc_tokens = list(map(_piece_to_id, para_tokens))
360
-
361
- # The -3 accounts for [CLS], [SEP] and [SEP]
362
- max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
363
-
364
- # We can have documents that are longer than the maximum sequence length.
365
- # To deal with this we do a sliding window approach, where we take chunks
366
- # of the up to our max length with a stride of `doc_stride`.
367
- _DocSpan = collections.namedtuple( # pylint: disable=invalid-name
368
- "DocSpan", ["start", "length"])
369
- doc_spans = []
370
- start_offset = 0
371
-
372
- while start_offset < len(all_doc_tokens):
373
- length = len(all_doc_tokens) - start_offset
374
- if length > max_tokens_for_doc:
375
- length = max_tokens_for_doc
376
- doc_spans.append(_DocSpan(start=start_offset, length=length))
377
- if start_offset + length == len(all_doc_tokens):
378
- break
379
- start_offset += min(length, doc_stride)
380
-
381
- for (doc_span_index, doc_span) in enumerate(doc_spans):
382
- tokens = []
383
- token_is_max_context = {}
384
- segment_ids = []
385
-
386
- # Paragraph mask used in XLNet.
387
- # 1 represents paragraph and class tokens.
388
- # 0 represents query and other special tokens.
389
- paragraph_mask = []
390
-
391
- cur_tok_start_to_orig_index = []
392
- cur_tok_end_to_orig_index = []
393
-
394
- # pylint: disable=cell-var-from-loop
395
- def process_query(seg_q):
396
- for token in query_tokens:
397
- tokens.append(token)
398
- segment_ids.append(seg_q)
399
- paragraph_mask.append(0)
400
- tokens.append(tokenizer.sp_model.PieceToId("[SEP]"))
401
- segment_ids.append(seg_q)
402
- paragraph_mask.append(0)
403
-
404
- def process_paragraph(seg_p):
405
- for i in range(doc_span.length):
406
- split_token_index = doc_span.start + i
407
-
408
- cur_tok_start_to_orig_index.append(
409
- tok_start_to_orig_index[split_token_index])
410
- cur_tok_end_to_orig_index.append(
411
- tok_end_to_orig_index[split_token_index])
412
-
413
- is_max_context = _check_is_max_context(doc_spans, doc_span_index,
414
- split_token_index)
415
- token_is_max_context[len(tokens)] = is_max_context
416
- tokens.append(all_doc_tokens[split_token_index])
417
- segment_ids.append(seg_p)
418
- paragraph_mask.append(1)
419
- tokens.append(tokenizer.sp_model.PieceToId("[SEP]"))
420
- segment_ids.append(seg_p)
421
- paragraph_mask.append(0)
422
- return len(tokens)
423
-
424
- def process_class(seg_class):
425
- class_index = len(segment_ids)
426
- tokens.append(tokenizer.sp_model.PieceToId("[CLS]"))
427
- segment_ids.append(seg_class)
428
- paragraph_mask.append(1)
429
- return class_index
430
-
431
- if xlnet_format:
432
- seg_p, seg_q, seg_class, seg_pad = 0, 1, 2, 3
433
- paragraph_len = process_paragraph(seg_p)
434
- process_query(seg_q)
435
- class_index = process_class(seg_class)
436
- else:
437
- seg_p, seg_q, seg_class, seg_pad = 1, 0, 0, 0
438
- class_index = process_class(seg_class)
439
- process_query(seg_q)
440
- paragraph_len = process_paragraph(seg_p)
441
-
442
- input_ids = tokens
443
-
444
- # The mask has 1 for real tokens and 0 for padding tokens. Only real
445
- # tokens are attended to.
446
- input_mask = [1] * len(input_ids)
447
-
448
- # Zero-pad up to the sequence length.
449
- while len(input_ids) < max_seq_length:
450
- input_ids.append(0)
451
- input_mask.append(0)
452
- segment_ids.append(seg_pad)
453
- paragraph_mask.append(0)
454
-
455
- assert len(input_ids) == max_seq_length
456
- assert len(input_mask) == max_seq_length
457
- assert len(segment_ids) == max_seq_length
458
- assert len(paragraph_mask) == max_seq_length
459
-
460
- span_is_impossible = example.is_impossible
461
- start_position = None
462
- end_position = None
463
- if is_training and not span_is_impossible:
464
- # For training, if our document chunk does not contain an annotation
465
- # we throw it out, since there is nothing to predict.
466
- doc_start = doc_span.start
467
- doc_end = doc_span.start + doc_span.length - 1
468
- out_of_span = False
469
- if not (tok_start_position >= doc_start and
470
- tok_end_position <= doc_end):
471
- out_of_span = True
472
- if out_of_span:
473
- # continue
474
- start_position = 0
475
- end_position = 0
476
- span_is_impossible = True
477
- else:
478
- doc_offset = 0 if xlnet_format else len(query_tokens) + 2
479
- start_position = tok_start_position - doc_start + doc_offset
480
- end_position = tok_end_position - doc_start + doc_offset
481
-
482
- if is_training and span_is_impossible:
483
- start_position = class_index
484
- end_position = class_index
485
-
486
- if example_index < 20:
487
- logging.info("*** Example ***")
488
- logging.info("unique_id: %s", (unique_id))
489
- logging.info("example_index: %s", (example_index))
490
- logging.info("doc_span_index: %s", (doc_span_index))
491
- logging.info("tok_start_to_orig_index: %s",
492
- " ".join([str(x) for x in cur_tok_start_to_orig_index]))
493
- logging.info("tok_end_to_orig_index: %s",
494
- " ".join([str(x) for x in cur_tok_end_to_orig_index]))
495
- logging.info(
496
- "token_is_max_context: %s", " ".join(
497
- ["%d:%s" % (x, y) for (x, y) in token_is_max_context.items()]))
498
- logging.info(
499
- "input_pieces: %s",
500
- " ".join([tokenizer.sp_model.IdToPiece(x) for x in tokens]))
501
- logging.info("input_ids: %s", " ".join([str(x) for x in input_ids]))
502
- logging.info("input_mask: %s", " ".join([str(x) for x in input_mask]))
503
- logging.info("segment_ids: %s", " ".join([str(x) for x in segment_ids]))
504
- logging.info("paragraph_mask: %s", " ".join(
505
- [str(x) for x in paragraph_mask]))
506
- logging.info("class_index: %d", class_index)
507
-
508
- if is_training and span_is_impossible:
509
- logging.info("impossible example span")
510
-
511
- if is_training and not span_is_impossible:
512
- pieces = [
513
- tokenizer.sp_model.IdToPiece(token)
514
- for token in tokens[start_position:(end_position + 1)]
515
- ]
516
- answer_text = tokenizer.sp_model.DecodePieces(pieces)
517
- logging.info("start_position: %d", (start_position))
518
- logging.info("end_position: %d", (end_position))
519
- logging.info("answer: %s", (tokenization.printable_text(answer_text)))
520
-
521
- # With multi processing, the example_index is actually the index
522
- # within the current process therefore we use example_index=None
523
- # to avoid being used in the future.
524
- # The current code does not use example_index of training data.
525
- if is_training:
526
- feat_example_index = None
527
- else:
528
- feat_example_index = example_index
529
-
530
- feature = InputFeatures(
531
- unique_id=unique_id,
532
- example_index=feat_example_index,
533
- doc_span_index=doc_span_index,
534
- tok_start_to_orig_index=cur_tok_start_to_orig_index,
535
- tok_end_to_orig_index=cur_tok_end_to_orig_index,
536
- token_is_max_context=token_is_max_context,
537
- tokens=[tokenizer.sp_model.IdToPiece(x) for x in tokens],
538
- input_ids=input_ids,
539
- input_mask=input_mask,
540
- paragraph_mask=paragraph_mask,
541
- segment_ids=segment_ids,
542
- paragraph_len=paragraph_len,
543
- class_index=class_index,
544
- start_position=start_position,
545
- end_position=end_position,
546
- is_impossible=span_is_impossible)
547
-
548
- # Run callback
549
- if is_training:
550
- output_fn(feature)
551
- else:
552
- output_fn(feature, is_padding=False)
553
-
554
- unique_id += 1
555
- if span_is_impossible:
556
- cnt_neg += 1
557
- else:
558
- cnt_pos += 1
559
-
560
- if not is_training and feature:
561
- assert batch_size
562
- num_padding = 0
563
- num_examples = unique_id - base_id
564
- if unique_id % batch_size != 0:
565
- num_padding = batch_size - (num_examples % batch_size)
566
- dummy_feature = copy.deepcopy(feature)
567
- for _ in range(num_padding):
568
- dummy_feature.unique_id = unique_id
569
-
570
- # Run callback
571
- output_fn(feature, is_padding=True)
572
- unique_id += 1
573
-
574
- logging.info("Total number of instances: %d = pos %d neg %d",
575
- cnt_pos + cnt_neg, cnt_pos, cnt_neg)
576
- return unique_id - base_id
577
-
578
-
579
- def _check_is_max_context(doc_spans, cur_span_index, position):
580
- """Check if this is the 'max context' doc span for the token."""
581
-
582
- # Because of the sliding window approach taken to scoring documents, a single
583
- # token can appear in multiple documents. E.g.
584
- # Doc: the man went to the store and bought a gallon of milk
585
- # Span A: the man went to the
586
- # Span B: to the store and bought
587
- # Span C: and bought a gallon of
588
- # ...
589
- #
590
- # Now the word 'bought' will have two scores from spans B and C. We only
591
- # want to consider the score with "maximum context", which we define as
592
- # the *minimum* of its left and right context (the *sum* of left and
593
- # right context will always be the same, of course).
594
- #
595
- # In the example the maximum context for 'bought' would be span C since
596
- # it has 1 left context and 3 right context, while span B has 4 left context
597
- # and 0 right context.
598
- best_score = None
599
- best_span_index = None
600
- for (span_index, doc_span) in enumerate(doc_spans):
601
- end = doc_span.start + doc_span.length - 1
602
- if position < doc_span.start:
603
- continue
604
- if position > end:
605
- continue
606
- num_left_context = position - doc_span.start
607
- num_right_context = end - position
608
- score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
609
- if best_score is None or score > best_score:
610
- best_score = score
611
- best_span_index = span_index
612
-
613
- return cur_span_index == best_span_index
614
-
615
-
616
- def write_predictions(all_examples,
617
- all_features,
618
- all_results,
619
- n_best_size,
620
- max_answer_length,
621
- do_lower_case,
622
- output_prediction_file,
623
- output_nbest_file,
624
- output_null_log_odds_file,
625
- version_2_with_negative=False,
626
- null_score_diff_threshold=0.0,
627
- verbose=False):
628
- """Write final predictions to the json file and log-odds of null if needed."""
629
- logging.info("Writing predictions to: %s", (output_prediction_file))
630
- logging.info("Writing nbest to: %s", (output_nbest_file))
631
-
632
- all_predictions, all_nbest_json, scores_diff_json = (
633
- postprocess_output(
634
- all_examples=all_examples,
635
- all_features=all_features,
636
- all_results=all_results,
637
- n_best_size=n_best_size,
638
- max_answer_length=max_answer_length,
639
- do_lower_case=do_lower_case,
640
- version_2_with_negative=version_2_with_negative,
641
- null_score_diff_threshold=null_score_diff_threshold,
642
- verbose=verbose))
643
-
644
- write_to_json_files(all_predictions, output_prediction_file)
645
- write_to_json_files(all_nbest_json, output_nbest_file)
646
- if version_2_with_negative:
647
- write_to_json_files(scores_diff_json, output_null_log_odds_file)
648
-
649
-
650
- def postprocess_output(all_examples,
651
- all_features,
652
- all_results,
653
- n_best_size,
654
- max_answer_length,
655
- do_lower_case,
656
- version_2_with_negative=False,
657
- null_score_diff_threshold=0.0,
658
- xlnet_format=False,
659
- verbose=False):
660
- """Postprocess model output, to form predicton results."""
661
-
662
- del do_lower_case, verbose
663
- example_index_to_features = collections.defaultdict(list)
664
- for feature in all_features:
665
- example_index_to_features[feature.example_index].append(feature)
666
-
667
- unique_id_to_result = {}
668
- for result in all_results:
669
- unique_id_to_result[result.unique_id] = result
670
-
671
- _PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
672
- "PrelimPrediction",
673
- ["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
674
-
675
- all_predictions = collections.OrderedDict()
676
- all_nbest_json = collections.OrderedDict()
677
- scores_diff_json = collections.OrderedDict()
678
-
679
- for (example_index, example) in enumerate(all_examples):
680
- features = example_index_to_features[example_index]
681
-
682
- prelim_predictions = []
683
- # keep track of the minimum score of null start+end of position 0
684
- score_null = 1000000 # large and positive
685
- min_null_feature_index = 0 # the paragraph slice with min mull score
686
- null_start_logit = 0 # the start logit at the slice with min null score
687
- null_end_logit = 0 # the end logit at the slice with min null score
688
- for (feature_index, feature) in enumerate(features):
689
- if feature.unique_id not in unique_id_to_result:
690
- logging.info("Skip eval example %s, not in pred.", feature.unique_id)
691
- continue
692
- result = unique_id_to_result[feature.unique_id]
693
-
694
- # if we could have irrelevant answers, get the min score of irrelevant
695
- if version_2_with_negative:
696
- if xlnet_format:
697
- feature_null_score = result.class_logits
698
- else:
699
- feature_null_score = result.start_logits[0] + result.end_logits[0]
700
- if feature_null_score < score_null:
701
- score_null = feature_null_score
702
- min_null_feature_index = feature_index
703
- null_start_logit = result.start_logits[0]
704
- null_end_logit = result.end_logits[0]
705
-
706
- doc_offset = 0 if xlnet_format else feature.tokens.index("[SEP]") + 1
707
-
708
- for (start_index, start_logit,
709
- end_index, end_logit) in _get_best_indexes_and_logits(
710
- result=result,
711
- n_best_size=n_best_size,
712
- xlnet_format=xlnet_format):
713
- # We could hypothetically create invalid predictions, e.g., predict
714
- # that the start of the span is in the question. We throw out all
715
- # invalid predictions.
716
- if start_index - doc_offset >= len(feature.tok_start_to_orig_index):
717
- continue
718
- if end_index - doc_offset >= len(feature.tok_end_to_orig_index):
719
- continue
720
- if not feature.token_is_max_context.get(start_index, False):
721
- continue
722
- if end_index < start_index:
723
- continue
724
- length = end_index - start_index + 1
725
- if length > max_answer_length:
726
- continue
727
- prelim_predictions.append(
728
- _PrelimPrediction(
729
- feature_index=feature_index,
730
- start_index=start_index - doc_offset,
731
- end_index=end_index - doc_offset,
732
- start_logit=start_logit,
733
- end_logit=end_logit))
734
-
735
- if version_2_with_negative and not xlnet_format:
736
- prelim_predictions.append(
737
- _PrelimPrediction(
738
- feature_index=min_null_feature_index,
739
- start_index=-1,
740
- end_index=-1,
741
- start_logit=null_start_logit,
742
- end_logit=null_end_logit))
743
- prelim_predictions = sorted(
744
- prelim_predictions,
745
- key=lambda x: (x.start_logit + x.end_logit),
746
- reverse=True)
747
-
748
- _NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
749
- "NbestPrediction", ["text", "start_logit", "end_logit"])
750
-
751
- seen_predictions = {}
752
- nbest = []
753
- for pred in prelim_predictions:
754
- if len(nbest) >= n_best_size:
755
- break
756
- feature = features[pred.feature_index]
757
- if pred.start_index >= 0 or xlnet_format: # this is a non-null prediction
758
- tok_start_to_orig_index = feature.tok_start_to_orig_index
759
- tok_end_to_orig_index = feature.tok_end_to_orig_index
760
- start_orig_pos = tok_start_to_orig_index[pred.start_index]
761
- end_orig_pos = tok_end_to_orig_index[pred.end_index]
762
-
763
- paragraph_text = example.paragraph_text
764
- final_text = paragraph_text[start_orig_pos:end_orig_pos + 1].strip()
765
- if final_text in seen_predictions:
766
- continue
767
-
768
- seen_predictions[final_text] = True
769
- else:
770
- final_text = ""
771
- seen_predictions[final_text] = True
772
-
773
- nbest.append(
774
- _NbestPrediction(
775
- text=final_text,
776
- start_logit=pred.start_logit,
777
- end_logit=pred.end_logit))
778
-
779
- # if we didn't include the empty option in the n-best, include it
780
- if version_2_with_negative and not xlnet_format:
781
- if "" not in seen_predictions:
782
- nbest.append(
783
- _NbestPrediction(
784
- text="", start_logit=null_start_logit,
785
- end_logit=null_end_logit))
786
- # In very rare edge cases we could have no valid predictions. So we
787
- # just create a nonce prediction in this case to avoid failure.
788
- if not nbest:
789
- nbest.append(
790
- _NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
791
-
792
- assert len(nbest) >= 1
793
-
794
- total_scores = []
795
- best_non_null_entry = None
796
- for entry in nbest:
797
- total_scores.append(entry.start_logit + entry.end_logit)
798
- if not best_non_null_entry:
799
- if entry.text:
800
- best_non_null_entry = entry
801
-
802
- probs = _compute_softmax(total_scores)
803
-
804
- nbest_json = []
805
- for (i, entry) in enumerate(nbest):
806
- output = collections.OrderedDict()
807
- output["text"] = entry.text
808
- output["probability"] = probs[i]
809
- output["start_logit"] = entry.start_logit
810
- output["end_logit"] = entry.end_logit
811
- nbest_json.append(output)
812
-
813
- assert len(nbest_json) >= 1
814
-
815
- if not version_2_with_negative:
816
- all_predictions[example.qas_id] = nbest_json[0]["text"]
817
- else:
818
- assert best_non_null_entry is not None
819
- if xlnet_format:
820
- score_diff = score_null
821
- scores_diff_json[example.qas_id] = score_diff
822
- all_predictions[example.qas_id] = best_non_null_entry.text
823
- else:
824
- # predict "" iff the null score - the score of best non-null > threshold
825
- score_diff = score_null - best_non_null_entry.start_logit - (
826
- best_non_null_entry.end_logit)
827
- scores_diff_json[example.qas_id] = score_diff
828
- if score_diff > null_score_diff_threshold:
829
- all_predictions[example.qas_id] = ""
830
- else:
831
- all_predictions[example.qas_id] = best_non_null_entry.text
832
-
833
- all_nbest_json[example.qas_id] = nbest_json
834
-
835
- return all_predictions, all_nbest_json, scores_diff_json
836
-
837
-
838
- def write_to_json_files(json_records, json_file):
839
- with tf.io.gfile.GFile(json_file, "w") as writer:
840
- writer.write(json.dumps(json_records, indent=4) + "\n")
841
-
842
-
843
- def _get_best_indexes_and_logits(result,
844
- n_best_size,
845
- xlnet_format=False):
846
- """Generates the n-best indexes and logits from a list."""
847
- if xlnet_format:
848
- for i in range(n_best_size):
849
- for j in range(n_best_size):
850
- j_index = i * n_best_size + j
851
- yield (result.start_indexes[i], result.start_logits[i],
852
- result.end_indexes[j_index], result.end_logits[j_index])
853
- else:
854
- start_index_and_score = sorted(enumerate(result.start_logits),
855
- key=lambda x: x[1], reverse=True)
856
- end_index_and_score = sorted(enumerate(result.end_logits),
857
- key=lambda x: x[1], reverse=True)
858
- for i in range(len(start_index_and_score)):
859
- if i >= n_best_size:
860
- break
861
- for j in range(len(end_index_and_score)):
862
- if j >= n_best_size:
863
- break
864
- yield (start_index_and_score[i][0], start_index_and_score[i][1],
865
- end_index_and_score[j][0], end_index_and_score[j][1])
866
-
867
-
868
- def _compute_softmax(scores):
869
- """Compute softmax probability over raw logits."""
870
- if not scores:
871
- return []
872
-
873
- max_score = None
874
- for score in scores:
875
- if max_score is None or score > max_score:
876
- max_score = score
877
-
878
- exp_scores = []
879
- total_sum = 0.0
880
- for score in scores:
881
- x = math.exp(score - max_score)
882
- exp_scores.append(x)
883
- total_sum += x
884
-
885
- probs = []
886
- for score in exp_scores:
887
- probs.append(score / total_sum)
888
- return probs
889
-
890
-
891
- class FeatureWriter(object):
892
- """Writes InputFeature to TF example file."""
893
-
894
- def __init__(self, filename, is_training):
895
- self.filename = filename
896
- self.is_training = is_training
897
- self.num_features = 0
898
- tf.io.gfile.makedirs(os.path.dirname(filename))
899
- self._writer = tf.io.TFRecordWriter(filename)
900
-
901
- def process_feature(self, feature):
902
- """Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
903
- self.num_features += 1
904
-
905
- def create_int_feature(values):
906
- feature = tf.train.Feature(
907
- int64_list=tf.train.Int64List(value=list(values)))
908
- return feature
909
-
910
- features = collections.OrderedDict()
911
- features["unique_ids"] = create_int_feature([feature.unique_id])
912
- features["input_ids"] = create_int_feature(feature.input_ids)
913
- features["input_mask"] = create_int_feature(feature.input_mask)
914
- features["segment_ids"] = create_int_feature(feature.segment_ids)
915
- if feature.paragraph_mask is not None:
916
- features["paragraph_mask"] = create_int_feature(feature.paragraph_mask)
917
- if feature.class_index is not None:
918
- features["class_index"] = create_int_feature([feature.class_index])
919
-
920
- if self.is_training:
921
- features["start_positions"] = create_int_feature([feature.start_position])
922
- features["end_positions"] = create_int_feature([feature.end_position])
923
- impossible = 0
924
- if feature.is_impossible:
925
- impossible = 1
926
- features["is_impossible"] = create_int_feature([impossible])
927
-
928
- tf_example = tf.train.Example(features=tf.train.Features(feature=features))
929
- self._writer.write(tf_example.SerializeToString())
930
-
931
- def close(self):
932
- self._writer.close()
933
-
934
-
935
- def generate_tf_record_from_json_file(input_file_path,
936
- sp_model_file,
937
- output_path,
938
- translated_input_folder=None,
939
- max_seq_length=384,
940
- do_lower_case=True,
941
- max_query_length=64,
942
- doc_stride=128,
943
- xlnet_format=False,
944
- version_2_with_negative=False):
945
- """Generates and saves training data into a tf record file."""
946
- train_examples = read_squad_examples(
947
- input_file=input_file_path,
948
- is_training=True,
949
- version_2_with_negative=version_2_with_negative,
950
- translated_input_folder=translated_input_folder)
951
- tokenizer = tokenization.FullSentencePieceTokenizer(
952
- sp_model_file=sp_model_file)
953
- train_writer = FeatureWriter(
954
- filename=output_path, is_training=True)
955
- number_of_examples = convert_examples_to_features(
956
- examples=train_examples,
957
- tokenizer=tokenizer,
958
- max_seq_length=max_seq_length,
959
- doc_stride=doc_stride,
960
- max_query_length=max_query_length,
961
- is_training=True,
962
- output_fn=train_writer.process_feature,
963
- xlnet_format=xlnet_format,
964
- do_lower_case=do_lower_case)
965
- train_writer.close()
966
-
967
- meta_data = {
968
- "task_type": "bert_squad",
969
- "train_data_size": number_of_examples,
970
- "max_seq_length": max_seq_length,
971
- "max_query_length": max_query_length,
972
- "doc_stride": doc_stride,
973
- "version_2_with_negative": version_2_with_negative,
974
- }
975
-
976
- return meta_data