Update coqa.py
Browse files12345678910111213141516171819232056782110111213141516222324252619272829304 unmodified lines3536373839404142434431323334353637383940414243444546474849505152535455565758596061626364656667454669704748497273747576775051525354798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123555657585960616263646512512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416566676869707172737416716816917017175767778798081828384858617417517617717887888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.## 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."""CoQA dataset.
This `CoQA` adds the "additional_answers" feature that's missing in the originaldatasets version:https://github.com/huggingface/datasets/blob/master/datasets/coqa/coqa.py"""CoQA: A Conversational Question Answering Challengehttps://arxiv.org/pdf/1808.07042.pdf
CoQA is a large-scale dataset for building Conversational Question Answeringsystems. The goal of the CoQA challenge is to measure the ability of machines tounderstand a text passage and answer a series of interconnected questions thatappear in a conversation.
Homepage: https://stanfordnlp.github.io/coqa/"""import inspectimport transformers.data.metrics.squad_metrics as squad_metricsimport lm_eval.datasets.coqa.coqafrom lm_eval.base import Task, rf, meanfrom itertools import zip_longestimport json
import datasets
_CITATION = """_CITATION = """\@misc{reddy2018coqa, title={CoQA: A Conversational Question Answering Challenge}, author={Siva Reddy and Danqi Chen and Christopher D. Manning},4 unmodified lines}"""
_DESCRIPTION = """\CoQA is a large-scale dataset for building Conversational Question Answeringsystems. The goal of the CoQA challenge is to measure the ability of machines tounderstand a text passage and answer a series of interconnected questions thatappear in a conversation."""
class CoQA(Task): VERSION = 1 DATASET_PATH = inspect.getfile(lm_eval.datasets.coqa.coqa) DATASET_NAME = None
def has_training_docs(self): return True
def has_validation_docs(self): return True
def has_test_docs(self): return False
def training_docs(self): return self.dataset["train"]
def validation_docs(self): return self.dataset["validation"]
def test_docs(self): pass
def doc_to_text(self, doc): # Given a passage p, the conversation history {q1, a1, . . . qi−1, ai−1} # and a question qi, the task is to predict the answer ai doc_text = doc["story"] + "\n\n" for (q, a) in zip_longest( doc["questions"]["input_text"], doc["answers"]["input_text"][:-1] ): # omit target answer ai question = f"Q: {q}\n\n" answer = f"A: {a}\n\n" if a is not None else "A:" doc_text += question + answer return doc_text
def should_decontaminate(self): return True_HOMEPAGE = "https://stanfordnlp.github.io/coqa/"
def doc_to_decontamination_query(self, doc): return doc["story"] + " " + "\n".join(doc["questions"]["input_text"])# TODO: Add the licence for the dataset here if you can find it_LICENSE = ""
@classmethod def get_answers(cls, doc, turn_id): # Returns unique answers and valid alternatives (Some questions in CoQA have multiple valid answers). answers = [] answer_forturn = doc["answers"]["input_text"][turn_id - 1] answers.append(answer_forturn)_URLS = { "train": "https://nlp.stanford.edu/data/coqa/coqa-train-v1.0.json", "validation": "https://nlp.stanford.edu/data/coqa/coqa-dev-v1.0.json",}
additional_answers = doc.get("additional_answers") if additional_answers: for key in additional_answers: additional_answer_for_turn = additional_answers[key]["input_text"][ turn_id - 1 ] if additional_answer_for_turn.lower() not in map(str.lower, answers): answers.append(additional_answer_for_turn) return answers
@classmethod def get_answer_choice(self, raw_text): # Function maps answers to CoQA answer categories # ~ 1/5 of the CoQA answers are Yes/No # ~ 2/3 of the CoQA answers are span-based # (answers overlap with the passage ignoring punctuation and case mismatch) if raw_text == "unknown": return "0" if squad_metrics.normalize_answer(raw_text) == "yes": return "1" if squad_metrics.normalize_answer(raw_text) == "no": return "2" return "3" # Not a yes/no question
@staticmethod def compute_scores(gold_list, pred): # tests for exact match and on the normalised answer (compute_exact) # test for overlap (compute_f1) f1_sum = 0.0 em_sum = 0.0 if len(gold_list) > 1: for i in range(len(gold_list)): gold_answers = gold_list[0:i] + gold_list[i + 1 :] # predictions compared against (n) golds and take maximum em_sum += max( squad_metrics.compute_exact(a, pred) for a in gold_answers ) f1_sum += max(squad_metrics.compute_f1(a, pred) for a in gold_answers) else: em_sum += max(squad_metrics.compute_exact(a, pred) for a in gold_list) f1_sum += max(squad_metrics.compute_f1(a, pred) for a in gold_list)
return { "em": em_sum / max(1, len(gold_list)), "f1": f1_sum / max(1, len(gold_list)),# `additional_answers` are not available in the train set so we fill them with# empty dicts of the same form._EMPTY_ADDITIONAL_ANSWER = { "0": [ { "span_start": -1, "span_end": -1, "span_text": "", "input_text": "", "turn_id": -1, }
def doc_to_target(self, doc, turnid=None): # Default to prediction of last turn. if turnid is None: turnid = len(doc["questions"]["input_text"]) raw_text = doc["answers"]["input_text"][turnid - 1] return " " + raw_text
def construct_requests(self, doc, ctx): """Uses RequestFactory to construct Requests and returns an iterable of Requests which will be sent to the LM.
:param doc: The document as returned from training_docs, validation_docs, or test_docs. :param ctx: str The context string, generated by fewshot_context. This includes the natural language description, as well as the few shot examples, and the question part of the document for `doc`. """ cont_request = rf.greedy_until(ctx, {"until": ["\nQ:"]}) return cont_request
def process_results(self, doc, results): """Take a single document and the LM results and evaluates, returning a dict where keys are the names of submetrics and values are the values of the metric for that one document
:param doc: The document as returned from training_docs, validation_docs, or test_docs. :param results: The results of the requests created in construct_requests. """ turn_id = len(doc["questions"]["input_text"]) gold_list = self.get_answers(doc, turn_id) pred = results[0].strip().split("\n")[0]
scores = self.compute_scores(gold_list, pred)
return { "f1": scores["f1"], "em": scores["em"], ], "1": [ { "span_start": -1, "span_end": -1, "span_text": "", "input_text": "", "turn_id": -1, }
def higher_is_better(self): return { "f1": True, "em": True, ], "2": [ { "span_start": -1, "span_end": -1, "span_text": "", "input_text": "", "turn_id": -1, } ],}
def aggregation(self): return { "f1": mean, "em": mean, }
class Coqa(datasets.GeneratorBasedBuilder): """CoQA is a large-scale dataset for building Conversational Question Answering systems."""
VERSION = datasets.Version("0.0.1")
BUILDER_CONFIGS = [ datasets.BuilderConfig( name="coqa", version=VERSION, description="The CoQA dataset." ), ]
def _info(self): features = datasets.Features( { "id": datasets.Value("string"), "source": datasets.Value("string"), "story": datasets.Value("string"), "questions": datasets.features.Sequence( { "input_text": datasets.Value("string"), "turn_id": datasets.Value("int32"), } ), "answers": datasets.features.Sequence( { "span_start": datasets.Value("int32"), "span_end": datasets.Value("int32"), "span_text": datasets.Value("string"), "input_text": datasets.Value("string"), "turn_id": datasets.Value("int32"), } ), "additional_answers": { "0": datasets.features.Sequence( { "span_start": datasets.Value("int32"), "span_end": datasets.Value("int32"), "span_text": datasets.Value("string"), "input_text": datasets.Value("string"), "turn_id": datasets.Value("int32"), } ), "1": datasets.features.Sequence( { "span_start": datasets.Value("int32"), "span_end": datasets.Value("int32"), "span_text": datasets.Value("string"), "input_text": datasets.Value("string"), "turn_id": datasets.Value("int32"), } ), "2": datasets.features.Sequence( { "span_start": datasets.Value("int32"), "span_end": datasets.Value("int32"), "span_text": datasets.Value("string"), "input_text": datasets.Value("string"), "turn_id": datasets.Value("int32"), } ), }, } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, )
def _split_generators(self, dl_manager): urls = {"train": _URLS["train"], "validation": _URLS["validation"]} data_dirs = dl_manager.download_and_extract(urls) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": data_dirs["train"], "split": datasets.Split.TRAIN, }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": data_dirs["validation"], "split": datasets.Split.VALIDATION, }, ), ]
# method parameters are unpacked from `gen_kwargs` as given in `_split_generators` def _generate_examples(self, filepath, split): with open(filepath, encoding="utf-8") as f: data = json.load(f) for row in data["data"]: id = row["id"] source = row["source"] story = row["story"] questions = [ {"input_text": q["input_text"], "turn_id": q["turn_id"]} for q in row["questions"] ] answers = [ { "span_start": a["span_start"], "span_end": a["span_end"], "span_text": a["span_text"], "input_text": a["input_text"], "turn_id": a["turn_id"], } for a in row["answers"] ] if split == datasets.Split.TRAIN: additional_answers = _EMPTY_ADDITIONAL_ANSWER else: additional_answers = { "0": [ { "span_start": a0["span_start"], "span_end": a0["span_end"], "span_text": a0["span_text"], "input_text": a0["input_text"], "turn_id": a0["turn_id"], } for a0 in row["additional_answers"]["0"] ], "1": [ { "span_start": a1["span_start"], "span_end": a1["span_end"], "span_text": a1["span_text"], "input_text": a1["input_text"], "turn_id": a1["turn_id"], } for a1 in row["additional_answers"]["1"] ], "2": [ { "span_start": a2["span_start"], "span_end": a2["span_end"], "span_text": a2["span_text"], "input_text": a2["input_text"], "turn_id": a2["turn_id"], } for a2 in row["additional_answers"]["2"] ], } yield row["id"], { "id": id, "story": story, "source": source, "questions": questions, "answers": answers, "additional_answers": additional_answers, }coqa.py+222-155