VictorSanh
commited on
Commit
•
e3e6197
1
Parent(s):
11892f2
converging
Browse files- P3.py +59 -97
- print_data_split_sizes.py +30 -0
P3.py
CHANGED
@@ -16,9 +16,8 @@
|
|
16 |
|
17 |
|
18 |
import datasets
|
19 |
-
import glob
|
20 |
import json
|
21 |
-
import
|
22 |
from collections import defaultdict
|
23 |
import tensorflow as tf
|
24 |
|
@@ -27,7 +26,7 @@ _CITATION = """\
|
|
27 |
TODO"""
|
28 |
|
29 |
_DESCRIPTION = """\
|
30 |
-
P3 (
|
31 |
|
32 |
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 is publicly available on [Promptsource](https://github.com/bigscience-workshop/promptsource).
|
33 |
|
@@ -38,53 +37,11 @@ _LICENSE = "Apache License 2.0"
|
|
38 |
|
39 |
_HOMEPAGE = "https://github.com/bigscience-workshop/promptsource"
|
40 |
|
41 |
-
_DATA_PATH = "data"
|
42 |
-
|
43 |
-
|
44 |
-
# def load_cached_task(cache_dir, split):
|
45 |
-
# # TODO(Victor): this info.*.json is actually done twice... -> factorize
|
46 |
-
# with tf.io.gfile.GFile(os.path.join(cache_dir, f"info.{split}.json")) as f:
|
47 |
-
# split_info = json.load(f)
|
48 |
-
# features = split_info["features"]
|
49 |
-
|
50 |
-
# # Use `FixedLenSequenceFeature` for sequences with variable length.
|
51 |
-
# def _feature_config(shape, dtype):
|
52 |
-
# if dtype in ("int32", "bool"):
|
53 |
-
# # int32 and bool are stored as int64 in the tf.train.Example protobuf.
|
54 |
-
# dtype = "int64"
|
55 |
-
# if shape and shape[0] is None:
|
56 |
-
# return tf.io.FixedLenSequenceFeature(
|
57 |
-
# shape[1:], dtype, allow_missing=True
|
58 |
-
# )
|
59 |
-
# return tf.io.FixedLenFeature(shape, dtype)
|
60 |
-
|
61 |
-
# feature_description = {
|
62 |
-
# feat: _feature_config(**desc) for feat, desc in features.items()
|
63 |
-
# }
|
64 |
-
|
65 |
-
# tfrecords = os.path.join(
|
66 |
-
# cache_dir, f"{split}.tfrecord-*-of-*{split_info['num_shards']}"
|
67 |
-
# )
|
68 |
-
# ds = tf.data.TFRecordDataset(tf.io.gfile.glob(tfrecords))
|
69 |
-
# ds = ds.map(
|
70 |
-
# lambda pb: tf.io.parse_single_example(pb, feature_description),
|
71 |
-
# num_parallel_calls=tf.data.experimental.AUTOTUNE
|
72 |
-
# )
|
73 |
-
# # Cast features back to the types from the info JSON since some features
|
74 |
-
# # must be cast for storage (e.g., in32 is stored as int64).
|
75 |
-
# ds = ds.map(
|
76 |
-
# lambda x: {k: tf.cast(v, features[k]["dtype"]) for k, v in x.items()},
|
77 |
-
# num_parallel_calls=tf.data.experimental.AUTOTUNE
|
78 |
-
# )
|
79 |
-
# return ds
|
80 |
-
|
81 |
-
def load_cached_task(features_file, tfrecord):
|
82 |
-
# # TODO(Victor): this info.*.json is actually done twice... -> factorize
|
83 |
-
# with tf.io.gfile.GFile(os.path.join(cache_dir, f"info.{split}.json")) as f:
|
84 |
-
with tf.io.gfile.GFile(features_file) as f:
|
85 |
-
split_info = json.load(f)
|
86 |
-
features = split_info["features"]
|
87 |
|
|
|
|
|
88 |
# Use `FixedLenSequenceFeature` for sequences with variable length.
|
89 |
def _feature_config(shape, dtype):
|
90 |
if dtype in ("int32", "bool"):
|
@@ -97,81 +54,88 @@ def load_cached_task(features_file, tfrecord):
|
|
97 |
return tf.io.FixedLenFeature(shape, dtype)
|
98 |
|
99 |
feature_description = {
|
100 |
-
feat: _feature_config(**desc) for feat, desc in
|
101 |
}
|
102 |
|
103 |
-
ds = tf.data.TFRecordDataset(tf.io.gfile.glob([tfrecord]))
|
104 |
ds = ds.map(
|
105 |
lambda pb: tf.io.parse_single_example(pb, feature_description),
|
106 |
num_parallel_calls=tf.data.experimental.AUTOTUNE
|
107 |
)
|
108 |
# Cast features back to the types from the info JSON since some features
|
109 |
-
# must be cast for storage (e.g.,
|
110 |
ds = ds.map(
|
111 |
-
lambda x: {k: tf.cast(v,
|
112 |
num_parallel_calls=tf.data.experimental.AUTOTUNE
|
113 |
)
|
114 |
return ds
|
115 |
|
116 |
|
117 |
-
def
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
124 |
|
125 |
-
if not os.path.exists(f"{folder_path}/COMPLETED"):
|
126 |
-
continue
|
127 |
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
|
|
|
|
|
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
task_and_their_splits[task_name] = {
|
141 |
"splits": [],
|
142 |
-
"
|
143 |
}
|
|
|
|
|
144 |
|
145 |
-
|
146 |
-
if task_and_their_splits[task_name]["features"] == []:
|
147 |
-
task_and_their_splits[task_name]["features"] = sorted(list(features.keys()))
|
148 |
-
else:
|
149 |
-
assert task_and_their_splits[task_name]["features"] == sorted(list(features.keys()))
|
150 |
-
return task_and_their_splits
|
151 |
|
152 |
|
153 |
-
|
154 |
_URLs = {
|
155 |
task_name: {
|
156 |
split_name: {
|
157 |
"tfrecord": f"{_DATA_PATH}/{task_name}/{split_name}.tfrecord-00000-of-00001",
|
158 |
-
"features_file": f"{_DATA_PATH}/{task_name}/info.{split_name}.json",
|
159 |
}
|
160 |
-
for split_name in
|
161 |
}
|
162 |
-
for task_name,
|
163 |
}
|
164 |
|
165 |
|
166 |
class P3Config(datasets.BuilderConfig):
|
167 |
"""BuilderConfig for P3."""
|
168 |
|
169 |
-
def __init__(self, splits,
|
170 |
"""BuilderConfig for P3.
|
171 |
|
172 |
Args:
|
173 |
splits: `List[str]`, the lists of splits which are available for this task
|
174 |
-
|
175 |
score_eval: `bool`, whether this is task formulated as a rank classification problem
|
176 |
**kwargs: keyword arguments forwarded to super.
|
177 |
"""
|
@@ -179,7 +143,7 @@ class P3Config(datasets.BuilderConfig):
|
|
179 |
# 0.1 initial commit
|
180 |
super(P3Config, self).__init__(version=datasets.Version("0.1.0"), **kwargs)
|
181 |
self.splits = splits
|
182 |
-
self.
|
183 |
self.score_eval = score_eval
|
184 |
|
185 |
|
@@ -189,11 +153,11 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
189 |
BUILDER_CONFIGS = [
|
190 |
P3Config(
|
191 |
name=task_name,
|
192 |
-
splits=
|
193 |
-
|
194 |
score_eval=task_name.endswith("score_eval")
|
195 |
)
|
196 |
-
for task_name,
|
197 |
]
|
198 |
|
199 |
def _info(self):
|
@@ -211,7 +175,7 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
211 |
}
|
212 |
|
213 |
features = {}
|
214 |
-
for feat_name in self.config.
|
215 |
features[feat_name] = _FEAT_MAPPING[feat_name]
|
216 |
|
217 |
return datasets.DatasetInfo(
|
@@ -233,7 +197,6 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
233 |
datasets.SplitGenerator(
|
234 |
name=datasets.Split.TRAIN,
|
235 |
gen_kwargs={
|
236 |
-
"features_file": data_dir[task_name][split_name]["features_file"],
|
237 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
238 |
}
|
239 |
)
|
@@ -244,7 +207,6 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
244 |
datasets.SplitGenerator(
|
245 |
name=datasets.Split.VALIDATION,
|
246 |
gen_kwargs={
|
247 |
-
"features_file": data_dir[task_name][split_name]["features_file"],
|
248 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
249 |
}
|
250 |
)
|
@@ -255,7 +217,6 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
255 |
datasets.SplitGenerator(
|
256 |
name=datasets.Split.TEST,
|
257 |
gen_kwargs={
|
258 |
-
"features_file": data_dir[task_name][split_name]["features_file"],
|
259 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
260 |
}
|
261 |
)
|
@@ -267,7 +228,6 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
267 |
datasets.SplitGenerator(
|
268 |
name=datasets.Split(special_split_name),
|
269 |
gen_kwargs={
|
270 |
-
"features_file": data_dir[task_name][special_split_name]["features_file"],
|
271 |
"tfrecord": data_dir[task_name][special_split_name]["tfrecord"],
|
272 |
}
|
273 |
)
|
@@ -275,7 +235,7 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
275 |
return split_generators
|
276 |
|
277 |
|
278 |
-
def _generate_examples(self,
|
279 |
"""This function returns the examples in the raw (text) form."""
|
280 |
_FEAT_MAPPING_FUNCTIONS = {
|
281 |
"answer_choices": lambda x: [choice.decode("utf-8") for choice in x],
|
@@ -289,7 +249,9 @@ class P3(datasets.GeneratorBasedBuilder):
|
|
289 |
}
|
290 |
|
291 |
key = 0
|
292 |
-
|
|
|
|
|
293 |
for ex in ds.as_numpy_iterator():
|
294 |
ex_dict = {}
|
295 |
for feat_name, feat_value in ex.items():
|
|
|
16 |
|
17 |
|
18 |
import datasets
|
|
|
19 |
import json
|
20 |
+
import urllib
|
21 |
from collections import defaultdict
|
22 |
import tensorflow as tf
|
23 |
|
|
|
26 |
TODO"""
|
27 |
|
28 |
_DESCRIPTION = """\
|
29 |
+
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).
|
30 |
|
31 |
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 is publicly available on [Promptsource](https://github.com/bigscience-workshop/promptsource).
|
32 |
|
|
|
37 |
|
38 |
_HOMEPAGE = "https://github.com/bigscience-workshop/promptsource"
|
39 |
|
40 |
+
_DATA_PATH = "/home/hf/P3/data"
|
41 |
+
_HUB_PATH = "https://huggingface.co/datasets/bigscience/P3/raw/main"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
+
|
44 |
+
def load_cached_task(features_dict, tfrecord):
|
45 |
# Use `FixedLenSequenceFeature` for sequences with variable length.
|
46 |
def _feature_config(shape, dtype):
|
47 |
if dtype in ("int32", "bool"):
|
|
|
54 |
return tf.io.FixedLenFeature(shape, dtype)
|
55 |
|
56 |
feature_description = {
|
57 |
+
feat: _feature_config(**desc) for feat, desc in features_dict.items()
|
58 |
}
|
59 |
|
60 |
+
ds = tf.data.TFRecordDataset(tf.io.gfile.glob([tfrecord])) #TODO handle multiple shards
|
61 |
ds = ds.map(
|
62 |
lambda pb: tf.io.parse_single_example(pb, feature_description),
|
63 |
num_parallel_calls=tf.data.experimental.AUTOTUNE
|
64 |
)
|
65 |
# Cast features back to the types from the info JSON since some features
|
66 |
+
# must be cast for storage (e.g., int32 is stored as int64).
|
67 |
ds = ds.map(
|
68 |
+
lambda x: {k: tf.cast(v, features_dict[k]["dtype"]) for k, v in x.items()},
|
69 |
num_parallel_calls=tf.data.experimental.AUTOTUNE
|
70 |
)
|
71 |
return ds
|
72 |
|
73 |
|
74 |
+
def read_from_url(url):
|
75 |
+
# TODO: there might be a better way to handle these downloads (especially regarding caching).
|
76 |
+
# TODO: Ultimately, we should rely on the cache if internet is not available.
|
77 |
+
try:
|
78 |
+
content = urllib.request.urlopen(url, timeout=10.0)
|
79 |
+
except urllib.error.URLError as e:
|
80 |
+
raise ConnectionError(e)
|
81 |
+
return content.read().decode("utf-8")
|
82 |
|
|
|
|
|
83 |
|
84 |
+
def find_task_splits_and_features_dict():
|
85 |
+
"""Get the task available (list was pre-computed by `print_data_split_sizes.py`), and get the features for each task."""
|
86 |
+
task_splits_and_features = defaultdict(dict)
|
87 |
+
|
88 |
+
data = read_from_url(f"{_HUB_PATH}/data_split_sizes.csv")
|
89 |
+
data = [t.strip() for t in data.splitlines()]
|
90 |
+
data = data[1:]
|
91 |
+
data = [t.split("|") for t in data]
|
92 |
+
data = [(t[0], json.loads(t[1])) for t in data]
|
93 |
+
|
94 |
+
for task_name, split_sizes in data:
|
95 |
+
if "adversarial_qa" not in task_name: #TODO remove
|
96 |
+
continue
|
97 |
|
98 |
+
for split_name in split_sizes.keys():
|
99 |
+
split_info = json.loads(
|
100 |
+
read_from_url(
|
101 |
+
f"{_HUB_PATH}/data/{task_name}/info.{split_name}.json"
|
102 |
+
)
|
103 |
+
)
|
104 |
+
features_dict = split_info["features"]
|
105 |
+
assert split_info["num_shards"] == 1 #TODO -> change to multiple shards
|
106 |
|
107 |
+
if not task_splits_and_features[task_name]:
|
108 |
+
task_splits_and_features[task_name] = {
|
|
|
109 |
"splits": [],
|
110 |
+
"features_dict": features_dict,
|
111 |
}
|
112 |
+
task_splits_and_features[task_name]["splits"].append(split_name)
|
113 |
+
assert features_dict == task_splits_and_features[task_name]["features_dict"]
|
114 |
|
115 |
+
return task_splits_and_features
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
|
118 |
+
_TASK_SPLITS_AND_FEATURES_DICT = find_task_splits_and_features_dict()
|
119 |
_URLs = {
|
120 |
task_name: {
|
121 |
split_name: {
|
122 |
"tfrecord": f"{_DATA_PATH}/{task_name}/{split_name}.tfrecord-00000-of-00001",
|
|
|
123 |
}
|
124 |
+
for split_name in splits_and_features_dict["splits"]
|
125 |
}
|
126 |
+
for task_name, splits_and_features_dict in _TASK_SPLITS_AND_FEATURES_DICT.items()
|
127 |
}
|
128 |
|
129 |
|
130 |
class P3Config(datasets.BuilderConfig):
|
131 |
"""BuilderConfig for P3."""
|
132 |
|
133 |
+
def __init__(self, splits, features_dict, score_eval, **kwargs):
|
134 |
"""BuilderConfig for P3.
|
135 |
|
136 |
Args:
|
137 |
splits: `List[str]`, the lists of splits which are available for this task
|
138 |
+
features_dict: `dict`, the dict of features for this task
|
139 |
score_eval: `bool`, whether this is task formulated as a rank classification problem
|
140 |
**kwargs: keyword arguments forwarded to super.
|
141 |
"""
|
|
|
143 |
# 0.1 initial commit
|
144 |
super(P3Config, self).__init__(version=datasets.Version("0.1.0"), **kwargs)
|
145 |
self.splits = splits
|
146 |
+
self.features_dict = features_dict
|
147 |
self.score_eval = score_eval
|
148 |
|
149 |
|
|
|
153 |
BUILDER_CONFIGS = [
|
154 |
P3Config(
|
155 |
name=task_name,
|
156 |
+
splits=splits_and_features_dict["splits"],
|
157 |
+
features_dict=splits_and_features_dict["features_dict"],
|
158 |
score_eval=task_name.endswith("score_eval")
|
159 |
)
|
160 |
+
for task_name, splits_and_features_dict in _TASK_SPLITS_AND_FEATURES_DICT.items()
|
161 |
]
|
162 |
|
163 |
def _info(self):
|
|
|
175 |
}
|
176 |
|
177 |
features = {}
|
178 |
+
for feat_name in self.config.features_dict.keys():
|
179 |
features[feat_name] = _FEAT_MAPPING[feat_name]
|
180 |
|
181 |
return datasets.DatasetInfo(
|
|
|
197 |
datasets.SplitGenerator(
|
198 |
name=datasets.Split.TRAIN,
|
199 |
gen_kwargs={
|
|
|
200 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
201 |
}
|
202 |
)
|
|
|
207 |
datasets.SplitGenerator(
|
208 |
name=datasets.Split.VALIDATION,
|
209 |
gen_kwargs={
|
|
|
210 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
211 |
}
|
212 |
)
|
|
|
217 |
datasets.SplitGenerator(
|
218 |
name=datasets.Split.TEST,
|
219 |
gen_kwargs={
|
|
|
220 |
"tfrecord": data_dir[task_name][split_name]["tfrecord"],
|
221 |
}
|
222 |
)
|
|
|
228 |
datasets.SplitGenerator(
|
229 |
name=datasets.Split(special_split_name),
|
230 |
gen_kwargs={
|
|
|
231 |
"tfrecord": data_dir[task_name][special_split_name]["tfrecord"],
|
232 |
}
|
233 |
)
|
|
|
235 |
return split_generators
|
236 |
|
237 |
|
238 |
+
def _generate_examples(self, tfrecord):
|
239 |
"""This function returns the examples in the raw (text) form."""
|
240 |
_FEAT_MAPPING_FUNCTIONS = {
|
241 |
"answer_choices": lambda x: [choice.decode("utf-8") for choice in x],
|
|
|
249 |
}
|
250 |
|
251 |
key = 0
|
252 |
+
features_dict = self.config.features_dict
|
253 |
+
ds = load_cached_task(features_dict, tfrecord)
|
254 |
+
|
255 |
for ex in ds.as_numpy_iterator():
|
256 |
ex_dict = {}
|
257 |
for feat_name, feat_value in ex.items():
|
print_data_split_sizes.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import glob
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
|
5 |
+
from collections import defaultdict
|
6 |
+
|
7 |
+
_DATA_PATH = "data"
|
8 |
+
|
9 |
+
data_split_sizes = defaultdict(dict)
|
10 |
+
|
11 |
+
for stats in glob.glob(f"{_DATA_PATH}/*/stats.*.json"):
|
12 |
+
folder_path = os.path.dirname(stats)
|
13 |
+
task_name = folder_path.split("/")[-1]
|
14 |
+
split_name = os.path.basename(stats).split(".")[1]
|
15 |
+
|
16 |
+
if not os.path.exists(f"{folder_path}/COMPLETED"):
|
17 |
+
continue
|
18 |
+
|
19 |
+
with open(stats, "r") as f:
|
20 |
+
split_stats = json.load(f)
|
21 |
+
nb_examples = split_stats["examples"]
|
22 |
+
|
23 |
+
if nb_examples > 0:
|
24 |
+
data_split_sizes[task_name][split_name] = nb_examples
|
25 |
+
|
26 |
+
with open("data_split_sizes.csv", "w", encoding="utf=8") as f:
|
27 |
+
f.write("Data(sub)set|Number of examples per splits\n")
|
28 |
+
for task_name in sorted(list(data_split_sizes.keys())):
|
29 |
+
split_sizes_dict = json.dumps(data_split_sizes[task_name])
|
30 |
+
f.write(f"{task_name}|{split_sizes_dict}\n")
|