hyg444 bzantium commited on
Commit
7dab970
·
0 Parent(s):

Duplicate from bzantium/LongBench

Browse files

Co-authored-by: Minho Ryu <bzantium@users.noreply.huggingface.co>

Files changed (9) hide show
  1. .gitattributes +55 -0
  2. LongBench.py +127 -0
  3. README.md +170 -0
  4. data.zip +3 -0
  5. metrics/edit_sim.py +36 -0
  6. metrics/exact_match.py +40 -0
  7. metrics/f1.py +52 -0
  8. metrics/longbench.py +449 -0
  9. metrics/rouge.py +28 -0
.gitattributes ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
12
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
+ *.model filter=lfs diff=lfs merge=lfs -text
14
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
15
+ *.npy filter=lfs diff=lfs merge=lfs -text
16
+ *.npz filter=lfs diff=lfs merge=lfs -text
17
+ *.onnx filter=lfs diff=lfs merge=lfs -text
18
+ *.ot filter=lfs diff=lfs merge=lfs -text
19
+ *.parquet filter=lfs diff=lfs merge=lfs -text
20
+ *.pb filter=lfs diff=lfs merge=lfs -text
21
+ *.pickle filter=lfs diff=lfs merge=lfs -text
22
+ *.pkl filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tar filter=lfs diff=lfs merge=lfs -text
30
+ *.tflite filter=lfs diff=lfs merge=lfs -text
31
+ *.tgz filter=lfs diff=lfs merge=lfs -text
32
+ *.wasm filter=lfs diff=lfs merge=lfs -text
33
+ *.xz filter=lfs diff=lfs merge=lfs -text
34
+ *.zip filter=lfs diff=lfs merge=lfs -text
35
+ *.zst filter=lfs diff=lfs merge=lfs -text
36
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
37
+ # Audio files - uncompressed
38
+ *.pcm filter=lfs diff=lfs merge=lfs -text
39
+ *.sam filter=lfs diff=lfs merge=lfs -text
40
+ *.raw filter=lfs diff=lfs merge=lfs -text
41
+ # Audio files - compressed
42
+ *.aac filter=lfs diff=lfs merge=lfs -text
43
+ *.flac filter=lfs diff=lfs merge=lfs -text
44
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
45
+ *.ogg filter=lfs diff=lfs merge=lfs -text
46
+ *.wav filter=lfs diff=lfs merge=lfs -text
47
+ # Image files - uncompressed
48
+ *.bmp filter=lfs diff=lfs merge=lfs -text
49
+ *.gif filter=lfs diff=lfs merge=lfs -text
50
+ *.png filter=lfs diff=lfs merge=lfs -text
51
+ *.tiff filter=lfs diff=lfs merge=lfs -text
52
+ # Image files - compressed
53
+ *.jpg filter=lfs diff=lfs merge=lfs -text
54
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
55
+ *.webp filter=lfs diff=lfs merge=lfs -text
LongBench.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import os
15
+
16
+ import datasets
17
+ import json
18
+
19
+
20
+ _DESCRIPTION = """\
21
+ LongBench is a comprehensive benchmark for multilingual and multi-task purposes, with the goal to fully measure and evaluate the ability of pre-trained language models to understand long text. This dataset consists of twenty different tasks, covering key long-text application scenarios such as multi-document QA, single-document QA, summarization, few-shot learning, synthetic tasks, and code completion.
22
+ """
23
+
24
+ _HOMEPAGE = "https://github.com/THUDM/LongBench"
25
+
26
+
27
+ _URL = r"https://huggingface.co/datasets/THUDM/LongBench/resolve/main/data.zip"
28
+
29
+ task_list = [
30
+ "narrativeqa",
31
+ "qasper",
32
+ "multifieldqa_en",
33
+ "multifieldqa_zh",
34
+ "hotpotqa",
35
+ "2wikimqa",
36
+ "musique",
37
+ "dureader",
38
+ "gov_report",
39
+ "qmsum",
40
+ "multi_news",
41
+ "vcsum",
42
+ "trec",
43
+ "triviaqa",
44
+ "samsum",
45
+ "lsht",
46
+ "passage_count",
47
+ "passage_retrieval_en",
48
+ "passage_retrieval_zh",
49
+ "lcc",
50
+ "repobench-p",
51
+ "qasper_e",
52
+ "multifieldqa_en_e",
53
+ "hotpotqa_e",
54
+ "2wikimqa_e",
55
+ "gov_report_e",
56
+ "multi_news_e",
57
+ "trec_e",
58
+ "triviaqa_e",
59
+ "samsum_e",
60
+ "passage_count_e",
61
+ "passage_retrieval_en_e",
62
+ "lcc_e",
63
+ "repobench-p_e"
64
+ ]
65
+
66
+
67
+ class LongBenchConfig(datasets.BuilderConfig):
68
+ def __init__(self, **kwargs):
69
+ super().__init__(version=datasets.Version("1.0.0"), **kwargs)
70
+
71
+
72
+ class LongBench(datasets.GeneratorBasedBuilder):
73
+ BUILDER_CONFIGS = [
74
+ LongBenchConfig(
75
+ name=task_name,
76
+ )
77
+ for task_name in task_list
78
+ ]
79
+
80
+ def _info(self):
81
+ features = datasets.Features(
82
+ {
83
+ "input": datasets.Value("string"),
84
+ "context": datasets.Value("string"),
85
+ "answers": [datasets.Value("string")],
86
+ "length": datasets.Value("int32"),
87
+ "dataset": datasets.Value("string"),
88
+ "language": datasets.Value("string"),
89
+ "all_classes": [datasets.Value("string")],
90
+ "_id": datasets.Value("string"),
91
+ }
92
+ )
93
+ return datasets.DatasetInfo(
94
+ description=_DESCRIPTION,
95
+ features=features,
96
+ homepage=_HOMEPAGE,
97
+ )
98
+
99
+ def _split_generators(self, dl_manager):
100
+ data_dir = dl_manager.download_and_extract(_URL)
101
+ task_name = self.config.name
102
+ return [
103
+ datasets.SplitGenerator(
104
+ name=datasets.Split.TEST,
105
+ gen_kwargs={
106
+ "filepath": os.path.join(
107
+ data_dir, "data", f"{task_name}.jsonl"
108
+ ),
109
+ },
110
+ )
111
+ ]
112
+
113
+ def _generate_examples(self, filepath):
114
+ with open(filepath, encoding="utf-8") as f:
115
+ for idx, line in enumerate(f):
116
+ key = f"{self.config.name}-{idx}"
117
+ item = json.loads(line)
118
+ yield key, {
119
+ "input": item["input"],
120
+ "context": item["context"],
121
+ "answers": item["answers"],
122
+ "length": item["length"],
123
+ "dataset": item["dataset"],
124
+ "language": item["language"],
125
+ "_id": item["_id"],
126
+ "all_classes": item["all_classes"],
127
+ }
README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ task_categories:
3
+ - question-answering
4
+ - text-generation
5
+ - summarization
6
+ - conversational
7
+ - text-classification
8
+ language:
9
+ - en
10
+ - zh
11
+ tags:
12
+ - Long Context
13
+ size_categories:
14
+ - 1K<n<10K
15
+ ---
16
+
17
+ # Introduction
18
+
19
+ **LongBench** is the first benchmark for bilingual, multitask, and comprehensive assessment of **long context understanding** capabilities of large language models. LongBench includes different languages (Chinese and English) to provide a more comprehensive evaluation of the large models' multilingual capabilities on long contexts. In addition, LongBench is composed of six major categories and twenty one different tasks, covering key long-text application scenarios such as single-document QA, multi-document QA, summarization, few-shot learning, synthetic tasks and code completion.
20
+
21
+ We are fully aware of the potentially high costs involved in the model evaluation process, especially in the context of long context scenarios (such as manual annotation costs or API call costs). Therefore, we adopt a fully automated evaluation method, aimed at measuring and evaluating the model's ability to understand long contexts at the lowest cost.
22
+
23
+ LongBench includes 14 English tasks, 5 Chinese tasks, and 2 code tasks, with the average length of most tasks ranging from 5k to 15k, and a total of 4,750 test data. For detailed statistics and construction methods of LongBench tasks, please refer [here](task.md). In addition, we provide LongBench-E, a test set with a more uniform length distribution constructed by uniform sampling, with comparable amounts of data in the 0-4k, 4k-8k, and 8k+ length intervals to provide an analysis of the model's performance variations at different input lengths.
24
+
25
+ Github Repo for LongBench: https://github.com/THUDM/LongBench
26
+ Arxiv Paper for LongBench: https://arxiv.org/pdf/2308.14508.pdf
27
+
28
+ # How to use it?
29
+
30
+ #### Loading Data
31
+
32
+ ```python
33
+ from datasets import load_dataset
34
+
35
+ datasets = ["narrativeqa", "qasper", "multifieldqa_en", "multifieldqa_zh", "hotpotqa", "2wikimqa", "musique", \
36
+ "dureader", "gov_report", "qmsum", "multi_news", "vcsum", "trec", "triviaqa", "samsum", "lsht", \
37
+ "passage_count", "passage_retrieval_en", "passage_retrieval_zh", "lcc", "repobench-p"]
38
+
39
+ for dataset in datasets:
40
+ data = load_dataset('THUDM/LongBench', dataset, split='test')
41
+ ```
42
+ Similarly, you can load the **LongBench-E** data
43
+ ```python
44
+ from datasets import load_dataset
45
+
46
+ datasets = ["qasper", "multifieldqa_en", "hotpotqa", "2wikimqa", "gov_report", "multi_news", "trec", \
47
+ "triviaqa", "samsum", "passage_count", "passage_retrieval_en", "lcc", "repobench-p"]
48
+
49
+ for dataset in datasets:
50
+ data = load_dataset('THUDM/LongBench', f"{dataset}_e", split='test')
51
+ ```
52
+ Alternatively, you can download the folder from [this link](https://huggingface.co/datasets/THUDM/LongBench/resolve/main/data.zip) to load the data.
53
+
54
+ #### Data Format
55
+
56
+ All data in **LongBench** (LongBench-E) are standardized to the following format:
57
+
58
+ ```json
59
+ {
60
+ "input": "The input/command for the task, usually short, such as questions in QA, queries in Few-shot tasks, etc",
61
+ "context": "The long context required for the task, such as documents, cross-file code, few-shot examples in Few-shot tasks",
62
+ "answers": "A List of all true answers",
63
+ "length": "Total length of the first three items (counted in characters for Chinese and words for English)",
64
+ "dataset": "The name of the dataset to which this piece of data belongs",
65
+ "language": "The language of this piece of data",
66
+ "all_classes": "All categories in classification tasks, null for non-classification tasks",
67
+ "_id": "Random id for each piece of data"
68
+ }
69
+ ```
70
+
71
+ #### Evaluation
72
+
73
+ This repository provides data download for LongBench. If you wish to use this dataset for automated evaluation, please refer to our [github](https://github.com/THUDM/LongBench).
74
+
75
+ # Task statistics
76
+
77
+ | Task | Task Type | Eval metric | Avg len |Language | \#Sample |
78
+ | :-------- | :-----------:| :-----------: |:-------: | :-----------: |:--------: |
79
+ | HotpotQA | Multi-doc QA | F1 |9,151 |EN |200 |
80
+ | 2WikiMultihopQA| Multi-doc QA | F1 |4,887 |EN |200 |
81
+ | MuSiQue| Multi-doc QA | F1 |11,214 |EN |200 |
82
+ | DuReader| Multi-doc QA | Rouge-L |15,768 |ZH |200 |
83
+ | MultiFieldQA-en| Single-doc QA | F1 |4,559 |EN |150 |
84
+ | MultiFieldQA-zh| Single-doc QA | F1 |6,701 |ZH |200 |
85
+ | NarrativeQA| Single-doc QA | F1 |18,409 |EN |200 |
86
+ | Qasper| Single-doc QA | F1 |3,619 |EN |200 |
87
+ | GovReport| Summarization | Rouge-L |8,734 |EN |200 |
88
+ | QMSum| Summarization | Rouge-L |10,614 |EN |200 |
89
+ | MultiNews| Summarization | Rouge-L |2,113 |EN |200 |
90
+ | VCSUM| Summarization | Rouge-L |15,380 |ZH |200 |
91
+ | TriviaQA| Few shot | F1 |8,209 |EN |200 |
92
+ | SAMSum| Few shot | Rouge-L |6,258 |EN |200 |
93
+ | TREC| Few shot | Accuracy |5,177 |EN |200 |
94
+ | LSHT| Few shot | Accuracy |22,337 |ZH |200 |
95
+ | PassageRetrieval-en| Synthetic | Accuracy |9,289 |EN |200 |
96
+ | PassageCount| Synthetic | Accuracy |11,141 |EN |200 |
97
+ | PassageRetrieval-zh | Synthetic | Accuracy |6,745 |ZH |200 |
98
+ | LCC| Code | Edit Sim |1,235 |Python/C#/Java |500 |
99
+ | RepoBench-P| Code | Edit Sim |4,206 |Python/Java |500 |
100
+
101
+ > Note: In order to avoid discrepancies caused by different tokenizers, we use the word count (using Python's split function) to calculate the average length of English datasets and code datasets, and use the character count to calculate the average length of Chinese datasets.
102
+
103
+ # Task description
104
+ | Task | Task Description |
105
+ | :---------------- | :----------------------------------------------------------- |
106
+ | HotpotQA | Answer related questions based on multiple given documents |
107
+ | 2WikiMultihopQA | Answer related questions based on multiple given documents |
108
+ | MuSiQue | Answer related questions based on multiple given documents |
109
+ | DuReader | Answer related Chinese questions based on multiple retrieved documents |
110
+ | MultiFieldQA-en | Answer English questions based on a long article, which comes from a relatively diverse field |
111
+ | MultiFieldQA-zh | Answer Chinese questions based on a long article, which comes from a relatively diverse field |
112
+ | NarrativeQA | Answer questions based on stories or scripts, including understanding of important elements such as characters, plots, themes, etc. |
113
+ | Qasper | Answer questions based on a NLP research paper, questions proposed and answered by NLP practitioners |
114
+ | GovReport | A summarization task that requires summarizing government work reports |
115
+ | MultiNews | A multi-doc summarization that requires summarizing over multiple news |
116
+ | QMSum | A summarization task that requires summarizing meeting records based on user queries |
117
+ | VCSUM | A summarization task that requires summarizing Chinese meeting records |
118
+ | SAMSum | A dialogue summarization task, providing several few-shot examples |
119
+ | TriviaQA | Single document question answering task, providing several few-shot examples |
120
+ | NQ | Single document question answering task, providing several few-shot examples |
121
+ | TREC | A classification task that requires categorizing questions, includes 50 categories in total |
122
+ | LSHT | A Chinese classification task that requires categorizing news, includes 24 categories in total |
123
+ | PassageRetrieval-en | Given 30 English Wikipedia paragraphs, determine which paragraph the given summary corresponds to |
124
+ | PassageCount | Determine the total number of different paragraphs in a given repetitive article |
125
+ | PassageRetrieval-zh | Given several Chinese paragraphs from the C4 data set, determine which paragraph the given abstract corresponds to |
126
+ | LCC | Given a long piece of code, predict the next line of code |
127
+ | RepoBench-P | Given code in multiple files within a GitHub repository (including cross-file dependencies), predict the next line of code |
128
+
129
+ # Task construction
130
+ > Note: For all tasks constructed from existing datasets, we use data from the validation or test set of the existing dataset (except for VCSUM).
131
+
132
+ - The tasks of [HotpotQA](https://hotpotqa.github.io/), [2WikiMultihopQA](https://aclanthology.org/2020.coling-main.580/), [MuSiQue](https://arxiv.org/abs/2108.00573), and [DuReader](https://github.com/baidu/DuReader) are built based on the original datasets and processed to be suitable for long context evaluation. Specifically, for questions in the validation set, we select the evidence passage that contains the answer and several distracting articles. These articles together with the original question constitute the input of the tasks.
133
+ - The tasks of MultiFiedQA-zh and MultiFieldQA-en consist of long artical data from about 10 sources, including Latex papers, judicial documents, government work reports, and PDF documents indexed by Google. For each long artical, we invite several PhD and master students to annotate, i.e., to ask questions based on the long artical and give the correct answers. To better automate evaluation, we ask the annotators to propose questions with definitive answers as much as possible.
134
+ - The tasks of [NarrativeQA](https://arxiv.org/pdf/1712.07040.pdf), [Qasper](https://arxiv.org/pdf/2105.03011.pdf), [GovReport](https://arxiv.org/pdf/2104.02112.pdf), [QMSum](https://arxiv.org/pdf/2104.05938.pdf) and [MultiNews](https://aclanthology.org/P19-1102.pdf) directly use the data provided by the original papers. In the specific construction, we use the template provided by [ZeroSCROLLS](https://www.zero.scrolls-benchmark.com/) to convert the corresponding data into pure text input.
135
+ - The [VCSUM](https://arxiv.org/abs/2305.05280) task is built based on the original dataset, and we design a corresponding template to convert the corresponding data into pure text input.
136
+ - The [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) task is constructed in the manner of [CoLT5](https://arxiv.org/abs/2303.09752), which provides several examples of question and answering based on documents, and requires the language model to answer related questions based on new documents.
137
+ - The tasks of [SAMSum](https://aclanthology.org/D19-5409.pdf), [TREC](https://aclanthology.org/C02-1150.pdf) and [LSHT](http://tcci.ccf.org.cn/conference/2014/dldoc/evatask6.pdf) are built based on the original datasets. For each question in the validation set, we sample several data from the training set to form few-shot examples. These examples together with the questions in the validation set constitute the input for this task.
138
+ - The PassageRetrieval-en task is constructed based on English Wikipedia. For each piece of data, we randomly sample 30 paragraphs from English Wikipedia and select one for summarization (using GPT-3.5-Turbo). This task requires the model to give the original paragraph name to which the summary corresponds.
139
+ - The PassageCount task is constructed based on the English wiki. For each piece of data, we randomly sample several passages from English Wikipedia, repeat each paragraph at random several times, and finally shuffle the paragraphs. This task requires the model to determine the total number of different paragraphs in the given context.
140
+ - The PasskeyRetrieval-zh task is constructed based on [C4](https://arxiv.org/abs/1910.10683). For each piece of data, we randomly sample several Chinese paragraphs from C4 and select one of them for summarization (using GPT-3.5-Turbo). This task requires the model to give the original paragraph name to which the summary corresponds.
141
+ - For the [LCC](https://arxiv.org/abs/2306.14893) task, we sample from the original code completion dataset. In the [RepoBench-P](https://arxiv.org/abs/2306.03091) task, we select the most challenging XF-F (Cross-File-First) setting from the original dataset and refer to the Oracle-Filled scenario in the paper. For each original piece of data, we randomly extract multiple cross-file code snippets, including the gold cross-file code snippet, and concatenate them as input, requiring the model to effectively use cross-file code for completion.
142
+
143
+ # LongBench-E statistics
144
+ | Task | Task Type | \#data in 0-4k | \#data in 4-8k | \#data in 8k+|
145
+ | :--------- | :-----------:| :-----------: |:---------: | :-------------: |
146
+ | HotpotQA | Multi-doc QA | 100 |100 |100 |
147
+ | 2WikiMultihopQA| Multi-doc QA | 100 |100 |100 |
148
+ | MultiFieldQA-en| Single-doc QA | 67 |70 |13 |
149
+ | Qasper| Single-doc QA | 100 |100 |24 |
150
+ | GovReport| Summarization | 100 |100 |100 |
151
+ | MultiNews| Summarization | 100 |100 |94 |
152
+ | TriviaQA| Few shot | 100 |100 |100 |
153
+ | SAMSum| Few shot | 100 |100 |100 |
154
+ | TREC| Few shot | 100 |100 |100 |
155
+ | PassageRetrieval-en| Synthetic | 100 |100 |100 |
156
+ | PassageCount| Synthetic | 100 |100 |100 |
157
+ | LCC| Code | 100 |100 |100 |
158
+ | RepoBench-P| Code | 100 |100 |100 |
159
+
160
+ # Citation
161
+ ```
162
+ @misc{bai2023longbench,
163
+ title={LongBench: A Bilingual, Multitask Benchmark for Long Context Understanding},
164
+ author={Yushi Bai and Xin Lv and Jiajie Zhang and Hongchang Lyu and Jiankai Tang and Zhidian Huang and Zhengxiao Du and Xiao Liu and Aohan Zeng and Lei Hou and Yuxiao Dong and Jie Tang and Juanzi Li},
165
+ year={2023},
166
+ eprint={2308.14508},
167
+ archivePrefix={arXiv},
168
+ primaryClass={cs.CL}
169
+ }
170
+ ```
data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb45b11a4133c6bc1d6a44b0f8e701335ff1e543195db1103472e575857f7f64
3
+ size 113932529
metrics/edit_sim.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+
3
+
4
+ def lev_dist(prediction, ground_truth):
5
+ @lru_cache(None) # for memorization
6
+ def min_dist(s1, s2):
7
+ if s1 == len(prediction) or s2 == len(ground_truth):
8
+ return len(prediction) - s1 + len(ground_truth) - s2
9
+ # no change required
10
+ if prediction[s1] == ground_truth[s2]:
11
+ return min_dist(s1 + 1, s2 + 1)
12
+ return 1 + min(
13
+ min_dist(s1, s2 + 1), # insert character
14
+ min_dist(s1 + 1, s2), # delete character
15
+ min_dist(s1 + 1, s2 + 1), # replace character
16
+ )
17
+ return min_dist(0, 0)
18
+
19
+
20
+ def edit_sim_score(a, b):
21
+ return 1 - lev_dist(a, b) / max(len(a), len(b))
22
+
23
+
24
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
25
+ scores_for_ground_truths = []
26
+ for ground_truth in ground_truths:
27
+ score = metric_fn(prediction, ground_truth)
28
+ scores_for_ground_truths.append(score)
29
+ return max(scores_for_ground_truths)
30
+
31
+
32
+ def compute_edit_sim(predictions, references):
33
+ edit_sim = 0
34
+ for prediction, ground_truths in zip(predictions, references):
35
+ edit_sim += metric_max_over_ground_truths(edit_sim_score, prediction, ground_truths)
36
+ return 100.0 * edit_sim / len(predictions)
metrics/exact_match.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import string
3
+
4
+
5
+ def normalize_answer(s):
6
+ """Lower text and remove punctuation, articles and extra whitespace."""
7
+
8
+ def remove_articles(text):
9
+ return re.sub(r"\b(a|an|the)\b", " ", text)
10
+
11
+ def white_space_fix(text):
12
+ return " ".join(text.split())
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
+ def lower(text):
19
+ return text.lower()
20
+
21
+ return white_space_fix(remove_articles(remove_punc(lower(s))))
22
+
23
+
24
+ def exact_match_score(prediction, ground_truth):
25
+ return normalize_answer(prediction) == normalize_answer(ground_truth)
26
+
27
+
28
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
29
+ scores_for_ground_truths = []
30
+ for ground_truth in ground_truths:
31
+ score = metric_fn(prediction, ground_truth)
32
+ scores_for_ground_truths.append(score)
33
+ return max(scores_for_ground_truths)
34
+
35
+
36
+ def compute_exact_match(predictions, references):
37
+ exact_match = 0
38
+ for prediction, ground_truths in zip(predictions, references):
39
+ exact_match += metric_max_over_ground_truths(exact_match_score, prediction, ground_truths)
40
+ return 100.0 * exact_match / len(predictions)
metrics/f1.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+
8
+ def normalize_answer(s):
9
+ """Lower text and remove punctuation, articles and extra whitespace."""
10
+
11
+ def remove_articles(text):
12
+ return re.sub(r"\b(a|an|the)\b", " ", text)
13
+
14
+ def white_space_fix(text):
15
+ return " ".join(text.split())
16
+
17
+ def remove_punc(text):
18
+ exclude = set(string.punctuation)
19
+ return "".join(ch for ch in text if ch not in exclude)
20
+
21
+ def lower(text):
22
+ return text.lower()
23
+
24
+ return white_space_fix(remove_articles(remove_punc(lower(s))))
25
+
26
+
27
+ def f1_score(prediction, ground_truth):
28
+ prediction_tokens = normalize_answer(prediction).split()
29
+ ground_truth_tokens = normalize_answer(ground_truth).split()
30
+ common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
31
+ num_same = sum(common.values())
32
+ if num_same == 0:
33
+ return 0
34
+ precision = 1.0 * num_same / len(prediction_tokens)
35
+ recall = 1.0 * num_same / len(ground_truth_tokens)
36
+ f1 = (2 * precision * recall) / (precision + recall)
37
+ return f1
38
+
39
+
40
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
41
+ scores_for_ground_truths = []
42
+ for ground_truth in ground_truths:
43
+ score = metric_fn(prediction, ground_truth)
44
+ scores_for_ground_truths.append(score)
45
+ return max(scores_for_ground_truths)
46
+
47
+
48
+ def compute_f1(predictions, references):
49
+ f1 = 0
50
+ for prediction, ground_truths in zip(predictions, references):
51
+ f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths)
52
+ return 100.0 * f1 / len(predictions)
metrics/longbench.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ LongBench 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, postprocess_text as rouge_postprocess_text # From: https://huggingface.co/datasets/bzantium/LongBench/raw/main/metrics/rouge.py
9
+ from .exact_match import compute_exact_match # From: https://huggingface.co/datasets/bzantium/LongBench/raw/main/metrics/exact_match.py
10
+ from .f1 import compute_f1 # From: https://huggingface.co/datasets/bzantium/LongBench/raw/main/metrics/f1.py
11
+ from .edit_sim import compute_edit_sim # From: https://huggingface.co/datasets/bzantium/LongBench/raw/main/metrics/edit_sim.py
12
+ # fmt: on
13
+
14
+ _CITATION = """\
15
+ @misc{bai2023longbench,
16
+ title={LongBench: A Bilingual, Multitask Benchmark for Long Context Understanding},
17
+ author={Yushi Bai and Xin Lv and Jiajie Zhang and Hongchang Lyu and Jiankai Tang and Zhidian Huang and Zhengxiao Du and Xiao Liu and Aohan Zeng and Lei Hou and Yuxiao Dong and Jie Tang and Juanzi Li},
18
+ year={2023},
19
+ eprint={2308.14508},
20
+ archivePrefix={arXiv},
21
+ primaryClass={cs.CL}
22
+ }
23
+ """
24
+
25
+ _DESCRIPTION = """\
26
+ LongBench is a comprehensive benchmark for multilingual and multi-task purposes, with the goal to fully measure and evaluate the ability of pre-trained language models to understand long text. This dataset consists of twenty different tasks, covering key long-text application scenarios such as multi-document QA, single-document QA, summarization, few-shot learning, synthetic tasks, and code completion.
27
+ """
28
+
29
+ _KWARGS_DESCRIPTION = """
30
+ Compute LongBench evaluation metric associated to each LongBench 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 LongBench subset, one or several of:
37
+ "exact_match": Exact Match score
38
+ "f1": F1 score
39
+ "rouge": ROUGE score
40
+
41
+ Use the following code to download the metric:
42
+ ```
43
+ import os, shutil
44
+ from huggingface_hub import hf_hub_download
45
+ def download_metric():
46
+ longbench_metric_path = hf_hub_download(repo_id="datasets/bzantium/LongBench", filename="metrics/longbench.py")
47
+ updated_longbench_metric_path = (
48
+ os.path.dirname(longbench_metric_path) + os.path.basename(longbench_metric_path).replace(".", "_") + ".py"
49
+ )
50
+ shutil.copy(longbench_metric_path, updated_longbench_metric_path)
51
+ return updated_longbench_metric_path
52
+
53
+ longbench_metric_path = download_metric()
54
+ ```
55
+
56
+ Examples:
57
+ predictions = ["exact match example", "hello there", "general kenobi"] # List[str]
58
+ references = [["exact match example"], ["hello", "hi there"], ["commander kenobi"]] # List[List[str]]
59
+
60
+ >>> longbench_metric = datasets.load_metric(longbench_metric_path, 'gov_report') # 'gov_report' or any of ["qmsum", "summ_screen_fd"]
61
+ >>> results = longbench_metric.compute(predictions=predictions, references=references)
62
+ >>> print(results)
63
+ {'rouge/rouge1': 72.2222, 'rouge/rouge2': 33.3333, 'rouge/rougeL': 72.2222, 'rouge/rougeLsum': 72.2222, 'rouge/geometric_mean': 55.8136,
64
+ 'num_predicted': 3, 'mean_prediction_length_characters': 14.6667, 'longbench_score': 55.8136,
65
+ 'display_keys': ['rouge/rouge1', 'rouge/rouge2', 'rouge/rougeL'], 'display': [72.2222, 33.3333, 72.2222]}
66
+
67
+ >>> longbench_metric = datasets.load_metric(longbench_metric_path, 'contract_nli') # 'contract_nli' or "quality"
68
+ >>> results = longbench_metric.compute(predictions=predictions, references=references)
69
+ >>> print(results)
70
+ {'exact_match': 33.3333, 'num_predicted': 3, 'mean_prediction_length_characters': 14.6667, 'longbench_score': 33.3333,
71
+ 'display_keys': ['exact_match'], 'display': [33.3333]}
72
+
73
+ >>> longbench_metric = datasets.load_metric(longbench_metric_path, 'narrativeqa') # 'narrativeqa' or "qasper"
74
+ >>> results = longbench_metric.compute(predictions=predictions, references=references)
75
+ >>> print(results)
76
+ {'f1': 72.2222, 'num_predicted': 3, 'mean_prediction_length_characters': 14.6667, 'longbench_score': 72.2222,
77
+ 'display_keys': ['f1'], 'display': [72.2222]}
78
+ """
79
+
80
+ DATASET_TO_METRICS = {
81
+ "narrativeqa": {
82
+ "metrics_to_compute": ["f1"],
83
+ "longbench_score_key": "f1",
84
+ "display_keys": ["f1"],
85
+ },
86
+ "qasper": {
87
+ "metrics_to_compute": ["f1"],
88
+ "longbench_score_key": "f1",
89
+ "display_keys": ["f1"],
90
+ },
91
+ "multifieldqa_en": {
92
+ "metrics_to_compute": ["f1"],
93
+ "longbench_score_key": "f1",
94
+ "display_keys": ["f1"],
95
+ },
96
+ "multifieldqa_zh": {
97
+ "metrics_to_compute": ["f1"],
98
+ "longbench_score_key": "f1",
99
+ "display_keys": ["f1"],
100
+ },
101
+ "hotpotqa": {
102
+ "metrics_to_compute": ["f1"],
103
+ "longbench_score_key": "f1",
104
+ "display_keys": ["f1"],
105
+ },
106
+ "2wikimqa": {
107
+ "metrics_to_compute": ["f1"],
108
+ "longbench_score_key": "f1",
109
+ "display_keys": ["f1"],
110
+ },
111
+ "musique": {
112
+ "metrics_to_compute": ["f1"],
113
+ "longbench_score_key": "f1",
114
+ "display_keys": ["f1"],
115
+ },
116
+ "dureader": {
117
+ "metrics_to_compute": ["rouge"],
118
+ "longbench_score_key": "rouge/geometric_mean",
119
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
120
+ },
121
+ "gov_report": {
122
+ "metrics_to_compute": ["rouge"],
123
+ "longbench_score_key": "rouge/geometric_mean",
124
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
125
+ },
126
+ "qmsum": {
127
+ "metrics_to_compute": ["rouge"],
128
+ "longbench_score_key": "rouge/geometric_mean",
129
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
130
+ },
131
+ "multi_news": {
132
+ "metrics_to_compute": ["rouge"],
133
+ "longbench_score_key": "rouge/geometric_mean",
134
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
135
+ },
136
+ "vcsum": {
137
+ "metrics_to_compute": ["rouge"],
138
+ "longbench_score_key": "rouge/geometric_mean",
139
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
140
+ },
141
+ "trec": {
142
+ "metrics_to_compute": ["exact_match"],
143
+ "longbench_score_key": "exact_match",
144
+ "display_keys": ["exact_match"],
145
+ },
146
+ "triviaqa": {
147
+ "metrics_to_compute": ["f1"],
148
+ "longbench_score_key": "f1",
149
+ "display_keys": ["f1"],
150
+ },
151
+ "samsum": {
152
+ "metrics_to_compute": ["rouge"],
153
+ "longbench_score_key": "rouge/geometric_mean",
154
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
155
+ },
156
+ "lsht": {
157
+ "metrics_to_compute": ["exact_match"],
158
+ "longbench_score_key": "exact_match",
159
+ "display_keys": ["exact_match"],
160
+ },
161
+ "passage_count": {
162
+ "metrics_to_compute": ["exact_match"],
163
+ "longbench_score_key": "exact_match",
164
+ "display_keys": ["exact_match"],
165
+ },
166
+ "passage_retrieval_en": {
167
+ "metrics_to_compute": ["exact_match"],
168
+ "longbench_score_key": "exact_match",
169
+ "display_keys": ["exact_match"],
170
+ },
171
+ "passage_retrieval_zh": {
172
+ "metrics_to_compute": ["exact_match"],
173
+ "longbench_score_key": "exact_match",
174
+ "display_keys": ["exact_match"],
175
+ },
176
+ "lcc": {
177
+ "metrics_to_compute": ["edit_sim"],
178
+ "longbench_score_key": "edit_sim",
179
+ "display_keys": ["edit_sim"],
180
+ },
181
+ "repobench-p": {
182
+ "metrics_to_compute": ["edit_sim"],
183
+ "longbench_score_key": "edit_sim",
184
+ "display_keys": ["edit_sim"],
185
+ },
186
+ "qasper_e": {
187
+ "metrics_to_compute": ["f1"],
188
+ "longbench_score_key": "f1",
189
+ "display_keys": ["f1"],
190
+ },
191
+ "multifieldqa_en_e": {
192
+ "metrics_to_compute": ["f1"],
193
+ "longbench_score_key": "f1",
194
+ "display_keys": ["f1"],
195
+ },
196
+ "hotpotqa_e": {
197
+ "metrics_to_compute": ["f1"],
198
+ "longbench_score_key": "f1",
199
+ "display_keys": ["f1"],
200
+ },
201
+ "2wikimqa_e": {
202
+ "metrics_to_compute": ["f1"],
203
+ "longbench_score_key": "f1",
204
+ "display_keys": ["f1"],
205
+ },
206
+ "gov_report_e": {
207
+ "metrics_to_compute": ["rouge"],
208
+ "longbench_score_key": "rouge/geometric_mean",
209
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
210
+ },
211
+ "multi_news_e": {
212
+ "metrics_to_compute": ["rouge"],
213
+ "longbench_score_key": "rouge/geometric_mean",
214
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
215
+ },
216
+ "trec_e": {
217
+ "metrics_to_compute": ["exact_match"],
218
+ "longbench_score_key": "exact_match",
219
+ "display_keys": ["exact_match"],
220
+ },
221
+ "triviaqa_e": {
222
+ "metrics_to_compute": ["f1"],
223
+ "longbench_score_key": "f1",
224
+ "display_keys": ["f1"],
225
+ },
226
+ "samsum_e": {
227
+ "metrics_to_compute": ["rouge"],
228
+ "longbench_score_key": "rouge/geometric_mean",
229
+ "display_keys": ["rouge/rouge1", "rouge/rouge2", "rouge/rougeL"],
230
+ },
231
+ "passage_count_e": {
232
+ "metrics_to_compute": ["exact_match"],
233
+ "longbench_score_key": "exact_match",
234
+ "display_keys": ["exact_match"],
235
+ },
236
+ "passage_retrieval_en_e": {
237
+ "metrics_to_compute": ["exact_match"],
238
+ "longbench_score_key": "exact_match",
239
+ "display_keys": ["exact_match"],
240
+ },
241
+ "lcc_e": {
242
+ "metrics_to_compute": ["edit_sim"],
243
+ "longbench_score_key": "edit_sim",
244
+ "display_keys": ["edit_sim"],
245
+ },
246
+ "repobench-p_e": {
247
+ "metrics_to_compute": ["edit_sim"],
248
+ "longbench_score_key": "edit_sim",
249
+ "display_keys": ["edit_sim"],
250
+ },
251
+ }
252
+
253
+
254
+ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
255
+ class longbench(datasets.Metric):
256
+ def __init__(self, *args, **kwargs):
257
+ super().__init__(*args, **kwargs)
258
+
259
+ self._compute_helper_kwargs_fn = {
260
+ "rouge": lambda: {
261
+ "metric_fn": compute_rouge,
262
+ "agg_fn": max,
263
+ "metric_fn_kwargs": {"use_stemmer": False},
264
+ "metric_returns_per_example": True,
265
+ "transform_single_input_fn": lambda text: rouge_postprocess_text(text),
266
+ "transform_result_fn": lambda output: {
267
+ key: (value[0] if isinstance(value, list) else value).fmeasure * 100
268
+ for key, value in output.items()
269
+ },
270
+ "transform_aggregated_result_fn": lambda output: output.update(
271
+ {"geometric_mean": (output["rouge1"] * output["rouge2"] * output["rougeL"]) ** (1.0 / 3.0)}
272
+ )
273
+ or output,
274
+ },
275
+ "exact_match": lambda: {
276
+ "metric_fn": compute_exact_match,
277
+ "agg_fn": None, # compute_exact_match already takes max
278
+ "transform_result_fn": lambda output: {None: output},
279
+ },
280
+ "f1": lambda: {
281
+ "metric_fn": compute_f1,
282
+ "agg_fn": None, # compute_f1 already takes max
283
+ "transform_result_fn": lambda output: {None: output},
284
+ },
285
+ "edit_sim": lambda: {
286
+ "metric_fn": compute_edit_sim,
287
+ "agg_fn": None, # compute_edit_sim already takes max
288
+ "transform_result_fn": lambda output: {None: output},
289
+ },
290
+ }
291
+
292
+ custom_metrics = (
293
+ [metric for metric in self.config_name.split(",") if len(metric) > 0]
294
+ if self.config_name.startswith(",")
295
+ else None
296
+ )
297
+ if custom_metrics is not None:
298
+ for metric in custom_metrics:
299
+ if metric not in self._compute_helper_kwargs_fn:
300
+ raise KeyError(
301
+ f"You should supply a metric name selected in {list(self._compute_helper_kwargs_fn.keys())}"
302
+ )
303
+ self._metrics_to_compute = custom_metrics
304
+ else:
305
+ if self.config_name not in DATASET_TO_METRICS:
306
+ raise KeyError(f"You should supply a configuration name selected in {list(DATASET_TO_METRICS.keys())}")
307
+ self._metrics_to_compute = DATASET_TO_METRICS[self.config_name]["metrics_to_compute"]
308
+
309
+ def _info(self):
310
+ return datasets.MetricInfo(
311
+ description=_DESCRIPTION,
312
+ citation=_CITATION,
313
+ inputs_description=_KWARGS_DESCRIPTION,
314
+ features=datasets.Features(
315
+ {
316
+ "predictions": datasets.Value("string"),
317
+ "references": datasets.Sequence(datasets.Value("string")),
318
+ }
319
+ ),
320
+ codebase_urls=[],
321
+ reference_urls=[],
322
+ )
323
+
324
+ def convert_from_map_format(self, id_to_pred, id_to_labels):
325
+ index_to_id = list(id_to_pred.keys())
326
+ predictions = [id_to_pred[id_] for id_ in index_to_id]
327
+ references = [id_to_labels[id_] for id_ in index_to_id]
328
+ return {"predictions": predictions, "references": references}
329
+
330
+ def _compute(self, predictions, references):
331
+ metrics = {}
332
+ for metric in self._metrics_to_compute:
333
+ result = _compute_helper(
334
+ deepcopy(predictions),
335
+ deepcopy(references),
336
+ **self._compute_helper_kwargs_fn[metric](),
337
+ )
338
+ metrics.update(
339
+ {(f"{metric}/{key}" if key is not None else metric): value for key, value in result.items()}
340
+ )
341
+ metrics["num_predicted"] = len(predictions)
342
+ prediction_lengths = [len(prediction) for prediction in predictions]
343
+ metrics["mean_prediction_length_characters"] = sum(prediction_lengths) / len(prediction_lengths)
344
+
345
+ metrics = {key: round(value, 4) for key, value in metrics.items()}
346
+
347
+ if self.config_name in DATASET_TO_METRICS:
348
+ longbench_score_key = DATASET_TO_METRICS[self.config_name]["longbench_score_key"]
349
+ if longbench_score_key is not None:
350
+ metrics["longbench_score"] = metrics[longbench_score_key]
351
+ else:
352
+ metrics["longbench_score"] = None
353
+
354
+ display_keys = DATASET_TO_METRICS[self.config_name]["display_keys"]
355
+ metrics["display_keys"] = display_keys
356
+ metrics["display"] = []
357
+ for display_key in display_keys:
358
+ metrics["display"].append(metrics[display_key])
359
+
360
+ return metrics
361
+
362
+
363
+ def _compute_helper(
364
+ predictions,
365
+ references,
366
+ metric_fn,
367
+ agg_fn,
368
+ metric_fn_kwargs=None,
369
+ transform_single_input_fn=None,
370
+ transform_result_fn=None,
371
+ transform_aggregated_result_fn=None,
372
+ metric_returns_per_example=False,
373
+ ):
374
+ if metric_fn_kwargs is None:
375
+ metric_fn_kwargs = {}
376
+
377
+ if agg_fn is None:
378
+ assert metric_returns_per_example is False
379
+
380
+ if transform_single_input_fn is not None:
381
+ predictions = [transform_single_input_fn(prediction) for prediction in predictions]
382
+ references = [
383
+ [transform_single_input_fn(reference) for reference in reference_list] for reference_list in references
384
+ ]
385
+
386
+ if transform_result_fn is None:
387
+ transform_result_fn = lambda x: x
388
+ do_transform_result = False
389
+ else:
390
+ do_transform_result = True
391
+
392
+ if transform_aggregated_result_fn is None:
393
+ transform_aggregated_result_fn = lambda x: x
394
+
395
+ if agg_fn is not None:
396
+ # Required when the metric doesn't do the aggregation we need
397
+ scores = defaultdict(list)
398
+ if metric_returns_per_example is False:
399
+ # If when given a list of prediction and references the metric returns an aggregated score,
400
+ # we need to compute the metric for each prediction and reference and then aggregate the results.
401
+ # This is only an issue when we want to get the best aggregated score (e.g. max) for prediction
402
+ # with multiple references.
403
+ for prediction, reference_list in zip(predictions, references):
404
+ prediction_scores = defaultdict(list)
405
+ for reference in reference_list:
406
+ result = transform_result_fn(metric_fn([prediction], [reference], **metric_fn_kwargs))
407
+ for key in result:
408
+ prediction_scores[key].append(result[key])
409
+ for key in prediction_scores:
410
+ scores[key].append(agg_fn(prediction_scores[key]))
411
+ else:
412
+ # Flatten the references and then aggregate per prediction with agg_fn
413
+ mapping = [[] for _ in range(len(predictions))]
414
+ flattened_predictions = []
415
+ flattened_references = []
416
+ for i, prediction in enumerate(predictions):
417
+ for reference in references[i]:
418
+ flattened_predictions.append(prediction)
419
+ flattened_references.append(reference)
420
+ mapping[i].append(len(flattened_references) - 1)
421
+
422
+ results = metric_fn(flattened_predictions, flattened_references, **metric_fn_kwargs)
423
+ if isinstance(results, dict):
424
+ # Convert a dictionary with lists per key to a list with dictionary with the same keys per element
425
+ results_list = [{k: None for k in results} for _ in range(len(flattened_predictions))]
426
+ for k, v in results.items():
427
+ for i in range(len(v)):
428
+ results_list[i][k] = v[i]
429
+ else:
430
+ results_list = results
431
+
432
+ if do_transform_result:
433
+ for i in range(len(results_list)):
434
+ results_list[i] = transform_result_fn(results_list[i])
435
+
436
+ for reference_indexes in mapping:
437
+ prediction_scores = defaultdict(list)
438
+ for reference_index in reference_indexes:
439
+ result = results_list[reference_index]
440
+ for key in result:
441
+ prediction_scores[key].append(result[key])
442
+ for key in prediction_scores:
443
+ scores[key].append(agg_fn(prediction_scores[key]))
444
+
445
+ return transform_aggregated_result_fn({key: sum(value) / len(value) for key, value in scores.items()})
446
+ else:
447
+ return transform_aggregated_result_fn(
448
+ transform_result_fn(metric_fn(predictions, references, **metric_fn_kwargs))
449
+ )
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))