Datasets:

Tasks:
Other
Modalities:
Text
Formats:
parquet
Languages:
English
ArXiv:
Libraries:
Datasets
Dask
License:
P3 / P3.py
mariosasko's picture
Fix TypeError when loading some subsets (#12)
255b4bb
raw
history blame
10 kB
# coding=utf-8
# Copyright 2020 BigScience Contributors.
#
# 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.
"""P3 (Public Pool of Prompts)"""
import os
import google.protobuf as _protobuf # From: protobuf
import datasets
from ._tfrecord_example_pb2 import SequenceExample
from .io_utils import iterate_tfrecord_file, parse_tfrecord_sequence_example
from .tasks_splits_and_features import _TASK_SPLITS_AND_FEATURES_DICT
_CITATION = """@misc{sanh2021multitask,
title={Multitask Prompted Training Enables Zero-Shot Task Generalization},
author={Victor Sanh and Albert Webson and Colin Raffel and Stephen H. Bach and Lintang Sutawika and Zaid Alyafeai and Antoine Chaffin and Arnaud Stiegler and Teven Le Scao and Arun Raja and Manan Dey and M Saiful Bari and Canwen Xu and Urmish Thakker and Shanya Sharma Sharma and Eliza Szczechla and Taewoon Kim and Gunjan Chhablani and Nihal Nayak and Debajyoti Datta and Jonathan Chang and Mike Tian-Jian Jiang and Han Wang and Matteo Manica and Sheng Shen and Zheng Xin Yong and Harshit Pandey and Rachel Bawden and Thomas Wang and Trishala Neeraj and Jos Rozen and Abheesht Sharma and Andrea Santilli and Thibault Fevry and Jason Alan Fries and Ryan Teehan and Stella Biderman and Leo Gao and Tali Bers and Thomas Wolf and Alexander M. Rush},
year={2021},
eprint={2110.08207},
archivePrefix={arXiv},
primaryClass={cs.LG}
}"""
_DESCRIPTION = """\
P3 (Public Pool of Prompts) is a collection of prompted English datasets covering a diverse set of NLP tasks. A prompt is the combination of an input template and a target template. The templates are functions mapping a data example into natural language for the input and target sequences. For example, in the case of an NLI dataset, the data example would include fields for *Premise, Hypothesis, Label*. An input template would be *If {Premise} is true, is it also true that {Hypothesis}?*, whereas a target template can be defined with the label choices *Choices[label]*. Here *Choices* is prompt-specific metadata that consists of the options *yes, maybe, no* corresponding to *label* being entailment (0), neutral (1) or contradiction (2).
Prompts are collected using [Promptsource](https://github.com/bigscience-workshop/promptsource), an interface to interactively write prompts on datasets, and collect prompt-specific metadata such as evaluation metrics. As of October 13th, there are 2'000 prompts collected for 270+ data(sub)sets. The collection of prompts of P3 is publicly available on [Promptsource](https://github.com/bigscience-workshop/promptsource).
To train [T0*](https://huggingface.co/bigscience/T0pp), we used a subset of the prompts available in Promptsource (see details [here](https://huggingface.co/bigscience/T0pp#training-data)). However, some of the prompts use `random.choice`, a method that selects uniformly at random an option in a list of valid possibilities. For reproducibility purposes, we release the collection of prompted examples used to train T0*. **The data available here are the materialized version of the prompted datasets used in [Multitask Prompted Training Enables Zero-Shot Task Generalization](https://arxiv.org/abs/2110.08207) which represent only a subset of the datasets for which there is at least one prompt in Promptsource.**
"""
_LICENSE = "Apache License 2.0"
_HOMEPAGE = "https://github.com/bigscience-workshop/promptsource"
_DATA_PATH = "data"
logger = datasets.logging.get_logger(__name__)
_URLs = {
task_name: {
split_name: [
os.path.join(
_DATA_PATH, task_name, split_name + ".tfrecord-00000-of-00001"
), # TODO -> handle multiple shards
]
for split_name in splits_and_features_dict["splits"]
}
for task_name, splits_and_features_dict in _TASK_SPLITS_AND_FEATURES_DICT.items()
}
class P3Config(datasets.BuilderConfig):
"""BuilderConfig for P3."""
def __init__(self, splits, features_dict, score_eval, **kwargs):
"""BuilderConfig for P3.
Args:
splits: `List[str]`, the lists of splits which are available for this task
features_dict: `dict`, the dict of features for this task
score_eval: `bool`, whether this is task formulated as a rank classification problem
**kwargs: keyword arguments forwarded to super.
"""
# Version history:
# 0.1 initial commit
super(P3Config, self).__init__(version=datasets.Version("0.1.0"), **kwargs)
self.splits = splits
self.features_dict = features_dict
self.score_eval = score_eval
class P3(datasets.GeneratorBasedBuilder):
"""Subset of P3 used in `Multitask Prompted Training Enables Zero-Shot Task Generalization`"""
BUILDER_CONFIGS = [
P3Config(
name=task_name,
splits=splits_and_features_dict["splits"],
features_dict=splits_and_features_dict["features_dict"],
score_eval=task_name.endswith("score_eval"),
)
for task_name, splits_and_features_dict in _TASK_SPLITS_AND_FEATURES_DICT.items()
]
def _info(self):
# All features available are: 'inputs', 'inputs_pretokenized', 'targets',
# 'targets_pretokenized', 'idx', 'is_correct', 'weight', and 'answer_choices'
_FEAT_MAPPING = {
"answer_choices": datasets.Sequence(datasets.Value("string")),
"inputs": datasets.Sequence(datasets.Value("int32")),
"inputs_pretokenized": datasets.Value("string"),
"targets": datasets.Sequence(datasets.Value("int32")),
"targets_pretokenized": datasets.Value("string"),
"idx": datasets.Sequence(datasets.Value("int32")),
"weight": datasets.Value("float32"),
"is_correct": datasets.Value("bool"),
}
features = {feat_name: _FEAT_MAPPING[feat_name] for feat_name in self.config.features_dict.keys()}
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(features),
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
license=_LICENSE,
)
def _split_generators(self, dl_manager):
split_generators = []
data_dir = dl_manager.download(_URLs[self.config.name])
if "train" in self.config.splits:
split_name = "train"
split_generators.append(
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"tfrecord_files": data_dir[split_name],
},
)
)
if "validation" in self.config.splits:
split_name = "validation"
split_generators.append(
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"tfrecord_files": data_dir[split_name],
},
)
)
if "test" in self.config.splits:
split_name = "test"
split_generators.append(
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"tfrecord_files": data_dir[split_name],
},
)
)
# Handle splits that are not train, validation or test
special_splits = set(self.config.splits) - set(["train", "validation", "test"])
for special_split_name in special_splits:
split_generators.append(
datasets.SplitGenerator(
name=datasets.Split(special_split_name),
gen_kwargs={
"tfrecord_files": data_dir[special_split_name],
},
)
)
return split_generators
def _generate_examples(self, tfrecord_files):
"""This function returns the examples in the raw (text) form."""
_POST_PROC_FUNCTIONS = {
"answer_choices": lambda x: [choice.decode("utf-8") for choice in x],
"inputs": lambda x: x.tolist(),
"inputs_pretokenized": lambda x: x[0].decode("utf-8"),
"targets": lambda x: x.tolist(),
"targets_pretokenized": lambda x: x[0].decode("utf-8"),
"idx": lambda x: x.tolist(),
"weight": lambda x: float(x),
"is_correct": lambda x: x,
}
def _prepare_col_spec(shape, dtype):
if dtype in ("int32", "bool"):
# int32 and bool are stored as int64 in the tf.train.Example protobuf.
dtype = "int64"
elif dtype == "string":
dtype = "str"
if shape and shape[0] is None:
shape = (-1, *shape[1:])
return (shape, dtype)
spec = {k: _prepare_col_spec(**v) for k, v in self.config.features_dict.items()}
idx = 0
for tfrecord_file in tfrecord_files:
with open(tfrecord_file, "rb") as f:
for example_bytes in iterate_tfrecord_file(f):
example = SequenceExample()
example.ParseFromString(example_bytes)
example = parse_tfrecord_sequence_example(example, spec)
example = {k: _POST_PROC_FUNCTIONS[k](v) for k, v in example.items()}
yield idx, example
idx += 1