-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval_utils.py
356 lines (284 loc) · 11.8 KB
/
eval_utils.py
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
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility function for nq evaluation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import glob
from gzip import GzipFile
import json
import multiprocessing
from absl import flags
from absl import logging
flags.DEFINE_integer(
"long_non_null_threshold",
2,
"Require this many non-null long answer annotations "
"to count gold as containing a long answer.",
)
flags.DEFINE_integer(
"short_non_null_threshold",
2,
"Require this many non-null short answer annotations "
"to count gold as containing a short answer.",
)
FLAGS = flags.FLAGS
# A data structure for storing prediction and annotation.
# When a example has multiple annotations, multiple NQLabel will be used.
NQLabel = collections.namedtuple(
"NQLabel",
[
"example_id", # the unique id for each NQ example.
"long_answer_span", # A Span object for long answer.
"short_answer_span_list", # A list of Spans for short answer.
# Note that In NQ, the short answers
# do not need to be in a single span.
"yes_no_answer", # Indicate if the short answer is an yes/no answer
# The possible values are "yes", "no", "none".
# (case insensitive)
# If the field is "yes", short_answer_span_list
# should be empty or only contain null spans.
"long_score", # The prediction score for the long answer prediction.
"short_score", # The prediction score for the short answer prediction.
],
)
class Span(object):
"""A class for handling token and byte spans.
The logic is:
1) if both start_byte != -1 and end_byte != -1 then the span is defined
by byte offsets
2) else, if start_token != -1 and end_token != -1 then the span is define
by token offsets
3) else, this is a null span.
Null spans means that there is no (long or short) answers.
If your systems only care about token spans rather than byte spans, set all
byte spans to -1.
"""
def __init__(self, start_byte, end_byte, start_token_idx, end_token_idx):
if (start_byte < 0 and end_byte >= 0) or (start_byte >= 0 and end_byte < 0):
raise ValueError("Inconsistent Null Spans (Byte).")
if (start_token_idx < 0 and end_token_idx >= 0) or (
start_token_idx >= 0 and end_token_idx < 0
):
raise ValueError("Inconsistent Null Spans (Token).")
if start_byte >= 0 and end_byte >= 0 and start_byte >= end_byte:
raise ValueError("Invalid byte spans (start_byte >= end_byte).")
if (start_token_idx >= 0 and end_token_idx >= 0) and (
start_token_idx >= end_token_idx
):
raise ValueError("Invalid token spans (start_token_idx >= end_token_idx)")
self.start_byte = start_byte
self.end_byte = end_byte
self.start_token_idx = start_token_idx
self.end_token_idx = end_token_idx
def is_null_span(self):
"""A span is a null span if the start and end are both -1."""
if (
self.start_byte < 0
and self.end_byte < 0
and self.start_token_idx < 0
and self.end_token_idx < 0
):
return True
return False
def __str__(self):
byte_str = "byte: [" + str(self.start_byte) + "," + str(self.end_byte) + ")"
tok_str = (
"tok: [" + str(self.start_token_idx) + "," + str(self.end_token_idx) + ")"
)
return byte_str + " " + tok_str
def __repr__(self):
return self.__str__()
def is_null_span_list(span_list):
"""Returns true iff all spans in span_list are null or span_list is empty."""
if not span_list or all([span.is_null_span() for span in span_list]):
return True
return False
def nonnull_span_equal(span_a, span_b):
"""Given two spans, return if they are equal.
Args:
span_a: a Span object.
span_b: a Span object. Only compare non-null spans. First, if the bytes are
not negative, compare byte offsets, Otherwise, compare token offsets.
Returns:
True or False
"""
assert isinstance(span_a, Span)
assert isinstance(span_b, Span)
assert not span_a.is_null_span()
assert not span_b.is_null_span()
# if byte offsets are not negative, compare byte offsets
if (span_a.start_byte >= 0 and span_a.end_byte >= 0) and (
span_b.start_byte >= 0 and span_b.end_byte >= 0
):
if (span_a.start_byte == span_b.start_byte) and (
span_a.end_byte == span_b.end_byte
):
return True
# if token offsets are not negative, compare token offsets
if (span_a.start_token_idx >= 0 and span_a.end_token_idx >= 0) and (
span_b.start_token_idx >= 0 and span_b.end_token_idx >= 0
):
if (span_a.start_token_idx == span_b.start_token_idx) and (
span_a.end_token_idx == span_b.end_token_idx
):
return True
return False
def span_set_equal(gold_span_list, pred_span_list):
"""Make the spans are completely equal besides null spans."""
gold_span_list = [span for span in gold_span_list if not span.is_null_span()]
pred_span_list = [span for span in pred_span_list if not span.is_null_span()]
for pspan in pred_span_list:
# not finding pspan equal to any spans in gold_span_list
if not any([nonnull_span_equal(pspan, gspan) for gspan in gold_span_list]):
return False
for gspan in gold_span_list:
# not finding gspan equal to any spans in pred_span_list
if not any([nonnull_span_equal(pspan, gspan) for pspan in pred_span_list]):
return False
return True
def gold_has_short_answer(gold_label_list):
"""Gets vote from multi-annotators for judging if there is a short answer."""
# We consider if there is a short answer if there is an short answer span or
# the yes/no answer is not none.
gold_has_answer = (
gold_label_list
and sum(
[
(
(not is_null_span_list(label.short_answer_span_list))
or (label.yes_no_answer != "none")
)
for label in gold_label_list
]
)
>= FLAGS.short_non_null_threshold
)
return gold_has_answer
def gold_has_long_answer(gold_label_list):
"""Gets vote from multi-annotators for judging if there is a long answer."""
gold_has_answer = gold_label_list and (
sum(
[
not label.long_answer_span.is_null_span() # long answer not null
for label in gold_label_list # for each annotator
]
)
>= FLAGS.long_non_null_threshold
)
return gold_has_answer
def read_prediction_json(predictions_path):
"""Read the prediction json with scores.
Args:
predictions_path: the path for the prediction json.
Returns:
A dictionary with key = example_id, value = NQInstancePrediction.
"""
logging.info("Reading predictions from file: %s", format(predictions_path))
with open(predictions_path, "r") as f:
predictions = json.loads(f.read())
nq_pred_dict = {}
for single_prediction in predictions["predictions"]:
if "long_answer" in single_prediction:
long_span = Span(
single_prediction["long_answer"]["start_byte"],
single_prediction["long_answer"]["end_byte"],
single_prediction["long_answer"]["start_token"],
single_prediction["long_answer"]["end_token"],
)
else:
long_span = Span(-1, -1, -1, -1) # Span is null if not presented.
short_span_list = []
if "short_answers" in single_prediction:
for short_item in single_prediction["short_answers"]:
short_span_list.append(
Span(
short_item["start_byte"],
short_item["end_byte"],
short_item["start_token"],
short_item["end_token"],
)
)
yes_no_answer = "none"
if "yes_no_answer" in single_prediction:
yes_no_answer = single_prediction["yes_no_answer"].lower()
if yes_no_answer not in ["yes", "no", "none"]:
raise ValueError("Invalid yes_no_answer value in prediction")
if yes_no_answer != "none" and not is_null_span_list(short_span_list):
raise ValueError("yes/no prediction and short answers cannot coexist.")
pred_item = NQLabel(
example_id=single_prediction["example_id"],
long_answer_span=long_span,
short_answer_span_list=short_span_list,
yes_no_answer=yes_no_answer,
long_score=single_prediction["long_answer_score"],
short_score=single_prediction["short_answers_score"],
)
nq_pred_dict[single_prediction["example_id"]] = pred_item
return nq_pred_dict
def read_annotation_from_one_split(gzipped_input_file):
"""Read annotation from one split of file."""
if isinstance(gzipped_input_file, str):
gzipped_input_file = open(gzipped_input_file, "rb")
logging.info("parsing %s ..... ", gzipped_input_file.name)
annotation_dict = {}
with GzipFile(fileobj=gzipped_input_file) as input_file:
for line in input_file:
json_example = json.loads(line)
example_id = json_example["example_id"]
# There are multiple annotations for one nq example.
annotation_list = []
for annotation in json_example["annotations"]:
long_span_rec = annotation["long_answer"]
long_span = Span(
long_span_rec["start_byte"],
long_span_rec["end_byte"],
long_span_rec["start_token"],
long_span_rec["end_token"],
)
short_span_list = []
for short_span_rec in annotation["short_answers"]:
short_span = Span(
short_span_rec["start_byte"],
short_span_rec["end_byte"],
short_span_rec["start_token"],
short_span_rec["end_token"],
)
short_span_list.append(short_span)
gold_label = NQLabel(
example_id=example_id,
long_answer_span=long_span,
short_answer_span_list=short_span_list,
long_score=0,
short_score=0,
yes_no_answer=annotation["yes_no_answer"].lower(),
)
annotation_list.append(gold_label)
annotation_dict[example_id] = annotation_list
return annotation_dict
def read_annotation(path_name, n_threads=10):
"""Read annotations with real multiple processes."""
input_paths = glob.glob(path_name)
pool = multiprocessing.Pool(n_threads)
try:
dict_list = pool.map(read_annotation_from_one_split, input_paths)
finally:
pool.close()
pool.join()
final_dict = {}
for single_dict in dict_list:
final_dict.update(single_dict)
return final_dict