ThierryZhou commited on
Commit
008ac1e
·
1 Parent(s): 37d8cfa

Update test.py

Browse files
Files changed (1) hide show
  1. test.py +619 -2
test.py CHANGED
@@ -1,2 +1,619 @@
1
- if __name__ == "__main__":
2
- print("hello world")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Test benchmark."""
18
+
19
+
20
+ import json
21
+ import os
22
+
23
+ import datasets
24
+
25
+
26
+ _SUPER_GLUE_CITATION = """\
27
+ @article{wang2019Test,
28
+ title={Test: 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
+ Note that each Test dataset has its own citation. Please see the source to
34
+ get the correct citation for each contained dataset.
35
+ """
36
+
37
+ _GLUE_DESCRIPTION = """\
38
+ Test (https://super.gluebenchmark.com/) is a new benchmark styled after
39
+ GLUE with a new set of more difficult language understanding tasks, improved
40
+ resources, and a new public leaderboard.
41
+ """
42
+
43
+ _BOOLQ_DESCRIPTION = """\
44
+ BoolQ (Boolean Questions, Clark et al., 2019a) is a QA task where each example consists of a short
45
+ passage and a yes/no question about the passage. The questions are provided anonymously and
46
+ unsolicited by users of the Google search engine, and afterwards paired with a paragraph from a
47
+ Wikipedia article containing the answer. Following the original work, we evaluate with accuracy."""
48
+
49
+ _CB_DESCRIPTION = """\
50
+ The CommitmentBank (De Marneffe et al., 2019) is a corpus of short texts in which at least
51
+ one sentence contains an embedded clause. Each of these embedded clauses is annotated with the
52
+ degree to which we expect that the person who wrote the text is committed to the truth of the clause.
53
+ The resulting task framed as three-class textual entailment on examples that are drawn from the Wall
54
+ Street Journal, fiction from the British National Corpus, and Switchboard. Each example consists
55
+ of a premise containing an embedded clause and the corresponding hypothesis is the extraction of
56
+ that clause. We use a subset of the data that had inter-annotator agreement above 0.85. The data is
57
+ imbalanced (relatively fewer neutral examples), so we evaluate using accuracy and F1, where for
58
+ multi-class F1 we compute the unweighted average of the F1 per class."""
59
+
60
+ _COPA_DESCRIPTION = """\
61
+ The Choice Of Plausible Alternatives (COPA, Roemmele et al., 2011) dataset is a causal
62
+ reasoning task in which a system is given a premise sentence and two possible alternatives. The
63
+ system must choose the alternative which has the more plausible causal relationship with the premise.
64
+ The method used for the construction of the alternatives ensures that the task requires causal reasoning
65
+ to solve. Examples either deal with alternative possible causes or alternative possible effects of the
66
+ premise sentence, accompanied by a simple question disambiguating between the two instance
67
+ types for the model. All examples are handcrafted and focus on topics from online blogs and a
68
+ photography-related encyclopedia. Following the recommendation of the authors, we evaluate using
69
+ accuracy."""
70
+
71
+ _RECORD_DESCRIPTION = """\
72
+ (Reading Comprehension with Commonsense Reasoning Dataset, Zhang et al., 2018) is a
73
+ multiple-choice QA task. Each example consists of a news article and a Cloze-style question about
74
+ the article in which one entity is masked out. The system must predict the masked out entity from a
75
+ given list of possible entities in the provided passage, where the same entity may be expressed using
76
+ multiple different surface forms, all of which are considered correct. Articles are drawn from CNN
77
+ and Daily Mail. Following the original work, we evaluate with max (over all mentions) token-level
78
+ F1 and exact match (EM)."""
79
+
80
+ _RTE_DESCRIPTION = """\
81
+ The Recognizing Textual Entailment (RTE) datasets come from a series of annual competitions
82
+ on textual entailment, the problem of predicting whether a given premise sentence entails a given
83
+ hypothesis sentence (also known as natural language inference, NLI). RTE was previously included
84
+ in GLUE, and we use the same data and format as before: We merge data from RTE1 (Dagan
85
+ et al., 2006), RTE2 (Bar Haim et al., 2006), RTE3 (Giampiccolo et al., 2007), and RTE5 (Bentivogli
86
+ et al., 2009). All datasets are combined and converted to two-class classification: entailment and
87
+ not_entailment. Of all the GLUE tasks, RTE was among those that benefited from transfer learning
88
+ the most, jumping from near random-chance performance (~56%) at the time of GLUE's launch to
89
+ 85% accuracy (Liu et al., 2019c) at the time of writing. Given the eight point gap with respect to
90
+ human performance, however, the task is not yet solved by machines, and we expect the remaining
91
+ gap to be difficult to close."""
92
+
93
+ _MULTIRC_DESCRIPTION = """\
94
+ The Multi-Sentence Reading Comprehension dataset (MultiRC, Khashabi et al., 2018)
95
+ is a true/false question-answering task. Each example consists of a context paragraph, a question
96
+ about that paragraph, and a list of possible answers to that question which must be labeled as true or
97
+ false. Question-answering (QA) is a popular problem with many datasets. We use MultiRC because
98
+ of a number of desirable properties: (i) each question can have multiple possible correct answers,
99
+ so each question-answer pair must be evaluated independent of other pairs, (ii) the questions are
100
+ designed such that answering each question requires drawing facts from multiple context sentences,
101
+ and (iii) the question-answer pair format more closely matches the API of other Test tasks
102
+ than span-based extractive QA does. The paragraphs are drawn from seven domains including news,
103
+ fiction, and historical text."""
104
+
105
+ _WIC_DESCRIPTION = """\
106
+ The Word-in-Context (WiC, Pilehvar and Camacho-Collados, 2019) dataset supports a word
107
+ sense disambiguation task cast as binary classification over sentence pairs. Given two sentences and a
108
+ polysemous (sense-ambiguous) word that appears in both sentences, the task is to determine whether
109
+ the word is used with the same sense in both sentences. Sentences are drawn from WordNet (Miller,
110
+ 1995), VerbNet (Schuler, 2005), and Wiktionary. We follow the original work and evaluate using
111
+ accuracy."""
112
+
113
+ _WSC_DESCRIPTION = """\
114
+ The Winograd Schema Challenge (WSC, Levesque et al., 2012) is a reading comprehension
115
+ task in which a system must read a sentence with a pronoun and select the referent of that pronoun
116
+ from a list of choices. Given the difficulty of this task and the headroom still left, we have included
117
+ WSC in Test and recast the dataset into its coreference form. The task is cast as a binary
118
+ classification problem, as opposed to N-multiple choice, in order to isolate the model's ability to
119
+ understand the coreference links within a sentence as opposed to various other strategies that may
120
+ come into play in multiple choice conditions. With that in mind, we create a split with 65% negative
121
+ majority class in the validation set, reflecting the distribution of the hidden test set, and 52% negative
122
+ class in the training set. The training and validation examples are drawn from the original Winograd
123
+ Schema dataset (Levesque et al., 2012), as well as those distributed by the affiliated organization
124
+ Commonsense Reasoning. The test examples are derived from fiction books and have been shared
125
+ with us by the authors of the original dataset. Previously, a version of WSC recast as NLI as included
126
+ in GLUE, known as WNLI. No substantial progress was made on WNLI, with many submissions
127
+ opting to submit only majority class predictions. WNLI was made especially difficult due to an
128
+ adversarial train/dev split: Premise sentences that appeared in the training set sometimes appeared
129
+ in the development set with a different hypothesis and a flipped label. If a system memorized the
130
+ training set without meaningfully generalizing, which was easy due to the small size of the training
131
+ set, it could perform far below chance on the development set. We remove this adversarial design
132
+ in the Test version of WSC by ensuring that no sentences are shared between the training,
133
+ validation, and test sets.
134
+ However, the validation and test sets come from different domains, with the validation set consisting
135
+ of ambiguous examples such that changing one non-noun phrase word will change the coreference
136
+ dependencies in the sentence. The test set consists only of more straightforward examples, with a
137
+ high number of noun phrases (and thus more choices for the model), but low to no ambiguity."""
138
+
139
+ _AXB_DESCRIPTION = """\
140
+ An expert-constructed,
141
+ diagnostic dataset that automatically tests models for a broad range of linguistic, commonsense, and
142
+ world knowledge. Each example in this broad-coverage diagnostic is a sentence pair labeled with
143
+ a three-way entailment relation (entailment, neutral, or contradiction) and tagged with labels that
144
+ indicate the phenomena that characterize the relationship between the two sentences. Submissions
145
+ to the GLUE leaderboard are required to include predictions from the submission's MultiNLI
146
+ classifier on the diagnostic dataset, and analyses of the results were shown alongside the main
147
+ leaderboard. Since this broad-coverage diagnostic task has proved difficult for top models, we retain
148
+ it in Test. However, since MultiNLI is not part of Test, we collapse contradiction
149
+ and neutral into a single not_entailment label, and request that submissions include predictions
150
+ on the resulting set from the model used for the RTE task.
151
+ """
152
+
153
+ _AXG_DESCRIPTION = """\
154
+ Winogender is designed to measure gender
155
+ bias in coreference resolution systems. We use the Diverse Natural Language Inference Collection
156
+ (DNC; Poliak et al., 2018) version that casts Winogender as a textual entailment task. Each example
157
+ consists of a premise sentence with a male or female pronoun and a hypothesis giving a possible
158
+ antecedent of the pronoun. Examples occur in minimal pairs, where the only difference between
159
+ an example and its pair is the gender of the pronoun in the premise. Performance on Winogender
160
+ is measured with both accuracy and the gender parity score: the percentage of minimal pairs for
161
+ which the predictions are the same. We note that a system can trivially obtain a perfect gender parity
162
+ score by guessing the same class for all examples, so a high gender parity score is meaningless unless
163
+ accompanied by high accuracy. As a diagnostic test of gender bias, we view the schemas as having high
164
+ positive predictive value and low negative predictive value; that is, they may demonstrate the presence
165
+ of gender bias in a system, but not prove its absence.
166
+ """
167
+
168
+ _BOOLQ_CITATION = """\
169
+ @inproceedings{clark2019boolq,
170
+ title={BoolQ: Exploring the Surprising Difficulty of Natural Yes/No Questions},
171
+ author={Clark, Christopher and Lee, Kenton and Chang, Ming-Wei, and Kwiatkowski, Tom and Collins, Michael, and Toutanova, Kristina},
172
+ booktitle={NAACL},
173
+ year={2019}
174
+ }"""
175
+
176
+ _CB_CITATION = """\
177
+ @article{de marneff_simons_tonhauser_2019,
178
+ title={The CommitmentBank: Investigating projection in naturally occurring discourse},
179
+ journal={proceedings of Sinn und Bedeutung 23},
180
+ author={De Marneff, Marie-Catherine and Simons, Mandy and Tonhauser, Judith},
181
+ year={2019}
182
+ }"""
183
+
184
+ _COPA_CITATION = """\
185
+ @inproceedings{roemmele2011choice,
186
+ title={Choice of plausible alternatives: An evaluation of commonsense causal reasoning},
187
+ author={Roemmele, Melissa and Bejan, Cosmin Adrian and Gordon, Andrew S},
188
+ booktitle={2011 AAAI Spring Symposium Series},
189
+ year={2011}
190
+ }"""
191
+
192
+ _RECORD_CITATION = """\
193
+ @article{zhang2018record,
194
+ title={Record: Bridging the gap between human and machine commonsense reading comprehension},
195
+ author={Zhang, Sheng and Liu, Xiaodong and Liu, Jingjing and Gao, Jianfeng and Duh, Kevin and Van Durme, Benjamin},
196
+ journal={arXiv preprint arXiv:1810.12885},
197
+ year={2018}
198
+ }"""
199
+
200
+ _RTE_CITATION = """\
201
+ @inproceedings{dagan2005pascal,
202
+ title={The PASCAL recognising textual entailment challenge},
203
+ author={Dagan, Ido and Glickman, Oren and Magnini, Bernardo},
204
+ booktitle={Machine Learning Challenges Workshop},
205
+ pages={177--190},
206
+ year={2005},
207
+ organization={Springer}
208
+ }
209
+ @inproceedings{bar2006second,
210
+ title={The second pascal recognising textual entailment challenge},
211
+ author={Bar-Haim, Roy and Dagan, Ido and Dolan, Bill and Ferro, Lisa and Giampiccolo, Danilo and Magnini, Bernardo and Szpektor, Idan},
212
+ booktitle={Proceedings of the second PASCAL challenges workshop on recognising textual entailment},
213
+ volume={6},
214
+ number={1},
215
+ pages={6--4},
216
+ year={2006},
217
+ organization={Venice}
218
+ }
219
+ @inproceedings{giampiccolo2007third,
220
+ title={The third pascal recognizing textual entailment challenge},
221
+ author={Giampiccolo, Danilo and Magnini, Bernardo and Dagan, Ido and Dolan, Bill},
222
+ booktitle={Proceedings of the ACL-PASCAL workshop on textual entailment and paraphrasing},
223
+ pages={1--9},
224
+ year={2007},
225
+ organization={Association for Computational Linguistics}
226
+ }
227
+ @inproceedings{bentivogli2009fifth,
228
+ title={The Fifth PASCAL Recognizing Textual Entailment Challenge.},
229
+ author={Bentivogli, Luisa and Clark, Peter and Dagan, Ido and Giampiccolo, Danilo},
230
+ booktitle={TAC},
231
+ year={2009}
232
+ }"""
233
+
234
+ _MULTIRC_CITATION = """\
235
+ @inproceedings{MultiRC2018,
236
+ author = {Daniel Khashabi and Snigdha Chaturvedi and Michael Roth and Shyam Upadhyay and Dan Roth},
237
+ title = {Looking Beyond the Surface:A Challenge Set for Reading Comprehension over Multiple Sentences},
238
+ booktitle = {Proceedings of North American Chapter of the Association for Computational Linguistics (NAACL)},
239
+ year = {2018}
240
+ }"""
241
+
242
+ _WIC_CITATION = """\
243
+ @article{DBLP:journals/corr/abs-1808-09121,
244
+ author={Mohammad Taher Pilehvar and os{\'{e}} Camacho{-}Collados},
245
+ title={WiC: 10, 000 Example Pairs for Evaluating Context-Sensitive Representations},
246
+ journal={CoRR},
247
+ volume={abs/1808.09121},
248
+ year={2018},
249
+ url={http://arxiv.org/abs/1808.09121},
250
+ archivePrefix={arXiv},
251
+ eprint={1808.09121},
252
+ timestamp={Mon, 03 Sep 2018 13:36:40 +0200},
253
+ biburl={https://dblp.org/rec/bib/journals/corr/abs-1808-09121},
254
+ bibsource={dblp computer science bibliography, https://dblp.org}
255
+ }"""
256
+
257
+ _WSC_CITATION = """\
258
+ @inproceedings{levesque2012winograd,
259
+ title={The winograd schema challenge},
260
+ author={Levesque, Hector and Davis, Ernest and Morgenstern, Leora},
261
+ booktitle={Thirteenth International Conference on the Principles of Knowledge Representation and Reasoning},
262
+ year={2012}
263
+ }"""
264
+
265
+ _AXG_CITATION = """\
266
+ @inproceedings{rudinger-EtAl:2018:N18,
267
+ author = {Rudinger, Rachel and Naradowsky, Jason and Leonard, Brian and {Van Durme}, Benjamin},
268
+ title = {Gender Bias in Coreference Resolution},
269
+ booktitle = {Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies},
270
+ month = {June},
271
+ year = {2018},
272
+ address = {New Orleans, Louisiana},
273
+ publisher = {Association for Computational Linguistics}
274
+ }
275
+ """
276
+
277
+
278
+ class TestConfig(datasets.BuilderConfig):
279
+ """BuilderConfig for Test."""
280
+
281
+ def __init__(self, features, data_url, citation, url, label_classes=("False", "True"), **kwargs):
282
+ """BuilderConfig for Test.
283
+ Args:
284
+ features: `list[string]`, list of the features that will appear in the
285
+ feature dict. Should not include "label".
286
+ data_url: `string`, url to download the zip file from.
287
+ citation: `string`, citation for the data set.
288
+ url: `string`, url for information about the data set.
289
+ label_classes: `list[string]`, the list of classes for the label if the
290
+ label is present as a string. Non-string labels will be cast to either
291
+ 'False' or 'True'.
292
+ **kwargs: keyword arguments forwarded to super.
293
+ """
294
+ # Version history:
295
+ # 1.0.2: Fixed non-nondeterminism in ReCoRD.
296
+ # 1.0.1: Change from the pre-release trial version of Test (v1.9) to
297
+ # the full release (v2.0).
298
+ # 1.0.0: S3 (new shuffling, sharding and slicing mechanism).
299
+ # 0.0.2: Initial version.
300
+ super(TestConfig, self).__init__(version=datasets.Version("1.0.2"), **kwargs)
301
+ self.features = features
302
+ self.label_classes = label_classes
303
+ self.data_url = data_url
304
+ self.citation = citation
305
+ self.url = url
306
+
307
+
308
+ class Test(datasets.GeneratorBasedBuilder):
309
+ """The Test benchmark."""
310
+
311
+ BUILDER_CONFIGS = [
312
+ TestConfig(
313
+ name="boolq",
314
+ description=_BOOLQ_DESCRIPTION,
315
+ features=["question", "passage"],
316
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/BoolQ.zip",
317
+ citation=_BOOLQ_CITATION,
318
+ url="https://github.com/google-research-datasets/boolean-questions",
319
+ ),
320
+ TestConfig(
321
+ name="cb",
322
+ description=_CB_DESCRIPTION,
323
+ features=["premise", "hypothesis"],
324
+ label_classes=["entailment", "contradiction", "neutral"],
325
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/CB.zip",
326
+ citation=_CB_CITATION,
327
+ url="https://github.com/mcdm/CommitmentBank",
328
+ ),
329
+ TestConfig(
330
+ name="copa",
331
+ description=_COPA_DESCRIPTION,
332
+ label_classes=["choice1", "choice2"],
333
+ # Note that question will only be the X in the statement "What's
334
+ # the X for this?".
335
+ features=["premise", "choice1", "choice2", "question"],
336
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/COPA.zip",
337
+ citation=_COPA_CITATION,
338
+ url="http://people.ict.usc.edu/~gordon/copa.html",
339
+ ),
340
+ TestConfig(
341
+ name="multirc",
342
+ description=_MULTIRC_DESCRIPTION,
343
+ features=["paragraph", "question", "answer"],
344
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/MultiRC.zip",
345
+ citation=_MULTIRC_CITATION,
346
+ url="https://cogcomp.org/multirc/",
347
+ ),
348
+ TestConfig(
349
+ name="record",
350
+ description=_RECORD_DESCRIPTION,
351
+ # Note that entities and answers will be a sequences of strings. Query
352
+ # will contain @placeholder as a substring, which represents the word
353
+ # to be substituted in.
354
+ features=["passage", "query", "entities", "answers"],
355
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/ReCoRD.zip",
356
+ citation=_RECORD_CITATION,
357
+ url="https://sheng-z.github.io/ReCoRD-explorer/",
358
+ ),
359
+ TestConfig(
360
+ name="rte",
361
+ description=_RTE_DESCRIPTION,
362
+ features=["premise", "hypothesis"],
363
+ label_classes=["entailment", "not_entailment"],
364
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/RTE.zip",
365
+ citation=_RTE_CITATION,
366
+ url="https://aclweb.org/aclwiki/Recognizing_Textual_Entailment",
367
+ ),
368
+ TestConfig(
369
+ name="wic",
370
+ description=_WIC_DESCRIPTION,
371
+ # Note that start1, start2, end1, and end2 will be integers stored as
372
+ # datasets.Value('int32').
373
+ features=["word", "sentence1", "sentence2", "start1", "start2", "end1", "end2"],
374
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/WiC.zip",
375
+ citation=_WIC_CITATION,
376
+ url="https://pilehvar.github.io/wic/",
377
+ ),
378
+ TestConfig(
379
+ name="wsc",
380
+ description=_WSC_DESCRIPTION,
381
+ # Note that span1_index and span2_index will be integers stored as
382
+ # datasets.Value('int32').
383
+ features=["text", "span1_index", "span2_index", "span1_text", "span2_text"],
384
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/WSC.zip",
385
+ citation=_WSC_CITATION,
386
+ url="https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WS.html",
387
+ ),
388
+ TestConfig(
389
+ name="wsc.fixed",
390
+ description=(
391
+ _WSC_DESCRIPTION + "\n\nThis version fixes issues where the spans are not actually "
392
+ "substrings of the text."
393
+ ),
394
+ # Note that span1_index and span2_index will be integers stored as
395
+ # datasets.Value('int32').
396
+ features=["text", "span1_index", "span2_index", "span1_text", "span2_text"],
397
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/WSC.zip",
398
+ citation=_WSC_CITATION,
399
+ url="https://cs.nyu.edu/faculty/davise/papers/WinogradSchemas/WS.html",
400
+ ),
401
+ TestConfig(
402
+ name="axb",
403
+ description=_AXB_DESCRIPTION,
404
+ features=["sentence1", "sentence2"],
405
+ label_classes=["entailment", "not_entailment"],
406
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/AX-b.zip",
407
+ citation="", # The GLUE citation is sufficient.
408
+ url="https://gluebenchmark.com/diagnostics",
409
+ ),
410
+ TestConfig(
411
+ name="axg",
412
+ description=_AXG_DESCRIPTION,
413
+ features=["premise", "hypothesis"],
414
+ label_classes=["entailment", "not_entailment"],
415
+ data_url="https://dl.fbaipublicfiles.com/glue/Test/data/v2/AX-g.zip",
416
+ citation=_AXG_CITATION,
417
+ url="https://github.com/rudinger/winogender-schemas",
418
+ ),
419
+ ]
420
+
421
+ def _info(self):
422
+ features = {feature: datasets.Value("string") for feature in self.config.features}
423
+ if self.config.name.startswith("wsc"):
424
+ features["span1_index"] = datasets.Value("int32")
425
+ features["span2_index"] = datasets.Value("int32")
426
+ if self.config.name == "wic":
427
+ features["start1"] = datasets.Value("int32")
428
+ features["start2"] = datasets.Value("int32")
429
+ features["end1"] = datasets.Value("int32")
430
+ features["end2"] = datasets.Value("int32")
431
+ if self.config.name == "multirc":
432
+ features["idx"] = dict(
433
+ {
434
+ "paragraph": datasets.Value("int32"),
435
+ "question": datasets.Value("int32"),
436
+ "answer": datasets.Value("int32"),
437
+ }
438
+ )
439
+ elif self.config.name == "record":
440
+ features["idx"] = dict(
441
+ {
442
+ "passage": datasets.Value("int32"),
443
+ "query": datasets.Value("int32"),
444
+ }
445
+ )
446
+ else:
447
+ features["idx"] = datasets.Value("int32")
448
+
449
+ if self.config.name == "record":
450
+ # Entities are the set of possible choices for the placeholder.
451
+ features["entities"] = datasets.features.Sequence(datasets.Value("string"))
452
+ # Answers are the subset of entities that are correct.
453
+ features["answers"] = datasets.features.Sequence(datasets.Value("string"))
454
+ else:
455
+ features["label"] = datasets.features.ClassLabel(names=self.config.label_classes)
456
+
457
+ return datasets.DatasetInfo(
458
+ description=_GLUE_DESCRIPTION + self.config.description,
459
+ features=datasets.Features(features),
460
+ homepage=self.config.url,
461
+ citation=self.config.citation + "\n" + _SUPER_GLUE_CITATION,
462
+ )
463
+
464
+ def _split_generators(self, dl_manager):
465
+ dl_dir = dl_manager.download_and_extract(self.config.data_url) or ""
466
+ task_name = _get_task_name_from_data_url(self.config.data_url)
467
+ dl_dir = os.path.join(dl_dir, task_name)
468
+ if self.config.name in ["axb", "axg"]:
469
+ return [
470
+ datasets.SplitGenerator(
471
+ name=datasets.Split.TEST,
472
+ gen_kwargs={
473
+ "data_file": os.path.join(dl_dir, f"{task_name}.jsonl"),
474
+ "split": datasets.Split.TEST,
475
+ },
476
+ ),
477
+ ]
478
+ return [
479
+ datasets.SplitGenerator(
480
+ name=datasets.Split.TRAIN,
481
+ gen_kwargs={
482
+ "data_file": os.path.join(dl_dir, "train.jsonl"),
483
+ "split": datasets.Split.TRAIN,
484
+ },
485
+ ),
486
+ datasets.SplitGenerator(
487
+ name=datasets.Split.VALIDATION,
488
+ gen_kwargs={
489
+ "data_file": os.path.join(dl_dir, "val.jsonl"),
490
+ "split": datasets.Split.VALIDATION,
491
+ },
492
+ ),
493
+ datasets.SplitGenerator(
494
+ name=datasets.Split.TEST,
495
+ gen_kwargs={
496
+ "data_file": os.path.join(dl_dir, "test.jsonl"),
497
+ "split": datasets.Split.TEST,
498
+ },
499
+ ),
500
+ ]
501
+
502
+ def _generate_examples(self, data_file, split):
503
+ with open(data_file, encoding="utf-8") as f:
504
+ for line in f:
505
+ row = json.loads(line)
506
+
507
+ if self.config.name == "multirc":
508
+ paragraph = row["passage"]
509
+ for question in paragraph["questions"]:
510
+ for answer in question["answers"]:
511
+ label = answer.get("label")
512
+ key = "%s_%s_%s" % (row["idx"], question["idx"], answer["idx"])
513
+ yield key, {
514
+ "paragraph": paragraph["text"],
515
+ "question": question["question"],
516
+ "answer": answer["text"],
517
+ "label": -1 if label is None else _cast_label(bool(label)),
518
+ "idx": {"paragraph": row["idx"], "question": question["idx"], "answer": answer["idx"]},
519
+ }
520
+ elif self.config.name == "record":
521
+ passage = row["passage"]
522
+ for qa in row["qas"]:
523
+ yield qa["idx"], {
524
+ "passage": passage["text"],
525
+ "query": qa["query"],
526
+ "entities": _get_record_entities(passage),
527
+ "answers": _get_record_answers(qa),
528
+ "idx": {"passage": row["idx"], "query": qa["idx"]},
529
+ }
530
+ else:
531
+ if self.config.name.startswith("wsc"):
532
+ row.update(row["target"])
533
+ example = {feature: row[feature] for feature in self.config.features}
534
+ if self.config.name == "wsc.fixed":
535
+ example = _fix_wst(example)
536
+ example["idx"] = row["idx"]
537
+
538
+ if "label" in row:
539
+ if self.config.name == "copa":
540
+ example["label"] = "choice2" if row["label"] else "choice1"
541
+ else:
542
+ example["label"] = _cast_label(row["label"])
543
+ else:
544
+ assert split == datasets.Split.TEST, row
545
+ example["label"] = -1
546
+ yield example["idx"], example
547
+
548
+
549
+ def _fix_wst(ex):
550
+ """Fixes most cases where spans are not actually substrings of text."""
551
+
552
+ def _fix_span_text(k):
553
+ """Fixes a single span."""
554
+ text = ex[k + "_text"]
555
+ index = ex[k + "_index"]
556
+
557
+ if text in ex["text"]:
558
+ return
559
+
560
+ if text in ("Kamenev and Zinoviev", "Kamenev, Zinoviev, and Stalin"):
561
+ # There is no way to correct these examples since the subjects have
562
+ # intervening text.
563
+ return
564
+
565
+ if "theyscold" in text:
566
+ ex["text"].replace("theyscold", "they scold")
567
+ ex["span2_index"] = 10
568
+ # Make sure case of the first words match.
569
+ first_word = ex["text"].split()[index]
570
+ if first_word[0].islower():
571
+ text = text[0].lower() + text[1:]
572
+ else:
573
+ text = text[0].upper() + text[1:]
574
+ # Remove punctuation in span.
575
+ text = text.rstrip(".")
576
+ # Replace incorrect whitespace character in span.
577
+ text = text.replace("\n", " ")
578
+ ex[k + "_text"] = text
579
+ assert ex[k + "_text"] in ex["text"], ex
580
+
581
+ _fix_span_text("span1")
582
+ _fix_span_text("span2")
583
+ return ex
584
+
585
+
586
+ def _cast_label(label):
587
+ """Converts the label into the appropriate string version."""
588
+ if isinstance(label, str):
589
+ return label
590
+ elif isinstance(label, bool):
591
+ return "True" if label else "False"
592
+ elif isinstance(label, int):
593
+ assert label in (0, 1)
594
+ return str(label)
595
+ else:
596
+ raise ValueError("Invalid label format.")
597
+
598
+
599
+ def _get_record_entities(passage):
600
+ """Returns the unique set of entities."""
601
+ text = passage["text"]
602
+ entities = set()
603
+ for entity in passage["entities"]:
604
+ entities.add(text[entity["start"] : entity["end"] + 1])
605
+ return sorted(entities)
606
+
607
+
608
+ def _get_record_answers(qa):
609
+ """Returns the unique set of answers."""
610
+ if "answers" not in qa:
611
+ return []
612
+ answers = set()
613
+ for answer in qa["answers"]:
614
+ answers.add(answer["text"])
615
+ return sorted(answers)
616
+
617
+
618
+ def _get_task_name_from_data_url(data_url):
619
+ return data_url.split("/")[-1].split(".")[0]