Datasets:
tau
/

Languages:
English
ArXiv:
Uri commited on
Commit
ee3ae9f
1 Parent(s): 5cc2cb7
metrics/accuracy.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ PATTERN = re.compile(r'\b[A-D]\b')
4
+
5
+
6
+ def find_answer(s):
7
+ match = PATTERN.search(s)
8
+ if match is None:
9
+ return None
10
+ return match.group()
11
+
12
+
13
+ def accuracy_score(prediction, ground_truth):
14
+ letter_ground_truth = find_answer(ground_truth)
15
+ assert letter_ground_truth in ["A", "B", "C", "D"], f"Invalid ground truth: {ground_truth}"
16
+ letter_prediction = find_answer(str(prediction))
17
+ return letter_prediction == letter_ground_truth
18
+
19
+
20
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
21
+ scores_for_ground_truths = []
22
+ for ground_truth in ground_truths:
23
+ score = metric_fn(prediction, ground_truth)
24
+ scores_for_ground_truths.append(score)
25
+ return max(scores_for_ground_truths)
26
+
27
+
28
+ def compute_accuracy(predictions, references):
29
+ accuracy = 0
30
+ for prediction, ground_truths in zip(predictions, references):
31
+ accuracy += metric_max_over_ground_truths(accuracy_score, prediction, ground_truths)
32
+ return 100.0 * accuracy / len(predictions)
metrics/concordance_index.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import string
3
+ from lifelines.utils import concordance_index
4
+
5
+
6
+ def keep_integers_commas_spaces(input_string):
7
+ cleaned_string = re.sub(r'[^0-9\s,]', '', str(input_string))
8
+ return cleaned_string
9
+
10
+
11
+ def normalize_answer(s):
12
+ """Lower text and remove punctuation, articles and extra whitespace."""
13
+
14
+ def remove_punc(text):
15
+ exclude = set(string.punctuation)
16
+ return "".join(ch for ch in text if ch not in exclude)
17
+
18
+ normalized_list = keep_integers_commas_spaces(s).replace(",", " ").strip(string.punctuation).split()
19
+ try:
20
+ normalized_list = [int(remove_punc(x).strip()) for x in normalized_list]
21
+ except ValueError:
22
+ return []
23
+ return normalized_list
24
+
25
+
26
+ def concordant_index_score(prediction, ground_truth):
27
+ normalized_prediction = normalize_answer(prediction)
28
+ normalized_ground_truth = normalize_answer(ground_truth)
29
+ if sorted(normalized_ground_truth) != sorted(normalized_prediction):
30
+ return 0.0
31
+
32
+ pred_order = summ_id_per_location_to_pos_of_id(normalized_prediction)
33
+ gold_order = summ_id_per_location_to_pos_of_id(normalized_ground_truth)
34
+
35
+ return concordance_index(gold_order, pred_order)
36
+
37
+
38
+ def summ_id_per_location_to_pos_of_id(id_per_location):
39
+ order = [-1] * len(id_per_location)
40
+ for i, id_ in enumerate(id_per_location, 1):
41
+ order[id_ - 1] = i
42
+ return order
43
+
44
+
45
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
46
+ scores_for_ground_truths = []
47
+ for ground_truth in ground_truths:
48
+ score = metric_fn(prediction, ground_truth)
49
+ scores_for_ground_truths.append(score)
50
+ return max(scores_for_ground_truths)
51
+
52
+
53
+ def compute_concordance_index(predictions, references):
54
+ concordant_index = 0
55
+ for prediction, ground_truths in zip(predictions, references):
56
+ concordant_index += metric_max_over_ground_truths(concordant_index_score, prediction, ground_truths)
57
+ return 100.0 * concordant_index / len(predictions)
metrics/exp_similarity.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ PATTERN = re.compile(r'\d+\.?\d*%')
4
+
5
+
6
+ def find_percentage(s):
7
+ match = PATTERN.search(s)
8
+ if match is None:
9
+ return None
10
+ return match.group(0)
11
+
12
+
13
+ def to_int(s):
14
+ percentage_string = find_percentage(s)
15
+ if percentage_string is None:
16
+ return None
17
+ percentage_string = percentage_string.replace("%", "")
18
+ percentage = float(percentage_string)
19
+ return percentage
20
+
21
+
22
+ def exp_similarity_score(prediction, ground_truth):
23
+ ground_truth_percentage = to_int(ground_truth)
24
+ pred_percentage = to_int(str(prediction))
25
+
26
+ if ground_truth_percentage is None:
27
+ raise ValueError(f"ground_truth_percentage is None: {ground_truth_percentage}")
28
+
29
+ if pred_percentage is None:
30
+ return 0.0
31
+
32
+ return 0.5 ** (abs(ground_truth_percentage - pred_percentage) / 10)
33
+
34
+
35
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
36
+ scores_for_ground_truths = []
37
+ for ground_truth in ground_truths:
38
+ score = metric_fn(prediction, ground_truth)
39
+ scores_for_ground_truths.append(score)
40
+ return max(scores_for_ground_truths)
41
+
42
+
43
+ def compute_exp_similarity(predictions, references):
44
+ exp_similarity = 0
45
+ for prediction, ground_truths in zip(predictions, references):
46
+ exp_similarity += metric_max_over_ground_truths(exp_similarity_score, prediction, ground_truths)
47
+ return 100 * exp_similarity / len(predictions)
metrics/f1.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/huggingface/datasets/blob/d3c7b9481d427ce41256edaf6773c47570f06f3b/metrics/squad/evaluate.py
2
+
3
+ import re
4
+ import string
5
+ from collections import Counter
6
+ from unidecode import unidecode
7
+
8
+
9
+ def normalize_answer(s):
10
+ """Lower text and remove punctuation, articles and extra whitespace."""
11
+
12
+ def remove_articles(text):
13
+ return re.sub(r"\b(a|an|the)\b", " ", text)
14
+
15
+ def white_space_fix(text):
16
+ return " ".join(text.split())
17
+
18
+ def remove_punc(text):
19
+ exclude = set(string.punctuation)
20
+ return "".join(ch for ch in text if ch not in exclude)
21
+
22
+ def lower(text):
23
+ return text.lower()
24
+
25
+ return unidecode(white_space_fix(remove_articles(remove_punc(lower(s)))))
26
+
27
+
28
+ def f1_score(prediction, ground_truth):
29
+ prediction_tokens = normalize_answer(prediction).split()
30
+ ground_truth_tokens = normalize_answer(ground_truth).split()
31
+ common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
32
+ num_same = sum(common.values())
33
+ if num_same == 0:
34
+ return 0
35
+ precision = 1.0 * num_same / len(prediction_tokens)
36
+ recall = 1.0 * num_same / len(ground_truth_tokens)
37
+ f1 = (2 * precision * recall) / (precision + recall)
38
+ return f1
39
+
40
+
41
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
42
+ scores_for_ground_truths = []
43
+ for ground_truth in ground_truths:
44
+ score = metric_fn(prediction, ground_truth)
45
+ scores_for_ground_truths.append(score)
46
+ return max(scores_for_ground_truths)
47
+
48
+
49
+ def compute_f1(predictions, references):
50
+ f1 = 0
51
+ for prediction, ground_truths in zip(predictions, references):
52
+ f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths)
53
+ return 100.0 * f1 / len(predictions)
metrics/rouge.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/huggingface/datasets/blob/d3c7b9481d427ce41256edaf6773c47570f06f3b/metrics/rouge/rouge.py
2
+ # Added multiprocessing
3
+
4
+ import multiprocessing
5
+ import nltk
6
+ from rouge_score import rouge_scorer
7
+ from multiprocessing import Pool
8
+
9
+
10
+ def compute_rouge(predictions, references, rouge_types=None, use_stemmer=False):
11
+ if rouge_types is None:
12
+ rouge_types = ["rouge1", "rouge2", "rougeL", "rougeLsum"]
13
+
14
+ scorer = rouge_scorer.RougeScorer(rouge_types=rouge_types, use_stemmer=use_stemmer)
15
+ with Pool() as p:
16
+ scores = p.starmap(scorer.score, zip(references, predictions))
17
+
18
+ result = {}
19
+ for key in scores[0]:
20
+ result[key] = list(score[key] for score in scores)
21
+
22
+ return result
23
+
24
+
25
+ # Copied from https://github.com/huggingface/transformers/blob/3977b58437b8ce1ea1da6e31747d888efec2419b/examples/pytorch/summarization/run_summarization.py#L520
26
+ def postprocess_text(text):
27
+ # rougeLSum expects newline after each sentence
28
+ return "\n".join(nltk.sent_tokenize(text))
metrics/zero_scrolls.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Zero-zero_scrolls benchmark metric. """
2
+
3
+ from collections import defaultdict
4
+ from copy import deepcopy
5
+ import datasets
6
+
7
+ # fmt: off
8
+ from .rouge import compute_rouge, \
9
+ postprocess_text as rouge_postprocess_text # From: https://huggingface.co/datasets/tau/zero_scrolls/raw/main/metrics/rouge.py
10
+ from .accuracy import \
11
+ compute_accuracy # From: https://huggingface.co/datasets/tau/zero_scrolls/raw/main/metrics/accuracy.py
12
+ from .f1 import compute_f1 # From: https://huggingface.co/datasets/tau/zero_scrolls/raw/main/metrics/f1.py
13
+ from .exp_similarity import \
14
+ compute_exp_similarity # From: https://huggingface.co/datasets/tau/zero_scrolls/raw/main/metrics/exp_similarity.py
15
+ from .concordance_index import \
16
+ compute_concordance_index # From: https://huggingface.co/datasets/tau/zero_scrolls/raw/main/metrics/concordance_index.py
17
+
18
+ # fmt: on
19
+
20
+ _CITATION = """
21
+ """
22
+
23
+ _DESCRIPTION = """
24
+ ZeroSCROLLS: Zero-Shot CompaRison Over Long Language Sequences.
25
+ A zero shot benchmark for long text reasoning.
26
+ https://zero.scrolls-benchmark.com/
27
+ """
28
+
29
+ _KWARGS_DESCRIPTION = """
30
+ Compute zero_scrolls evaluation metric associated to each zero_scrolls dataset.
31
+ Args:
32
+ predictions: list of predictions to score.
33
+ Each prediction should be a string.
34
+ references: list of lists of references for each example.
35
+ Each reference should be a string.
36
+ Returns: depending on the zero_scrolls subset, one or several of:
37
+ "accuracy": Accuracy score
38
+ "f1": F1 score
39
+ "rouge": ROUGE score
40
+ "exp_similarity": Exponential Similarity score
41
+ "concordance_index": Concordance Index score
42
+
43
+ Use the following code to download the metric:
44
+ ```
45
+ import os, shutil
46
+ from huggingface_hub import hf_hub_download
47
+ def download_metric():
48
+ zero_scrolls_metric_path = hf_hub_download(repo_id="tau/zero_scrolls", repo_type="dataset", filename="metrics/zero_scrolls.py")
49
+ updated_zero_scrolls_metric_path = (
50
+ os.path.dirname(zero_scrolls_metric_path) + os.path.basename(zero_scrolls_metric_path).replace(".", "_") + ".py"
51
+ )
52
+ shutil.copy(zero_scrolls_metric_path, updated_zero_scrolls_metric_path)
53
+ return updated_zero_scrolls_metric_path
54
+
55
+ zero_scrolls_metric_path = download_metric()
56
+ ```
57
+
58
+ Examples:
59
+
60
+ >>> predictions = ["hello there", "general kenobi"] # List[str]
61
+ >>> references = [["hello", "hi there"], ["commander kenobi"]] # List[List[str]]
62
+ >>> zero_scrolls_metric = datasets.load_metric(zero_scrolls_metric_path, 'gov_report') # "gov_report" or "summ_screen_fd" or "qmsum" or "squality]
63
+ >>> results = zero_scrolls_metric.compute(predictions=predictions, references=references)
64
+ >>> print(results)
65
+ {'rouge/rouge1': 72.2222, 'rouge/rouge2': 33.3333, 'rouge/rougeL': 72.2222, 'rouge/rougeLsum': 72.2222, 'rouge/geometric_mean': 55.8136,
66
+ 'num_predicted': 3, 'mean_prediction_length_characters': 14.6667, 'zero_scrolls_score': 55.8136,
67
+ 'display_keys': ['rouge/rouge1', 'rouge/rouge2', 'rouge/rougeL'], 'display': [72.2222, 33.3333, 72.2222]}
68
+
69
+ >>> zero_scrolls_metric = datasets.load_metric(zero_scrolls_metric_path, 'narrative_qa') # "qasper" or "narrative_qa" or "musique"
70
+ >>> results = zero_scrolls_metric.compute(predictions=predictions, references=references)
71
+ >>> print(results)
72
+ {'f1': 72.2222, 'num_predicted': 3, 'mean_prediction_length_characters': 14.6667, 'zero_scrolls_score': 72.2222,
73
+ 'display_keys': ['f1'], 'display': [72.2222]}
74
+
75
+ >>> predictions = ["The answer is (B)", "D", "A"] # List[str]
76
+ >>> references = [["B"], ["C"], ["C"]] # List[List[str]]
77
+ >>> zero_scrolls_metric = datasets.load_metric(zero_scrolls_metric_path, 'quality')
78
+ >>> results = zero_scrolls_metric.compute(predictions=predictions, references=references)
79
+ >>> print(results)
80
+ {'accuracy': 33.3333, 'num_predicted': 3, 'mean_prediction_length_characters': 6.3333, 'zero_scrolls_score': 33.3333, 'display_keys': ['accuracy'], 'display': [33.3333]}
81
+ 'display_keys': ['accuracy'], 'display': [33.3333]}
82
+
83
+ >>> predictions = ["Answer: 4,1,2,3", "2,4,5,4,1"] # List[str]
84
+ >>> references = [["1,2,3,4"], ["5,3,2,1,4"]] # List[List[str]]
85
+ >>> zero_scrolls_metric = datasets.load_metric(zero_scrolls_metric_path, 'book_sum_sort')
86
+ >>> results = zero_scrolls_metric.compute(predictions=predictions, references=references)
87
+ >>> print(results)
88
+ {'concordance_index': 25.0, 'num_predicted': 2, 'mean_prediction_length_characters': 12.0, 'zero_scrolls_score': 25.0, 'display_keys': ['concordance_index'], 'display': [25.0]}
89
+
90
+ >>> predictions = ["There are 30% positive reviews", "25%"] # List[str]
91
+ >>> references = [["40%"], ["82%"]] # List[List[str]]
92
+ >>> zero_scrolls_metric = datasets.load_metric(zero_scrolls_metric_path, 'space_digest')
93
+ >>> results = zero_scrolls_metric.compute(predictions=predictions, references=references)
94
+ >>> print(results)
95
+ {'exp_similarity': 25.9618, 'num_predicted': 2, 'mean_prediction_length_characters': 16.5, 'zero_scrolls_score': 25.9618, 'display_keys': ['exp_similarity'], 'display': [25.9618]}
96
+ """
97
+
98
+ DATASET_TO_METRICS = {
99
+ "gov_report": {
100
+ "metrics_to_compute": ["rouge"],
101
+ "zero_scrolls_score_key": "rouge/geometric_mean",
102
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
103
+ },
104
+ "narrative_qa": {
105
+ "metrics_to_compute": ["f1"],
106
+ "zero_scrolls_score_key": "f1",
107
+ "display_keys": ["f1"],
108
+ },
109
+ "qasper": {
110
+ "metrics_to_compute": ["f1"],
111
+ "zero_scrolls_score_key": "f1",
112
+ "display_keys": ["f1"],
113
+ },
114
+ "qmsum": {
115
+ "metrics_to_compute": ["rouge"],
116
+ "zero_scrolls_score_key": "rouge/geometric_mean",
117
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
118
+ },
119
+ "summ_screen_fd": {
120
+ "metrics_to_compute": ["rouge"],
121
+ "zero_scrolls_score_key": "rouge/geometric_mean",
122
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
123
+ },
124
+ "quality": {
125
+ "metrics_to_compute": ["accuracy"],
126
+ "zero_scrolls_score_key": "accuracy",
127
+ "display_keys": ["accuracy"],
128
+ },
129
+ "quality_hard": {
130
+ "metrics_to_compute": ["accuracy"],
131
+ "zero_scrolls_score_key": None,
132
+ "display_keys": ["accuracy"],
133
+ },
134
+ "squality": {
135
+ "metrics_to_compute": ["rouge"],
136
+ "zero_scrolls_score_key": "rouge/geometric_mean",
137
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
138
+ },
139
+ "musique": {
140
+ "metrics_to_compute": ["f1"],
141
+ "zero_scrolls_score_key": "f1",
142
+ "display_keys": ["f1"],
143
+ },
144
+ "space_digest": {
145
+ "metrics_to_compute": ["exp_similarity"],
146
+ "zero_scrolls_score_key": "exp_similarity",
147
+ "display_keys": ["exp_similarity"],
148
+ },
149
+ "book_sum_sort": {
150
+ "metrics_to_compute": ["concordance_index"],
151
+ "zero_scrolls_score_key": "concordance_index",
152
+ "display_keys": ["concordance_index"],
153
+ },
154
+ }
155
+
156
+
157
+ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
158
+ class ZeroScrolls(datasets.Metric):
159
+ def __init__(self, *args, **kwargs):
160
+ super().__init__(*args, **kwargs)
161
+
162
+ self._compute_helper_kwargs_fn = {
163
+ "rouge": lambda: {
164
+ "metric_fn": compute_rouge,
165
+ "agg_fn": max,
166
+ "metric_fn_kwargs": {"use_stemmer": False},
167
+ "metric_returns_per_example": True,
168
+ "transform_single_input_fn": lambda text: rouge_postprocess_text(text),
169
+ "transform_result_fn": lambda output: {
170
+ key: (value[0] if isinstance(value, list) else value).fmeasure * 100
171
+ for key, value in output.items()
172
+ },
173
+ "transform_aggregated_result_fn": lambda output: output.update(
174
+ {"geometric_mean": (output["rouge1"] * output["rouge2"] * output["rougeL"]) ** (1.0 / 3.0)}
175
+ )
176
+ or output,
177
+ },
178
+ "accuracy": lambda: {
179
+ "metric_fn": compute_accuracy,
180
+ "agg_fn": None, # compute_accuracy already takes max
181
+ "transform_result_fn": lambda output: {None: output},
182
+ },
183
+ "f1": lambda: {
184
+ "metric_fn": compute_f1,
185
+ "agg_fn": None, # compute_f1 already takes max
186
+ "transform_result_fn": lambda output: {None: output},
187
+ },
188
+ "exp_similarity": lambda: {
189
+ "metric_fn": compute_exp_similarity,
190
+ "agg_fn": None, # compute_exp_similarity already takes max
191
+ "transform_result_fn": lambda output: {None: output},
192
+ },
193
+ "concordance_index": lambda: {
194
+ "metric_fn": compute_concordance_index,
195
+ "agg_fn": None, # compute_concordance_index already takes max
196
+ "transform_result_fn": lambda output: {None: output},
197
+ },
198
+ }
199
+
200
+ custom_metrics = (
201
+ [metric for metric in self.config_name.split(",") if len(metric) > 0]
202
+ if self.config_name.startswith(",")
203
+ else None
204
+ )
205
+ if custom_metrics is not None:
206
+ for metric in custom_metrics:
207
+ if metric not in self._compute_helper_kwargs_fn:
208
+ raise KeyError(
209
+ f"You should supply a metric name selected in {list(self._compute_helper_kwargs_fn.keys())}"
210
+ )
211
+ self._metrics_to_compute = custom_metrics
212
+ else:
213
+ if self.config_name not in DATASET_TO_METRICS:
214
+ raise KeyError(f"You should supply a configuration name selected in {list(DATASET_TO_METRICS.keys())}")
215
+ self._metrics_to_compute = DATASET_TO_METRICS[self.config_name]["metrics_to_compute"]
216
+
217
+ def _info(self):
218
+ return datasets.MetricInfo(
219
+ description=_DESCRIPTION,
220
+ citation=_CITATION,
221
+ inputs_description=_KWARGS_DESCRIPTION,
222
+ features=datasets.Features(
223
+ {
224
+ "predictions": datasets.Value("string"),
225
+ "references": datasets.Sequence(datasets.Value("string")),
226
+ }
227
+ ),
228
+ codebase_urls=[],
229
+ reference_urls=[],
230
+ )
231
+
232
+ def convert_from_map_format(self, id_to_pred, id_to_labels):
233
+ index_to_id = list(id_to_pred.keys())
234
+ predictions = [id_to_pred[id_] for id_ in index_to_id]
235
+ references = [id_to_labels[id_] for id_ in index_to_id]
236
+ return {"predictions": predictions, "references": references}
237
+
238
+ def _compute(self, predictions, references):
239
+ metrics = {}
240
+ for metric in self._metrics_to_compute:
241
+ result = _compute_helper(
242
+ deepcopy(predictions),
243
+ deepcopy(references),
244
+ **self._compute_helper_kwargs_fn[metric](),
245
+ )
246
+ metrics.update(
247
+ {(f"{metric}/{key}" if key is not None else metric): value for key, value in result.items()}
248
+ )
249
+ metrics["num_predicted"] = len(predictions)
250
+ prediction_lengths = [len(prediction) for prediction in predictions]
251
+ metrics["mean_prediction_length_characters"] = sum(prediction_lengths) / len(prediction_lengths)
252
+
253
+ metrics = {key: round(value, 4) for key, value in metrics.items()}
254
+
255
+ if self.config_name in DATASET_TO_METRICS:
256
+ zero_scrolls_score_key = DATASET_TO_METRICS[self.config_name]["zero_scrolls_score_key"]
257
+ if zero_scrolls_score_key is not None:
258
+ metrics["zero_scrolls_score"] = metrics[zero_scrolls_score_key]
259
+ else:
260
+ metrics["zero_scrolls_score"] = None
261
+
262
+ display_keys = DATASET_TO_METRICS[self.config_name]["display_keys"]
263
+ metrics["display_keys"] = display_keys
264
+ metrics["display"] = []
265
+ for display_key in display_keys:
266
+ metrics["display"].append(metrics[display_key])
267
+
268
+ return metrics
269
+
270
+
271
+ def _compute_helper(
272
+ predictions,
273
+ references,
274
+ metric_fn,
275
+ agg_fn,
276
+ metric_fn_kwargs=None,
277
+ transform_single_input_fn=None,
278
+ transform_result_fn=None,
279
+ transform_aggregated_result_fn=None,
280
+ metric_returns_per_example=False,
281
+ ):
282
+ if metric_fn_kwargs is None:
283
+ metric_fn_kwargs = {}
284
+
285
+ if agg_fn is None:
286
+ assert metric_returns_per_example is False
287
+
288
+ if transform_single_input_fn is not None:
289
+ predictions = [transform_single_input_fn(prediction) for prediction in predictions]
290
+ references = [
291
+ [transform_single_input_fn(reference) for reference in reference_list] for reference_list in references
292
+ ]
293
+
294
+ if transform_result_fn is None:
295
+ transform_result_fn = lambda x: x
296
+ do_transform_result = False
297
+ else:
298
+ do_transform_result = True
299
+
300
+ if transform_aggregated_result_fn is None:
301
+ transform_aggregated_result_fn = lambda x: x
302
+
303
+ if agg_fn is not None:
304
+ # Required when the metric doesn't do the aggregation we need
305
+ scores = defaultdict(list)
306
+ if metric_returns_per_example is False:
307
+ # If when given a list of prediction and references the metric returns an aggregated score,
308
+ # we need to compute the metric for each prediction and reference and then aggregate the results.
309
+ # This is only an issue when we want to get the best aggregated score (e.g. max) for prediction
310
+ # with multiple references.
311
+ for prediction, reference_list in zip(predictions, references):
312
+ prediction_scores = defaultdict(list)
313
+ for reference in reference_list:
314
+ result = transform_result_fn(metric_fn([prediction], [reference], **metric_fn_kwargs))
315
+ for key in result:
316
+ prediction_scores[key].append(result[key])
317
+ for key in prediction_scores:
318
+ scores[key].append(agg_fn(prediction_scores[key]))
319
+ else:
320
+ # Flatten the references and then aggregate per prediction with agg_fn
321
+ mapping = [[] for _ in range(len(predictions))]
322
+ flattened_predictions = []
323
+ flattened_references = []
324
+ for i, prediction in enumerate(predictions):
325
+ for reference in references[i]:
326
+ flattened_predictions.append(prediction)
327
+ flattened_references.append(reference)
328
+ mapping[i].append(len(flattened_references) - 1)
329
+
330
+ results = metric_fn(flattened_predictions, flattened_references, **metric_fn_kwargs)
331
+ if isinstance(results, dict):
332
+ # Convert a dictionary with lists per key to a list with dictionary with the same keys per element
333
+ results_list = [{k: None for k in results} for _ in range(len(flattened_predictions))]
334
+ for k, v in results.items():
335
+ for i in range(len(v)):
336
+ results_list[i][k] = v[i]
337
+ else:
338
+ results_list = results
339
+
340
+ if do_transform_result:
341
+ for i in range(len(results_list)):
342
+ results_list[i] = transform_result_fn(results_list[i])
343
+
344
+ for reference_indexes in mapping:
345
+ prediction_scores = defaultdict(list)
346
+ for reference_index in reference_indexes:
347
+ result = results_list[reference_index]
348
+ for key in result:
349
+ prediction_scores[key].append(result[key])
350
+ for key in prediction_scores:
351
+ scores[key].append(agg_fn(prediction_scores[key]))
352
+
353
+ return transform_aggregated_result_fn({key: sum(value) / len(value) for key, value in scores.items()})
354
+ else:
355
+ return transform_aggregated_result_fn(
356
+ transform_result_fn(metric_fn(predictions, references, **metric_fn_kwargs))
357
+ )
zero_scrolls.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Lint as: python3
3
+ """The Zero-SCROLLS benchmark."""
4
+
5
+ import json
6
+ import os
7
+ import datasets
8
+
9
+ _ZERO_SCROLLS_CITATION = """
10
+
11
+ Note that each ZeroSCROLLS task has its own citation. Please see the source to
12
+ get the correct citation for each one.
13
+ """
14
+
15
+ _ZERO_SCROLLS_DESCRIPTION = """
16
+ ZeroSCROLLS: Zero-Shot CompaRison Over Long Language Sequences.
17
+ A zero shot benchmark for long text reasoning.
18
+ https://zero.scrolls-benchmark.com/
19
+ """
20
+
21
+ _SCROLLS_CITATION = """
22
+ @misc{shaham2022scrolls,
23
+ title={SCROLLS: Standardized CompaRison Over Long Language Sequences},
24
+ 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},
25
+ year={2022},
26
+ eprint={2201.03533},
27
+ archivePrefix={arXiv},
28
+ primaryClass={cs.CL}
29
+ }
30
+ """
31
+
32
+ _SCROLLS_DESCRIPTION = """
33
+ SCROLLS: Standardized CompaRison Over Long Language Sequences.
34
+ A suite of natural language datasets that require reasoning over long texts.
35
+ https://scrolls-benchmark.com/
36
+ """
37
+
38
+ _SUMM_SCREEN_DESCRIPTION = """
39
+ SummScreenFD (Chen et al., 2021) is a summarization dataset in the domain of TV shows (e.g. Friends, Game of Thrones).
40
+ Given a transcript of a specific episode, the goal is to produce the episode's recap.
41
+ The original dataset is divided into two complementary subsets, based on the source of its community contributed transcripts.
42
+ For SCROLLS, we use the ForeverDreaming (FD) subset, as it incorporates 88 different shows,
43
+ making it a more diverse alternative to the TV MegaSite (TMS) subset, which has only 10 shows.
44
+ Community-authored recaps for the ForeverDreaming transcripts were collected from English Wikipedia and TVMaze."""
45
+
46
+ _QASPER_DESCRIPTION = """
47
+ Qasper (Dasigi et al., 2021) is a question answering dataset over NLP papers filtered from the Semantic Scholar Open Research Corpus (S2ORC).
48
+ Questions were written by NLP practitioners after reading only the title and abstract of the papers,
49
+ while another set of NLP practitioners annotated the answers given the entire document.
50
+ Qasper contains abstractive, extractive, and yes/no questions, as well as unanswerable ones."""
51
+
52
+ _QMSUM_DESCRIPTION = """
53
+ QMSum (Zhong et al., 2021) is a query-based summarization dataset, consisting of 232 meetings transcripts from multiple domains.
54
+ The corpus covers academic group meetings at the International Computer Science Institute and their summaries, industrial product meetings for designing a remote control,
55
+ and committee meetings of the Welsh and Canadian Parliaments, dealing with a variety of public policy issues.
56
+ Annotators were tasked with writing queries about the broad contents of the meetings, as well as specific questions about certain topics or decisions,
57
+ while ensuring that the relevant text for answering each query spans at least 200 words or 10 turns."""
58
+
59
+ _NARRATIVE_QA_DESCRIPTION = """
60
+ NarrativeQA (Kočiský et al., 2021) is an established question answering dataset over entire books from Project Gutenberg and movie scripts from different websites.
61
+ Annotators were given summaries of the books and scripts obtained from Wikipedia, and asked to generate question-answer pairs,
62
+ resulting in about 30 questions and answers for each of the 1,567 books and scripts.
63
+ They were encouraged to use their own words rather then copying, and avoid asking yes/no questions or ones about the cast.
64
+ Each question was then answered by an additional annotator, providing each question with two reference answers (unless both answers are identical).."""
65
+
66
+ _GOV_REPORT_DESCRIPTION = """
67
+ GovReport (Huang et al., 2021) is a summarization dataset of reports addressing various national policy issues published by the
68
+ Congressional Research Service and the U.S. Government Accountability Office, where each document is paired with a hand-written executive summary.
69
+ The reports and their summaries are longer than their equivalents in other popular long-document summarization datasets;
70
+ for example, GovReport's documents are approximately 1.5 and 2.5 times longer than the documents in Arxiv and PubMed, respectively."""
71
+
72
+ _QUALITY_DESCRIPTION = """
73
+ QuALITY (Pang et al., 2022) is a multiple-choice question answering dataset over articles and stories sourced from Project Gutenberg,
74
+ the Open American National Corpus, and more.
75
+ Experienced writers wrote questions and distractors, and were incentivized to write answerable, unambiguous questions such that in order to correctly answer them,
76
+ human annotators must read large portions of the given document.
77
+ Reference answers were then calculated using the majority vote between of the annotators and writer's answers.
78
+ To measure the difficulty of their questions, Pang et al. conducted a speed validation process,
79
+ where another set of annotators were asked to answer questions given only a short period of time to skim through the document.
80
+ 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."""
81
+
82
+ _SQUALITY_DESCRIPTION = """
83
+ SQuALITY (Wang et al., 2022) is a question-focused summarization dataset, where given a story from Project Gutenberg,
84
+ the task is to produce a summary of the story or aspects of it based on a guiding question.
85
+ The questions and summaries are original and crowdsourced; experienced writers were guided to design questions that require reading significant parts of the story to answer correctly.
86
+ """
87
+
88
+ _MUSIQUE_DESCRIPTION = """
89
+ MuSiQue (Trivedi et al,. 2022) is a multi-hop question answering dataset, where the inputs are 20 Wikipedia paragraphs and a question that requires multiple hops between different paragraphs.
90
+ In the original dataset, each question also has an unanswerable twin question, where the correct answer is not present in the paragraphs.
91
+ """
92
+
93
+ _SPACE_DIGEST_DESCRIPTION = """
94
+ SpaceDigest is a new sentiment aggregation task.
95
+ Given 50 hotel reviews (without their ratings) from the Space dataset (Angelidis et al., 2021), the task is to determine the percentage of positive reviews.
96
+ """
97
+
98
+ _BOOK_SUM_DESCRIPTION = """
99
+ BookSumSort is a new task based on the BookSum dataset (Kry ́sci ́nski et al., 2021), which contains summaries of chapters (or parts) of novels, plays, and long poems from various sources.
100
+ Given a shuffled list of chapter summaries, the task is to reorder them according to the original order of summaries in BookSum.
101
+ """
102
+
103
+ _SUMM_SCREEN_CITATION = r"""
104
+ @inproceedings{chen-etal-2022-summscreen,
105
+ title = "{S}umm{S}creen: A Dataset for Abstractive Screenplay Summarization",
106
+ author = "Chen, Mingda and
107
+ Chu, Zewei and
108
+ Wiseman, Sam and
109
+ Gimpel, Kevin",
110
+ booktitle = "Proceedings of the 60th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
111
+ month = may,
112
+ year = "2022",
113
+ address = "Dublin, Ireland",
114
+ publisher = "Association for Computational Linguistics",
115
+ url = "https://aclanthology.org/2022.acl-long.589",
116
+ doi = "10.18653/v1/2022.acl-long.589",
117
+ pages = "8602--8615",
118
+ abstract = "We introduce SummScreen, a summarization dataset comprised of pairs of TV series transcripts and human written recaps. The dataset provides a challenging testbed for abstractive summarization for several reasons. Plot details are often expressed indirectly in character dialogues and may be scattered across the entirety of the transcript. These details must be found and integrated to form the succinct plot descriptions in the recaps. Also, TV scripts contain content that does not directly pertain to the central plot but rather serves to develop characters or provide comic relief. This information is rarely contained in recaps. Since characters are fundamental to TV series, we also propose two entity-centric evaluation metrics. Empirically, we characterize the dataset by evaluating several methods, including neural models and those based on nearest neighbors. An oracle extractive approach outperforms all benchmarked models according to automatic metrics, showing that the neural models are unable to fully exploit the input transcripts. Human evaluation and qualitative analysis reveal that our non-oracle models are competitive with their oracle counterparts in terms of generating faithful plot events and can benefit from better content selectors. Both oracle and non-oracle models generate unfaithful facts, suggesting future research directions.",
119
+ }"""
120
+
121
+ _QASPER_CITATION = r"""
122
+ @inproceedings{dasigi-etal-2021-dataset,
123
+ title = "A Dataset of Information-Seeking Questions and Answers Anchored in Research Papers",
124
+ author = "Dasigi, Pradeep and
125
+ Lo, Kyle and
126
+ Beltagy, Iz and
127
+ Cohan, Arman and
128
+ Smith, Noah A. and
129
+ Gardner, Matt",
130
+ booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
131
+ month = jun,
132
+ year = "2021",
133
+ address = "Online",
134
+ publisher = "Association for Computational Linguistics",
135
+ url = "https://aclanthology.org/2021.naacl-main.365",
136
+ doi = "10.18653/v1/2021.naacl-main.365",
137
+ pages = "4599--4610"
138
+ }"""
139
+
140
+ _QMSUM_CITATION = r"""@inproceedings{zhong-etal-2021-qmsum,
141
+ title = "{QMS}um: A New Benchmark for Query-based Multi-domain Meeting Summarization",
142
+ author = "Zhong, Ming and
143
+ Yin, Da and
144
+ Yu, Tao and
145
+ Zaidi, Ahmad and
146
+ Mutuma, Mutethia and
147
+ Jha, Rahul and
148
+ Awadallah, Ahmed Hassan and
149
+ Celikyilmaz, Asli and
150
+ Liu, Yang and
151
+ Qiu, Xipeng and
152
+ Radev, Dragomir",
153
+ booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
154
+ month = jun,
155
+ year = "2021",
156
+ address = "Online",
157
+ publisher = "Association for Computational Linguistics",
158
+ url = "https://aclanthology.org/2021.naacl-main.472",
159
+ doi = "10.18653/v1/2021.naacl-main.472",
160
+ pages = "5905--5921"
161
+ }"""
162
+
163
+ _NARRATIVE_QA_CITATION = r"""
164
+ @article{kocisky-etal-2018-narrativeqa,
165
+ title = "The {N}arrative{QA} Reading Comprehension Challenge",
166
+ author = "Ko{\v{c}}isk{\'y}, Tom{\'a}{\v{s}} and
167
+ Schwarz, Jonathan and
168
+ Blunsom, Phil and
169
+ Dyer, Chris and
170
+ Hermann, Karl Moritz and
171
+ Melis, G{\'a}bor and
172
+ Grefenstette, Edward",
173
+ journal = "Transactions of the Association for Computational Linguistics",
174
+ volume = "6",
175
+ year = "2018",
176
+ address = "Cambridge, MA",
177
+ publisher = "MIT Press",
178
+ url = "https://aclanthology.org/Q18-1023",
179
+ doi = "10.1162/tacl_a_00023",
180
+ pages = "317--328"
181
+ }"""
182
+
183
+ _GOV_REPORT_CITATION = r"""
184
+ @inproceedings{huang-etal-2021-efficient,
185
+ title = "Efficient Attentions for Long Document Summarization",
186
+ author = "Huang, Luyang and
187
+ Cao, Shuyang and
188
+ Parulian, Nikolaus and
189
+ Ji, Heng and
190
+ Wang, Lu",
191
+ booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
192
+ month = jun,
193
+ year = "2021",
194
+ address = "Online",
195
+ publisher = "Association for Computational Linguistics",
196
+ url = "https://aclanthology.org/2021.naacl-main.112",
197
+ doi = "10.18653/v1/2021.naacl-main.112",
198
+ pages = "1419--1436"
199
+ }"""
200
+
201
+ _QUALITY_CITATION = """\
202
+ @inproceedings{pang-etal-2022-quality,
203
+ title = "{Q}u{ALITY}: Question Answering with Long Input Texts, Yes!",
204
+ author = "Pang, Richard Yuanzhe and
205
+ Parrish, Alicia and
206
+ Joshi, Nitish and
207
+ Nangia, Nikita and
208
+ Phang, Jason and
209
+ Chen, Angelica and
210
+ Padmakumar, Vishakh and
211
+ Ma, Johnny and
212
+ Thompson, Jana and
213
+ He, He and
214
+ Bowman, Samuel",
215
+ booktitle = "Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies",
216
+ month = jul,
217
+ year = "2022",
218
+ address = "Seattle, United States",
219
+ publisher = "Association for Computational Linguistics",
220
+ url = "https://aclanthology.org/2022.naacl-main.391",
221
+ doi = "10.18653/v1/2022.naacl-main.391",
222
+ pages = "5336--5358"
223
+ }
224
+ """
225
+ _SQUALITY_CITATION = """\
226
+ @inproceedings{wang-etal-2022-squality,
227
+ title = "{SQ}u{ALITY}: Building a Long-Document Summarization Dataset the Hard Way",
228
+ author = "Wang, Alex and
229
+ Pang, Richard Yuanzhe and
230
+ Chen, Angelica and
231
+ Phang, Jason and
232
+ Bowman, Samuel R.",
233
+ booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
234
+ month = dec,
235
+ year = "2022",
236
+ address = "Abu Dhabi, United Arab Emirates",
237
+ publisher = "Association for Computational Linguistics",
238
+ url = "https://aclanthology.org/2022.emnlp-main.75",
239
+ pages = "1139--1156"
240
+ }
241
+ """
242
+ _MUSIQUE_CITATION = """\
243
+ @article{trivedi-etal-2022-musique,
244
+ title = "♫ {M}u{S}i{Q}ue: Multihop Questions via Single-hop Question Composition",
245
+ author = "Trivedi, Harsh and
246
+ Balasubramanian, Niranjan and
247
+ Khot, Tushar and
248
+ Sabharwal, Ashish",
249
+ journal = "Transactions of the Association for Computational Linguistics",
250
+ volume = "10",
251
+ year = "2022",
252
+ address = "Cambridge, MA",
253
+ publisher = "MIT Press",
254
+ url = "https://aclanthology.org/2022.tacl-1.31",
255
+ doi = "10.1162/tacl_a_00475",
256
+ pages = "539--554"
257
+ }
258
+ """
259
+
260
+ _SPACE_CITATION = """\
261
+ @article{angelidis-etal-2021-extractive,
262
+ title = "Extractive Opinion Summarization in Quantized Transformer Spaces",
263
+ author = "Angelidis, Stefanos and
264
+ Amplayo, Reinald Kim and
265
+ Suhara, Yoshihiko and
266
+ Wang, Xiaolan and
267
+ Lapata, Mirella",
268
+ journal = "Transactions of the Association for Computational Linguistics",
269
+ volume = "9",
270
+ year = "2021",
271
+ address = "Cambridge, MA",
272
+ publisher = "MIT Press",
273
+ url = "https://aclanthology.org/2021.tacl-1.17",
274
+ doi = "10.1162/tacl_a_00366",
275
+ pages = "277--293"
276
+ }
277
+ """
278
+ _BOOK_SUM_CITATION = """\
279
+ @inproceedings{kryscinski-etal-2022-booksum,
280
+ title = "{BOOKSUM}: A Collection of Datasets for Long-form Narrative Summarization",
281
+ author = "Kryscinski, Wojciech and
282
+ Rajani, Nazneen and
283
+ Agarwal, Divyansh and
284
+ Xiong, Caiming and
285
+ Radev, Dragomir",
286
+ booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2022",
287
+ month = dec,
288
+ year = "2022",
289
+ address = "Abu Dhabi, United Arab Emirates",
290
+ publisher = "Association for Computational Linguistics",
291
+ url = "https://aclanthology.org/2022.findings-emnlp.488",
292
+ pages = "6536--6558"
293
+ }
294
+ """
295
+
296
+ FEATURE_TO_TYPE = {
297
+ "id": "string",
298
+ "pid": "string",
299
+ "input": "string",
300
+ "output": "string",
301
+ "document_start_index": "int32",
302
+ "document_end_index": "int32",
303
+ "query_start_index": "int32",
304
+ "query_end_index": "int32",
305
+ "truncation_seperator": "string"
306
+ }
307
+
308
+
309
+ class ZeroScrollsConfig(datasets.BuilderConfig):
310
+ """BuilderConfig for SCROLLS."""
311
+
312
+ def __init__(self, features, data_url, citation, url, **kwargs):
313
+ """BuilderConfig for SCROLLS.
314
+ Args:
315
+ features: `list[string]`, list of the features that will appear in the
316
+ feature dict. Should not include "label".
317
+ data_url: `string`, url to download the zip file from.
318
+ citation: `string`, citation for the data set.
319
+ url: `string`, url for information about the data set.
320
+ label_classes: `list[string]`, the list of classes for the label if the
321
+ label is present as a string. Non-string labels will be cast to either
322
+ 'False' or 'True'.
323
+ **kwargs: keyword arguments forwarded to super.
324
+ """
325
+ super(ZeroScrollsConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
326
+ self.features = features
327
+ self.data_url = data_url
328
+ self.citation = citation
329
+ self.url = url
330
+
331
+
332
+ class QualityConfig(ZeroScrollsConfig):
333
+ def __init__(self, **kwargs):
334
+ super().__init__(**kwargs)
335
+ self.hard_only = False
336
+
337
+
338
+ class ZeroScrolls(datasets.GeneratorBasedBuilder):
339
+ """The SCROLLS benchmark."""
340
+
341
+ features = list(FEATURE_TO_TYPE.keys())
342
+ features_with_multiple_inder_docs = features + ["inner_docs_start_indices"]
343
+ DEFAULT_WRITER_BATCH_SIZE = 1000 # because Narrative QA is a rather large dataset
344
+ BUILDER_CONFIGS = [
345
+ ZeroScrollsConfig(
346
+ name="summ_screen_fd",
347
+ description=_SUMM_SCREEN_DESCRIPTION,
348
+ features=features,
349
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/summ_screen_fd.zip",
350
+ citation=_SUMM_SCREEN_CITATION,
351
+ url="https://github.com/mingdachen/SummScreen",
352
+ ),
353
+ ZeroScrollsConfig(
354
+ name="qasper",
355
+ description=_QASPER_DESCRIPTION,
356
+ features=features,
357
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/qasper.zip",
358
+ citation=_QASPER_CITATION,
359
+ url="https://allenai.org/project/qasper",
360
+ ),
361
+ ZeroScrollsConfig(
362
+ name="qmsum",
363
+ description=_QMSUM_DESCRIPTION,
364
+ features=features,
365
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/qmsum.zip",
366
+ citation=_QMSUM_CITATION,
367
+ url="https://github.com/Yale-LILY/QMSum",
368
+ ),
369
+ ZeroScrollsConfig(
370
+ name="narrative_qa",
371
+ description=_NARRATIVE_QA_DESCRIPTION,
372
+ features=features,
373
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/narrative_qa.zip",
374
+ citation=_NARRATIVE_QA_CITATION,
375
+ url="https://deepmind.com/research/publications/narrativeqa-reading-comprehension-challenge",
376
+ ),
377
+ ZeroScrollsConfig(
378
+ name="gov_report",
379
+ description=_GOV_REPORT_DESCRIPTION,
380
+ features=features,
381
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/gov_report.zip",
382
+ citation=_GOV_REPORT_CITATION,
383
+ url="https://gov-report-data.github.io/",
384
+ ),
385
+ QualityConfig(
386
+ name="quality",
387
+ description=_QUALITY_DESCRIPTION,
388
+ features=features,
389
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/quality.zip",
390
+ citation=_QUALITY_CITATION,
391
+ url="https://github.com/nyu-mll/quality",
392
+ ),
393
+ ZeroScrollsConfig(
394
+ name="squality",
395
+ description=_SQUALITY_DESCRIPTION,
396
+ features=features,
397
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/squality.zip",
398
+ citation=_SQUALITY_CITATION,
399
+ url="https://github.com/nyu-mll/SQuALITY",
400
+ ),
401
+ ZeroScrollsConfig(
402
+ name="musique",
403
+ description=_MUSIQUE_DESCRIPTION,
404
+ features=features_with_multiple_inder_docs,
405
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/musique.zip",
406
+ citation=_MUSIQUE_CITATION,
407
+ url="https://github.com/stonybrooknlp/musique",
408
+ ),
409
+ ZeroScrollsConfig(
410
+ name="space_digest",
411
+ description=_SPACE_DIGEST_DESCRIPTION,
412
+ features=features_with_multiple_inder_docs,
413
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/space_digest.zip",
414
+ citation=_SPACE_CITATION,
415
+ url="https://github.com/stangelid/qt",
416
+ ),
417
+ ZeroScrollsConfig(
418
+ name="book_sum_sort",
419
+ description=_BOOK_SUM_DESCRIPTION,
420
+ features=features_with_multiple_inder_docs,
421
+ data_url="https://zero-scrolls-tau.s3.us-east-2.amazonaws.com/book_sum_sort.zip",
422
+ citation=_BOOK_SUM_CITATION,
423
+ url="https://github.com/salesforce/booksum",
424
+ ),
425
+ ]
426
+
427
+ def _info(self):
428
+
429
+ features = {feature: datasets.Value(FEATURE_TO_TYPE[feature]) for feature in self.config.features if
430
+ feature != "inner_docs_start_indices"}
431
+ if "inner_docs_start_indices" in self.config.features:
432
+ features["inner_docs_start_indices"] = datasets.Sequence(datasets.Value("int32"))
433
+
434
+ return datasets.DatasetInfo(
435
+ description=_ZERO_SCROLLS_DESCRIPTION + self.config.description,
436
+ features=datasets.Features(features),
437
+ homepage=self.config.url,
438
+ citation=self.config.citation + "\n" + _SCROLLS_CITATION + "\n" + _ZERO_SCROLLS_CITATION,
439
+ )
440
+
441
+ def _split_generators(self, dl_manager):
442
+ dl_dir = dl_manager.download_and_extract(self.config.data_url)
443
+ task_name = _get_task_name_from_data_url(self.config.data_url)
444
+ dl_dir = os.path.join(dl_dir, task_name)
445
+
446
+ data_files = {} if self.config.data_files is not None else None
447
+ if data_files is not None:
448
+ for split, paths in self.config.data_files.items():
449
+ data_files[split] = paths[0]
450
+
451
+ return [
452
+ datasets.SplitGenerator(
453
+ name=datasets.Split.TEST,
454
+ gen_kwargs={
455
+ "data_file": os.path.join(dl_dir, "test.jsonl") if data_files is None else data_files["test"],
456
+ "split": datasets.Split.TEST,
457
+ },
458
+ ),
459
+ ]
460
+
461
+ def _generate_examples(self, data_file, split):
462
+ with open(data_file, encoding="utf-8") as f:
463
+ for line in f:
464
+ row = json.loads(line)
465
+
466
+ if self.config.name == "quality":
467
+ is_hard = row.pop("is_hard", False)
468
+ if self.config.hard_only and not is_hard:
469
+ continue
470
+
471
+ yield row["pid"], row
472
+
473
+
474
+ def _get_task_name_from_data_url(data_url):
475
+ return data_url.split("/")[-1].split(".")[0]