Ian Porada
commited on
Commit
·
f1eaa06
1
Parent(s):
d092e58
Revert "Delete superglue_wsc.py with huggingface_hub"
Browse filesThis reverts commit 71b794c3c9c29a59622ff2f88489586673146a36.
- superglue_wsc.py +354 -0
superglue_wsc.py
ADDED
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets 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 |
+
|
16 |
+
# Lint as: python3
|
17 |
+
"""The WSC from the SuperGLUE benchmark."""
|
18 |
+
|
19 |
+
|
20 |
+
import json
|
21 |
+
import os
|
22 |
+
|
23 |
+
import datasets
|
24 |
+
|
25 |
+
|
26 |
+
_SUPER_GLUE_CITATION = """\
|
27 |
+
@article{wang2019superglue,
|
28 |
+
title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},
|
29 |
+
author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},
|
30 |
+
journal={arXiv preprint arXiv:1905.00537},
|
31 |
+
year={2019}
|
32 |
+
}
|
33 |
+
|
34 |
+
Note that each SuperGLUE dataset has its own citation. Please see the source to
|
35 |
+
get the correct citation for each contained dataset.
|
36 |
+
"""
|
37 |
+
|
38 |
+
_GLUE_DESCRIPTION = """\
|
39 |
+
SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after
|
40 |
+
GLUE with a new set of more difficult language understanding tasks, improved
|
41 |
+
resources, and a new public leaderboard.
|
42 |
+
|
43 |
+
"""
|
44 |
+
|
45 |
+
_WSC_DESCRIPTION = """\
|
46 |
+
The Winograd Schema Challenge (WSC, Levesque et al., 2012) is a reading comprehension
|
47 |
+
task in which a system must read a sentence with a pronoun and select the referent of that pronoun
|
48 |
+
from a list of choices. Given the difficulty of this task and the headroom still left, we have included
|
49 |
+
WSC in SuperGLUE and recast the dataset into its coreference form. The task is cast as a binary
|
50 |
+
classification problem, as opposed to N-multiple choice, in order to isolate the model's ability to
|
51 |
+
understand the coreference links within a sentence as opposed to various other strategies that may
|
52 |
+
come into play in multiple choice conditions. With that in mind, we create a split with 65% negative
|
53 |
+
majority class in the validation set, reflecting the distribution of the hidden test set, and 52% negative
|
54 |
+
class in the training set. The training and validation examples are drawn from the original Winograd
|
55 |
+
Schema dataset (Levesque et al., 2012), as well as those distributed by the affiliated organization
|
56 |
+
Commonsense Reasoning. The test examples are derived from fiction books and have been shared
|
57 |
+
with us by the authors of the original dataset. Previously, a version of WSC recast as NLI as included
|
58 |
+
in GLUE, known as WNLI. No substantial progress was made on WNLI, with many submissions
|
59 |
+
opting to submit only majority class predictions. WNLI was made especially difficult due to an
|
60 |
+
adversarial train/dev split: Premise sentences that appeared in the training set sometimes appeared
|
61 |
+
in the development set with a different hypothesis and a flipped label. If a system memorized the
|
62 |
+
training set without meaningfully generalizing, which was easy due to the small size of the training
|
63 |
+
set, it could perform far below chance on the development set. We remove this adversarial design
|
64 |
+
in the SuperGLUE version of WSC by ensuring that no sentences are shared between the training,
|
65 |
+
validation, and test sets.
|
66 |
+
|
67 |
+
However, the validation and test sets come from different domains, with the validation set consisting
|
68 |
+
of ambiguous examples such that changing one non-noun phrase word will change the coreference
|
69 |
+
dependencies in the sentence. The test set consists only of more straightforward examples, with a
|
70 |
+
high number of noun phrases (and thus more choices for the model), but low to no ambiguity."""
|
71 |
+
|
72 |
+
|
73 |
+
_WSC_CITATION = """\
|
74 |
+
@inproceedings{levesque2012winograd,
|
75 |
+
title={The winograd schema challenge},
|
76 |
+
author={Levesque, Hector and Davis, Ernest and Morgenstern, Leora},
|
77 |
+
booktitle={Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning},
|
78 |
+
year={2012}
|
79 |
+
}"""
|
80 |
+
|
81 |
+
|
82 |
+
class SuperGlueConfig(datasets.BuilderConfig):
|
83 |
+
"""BuilderConfig for SuperGLUE."""
|
84 |
+
|
85 |
+
def __init__(self, features, data_url, citation, url, label_classes=("False", "True"), **kwargs):
|
86 |
+
"""BuilderConfig for SuperGLUE.
|
87 |
+
|
88 |
+
Args:
|
89 |
+
features: `list[string]`, list of the features that will appear in the
|
90 |
+
feature dict. Should not include "label".
|
91 |
+
data_url: `string`, url to download the zip file from.
|
92 |
+
citation: `string`, citation for the data set.
|
93 |
+
url: `string`, url for information about the data set.
|
94 |
+
label_classes: `list[string]`, the list of classes for the label if the
|
95 |
+
label is present as a string. Non-string labels will be cast to either
|
96 |
+
'False' or 'True'.
|
97 |
+
**kwargs: keyword arguments forwarded to super.
|
98 |
+
"""
|
99 |
+
# Version history:
|
100 |
+
# 1.0.3: Fix not including entity position in ReCoRD.
|
101 |
+
# 1.0.2: Fixed non-nondeterminism in ReCoRD.
|
102 |
+
# 1.0.1: Change from the pre-release trial version of SuperGLUE (v1.9) to
|
103 |
+
# the full release (v2.0).
|
104 |
+
# 1.0.0: S3 (new shuffling, sharding and slicing mechanism).
|
105 |
+
# 0.0.2: Initial version.
|
106 |
+
super(SuperGlueConfig, self).__init__(version=datasets.Version("1.0.3"), **kwargs)
|
107 |
+
self.features = features
|
108 |
+
self.label_classes = label_classes
|
109 |
+
self.data_url = data_url
|
110 |
+
self.citation = citation
|
111 |
+
self.url = url
|
112 |
+
|
113 |
+
|
114 |
+
class SuperGlue(datasets.GeneratorBasedBuilder):
|
115 |
+
"""The SuperGLUE benchmark."""
|
116 |
+
|
117 |
+
BUILDER_CONFIGS = [
|
118 |
+
SuperGlueConfig(
|
119 |
+
name="wsc",
|
120 |
+
description=_WSC_DESCRIPTION,
|
121 |
+
# Note that span1_index and span2_index will be integers stored as
|
122 |
+
# datasets.Value('int32').
|
123 |
+
features=["text", "span1_index", "span2_index", "span1_text", "span2_text"],
|
124 |
+
data_url="https://dl.fbaipublicfiles.com/glue/superglue/data/v2/WSC.zip",
|
125 |
+
citation=_WSC_CITATION,
|
126 |
+
url="https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WS.html",
|
127 |
+
),
|
128 |
+
SuperGlueConfig(
|
129 |
+
name="wsc.fixed",
|
130 |
+
description=(
|
131 |
+
_WSC_DESCRIPTION + "\n\nThis version fixes issues where the spans are not actually "
|
132 |
+
"substrings of the text."
|
133 |
+
),
|
134 |
+
# Note that span1_index and span2_index will be integers stored as
|
135 |
+
# datasets.Value('int32').
|
136 |
+
features=["text", "span1_index", "span2_index", "span1_text", "span2_text"],
|
137 |
+
data_url="https://dl.fbaipublicfiles.com/glue/superglue/data/v2/WSC.zip",
|
138 |
+
citation=_WSC_CITATION,
|
139 |
+
url="https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WS.html",
|
140 |
+
),
|
141 |
+
]
|
142 |
+
|
143 |
+
def _info(self):
|
144 |
+
features = {feature: datasets.Value("string") for feature in self.config.features}
|
145 |
+
if self.config.name.startswith("wsc"):
|
146 |
+
features["span1_index"] = datasets.Value("int32")
|
147 |
+
features["span2_index"] = datasets.Value("int32")
|
148 |
+
if self.config.name == "wic":
|
149 |
+
features["start1"] = datasets.Value("int32")
|
150 |
+
features["start2"] = datasets.Value("int32")
|
151 |
+
features["end1"] = datasets.Value("int32")
|
152 |
+
features["end2"] = datasets.Value("int32")
|
153 |
+
if self.config.name == "multirc":
|
154 |
+
features["idx"] = dict(
|
155 |
+
{
|
156 |
+
"paragraph": datasets.Value("int32"),
|
157 |
+
"question": datasets.Value("int32"),
|
158 |
+
"answer": datasets.Value("int32"),
|
159 |
+
}
|
160 |
+
)
|
161 |
+
elif self.config.name == "record":
|
162 |
+
features["idx"] = dict(
|
163 |
+
{
|
164 |
+
"passage": datasets.Value("int32"),
|
165 |
+
"query": datasets.Value("int32"),
|
166 |
+
}
|
167 |
+
)
|
168 |
+
else:
|
169 |
+
features["idx"] = datasets.Value("int32")
|
170 |
+
|
171 |
+
if self.config.name == "record":
|
172 |
+
# Entities are the set of possible choices for the placeholder.
|
173 |
+
features["entities"] = datasets.features.Sequence(datasets.Value("string"))
|
174 |
+
# The start and end indices of paragraph text for each entity.
|
175 |
+
features["entity_spans"] = datasets.features.Sequence(
|
176 |
+
{
|
177 |
+
"text": datasets.Value("string"),
|
178 |
+
"start": datasets.Value("int32"),
|
179 |
+
"end": datasets.Value("int32"),
|
180 |
+
}
|
181 |
+
)
|
182 |
+
# Answers are the subset of entities that are correct.
|
183 |
+
features["answers"] = datasets.features.Sequence(datasets.Value("string"))
|
184 |
+
else:
|
185 |
+
features["label"] = datasets.features.ClassLabel(names=self.config.label_classes)
|
186 |
+
|
187 |
+
return datasets.DatasetInfo(
|
188 |
+
description=_GLUE_DESCRIPTION + self.config.description,
|
189 |
+
features=datasets.Features(features),
|
190 |
+
homepage=self.config.url,
|
191 |
+
citation=self.config.citation + "\n" + _SUPER_GLUE_CITATION,
|
192 |
+
)
|
193 |
+
|
194 |
+
def _split_generators(self, dl_manager):
|
195 |
+
dl_dir = dl_manager.download_and_extract(self.config.data_url) or ""
|
196 |
+
task_name = _get_task_name_from_data_url(self.config.data_url)
|
197 |
+
dl_dir = os.path.join(dl_dir, task_name)
|
198 |
+
if self.config.name in ["axb", "axg"]:
|
199 |
+
return [
|
200 |
+
datasets.SplitGenerator(
|
201 |
+
name=datasets.Split.TEST,
|
202 |
+
gen_kwargs={
|
203 |
+
"data_file": os.path.join(dl_dir, f"{task_name}.jsonl"),
|
204 |
+
"split": datasets.Split.TEST,
|
205 |
+
},
|
206 |
+
),
|
207 |
+
]
|
208 |
+
return [
|
209 |
+
datasets.SplitGenerator(
|
210 |
+
name=datasets.Split.TRAIN,
|
211 |
+
gen_kwargs={
|
212 |
+
"data_file": os.path.join(dl_dir, "train.jsonl"),
|
213 |
+
"split": datasets.Split.TRAIN,
|
214 |
+
},
|
215 |
+
),
|
216 |
+
datasets.SplitGenerator(
|
217 |
+
name=datasets.Split.VALIDATION,
|
218 |
+
gen_kwargs={
|
219 |
+
"data_file": os.path.join(dl_dir, "val.jsonl"),
|
220 |
+
"split": datasets.Split.VALIDATION,
|
221 |
+
},
|
222 |
+
),
|
223 |
+
datasets.SplitGenerator(
|
224 |
+
name=datasets.Split.TEST,
|
225 |
+
gen_kwargs={
|
226 |
+
"data_file": os.path.join(dl_dir, "test.jsonl"),
|
227 |
+
"split": datasets.Split.TEST,
|
228 |
+
},
|
229 |
+
),
|
230 |
+
]
|
231 |
+
|
232 |
+
def _generate_examples(self, data_file, split):
|
233 |
+
with open(data_file, encoding="utf-8") as f:
|
234 |
+
for line in f:
|
235 |
+
row = json.loads(line)
|
236 |
+
|
237 |
+
if self.config.name == "multirc":
|
238 |
+
paragraph = row["passage"]
|
239 |
+
for question in paragraph["questions"]:
|
240 |
+
for answer in question["answers"]:
|
241 |
+
label = answer.get("label")
|
242 |
+
key = "%s_%s_%s" % (row["idx"], question["idx"], answer["idx"])
|
243 |
+
yield key, {
|
244 |
+
"paragraph": paragraph["text"],
|
245 |
+
"question": question["question"],
|
246 |
+
"answer": answer["text"],
|
247 |
+
"label": -1 if label is None else _cast_label(bool(label)),
|
248 |
+
"idx": {"paragraph": row["idx"], "question": question["idx"], "answer": answer["idx"]},
|
249 |
+
}
|
250 |
+
elif self.config.name == "record":
|
251 |
+
passage = row["passage"]
|
252 |
+
entity_texts, entity_spans = _get_record_entities(passage)
|
253 |
+
for qa in row["qas"]:
|
254 |
+
yield qa["idx"], {
|
255 |
+
"passage": passage["text"],
|
256 |
+
"query": qa["query"],
|
257 |
+
"entities": entity_texts,
|
258 |
+
"entity_spans": entity_spans,
|
259 |
+
"answers": _get_record_answers(qa),
|
260 |
+
"idx": {"passage": row["idx"], "query": qa["idx"]},
|
261 |
+
}
|
262 |
+
else:
|
263 |
+
if self.config.name.startswith("wsc"):
|
264 |
+
row.update(row["target"])
|
265 |
+
example = {feature: row[feature] for feature in self.config.features}
|
266 |
+
if self.config.name == "wsc.fixed":
|
267 |
+
example = _fix_wst(example)
|
268 |
+
example["idx"] = row["idx"]
|
269 |
+
|
270 |
+
if "label" in row:
|
271 |
+
if self.config.name == "copa":
|
272 |
+
example["label"] = "choice2" if row["label"] else "choice1"
|
273 |
+
else:
|
274 |
+
example["label"] = _cast_label(row["label"])
|
275 |
+
else:
|
276 |
+
assert split == datasets.Split.TEST, row
|
277 |
+
example["label"] = -1
|
278 |
+
yield example["idx"], example
|
279 |
+
|
280 |
+
|
281 |
+
def _fix_wst(ex):
|
282 |
+
"""Fixes most cases where spans are not actually substrings of text."""
|
283 |
+
|
284 |
+
def _fix_span_text(k):
|
285 |
+
"""Fixes a single span."""
|
286 |
+
text = ex[k + "_text"]
|
287 |
+
index = ex[k + "_index"]
|
288 |
+
|
289 |
+
if text in ex["text"]:
|
290 |
+
return
|
291 |
+
|
292 |
+
if text in ("Kamenev and Zinoviev", "Kamenev, Zinoviev, and Stalin"):
|
293 |
+
# There is no way to correct these examples since the subjects have
|
294 |
+
# intervening text.
|
295 |
+
return
|
296 |
+
|
297 |
+
if "theyscold" in text:
|
298 |
+
ex["text"].replace("theyscold", "they scold")
|
299 |
+
ex["span2_index"] = 10
|
300 |
+
# Make sure case of the first words match.
|
301 |
+
first_word = ex["text"].split()[index]
|
302 |
+
if first_word[0].islower():
|
303 |
+
text = text[0].lower() + text[1:]
|
304 |
+
else:
|
305 |
+
text = text[0].upper() + text[1:]
|
306 |
+
# Remove punctuation in span.
|
307 |
+
text = text.rstrip(".")
|
308 |
+
# Replace incorrect whitespace character in span.
|
309 |
+
text = text.replace("\n", " ")
|
310 |
+
ex[k + "_text"] = text
|
311 |
+
assert ex[k + "_text"] in ex["text"], ex
|
312 |
+
|
313 |
+
_fix_span_text("span1")
|
314 |
+
_fix_span_text("span2")
|
315 |
+
return ex
|
316 |
+
|
317 |
+
|
318 |
+
def _cast_label(label):
|
319 |
+
"""Converts the label into the appropriate string version."""
|
320 |
+
if isinstance(label, str):
|
321 |
+
return label
|
322 |
+
elif isinstance(label, bool):
|
323 |
+
return "True" if label else "False"
|
324 |
+
elif isinstance(label, int):
|
325 |
+
assert label in (0, 1)
|
326 |
+
return str(label)
|
327 |
+
else:
|
328 |
+
raise ValueError("Invalid label format.")
|
329 |
+
|
330 |
+
|
331 |
+
def _get_record_entities(passage):
|
332 |
+
"""Returns the unique set of entities."""
|
333 |
+
text = passage["text"]
|
334 |
+
entity_spans = list()
|
335 |
+
for entity in passage["entities"]:
|
336 |
+
entity_text = text[entity["start"] : entity["end"] + 1]
|
337 |
+
entity_spans.append({"text": entity_text, "start": entity["start"], "end": entity["end"] + 1})
|
338 |
+
entity_spans = sorted(entity_spans, key=lambda e: e["start"]) # sort by start index
|
339 |
+
entity_texts = set(e["text"] for e in entity_spans) # for backward compatability
|
340 |
+
return entity_texts, entity_spans
|
341 |
+
|
342 |
+
|
343 |
+
def _get_record_answers(qa):
|
344 |
+
"""Returns the unique set of answers."""
|
345 |
+
if "answers" not in qa:
|
346 |
+
return []
|
347 |
+
answers = set()
|
348 |
+
for answer in qa["answers"]:
|
349 |
+
answers.add(answer["text"])
|
350 |
+
return sorted(answers)
|
351 |
+
|
352 |
+
|
353 |
+
def _get_task_name_from_data_url(data_url):
|
354 |
+
return data_url.split("/")[-1].split(".")[0]
|