File size: 34,675 Bytes
909639c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76c0162
 
 
 
 
 
909639c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# coding=utf-8
# Lint as: python3
"""Data for SLED, based on the SCROLLS benchmark."""
import json
import os
import random
import re

import datasets

import numpy as np


_SLED_DESCRIPTION = """
Efficient Long-Text Understanding with Short-Text Models.
Our SLiding-Encoder and Decoder uses any pretrained encoder-decoder model, to independtly encode overlapping chunks of 
the inputs, and perform fusion-in-decoder to achieve linear-memory requirment for long-range natural language understanding.

"""

_SCROLLS_DESCRIPTION = """
SCROLLS: Standardized CompaRison Over Long Language Sequences.
A suite of natural language datasets that require reasoning over long texts.
https://scrolls-benchmark.com/

"""

_SUMM_SCREEN_DESCRIPTION = """
SummScreenFD (Chen  et al., 2021) is a summarization dataset in the domain of TV shows (e.g. Friends, Game of Thrones).
Given a transcript of a specific episode, the goal is to produce the episode's recap.
The original dataset is divided into two complementary subsets, based on the source of its community contributed transcripts. 
For SCROLLS, we use the ForeverDreaming (FD) subset, as it incorporates 88 different shows, 
making it a more diverse alternative to the TV MegaSite (TMS) subset, which has only 10 shows. 
Community-authored recaps for the ForeverDreaming transcripts were collected from English Wikipedia and TVMaze."""

_QASPER_DESCRIPTION = """
Qasper (Dasigi et al., 2021) is a question answering dataset over NLP papers filtered from the Semantic Scholar Open Research Corpus (S2ORC).
Questions were written by NLP practitioners after reading only the title and abstract of the papers, 
while another set of NLP practitioners annotated the answers given the entire document.
Qasper contains abstractive, extractive, and yes/no questions, as well as unanswerable ones."""

_QMSUM_DESCRIPTION = """
QMSum (Zhong et al., 2021) is a query-based summarization dataset, consisting of 232 meetings transcripts from multiple domains. 
The corpus covers academic group meetings at the International Computer Science Institute and their summaries, industrial product meetings for designing a remote control, 
and committee meetings of the Welsh and Canadian Parliaments, dealing with a variety of public policy issues.
Annotators were tasked with writing queries about the broad contents of the meetings, as well as specific questions about certain topics or decisions, 
while ensuring that the relevant text for answering each query spans at least 200 words or 10 turns."""

_NARRATIVE_QA_DESCRIPTION = """
NarrativeQA (Kočiský et al., 2021) is an established question answering dataset over entire books from Project Gutenberg and movie scripts from different websites.
Annotators were given summaries of the books and scripts obtained from Wikipedia, and asked to generate question-answer pairs, 
resulting in about 30 questions and answers for each of the 1,567 books and scripts.
They were encouraged to use their own words rather then copying, and avoid asking yes/no questions or ones about the cast.
Each question was then answered by an additional annotator, providing each question with two reference answers (unless both answers are identical).."""

_GOV_REPORT_DESCRIPTION = """
GovReport (Huang et al., 2021) is a summarization dataset of reports addressing various national policy issues published by the 
Congressional Research Service and the U.S. Government Accountability Office, where each document is paired with a hand-written executive summary.
The reports and their summaries are longer than their equivalents in other popular long-document summarization datasets; 
for example, GovReport's documents are approximately 1.5 and 2.5 times longer than the documents in Arxiv and PubMed, respectively."""

_CONTRACT_NLI_DESCRIPTION = """
Contract NLI (Koreeda and Manning, 2021) is a natural language inference dataset in the legal domain.
Given a non-disclosure agreement (the premise), the task is to predict whether a particular legal statement (the hypothesis) is entailed, not entailed (neutral), or cannot be entailed (contradiction) from the contract.
The NDAs were manually picked after simple filtering from the Electronic Data Gathering, Analysis, and Retrieval system (EDGAR) and Google.
The dataset contains a total of 607 contracts and 17 unique hypotheses, which were combined to produce the dataset's 10,319 examples."""

_QUALITY_DESCRIPTION = """
QuALITY (Pang et al., 2021) is a multiple-choice question answering dataset over articles and stories sourced from Project Gutenberg, 
the Open American National Corpus, and more.
Experienced writers wrote questions and distractors, and were incentivized to write answerable, unambiguous questions such that in order to correctly answer them, 
human annotators must read large portions of the given document. 
Reference answers were then calculated using the majority vote between of the annotators and writer's answers.
To measure the difficulty of their questions, Pang et al. conducted a speed validation process, 
where another set of annotators were asked to answer questions given only a short period of time to skim through the document.
As a result, 50% of the questions in QuALITY are labeled as hard, i.e. the majority of the annotators in the speed validation setting chose the wrong answer."""

_SQUAD_DESCRIPTION = """\
Stanford Question Answering Dataset (SQuAD) is a reading comprehension \
dataset, consisting of questions posed by crowdworkers on a set of Wikipedia \
articles, where the answer to every question is a segment of text, or span, \
from the corresponding reading passage, or the question might be unanswerable.
"""

_HOTPOTQA_DESCRIPTION = """\
HotpotQA is a new dataset with 113k Wikipedia-based question-answer pairs with four key features:
(1) the questions require finding and reasoning over multiple supporting documents to answer;
(2) the questions are diverse and not constrained to any pre-existing knowledge bases or knowledge schemas;
(3) we provide sentence-level supporting facts required for reasoning, allowingQA systems to reason with strong supervisionand explain the predictions;
(4) we offer a new type of factoid comparison questions to testQA systems’ ability to extract relevant facts and perform necessary comparison.
"""

_SLED_CITATION = """
@inproceedings{Ivgi2022EfficientLU,
  title={Efficient Long-Text Understanding with Short-Text Models},
  author={Maor Ivgi and Uri Shaham and Jonathan Berant},
  year={2022}
}
Note that each SLED dataset has its own citation. Please see the source to
get the correct citation for each contained dataset (and also cite the SCROLLS dataset on which it is based).
"""

_SCROLLS_CITATION = """
@misc{shaham2022scrolls,
      title={SCROLLS: Standardized CompaRison Over Long Language Sequences}, 
      author={Uri Shaham and Elad Segal and Maor Ivgi and Avia Efrat and Ori Yoran and Adi Haviv and Ankit Gupta and Wenhan Xiong and Mor Geva and Jonathan Berant and Omer Levy},
      year={2022},
      eprint={2201.03533},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
Note that each SCROLLS dataset has its own citation. Please see the source to
get the correct citation for each contained dataset.
"""

_SUMM_SCREEN_CITATION = r"""
@misc{chen2021summscreen,
      title={SummScreen: A Dataset for Abstractive Screenplay Summarization}, 
      author={Mingda Chen and Zewei Chu and Sam Wiseman and Kevin Gimpel},
      year={2021},
      eprint={2104.07091},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}"""

_QASPER_CITATION = r"""
@inproceedings{dasigi-etal-2021-dataset,
    title = "A Dataset of Information-Seeking Questions and Answers Anchored in Research Papers",
    author = "Dasigi, Pradeep  and
      Lo, Kyle  and
      Beltagy, Iz  and
      Cohan, Arman  and
      Smith, Noah A.  and
      Gardner, Matt",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.365",
    doi = "10.18653/v1/2021.naacl-main.365",
    pages = "4599--4610",
    abstract = "Readers of academic research papers often read with the goal of answering specific questions. Question Answering systems that can answer those questions can make consumption of the content much more efficient. However, building such tools requires data that reflect the difficulty of the task arising from complex reasoning about claims made in multiple parts of a paper. In contrast, existing information-seeking question answering datasets usually contain questions about generic factoid-type information. We therefore present Qasper, a dataset of 5049 questions over 1585 Natural Language Processing papers. Each question is written by an NLP practitioner who read only the title and abstract of the corresponding paper, and the question seeks information present in the full text. The questions are then answered by a separate set of NLP practitioners who also provide supporting evidence to answers. We find that existing models that do well on other QA tasks do not perform well on answering these questions, underperforming humans by at least 27 F1 points when answering them from entire papers, motivating further research in document-grounded, information-seeking QA, which our dataset is designed to facilitate.",
}"""

_QMSUM_CITATION = r"""@inproceedings{zhong-etal-2021-qmsum,
    title = "{QMS}um: A New Benchmark for Query-based Multi-domain Meeting Summarization",
    author = "Zhong, Ming  and
      Yin, Da  and
      Yu, Tao  and
      Zaidi, Ahmad  and
      Mutuma, Mutethia  and
      Jha, Rahul  and
      Awadallah, Ahmed Hassan  and
      Celikyilmaz, Asli  and
      Liu, Yang  and
      Qiu, Xipeng  and
      Radev, Dragomir",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.472",
    doi = "10.18653/v1/2021.naacl-main.472",
    pages = "5905--5921",
    abstract = "Meetings are a key component of human collaboration. As increasing numbers of meetings are recorded and transcribed, meeting summaries have become essential to remind those who may or may not have attended the meetings about the key decisions made and the tasks to be completed. However, it is hard to create a single short summary that covers all the content of a long meeting involving multiple people and topics. In order to satisfy the needs of different types of users, we define a new query-based multi-domain meeting summarization task, where models have to select and summarize relevant spans of meetings in response to a query, and we introduce QMSum, a new benchmark for this task. QMSum consists of 1,808 query-summary pairs over 232 meetings in multiple domains. Besides, we investigate a locate-then-summarize method and evaluate a set of strong summarization baselines on the task. Experimental results and manual analysis reveal that QMSum presents significant challenges in long meeting summarization for future research. Dataset is available at \url{https://github.com/Yale-LILY/QMSum}.",
}"""

_NARRATIVE_QA_CITATION = r"""
@article{kovcisky2018narrativeqa,
  title={The narrativeqa reading comprehension challenge},
  author={Ko{\v{c}}isk{\'y}, Tom{\'a}{\v{s}} and Schwarz, Jonathan and Blunsom, Phil and Dyer, Chris and Hermann, Karl Moritz and Melis, G{\'a}bor and Grefenstette, Edward},
  journal={Transactions of the Association for Computational Linguistics},
  volume={6},
  pages={317--328},
  year={2018},
  publisher={MIT Press}
}"""

_GOV_REPORT_CITATION = r"""
@inproceedings{huang-etal-2021-efficient,
    title = "Efficient Attentions for Long Document Summarization",
    author = "Huang, Luyang  and
      Cao, Shuyang  and
      Parulian, Nikolaus  and
      Ji, Heng  and
      Wang, Lu",
    booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
    month = jun,
    year = "2021",
    address = "Online",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2021.naacl-main.112",
    doi = "10.18653/v1/2021.naacl-main.112",
    pages = "1419--1436",
    abstract = "The quadratic computational and memory complexities of large Transformers have limited their scalability for long document summarization. In this paper, we propose Hepos, a novel efficient encoder-decoder attention with head-wise positional strides to effectively pinpoint salient information from the source. We further conduct a systematic study of existing efficient self-attentions. Combined with Hepos, we are able to process ten times more tokens than existing models that use full attentions. For evaluation, we present a new dataset, GovReport, with significantly longer documents and summaries. Results show that our models produce significantly higher ROUGE scores than competitive comparisons, including new state-of-the-art results on PubMed. Human evaluation also shows that our models generate more informative summaries with fewer unfaithful errors.",
}"""

_CONTRACT_NLI_CITATION = """\
@inproceedings{koreeda-manning-2021-contractnli,
    title = "ContractNLI: A Dataset for Document-level Natural Language Inference for Contracts",
    author = "Koreeda, Yuta  and
      Manning, Christopher D.",
    booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2021",
    year = "2021",
    publisher = "Association for Computational Linguistics"
}
"""
_QUALITY_CITATION = """\
@article{pang2021quality,
  title={{QuALITY}: Question Answering with Long Input Texts, Yes!},
  author={Pang, Richard Yuanzhe and Parrish, Alicia and Joshi, Nitish and Nangia, Nikita and Phang, Jason and Chen, Angelica and Padmakumar, Vishakh and Ma, Johnny and Thompson, Jana and He, He and Bowman, Samuel R.},
  journal={arXiv preprint arXiv:2112.08608},
  year={2021}
}
"""
_SQUAD_CITATION = """\
@article{2016arXiv160605250R,
       author = {{Rajpurkar}, Pranav and {Zhang}, Jian and {Lopyrev},
                 Konstantin and {Liang}, Percy},
        title = "{SQuAD: 100,000+ Questions for Machine Comprehension of Text}",
      journal = {arXiv e-prints},
         year = 2016,
          eid = {arXiv:1606.05250},
        pages = {arXiv:1606.05250},
archivePrefix = {arXiv},
       eprint = {1606.05250},
}
"""
_HOTPOTQA_CITATION = """
@inproceedings{yang2018hotpotqa,
  title={{HotpotQA}: A Dataset for Diverse, Explainable Multi-hop Question Answering},
  author={Yang, Zhilin and Qi, Peng and Zhang, Saizheng and Bengio, Yoshua and Cohen, William W. and Salakhutdinov, Ruslan and Manning, Christopher D.},
  booktitle={Conference on Empirical Methods in Natural Language Processing ({EMNLP})},
  year={2018}
}
"""


class SLEDConfig(datasets.BuilderConfig):
    """BuilderConfig for SLED."""

    def __init__(self, features, data_url, citation, url, **kwargs):
        """BuilderConfig for SLED.
        Args:
          features: `list[string]`, list of the features that will appear in the
            feature dict. Should not include "label".
          data_url: `string`, url to download the zip file from.
          citation: `string`, citation for the data set.
          url: `string`, url for information about the data set.
          label_classes: `list[string]`, the list of classes for the label if the
            label is present as a string. Non-string labels will be cast to either
            'False' or 'True'.
          **kwargs: keyword arguments forwarded to super.
        """
        super(SLEDConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
        self.features = features
        self.data_url = data_url
        self.citation = citation
        self.url = url


class SquadConfig(SLEDConfig):
    """BuilderConfig for SQUAD."""
    _URL = "https://rajpurkar.github.io/SQuAD-explorer/dataset/"
    _URLS = {
        "train": _URL + "train-v1.1.json",
        "dev": _URL + "dev-v1.1.json",
    }

    def __init__(self, n_distractors=0, random_order=True, **kwargs):
        """BuilderConfig for SQUAD.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(SquadConfig, self).__init__(**kwargs)
        self.n_distractors = n_distractors
        self.random_order = random_order


class HotpotQAConfig(SLEDConfig):
    """BuilderConfig for HotpotQA distractors settings"""
    _URL_BASE = "http://curtis.ml.cmu.edu/datasets/hotpot/"
    _HOMEPAGE = '"https://hotpotqa.github.io/"'

    def __init__(self, gold_passages, distractors=True, **kwargs):
        """
        gold_passages should be one of first, second and both
        """
        super(HotpotQAConfig, self).__init__(**kwargs)
        self.gold_passages = gold_passages
        self.distractors = distractors


class QualityConfig(SLEDConfig):
    def __init__(self, prefix_only=False, **kwargs):
        super().__init__(**kwargs)
        self.hard_only = False
        self.prefix_only = prefix_only


features_qa = ["id", "pid", "input", 'input_prefix', "output"]
features = ["id", "pid", "input", "output"]


class SLED(datasets.GeneratorBasedBuilder):
    """The SCROLLS benchmark with modifications for SLED. + tasks based on SQuAD 1.1 and HotpotQA"""

    DEFAULT_WRITER_BATCH_SIZE = 1000  # because Narrative QA is a rather large dataset
    BUILDER_CONFIGS = [
                          SLEDConfig(
                              name="summ_screen_fd",
                              description=_SUMM_SCREEN_DESCRIPTION,
                              features=features,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/summ_screen_fd.zip",
                              citation=_SUMM_SCREEN_CITATION,
                              url="https://github.com/mingdachen/SummScreen",
                          ),
                          SLEDConfig(
                              name="qasper",
                              description=_QASPER_DESCRIPTION,
                              features=features_qa,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/qasper.zip",
                              citation=_QASPER_CITATION,
                              url="https://allenai.org/project/qasper",
                          ),
                          SLEDConfig(
                              name="qmsum",
                              description=_QMSUM_DESCRIPTION,
                              features=features_qa,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/qmsum.zip",
                              citation=_QMSUM_CITATION,
                              url="https://github.com/Yale-LILY/QMSum",
                          ),
                          SLEDConfig(
                              name="narrative_qa",
                              description=_NARRATIVE_QA_DESCRIPTION,
                              features=features_qa,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/narrative_qa.zip",
                              citation=_NARRATIVE_QA_CITATION,
                              url="https://deepmind.com/research/publications/narrativeqa-reading-comprehension-challenge",
                          ),
                          SLEDConfig(
                              name="gov_report",
                              description=_GOV_REPORT_CITATION,
                              features=features,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/gov_report.zip",
                              citation=_GOV_REPORT_DESCRIPTION,
                              url="https://gov-report-data.github.io/",
                          ),
                          SLEDConfig(
                              name="contract_nli",
                              description=_CONTRACT_NLI_DESCRIPTION,
                              features=features_qa,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/contract_nli.zip",
                              citation=_CONTRACT_NLI_CITATION,
                              url="https://stanfordnlp.github.io/contract-nli/",
                          ),
                          QualityConfig(
                              name="quality",
                              prefix_only=False,
                              description=_QUALITY_CITATION,
                              features=features_qa,
                              data_url="https://scrolls-tau.s3.us-east-2.amazonaws.com/quality.zip",
                              citation=_QUALITY_DESCRIPTION,
                              url="https://github.com/nyu-mll/quality",
                          ),
                          SquadConfig(
                              name="squad",
                              data_url=SquadConfig._URLS,
                              features=features_qa,
                              citation=_SQUAD_CITATION,
                              url=SquadConfig._URL,
                              description=_SQUAD_DESCRIPTION
                          ),
                          SquadConfig(
                              name="squad_shuffled_distractors",
                              data_url=SquadConfig._URLS,
                              n_distractors=9,
                              random_order=True,
                              features=features_qa,
                              citation=_SQUAD_CITATION,
                              url=SquadConfig._URL,
                              description=_SQUAD_DESCRIPTION
                          ),
                          SquadConfig(
                              name="squad_ordered_distractors",
                              data_url=SquadConfig._URLS,
                              n_distractors=9,
                              random_order=False,
                              features=features_qa,
                              citation=_SQUAD_CITATION,
                              url=SquadConfig._URL,
                              description=_SQUAD_DESCRIPTION
                          ),
                          HotpotQAConfig(
                              name=f"hotpotqa",
                              data_url=HotpotQAConfig._URL_BASE,
                              gold_passages='both',
                              distractors=False,
                              features=features_qa,
                              citation=_HOTPOTQA_CITATION,
                              url=HotpotQAConfig._HOMEPAGE,
                              description=_HOTPOTQA_DESCRIPTION
                          ),
                          HotpotQAConfig(
                              name=f"hotpotqa_second_only",
                              data_url=HotpotQAConfig._URL_BASE,
                              gold_passages='second',
                              distractors=False,
                              features=features_qa,
                              citation=_HOTPOTQA_CITATION,
                              url=HotpotQAConfig._HOMEPAGE,
                              description=_HOTPOTQA_DESCRIPTION
                          )]

    def _info(self):
        features = {feature: datasets.Value("string") for feature in self.config.features}

        return datasets.DatasetInfo(
            description=_SLED_DESCRIPTION + _SCROLLS_DESCRIPTION + self.config.description,
            features=datasets.Features(features),
            homepage=self.config.url,
            citation=self.config.citation + "\n" + _SCROLLS_CITATION + "\n" + _SLED_CITATION
        )

    def _scrolls_split_generators(self, dl_manager):
        dl_dir = dl_manager.download_and_extract(self.config.data_url)
        task_name = _get_task_name_from_data_url(self.config.data_url)
        dl_dir = os.path.join(dl_dir, task_name)

        data_files = {} if self.config.data_files is not None else None
        if data_files is not None:
            for split, paths in self.config.data_files.items():
                data_files[split] = paths[0]

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "data_file": os.path.join(dl_dir, "train.jsonl"),
                    "split": datasets.Split.TRAIN,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "data_file": os.path.join(dl_dir, "validation.jsonl"),
                    "split": datasets.Split.VALIDATION,
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "data_file": os.path.join(dl_dir, "test.jsonl") if data_files is None else data_files["test"],
                    "split": datasets.Split.TEST,
                },
            ),
        ]

    def _squad_split_generators(self, dl_manager):

        downloaded_files = dl_manager.download_and_extract(self.config.data_url)

        return [
            datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}),
            datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["dev"]}),
        ]

    def _hotpotqa_split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        paths = {
            datasets.Split.TRAIN: HotpotQAConfig._URL_BASE + "hotpot_train_v1.1.json",
            datasets.Split.VALIDATION: HotpotQAConfig._URL_BASE + "hotpot_dev_distractor_v1.json",
        }

        files = dl_manager.download(paths)

        split_generators = []
        for split in files:
            split_generators.append(datasets.SplitGenerator(name=split, gen_kwargs={"data_file": files[split]}))

        return split_generators

    def _split_generators(self, dl_manager):
        if 'squad' in self.config.name:
            return self._squad_split_generators(dl_manager)
        elif 'hotpotqa' in self.config.name:
            return self._hotpotqa_split_generators(dl_manager)
        else:
            return self._scrolls_split_generators(dl_manager)

    def _scrolls_gen(self, data_file, split):
        def prefix_splitter(line):
            row = json.loads(line)
            i = row['input'].find('\n\n')
            row['input'], row['input_prefix'] = row['input'][i + 2:], row['input'][:i]
            return row

        def get_quality_splitter(prefix_only):
            def quality_prefix_splitter(line):
                # quality has 4 answers, and they are also split by \n\n in scrolls, but not consistently
                row = json.loads(line)
                # using index rather then find to get an exception if we have a bad example
                inp = row['input']
                last_answer_idx = inp.index("(D)")
                context_start_ind = inp[last_answer_idx:].index("\n\n") + 1 + last_answer_idx
                row['input'], row['input_prefix'] = inp[context_start_ind+2:].strip(), row['input'][:context_start_ind].strip()
                if prefix_only:
                    row['input'] = ''
                return row
            return quality_prefix_splitter

        # if this is a dataset that should be treated as a qa dataset, choose the loader accordingly
        loader = (lambda line: json.loads(line)) if 'input_prefix' not in self.config.features else prefix_splitter
        if 'quality' in self.config.name:
            loader = get_quality_splitter(self.config.prefix_only)

        with open(data_file, encoding="utf-8") as f:
            for line in f:
                row = loader(line)

                if "quality" in self.config.name:
                    is_hard = row.pop("is_hard", False)
                    if self.config.hard_only and not is_hard:
                        continue

                yield row["pid"], row

    def _squad_gen(self, filepath, split):
        """This function returns the examples in the raw (text) form."""
        key = 0
        np.random.seed(42)
        random.seed(42)
        with open(filepath, encoding="utf-8") as f:
            squad = json.load(f)
            n_distractors = self.config.n_distractors
            random_order = self.config.random_order
            context_list = []
            if n_distractors > 0:
                context_list = [(paragraph["context"], article["title"]) for article in squad["data"] for paragraph in
                                article["paragraphs"]]
            for article in squad["data"]:
                title = article.get("title", "")
                for paragraph in article["paragraphs"]:
                    orig_context = paragraph["context"]  # do not strip leading blank spaces GH-2585
                    for qa in paragraph["qas"]:
                        # answer_starts = [answer["answer_start"] for answer in qa["answers"]]
                        # Due to usage of answer starts, we may have multiple positions with the same answer
                        # (exact value). To avoid redundant duplication of the answer, we take the unique set of answers
                        answers = list({answer["text"] for answer in qa["answers"]})
                        # train and validation gets the same treatment - splitting into multiple examples
                        for i, answer in enumerate(answers):  # generate multiple example
                            context = self._prepare_squad_context(orig_context, context_list, n_distractors,
                                                                  random_order, title, answers)
                            if n_distractors > 1:
                                assert len(context.split('\n\n')) == n_distractors+1
                            yield key, {
                                # In scrolls, id is based on the question+ context (i.e. input id), while pid is added a suffix
                                # enumerating the duplication, based on the answer. This duplication and enumeration happens both in
                                # train and validation
                                "pid": qa["id"] + f'_{i}',
                                "id": qa["id"],
                                "input": f"{context}".strip(),
                                'input_prefix': qa['question'].strip(),
                                "output": answer,  # does not give the answer start
                            }
                            key += 1

    def _prepare_squad_context(self, context, context_list, n_distractors, random_order, title, answers):
        if n_distractors > 0:
            n_iter = 0
            distractors = []
            pattern = re.compile('|'.join(f'(?:\\b{re.escape(answer)}\\b)' for answer in answers))
            for i in np.random.permutation(len(context_list)):
                distractor, dist_title = context_list[i]
                if dist_title == title:
                    continue
                # assert any(answer in distractor for answer in answers) == (len(pattern.findall(distractor)) > 0)
                # if any(answer in distractor for answer in answers):
                if len(pattern.findall(distractor)) > 0:
                    continue
                if distractor in distractors:
                    continue
                distractors.append(distractor)

                if len(distractors) == n_distractors:
                    break

                n_iter += 1
                if n_iter == 10:
                    raise RuntimeError('reached maximum attempts to create context distractors!')

            context = [context] + distractors
            if random_order:
                random.shuffle(context)
            context = '\n\n'.join(context)
        return context

    def _generate_examples(self, data_file=None, split=None, filepath=None):
        if 'squad' in self.config.name:
            gen = self._squad_gen(filepath, split)
        elif 'hotpotqa' in self.config.name:
            gen = self._hotpotqa_gen(data_file)
        else:
            gen = self._scrolls_gen(data_file, split)

        for key, row in gen:
            yield key, row

    def _hotpotqa_gen(self, data_file):
        """This function returns the examples."""
        data = json.load(open(data_file))

        for idx, example in enumerate(data):

            # Test set has missing keys
            for k in ["answer", "type", "level"]:
                if k not in example.keys():
                    example[k] = None

            gold_context_labels = list(
                dict.fromkeys([sf[0] for sf in example['supporting_facts']]))  # remove duplicates but keep order
            assert len(gold_context_labels) == 2
            context = {title: ' '.join(sentences) for title, sentences in example["context"]}
            gold_context_first = context.pop(gold_context_labels[0])
            gold_context_second = context.pop(gold_context_labels[1])
            distractors = list(context.values())

            if self.config.gold_passages == 'first':
                context = [gold_context_first]
            elif self.config.gold_passages == 'second':
                context = [gold_context_second]
            elif self.config.gold_passages == 'both':
                context = [gold_context_first, gold_context_second]
            else:
                raise NotImplementedError(f'Unknown gold context config: {self.config.gold_passages}')

            if self.config.distractors:
                context = context + distractors
                context = context[:9]  # so that we will always have only 9 passages
                random.shuffle(context)
            context = '\n\n'.join(context)

            # there is a single answer for each question
            yield idx, {
                "id": example["_id"],
                "pid": example["_id"] + '_0',
                "input": context,
                "input_prefix": example["question"],
                "output": example["answer"],
            }


def _get_task_name_from_data_url(data_url):
    return data_url.split("/")[-1].split(".")[0]