|
|
|
|
|
"""Data for SLED, based on the SCROLLS benchmark.""" |
|
import itertools |
|
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 = """ |
|
27 @inproceedings{yang2018hotpotqa, |
|
28 title={{HotpotQA}: A Dataset for Diverse, Explainable Multi-hop Question Answering}, |
|
29 author={Yang, Zhilin and Qi, Peng and Zhang, Saizheng and Bengio, Yoshua and Cohen, William W. and Salakhutdinov, Ruslan and Manning, Christopher D.}, |
|
30 booktitle={Conference on Empirical Methods in Natural Language Processing ({EMNLP})}, |
|
31 year={2018} |
|
32 } |
|
""" |
|
|
|
|
|
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 |
|
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): |
|
|
|
row = json.loads(line) |
|
|
|
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 |
|
|
|
|
|
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"] |
|
for qa in paragraph["qas"]: |
|
|
|
|
|
|
|
answers = list({answer["text"] for answer in qa["answers"]}) |
|
|
|
for i, answer in enumerate(answers): |
|
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, { |
|
|
|
|
|
|
|
"pid": qa["id"] + f'_{i}', |
|
"id": qa["id"], |
|
"input": f"{context}".strip(), |
|
'input_prefix': qa['question'].strip(), |
|
"output": answer, |
|
} |
|
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 |
|
|
|
|
|
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): |
|
|
|
|
|
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']])) |
|
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] |
|
random.shuffle(context) |
|
context = '\n\n'.join(context) |
|
|
|
|
|
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] |
|
|