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team 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
+ Post-processing utilities for question answering.
16
+ """
17
+
18
+ import collections
19
+ import json
20
+ import logging
21
+ import os
22
+ from typing import Optional
23
+
24
+ import numpy as np
25
+ from tqdm.auto import tqdm
26
+
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ def postprocess_qa_predictions(
32
+ examples,
33
+ features,
34
+ predictions: tuple[np.ndarray, np.ndarray],
35
+ version_2_with_negative: bool = False,
36
+ n_best_size: int = 20,
37
+ max_answer_length: int = 30,
38
+ null_score_diff_threshold: float = 0.0,
39
+ output_dir: Optional[str] = None,
40
+ prefix: Optional[str] = None,
41
+ log_level: Optional[int] = logging.WARNING,
42
+ ):
43
+ """
44
+ Post-processes the predictions of a question-answering model to convert them to answers that are substrings of the
45
+ original contexts. This is the base postprocessing functions for models that only return start and end logits.
46
+
47
+ Args:
48
+ examples: The non-preprocessed dataset (see the main script for more information).
49
+ features: The processed dataset (see the main script for more information).
50
+ predictions (:obj:`Tuple[np.ndarray, np.ndarray]`):
51
+ The predictions of the model: two arrays containing the start logits and the end logits respectively. Its
52
+ first dimension must match the number of elements of :obj:`features`.
53
+ version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`):
54
+ Whether or not the underlying dataset contains examples with no answers.
55
+ n_best_size (:obj:`int`, `optional`, defaults to 20):
56
+ The total number of n-best predictions to generate when looking for an answer.
57
+ max_answer_length (:obj:`int`, `optional`, defaults to 30):
58
+ The maximum length of an answer that can be generated. This is needed because the start and end predictions
59
+ are not conditioned on one another.
60
+ null_score_diff_threshold (:obj:`float`, `optional`, defaults to 0):
61
+ The threshold used to select the null answer: if the best answer has a score that is less than the score of
62
+ the null answer minus this threshold, the null answer is selected for this example (note that the score of
63
+ the null answer for an example giving several features is the minimum of the scores for the null answer on
64
+ each feature: all features must be aligned on the fact they `want` to predict a null answer).
65
+
66
+ Only useful when :obj:`version_2_with_negative` is :obj:`True`.
67
+ output_dir (:obj:`str`, `optional`):
68
+ If provided, the dictionaries of predictions, n_best predictions (with their scores and logits) and, if
69
+ :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null
70
+ answers, are saved in `output_dir`.
71
+ prefix (:obj:`str`, `optional`):
72
+ If provided, the dictionaries mentioned above are saved with `prefix` added to their names.
73
+ log_level (:obj:`int`, `optional`, defaults to ``logging.WARNING``):
74
+ ``logging`` log level (e.g., ``logging.WARNING``)
75
+ """
76
+ if len(predictions) != 2:
77
+ raise ValueError("`predictions` should be a tuple with two elements (start_logits, end_logits).")
78
+ all_start_logits, all_end_logits = predictions
79
+
80
+ if len(predictions[0]) != len(features):
81
+ raise ValueError(f"Got {len(predictions[0])} predictions and {len(features)} features.")
82
+
83
+ # Build a map example to its corresponding features.
84
+ example_id_to_index = {k: i for i, k in enumerate(examples["id"])}
85
+ features_per_example = collections.defaultdict(list)
86
+ for i, feature in enumerate(features):
87
+ features_per_example[example_id_to_index[feature["example_id"]]].append(i)
88
+
89
+ # The dictionaries we have to fill.
90
+ all_predictions = collections.OrderedDict()
91
+ all_nbest_json = collections.OrderedDict()
92
+ if version_2_with_negative:
93
+ scores_diff_json = collections.OrderedDict()
94
+
95
+ # Logging.
96
+ logger.setLevel(log_level)
97
+ logger.info(f"Post-processing {len(examples)} example predictions split into {len(features)} features.")
98
+
99
+ # Let's loop over all the examples!
100
+ for example_index, example in enumerate(tqdm(examples)):
101
+ # Those are the indices of the features associated to the current example.
102
+ feature_indices = features_per_example[example_index]
103
+
104
+ min_null_prediction = None
105
+ prelim_predictions = []
106
+
107
+ # Looping through all the features associated to the current example.
108
+ for feature_index in feature_indices:
109
+ # We grab the predictions of the model for this feature.
110
+ start_logits = all_start_logits[feature_index]
111
+ end_logits = all_end_logits[feature_index]
112
+ # This is what will allow us to map some the positions in our logits to span of texts in the original
113
+ # context.
114
+ offset_mapping = features[feature_index]["offset_mapping"]
115
+ # Optional `token_is_max_context`, if provided we will remove answers that do not have the maximum context
116
+ # available in the current feature.
117
+ token_is_max_context = features[feature_index].get("token_is_max_context", None)
118
+
119
+ # Update minimum null prediction.
120
+ feature_null_score = start_logits[0] + end_logits[0]
121
+ if min_null_prediction is None or min_null_prediction["score"] > feature_null_score:
122
+ min_null_prediction = {
123
+ "offsets": (0, 0),
124
+ "score": feature_null_score,
125
+ "start_logit": start_logits[0],
126
+ "end_logit": end_logits[0],
127
+ }
128
+
129
+ # Go through all possibilities for the `n_best_size` greater start and end logits.
130
+ start_indexes = np.argsort(start_logits)[-1 : -n_best_size - 1 : -1].tolist()
131
+ end_indexes = np.argsort(end_logits)[-1 : -n_best_size - 1 : -1].tolist()
132
+ for start_index in start_indexes:
133
+ for end_index in end_indexes:
134
+ # Don't consider out-of-scope answers, either because the indices are out of bounds or correspond
135
+ # to part of the input_ids that are not in the context.
136
+ if (
137
+ start_index >= len(offset_mapping)
138
+ or end_index >= len(offset_mapping)
139
+ or offset_mapping[start_index] is None
140
+ or len(offset_mapping[start_index]) < 2
141
+ or offset_mapping[end_index] is None
142
+ or len(offset_mapping[end_index]) < 2
143
+ ):
144
+ continue
145
+ # Don't consider answers with a length that is either < 0 or > max_answer_length.
146
+ if end_index < start_index or end_index - start_index + 1 > max_answer_length:
147
+ continue
148
+ # Don't consider answer that don't have the maximum context available (if such information is
149
+ # provided).
150
+ if token_is_max_context is not None and not token_is_max_context.get(str(start_index), False):
151
+ continue
152
+
153
+ prelim_predictions.append(
154
+ {
155
+ "offsets": (offset_mapping[start_index][0], offset_mapping[end_index][1]),
156
+ "score": start_logits[start_index] + end_logits[end_index],
157
+ "start_logit": start_logits[start_index],
158
+ "end_logit": end_logits[end_index],
159
+ }
160
+ )
161
+ if version_2_with_negative and min_null_prediction is not None:
162
+ # Add the minimum null prediction
163
+ prelim_predictions.append(min_null_prediction)
164
+ null_score = min_null_prediction["score"]
165
+
166
+ # Only keep the best `n_best_size` predictions.
167
+ predictions = sorted(prelim_predictions, key=lambda x: x["score"], reverse=True)[:n_best_size]
168
+
169
+ # Add back the minimum null prediction if it was removed because of its low score.
170
+ if (
171
+ version_2_with_negative
172
+ and min_null_prediction is not None
173
+ and not any(p["offsets"] == (0, 0) for p in predictions)
174
+ ):
175
+ predictions.append(min_null_prediction)
176
+
177
+ # Use the offsets to gather the answer text in the original context.
178
+ context = example["context"]
179
+ for pred in predictions:
180
+ offsets = pred.pop("offsets")
181
+ pred["text"] = context[offsets[0] : offsets[1]]
182
+
183
+ # In the very rare edge case we have not a single non-null prediction, we create a fake prediction to avoid
184
+ # failure.
185
+ if len(predictions) == 0 or (len(predictions) == 1 and predictions[0]["text"] == ""):
186
+ predictions.insert(0, {"text": "empty", "start_logit": 0.0, "end_logit": 0.0, "score": 0.0})
187
+
188
+ # Compute the softmax of all scores (we do it with numpy to stay independent from torch/tf in this file, using
189
+ # the LogSumExp trick).
190
+ scores = np.array([pred.pop("score") for pred in predictions])
191
+ exp_scores = np.exp(scores - np.max(scores))
192
+ probs = exp_scores / exp_scores.sum()
193
+
194
+ # Include the probabilities in our predictions.
195
+ for prob, pred in zip(probs, predictions):
196
+ pred["probability"] = prob
197
+
198
+ # Pick the best prediction. If the null answer is not possible, this is easy.
199
+ if not version_2_with_negative:
200
+ all_predictions[example["id"]] = predictions[0]["text"]
201
+ else:
202
+ # Otherwise we first need to find the best non-empty prediction.
203
+ i = 0
204
+ while predictions[i]["text"] == "":
205
+ i += 1
206
+ best_non_null_pred = predictions[i]
207
+
208
+ # Then we compare to the null prediction using the threshold.
209
+ score_diff = null_score - best_non_null_pred["start_logit"] - best_non_null_pred["end_logit"]
210
+ scores_diff_json[example["id"]] = float(score_diff) # To be JSON-serializable.
211
+ if score_diff > null_score_diff_threshold:
212
+ all_predictions[example["id"]] = ""
213
+ else:
214
+ all_predictions[example["id"]] = best_non_null_pred["text"]
215
+
216
+ # Make `predictions` JSON-serializable by casting np.float back to float.
217
+ all_nbest_json[example["id"]] = [
218
+ {k: (float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v) for k, v in pred.items()}
219
+ for pred in predictions
220
+ ]
221
+
222
+ # If we have an output_dir, let's save all those dicts.
223
+ if output_dir is not None:
224
+ if not os.path.isdir(output_dir):
225
+ raise OSError(f"{output_dir} is not a directory.")
226
+
227
+ prediction_file = os.path.join(
228
+ output_dir, "predictions.json" if prefix is None else f"{prefix}_predictions.json"
229
+ )
230
+ nbest_file = os.path.join(
231
+ output_dir, "nbest_predictions.json" if prefix is None else f"{prefix}_nbest_predictions.json"
232
+ )
233
+ if version_2_with_negative:
234
+ null_odds_file = os.path.join(
235
+ output_dir, "null_odds.json" if prefix is None else f"{prefix}_null_odds.json"
236
+ )
237
+
238
+ logger.info(f"Saving predictions to {prediction_file}.")
239
+ with open(prediction_file, "w") as writer:
240
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
241
+ logger.info(f"Saving nbest_preds to {nbest_file}.")
242
+ with open(nbest_file, "w") as writer:
243
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
244
+ if version_2_with_negative:
245
+ logger.info(f"Saving null_odds to {null_odds_file}.")
246
+ with open(null_odds_file, "w") as writer:
247
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
248
+
249
+ return all_predictions
250
+
251
+
252
+ def postprocess_qa_predictions_with_beam_search(
253
+ examples,
254
+ features,
255
+ predictions: tuple[np.ndarray, np.ndarray],
256
+ version_2_with_negative: bool = False,
257
+ n_best_size: int = 20,
258
+ max_answer_length: int = 30,
259
+ start_n_top: int = 5,
260
+ end_n_top: int = 5,
261
+ output_dir: Optional[str] = None,
262
+ prefix: Optional[str] = None,
263
+ log_level: Optional[int] = logging.WARNING,
264
+ ):
265
+ """
266
+ Post-processes the predictions of a question-answering model with beam search to convert them to answers that are substrings of the
267
+ original contexts. This is the postprocessing functions for models that return start and end logits, indices, as well as
268
+ cls token predictions.
269
+
270
+ Args:
271
+ examples: The non-preprocessed dataset (see the main script for more information).
272
+ features: The processed dataset (see the main script for more information).
273
+ predictions (:obj:`Tuple[np.ndarray, np.ndarray]`):
274
+ The predictions of the model: two arrays containing the start logits and the end logits respectively. Its
275
+ first dimension must match the number of elements of :obj:`features`.
276
+ version_2_with_negative (:obj:`bool`, `optional`, defaults to :obj:`False`):
277
+ Whether or not the underlying dataset contains examples with no answers.
278
+ n_best_size (:obj:`int`, `optional`, defaults to 20):
279
+ The total number of n-best predictions to generate when looking for an answer.
280
+ max_answer_length (:obj:`int`, `optional`, defaults to 30):
281
+ The maximum length of an answer that can be generated. This is needed because the start and end predictions
282
+ are not conditioned on one another.
283
+ start_n_top (:obj:`int`, `optional`, defaults to 5):
284
+ The number of top start logits too keep when searching for the :obj:`n_best_size` predictions.
285
+ end_n_top (:obj:`int`, `optional`, defaults to 5):
286
+ The number of top end logits too keep when searching for the :obj:`n_best_size` predictions.
287
+ output_dir (:obj:`str`, `optional`):
288
+ If provided, the dictionaries of predictions, n_best predictions (with their scores and logits) and, if
289
+ :obj:`version_2_with_negative=True`, the dictionary of the scores differences between best and null
290
+ answers, are saved in `output_dir`.
291
+ prefix (:obj:`str`, `optional`):
292
+ If provided, the dictionaries mentioned above are saved with `prefix` added to their names.
293
+ log_level (:obj:`int`, `optional`, defaults to ``logging.WARNING``):
294
+ ``logging`` log level (e.g., ``logging.WARNING``)
295
+ """
296
+ if len(predictions) != 5:
297
+ raise ValueError("`predictions` should be a tuple with five elements.")
298
+ start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits = predictions
299
+
300
+ if len(predictions[0]) != len(features):
301
+ raise ValueError(f"Got {len(predictions[0])} predictions and {len(features)} features.")
302
+
303
+ # Build a map example to its corresponding features.
304
+ example_id_to_index = {k: i for i, k in enumerate(examples["id"])}
305
+ features_per_example = collections.defaultdict(list)
306
+ for i, feature in enumerate(features):
307
+ features_per_example[example_id_to_index[feature["example_id"]]].append(i)
308
+
309
+ # The dictionaries we have to fill.
310
+ all_predictions = collections.OrderedDict()
311
+ all_nbest_json = collections.OrderedDict()
312
+ scores_diff_json = collections.OrderedDict() if version_2_with_negative else None
313
+
314
+ # Logging.
315
+ logger.setLevel(log_level)
316
+ logger.info(f"Post-processing {len(examples)} example predictions split into {len(features)} features.")
317
+
318
+ # Let's loop over all the examples!
319
+ for example_index, example in enumerate(tqdm(examples)):
320
+ # Those are the indices of the features associated to the current example.
321
+ feature_indices = features_per_example[example_index]
322
+
323
+ min_null_score = None
324
+ prelim_predictions = []
325
+
326
+ # Looping through all the features associated to the current example.
327
+ for feature_index in feature_indices:
328
+ # We grab the predictions of the model for this feature.
329
+ start_log_prob = start_top_log_probs[feature_index]
330
+ start_indexes = start_top_index[feature_index]
331
+ end_log_prob = end_top_log_probs[feature_index]
332
+ end_indexes = end_top_index[feature_index]
333
+ feature_null_score = cls_logits[feature_index]
334
+ # This is what will allow us to map some the positions in our logits to span of texts in the original
335
+ # context.
336
+ offset_mapping = features[feature_index]["offset_mapping"]
337
+ # Optional `token_is_max_context`, if provided we will remove answers that do not have the maximum context
338
+ # available in the current feature.
339
+ token_is_max_context = features[feature_index].get("token_is_max_context", None)
340
+
341
+ # Update minimum null prediction
342
+ if min_null_score is None or feature_null_score < min_null_score:
343
+ min_null_score = feature_null_score
344
+
345
+ # Go through all possibilities for the `n_start_top`/`n_end_top` greater start and end logits.
346
+ for i in range(start_n_top):
347
+ for j in range(end_n_top):
348
+ start_index = int(start_indexes[i])
349
+ j_index = i * end_n_top + j
350
+ end_index = int(end_indexes[j_index])
351
+ # Don't consider out-of-scope answers (last part of the test should be unnecessary because of the
352
+ # p_mask but let's not take any risk)
353
+ if (
354
+ start_index >= len(offset_mapping)
355
+ or end_index >= len(offset_mapping)
356
+ or offset_mapping[start_index] is None
357
+ or len(offset_mapping[start_index]) < 2
358
+ or offset_mapping[end_index] is None
359
+ or len(offset_mapping[end_index]) < 2
360
+ ):
361
+ continue
362
+
363
+ # Don't consider answers with a length negative or > max_answer_length.
364
+ if end_index < start_index or end_index - start_index + 1 > max_answer_length:
365
+ continue
366
+ # Don't consider answer that don't have the maximum context available (if such information is
367
+ # provided).
368
+ if token_is_max_context is not None and not token_is_max_context.get(str(start_index), False):
369
+ continue
370
+ prelim_predictions.append(
371
+ {
372
+ "offsets": (offset_mapping[start_index][0], offset_mapping[end_index][1]),
373
+ "score": start_log_prob[i] + end_log_prob[j_index],
374
+ "start_log_prob": start_log_prob[i],
375
+ "end_log_prob": end_log_prob[j_index],
376
+ }
377
+ )
378
+
379
+ # Only keep the best `n_best_size` predictions.
380
+ predictions = sorted(prelim_predictions, key=lambda x: x["score"], reverse=True)[:n_best_size]
381
+
382
+ # Use the offsets to gather the answer text in the original context.
383
+ context = example["context"]
384
+ for pred in predictions:
385
+ offsets = pred.pop("offsets")
386
+ pred["text"] = context[offsets[0] : offsets[1]]
387
+
388
+ # In the very rare edge case we have not a single non-null prediction, we create a fake prediction to avoid
389
+ # failure.
390
+ if len(predictions) == 0:
391
+ # Without predictions min_null_score is going to be None and None will cause an exception later
392
+ min_null_score = -2e-6
393
+ predictions.insert(0, {"text": "", "start_logit": -1e-6, "end_logit": -1e-6, "score": min_null_score})
394
+
395
+ # Compute the softmax of all scores (we do it with numpy to stay independent from torch/tf in this file, using
396
+ # the LogSumExp trick).
397
+ scores = np.array([pred.pop("score") for pred in predictions])
398
+ exp_scores = np.exp(scores - np.max(scores))
399
+ probs = exp_scores / exp_scores.sum()
400
+
401
+ # Include the probabilities in our predictions.
402
+ for prob, pred in zip(probs, predictions):
403
+ pred["probability"] = prob
404
+
405
+ # Pick the best prediction and set the probability for the null answer.
406
+ all_predictions[example["id"]] = predictions[0]["text"]
407
+ if version_2_with_negative:
408
+ scores_diff_json[example["id"]] = float(min_null_score)
409
+
410
+ # Make `predictions` JSON-serializable by casting np.float back to float.
411
+ all_nbest_json[example["id"]] = [
412
+ {k: (float(v) if isinstance(v, (np.float16, np.float32, np.float64)) else v) for k, v in pred.items()}
413
+ for pred in predictions
414
+ ]
415
+
416
+ # If we have an output_dir, let's save all those dicts.
417
+ if output_dir is not None:
418
+ if not os.path.isdir(output_dir):
419
+ raise OSError(f"{output_dir} is not a directory.")
420
+
421
+ prediction_file = os.path.join(
422
+ output_dir, "predictions.json" if prefix is None else f"{prefix}_predictions.json"
423
+ )
424
+ nbest_file = os.path.join(
425
+ output_dir, "nbest_predictions.json" if prefix is None else f"{prefix}_nbest_predictions.json"
426
+ )
427
+ if version_2_with_negative:
428
+ null_odds_file = os.path.join(
429
+ output_dir, "null_odds.json" if prefix is None else f"{prefix}_null_odds.json"
430
+ )
431
+
432
+ logger.info(f"Saving predictions to {prediction_file}.")
433
+ with open(prediction_file, "w") as writer:
434
+ writer.write(json.dumps(all_predictions, indent=4) + "\n")
435
+ logger.info(f"Saving nbest_preds to {nbest_file}.")
436
+ with open(nbest_file, "w") as writer:
437
+ writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
438
+ if version_2_with_negative:
439
+ logger.info(f"Saving null_odds to {null_odds_file}.")
440
+ with open(null_odds_file, "w") as writer:
441
+ writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
442
+
443
+ return all_predictions, scores_diff_json