# coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Dynabench.QA""" from __future__ import absolute_import, division, print_function import json import os from collections import OrderedDict import datasets logger = datasets.logging.get_logger(__name__) _VERSION = datasets.Version("1.0.0") _NUM_ROUNDS = 1 _DESCRIPTION = """\ Dynabench.QA is a Reading Comprehension dataset collected using a human-and-model-in-the-loop. """.strip() class DynabenchRoundDetails: """Round details for DynabenchQA datasets.""" def __init__(self, citation, description, homepage, data_license, data_url, data_features, data_subset_map=None): self.citation = citation self.description = description self.homepage = homepage self.data_license = data_license self.data_url = data_url self.data_features = data_features self.data_subset_map = data_subset_map # Provide the details for each round _ROUND_DETAILS = { 1: DynabenchRoundDetails( citation="""\ @article{bartolo2020beat, author = {Bartolo, Max and Roberts, Alastair and Welbl, Johannes and Riedel, Sebastian and Stenetorp, Pontus}, title = {Beat the AI: Investigating Adversarial Human Annotation for Reading Comprehension}, journal = {Transactions of the Association for Computational Linguistics}, volume = {8}, number = {}, pages = {662-678}, year = {2020}, doi = {10.1162/tacl_a_00338}, URL = { https://doi.org/10.1162/tacl_a_00338 }, eprint = { https://doi.org/10.1162/tacl_a_00338 }, abstract = { Innovations in annotation methodology have been a catalyst for Reading Comprehension (RC) datasets and models. One recent trend to challenge current RC models is to involve a model in the annotation process: Humans create questions adversarially, such that the model fails to answer them correctly. In this work we investigate this annotation methodology and apply it in three different settings, collecting a total of 36,000 samples with progressively stronger models in the annotation loop. This allows us to explore questions such as the reproducibility of the adversarial effect, transfer from data collected with varying model-in-the-loop strengths, and generalization to data collected without a model. We find that training on adversarially collected samples leads to strong generalization to non-adversarially collected datasets, yet with progressive performance deterioration with increasingly stronger models-in-the-loop. Furthermore, we find that stronger models can still learn from datasets collected with substantially weaker models-in-the-loop. When trained on data collected with a BiDAF model in the loop, RoBERTa achieves 39.9F1 on questions that it cannot answer when trained on SQuAD—only marginally lower than when trained on data collected using RoBERTa itself (41.0F1). } } """.strip(), description="""\ Dynabench.QA is a Reading Comprehension dataset collected using a human-and-model-in-the-loop. Round 1 is the AdversarialQA dataset from Bartolo et al., 2020, and consists of questions posed by crowdworkers on a set of Wikipedia articles using an adversarial model-in-the-loop. We use three different models; BiDAF (Seo et al., 2016), BERT-Large (Devlin et al., 2018), and RoBERTa-Large (Liu et al., 2019) in the annotation loop and construct three datasets; D(BiDAF), D(BERT), and D(RoBERTa), each with 10,000 training examples, 1,000 validation, and 1,000 test examples. The adversarial human annotation paradigm ensures that these datasets consist of questions that current state-of-the-art models (at least the ones used as adversaries in the annotation loop) find challenging. For more details on the dataset construction process, see https://adversarialqa.github.io. """.strip(), homepage="https://dynabench.org/tasks/2", data_license="CC BY-SA 3.0", data_url="https://adversarialqa.github.io/data/aqa_v1.0.zip", data_features=datasets.Features( { "id": datasets.Value("string"), "title": datasets.Value("string"), "context": datasets.Value("string"), "question": datasets.Value("string"), "answers": datasets.features.Sequence( { "text": datasets.Value("string"), "answer_start": datasets.Value("int32"), } ), "metadata": { "split": datasets.Value("string"), "round": datasets.Value("int32"), "subset": datasets.Value("string"), "model_in_the_loop": datasets.Value("string"), }, } ), data_subset_map=OrderedDict({ "all": { "dir": "combined", "model": "Combined", }, "dbidaf": { "dir": "1_dbidaf", "model": "BiDAF", }, "dbert": { "dir": "2_dbert", "model": "BERT-Large", }, "droberta": { "dir": "3_droberta", "model": "RoBERTa-Large", }, }), ) } class DynabenchQAConfig(datasets.BuilderConfig): """BuilderConfig for DynabenchQA datasets.""" def __init__(self, round, subset='all', **kwargs): """BuilderConfig for Wikipedia. Args: round: integer, the dynabench round to load. subset: string, the subset of that round's data to load or 'all'. **kwargs: keyword arguments forwarded to super. """ assert isinstance(round, int), "round ({}) must be set and of type integer".format(round) assert 0 < round <= _NUM_ROUNDS, \ "round (received {}) must be between 1 and {}".format(round, _NUM_ROUNDS) super(DynabenchQAConfig, self).__init__( name="dynabench.qa.r{}.{}".format(round, subset), description="Dynabench QA dataset for round {}, showing dataset selection: {}.".format(round, subset), **kwargs, ) self.round = round self.subset = subset class DynabenchQA(datasets.GeneratorBasedBuilder): """Dynabench.QA""" BUILDER_CONFIG_CLASS = DynabenchQAConfig BUILDER_CONFIGS = [ DynabenchQAConfig( version=_VERSION, round=round, subset=subset, ) # pylint:disable=g-complex-comprehension for round in range(1, _NUM_ROUNDS+1) for subset in _ROUND_DETAILS[round].data_subset_map ] def _info(self): round_details = _ROUND_DETAILS[self.config.round] return datasets.DatasetInfo( description=round_details.description, features=round_details.data_features, homepage=round_details.homepage, citation=round_details.citation, supervised_keys=None, # No default supervised_keys (as we have to pass both question and context as input). ) @staticmethod def _get_filepath(dl_dir, round, subset, split): round_details = _ROUND_DETAILS[round] return os.path.join(dl_dir, round_details.data_subset_map[subset]["dir"], split + ".json") def _split_generators(self, dl_manager): round_details = _ROUND_DETAILS[self.config.round] dl_dir = dl_manager.download_and_extract(round_details.data_url) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": self._get_filepath(dl_dir, self.config.round, self.config.subset, "train"), "split": "train", "round": self.config.round, "subset": self.config.subset, "model_in_the_loop": round_details.data_subset_map[self.config.subset]["model"], }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "filepath": self._get_filepath(dl_dir, self.config.round, self.config.subset, "dev"), "split": "validation", "round": self.config.round, "subset": self.config.subset, "model_in_the_loop": round_details.data_subset_map[self.config.subset]["model"], }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "filepath": self._get_filepath(dl_dir, self.config.round, self.config.subset, "test"), "split": "test", "round": self.config.round, "subset": self.config.subset, "model_in_the_loop": round_details.data_subset_map[self.config.subset]["model"], }, ), ] def _generate_examples(self, filepath, split, round, subset, model_in_the_loop): """This function returns the examples in the raw (text) form.""" logger.info("generating examples from = %s", filepath) with open(filepath, encoding="utf-8") as f: squad = json.load(f) for article in squad["data"]: title = article.get("title", "").strip() for paragraph in article["paragraphs"]: context = paragraph["context"].strip() for qa in paragraph["qas"]: question = qa["question"].strip() id_ = qa["id"] answer_starts = [answer["answer_start"] for answer in qa["answers"]] answers = [answer["text"].strip() for answer in qa["answers"]] # Features currently used are "context", "question", and "answers". # Others are extracted here for the ease of future expansions. yield id_, { "title": title, "context": context, "question": question, "id": id_, "answers": { "answer_start": answer_starts, "text": answers, }, "metadata": { "split": split, "round": round, "subset": subset, "model_in_the_loop": model_in_the_loop }, }