tliu commited on
Commit
c95c7b0
·
verified ·
1 Parent(s): 6e3a1fb

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. evaluation-pipeline/.coveragerc +21 -0
  3. evaluation-pipeline/.flake8 +5 -0
  4. evaluation-pipeline/.gitignore +56 -0
  5. evaluation-pipeline/.gitmodules +3 -0
  6. evaluation-pipeline/.pre-commit-config.yaml +44 -0
  7. evaluation-pipeline/CODEOWNERS +1 -0
  8. evaluation-pipeline/LICENSE.md +21 -0
  9. evaluation-pipeline/README.md +237 -0
  10. evaluation-pipeline/aoa_data/sent_words.json +0 -0
  11. evaluation-pipeline/aoa_data/word_list.csv +592 -0
  12. evaluation-pipeline/assets/babylm.png +3 -0
  13. evaluation-pipeline/babylm_eval.py +97 -0
  14. evaluation-pipeline/collect_results.py +85 -0
  15. evaluation-pipeline/docs/img/fewshot_example_gpt3.png +3 -0
  16. evaluation-pipeline/docs/task_guide.md +300 -0
  17. evaluation-pipeline/filter_data.zip +3 -0
  18. evaluation-pipeline/finetune_all_tasks.sh +20 -0
  19. evaluation-pipeline/finetune_classification.py +728 -0
  20. evaluation-pipeline/finetune_model.sh +46 -0
  21. evaluation-pipeline/ignore.txt +9 -0
  22. evaluation-pipeline/lm_eval/__init__.py +3 -0
  23. evaluation-pipeline/lm_eval/__pycache__/__init__.cpython-310.pyc +0 -0
  24. evaluation-pipeline/lm_eval/__pycache__/evaluator.cpython-310.pyc +0 -0
  25. evaluation-pipeline/lm_eval/api/__init__.py +0 -0
  26. evaluation-pipeline/lm_eval/api/__pycache__/__init__.cpython-310.pyc +0 -0
  27. evaluation-pipeline/lm_eval/api/__pycache__/metric.cpython-310.pyc +0 -0
  28. evaluation-pipeline/lm_eval/api/__pycache__/model.cpython-310.pyc +0 -0
  29. evaluation-pipeline/lm_eval/api/__pycache__/request.cpython-310.pyc +0 -0
  30. evaluation-pipeline/lm_eval/api/__pycache__/task.cpython-310.pyc +0 -0
  31. evaluation-pipeline/lm_eval/api/__pycache__/utils.cpython-310.pyc +0 -0
  32. evaluation-pipeline/lm_eval/api/metric.py +371 -0
  33. evaluation-pipeline/lm_eval/api/model.py +454 -0
  34. evaluation-pipeline/lm_eval/api/request.py +53 -0
  35. evaluation-pipeline/lm_eval/api/task.py +874 -0
  36. evaluation-pipeline/lm_eval/api/utils.py +357 -0
  37. evaluation-pipeline/lm_eval/datasets/README.md +6 -0
  38. evaluation-pipeline/lm_eval/datasets/__init__.py +0 -0
  39. evaluation-pipeline/lm_eval/datasets/__pycache__/__init__.cpython-310.pyc +0 -0
  40. evaluation-pipeline/lm_eval/datasets/arithmetic/__init__.py +0 -0
  41. evaluation-pipeline/lm_eval/datasets/arithmetic/arithmetic.py +216 -0
  42. evaluation-pipeline/lm_eval/datasets/arithmetic/dataset_infos.json +1 -0
  43. evaluation-pipeline/lm_eval/datasets/asdiv/__init__.py +0 -0
  44. evaluation-pipeline/lm_eval/datasets/asdiv/asdiv.py +111 -0
  45. evaluation-pipeline/lm_eval/datasets/asdiv/dataset_infos.json +1 -0
  46. evaluation-pipeline/lm_eval/datasets/coqa/__init__.py +0 -0
  47. evaluation-pipeline/lm_eval/datasets/coqa/coqa.py +245 -0
  48. evaluation-pipeline/lm_eval/datasets/coqa/dataset_infos.json +1 -0
  49. evaluation-pipeline/lm_eval/datasets/drop/__init__.py +0 -0
  50. evaluation-pipeline/lm_eval/datasets/drop/dataset_infos.json +1 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ evaluation-pipeline/assets/babylm.png filter=lfs diff=lfs merge=lfs -text
37
+ evaluation-pipeline/docs/img/fewshot_example_gpt3.png filter=lfs diff=lfs merge=lfs -text
38
+ evaluation-pipeline/sample_predictions.json filter=lfs diff=lfs merge=lfs -text
evaluation-pipeline/.coveragerc ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ omit =
3
+ # Requires manual data download
4
+ lm_eval/tasks/jigsaw_unintended_bias.py
5
+
6
+ [report]
7
+ exclude_lines =
8
+ # Skip any pass lines such as may be used for @abstractmethod
9
+ pass
10
+
11
+ # Have to re-enable the standard pragma
12
+ pragma: no cover
13
+
14
+ # Don't complain about missing debug-only code:
15
+ def __repr__
16
+ if self\.debug
17
+
18
+ # Don't complain if tests don't hit defensive assertion code:
19
+ raise AssertionError
20
+ raise NotImplementedError
21
+ return NotImplemented
evaluation-pipeline/.flake8 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [flake8]
2
+ ignore = E203, E266, E501, W503, F403, F401, C901
3
+ max-line-length = 127
4
+ max-complexity = 10
5
+ select = B,C,E,F,W,T4,B9
evaluation-pipeline/.gitignore ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Distribution / Packaging
2
+ .Python
3
+ build/
4
+ develop-eggs/
5
+ dist/
6
+ downloads/
7
+ eggs/
8
+ .eggs/
9
+ lib/
10
+ lib64/
11
+ parts/
12
+ sdist/
13
+ var/
14
+ wheels/
15
+ share/python-wheels/
16
+ *.egg-info/
17
+ .installed.cfg
18
+ *.egg
19
+ *.pyc
20
+ *.log
21
+ *.db
22
+ MANIFEST
23
+
24
+ # Directories
25
+ data/
26
+ outputs/
27
+ lm_cache/
28
+
29
+ # Editors
30
+ .idea
31
+ .vscode
32
+ .ipynb_checkpoints
33
+
34
+ # Environments
35
+ .env
36
+ .venv
37
+ env/
38
+ venv/
39
+ ENV/
40
+ env.bak/
41
+ venv.bak/
42
+
43
+ # Unit test / coverage reports
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+
48
+ # local testing files
49
+ test/
50
+
51
+ # baseline models
52
+ baselines/
53
+
54
+ # outputs from running scripts
55
+ .out
56
+ .err
evaluation-pipeline/.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "lm_eval/datasets/biomedical"]
2
+ path = lm_eval/datasets/biomedical
3
+ url = https://github.com/bigscience-workshop/biomedical
evaluation-pipeline/.pre-commit-config.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore test linting to avoid conflicting changes to version stability.
2
+ exclude: ^tests/testdata/
3
+ repos:
4
+ - repo: https://github.com/pre-commit/pre-commit-hooks
5
+ rev: v4.1.0
6
+ hooks:
7
+ - id: check-added-large-files
8
+ - id: check-ast
9
+ - id: check-byte-order-marker
10
+ - id: check-case-conflict
11
+ - id: check-json
12
+ - id: check-merge-conflict
13
+ - id: check-symlinks
14
+ - id: check-yaml
15
+ - id: destroyed-symlinks
16
+ - id: detect-private-key
17
+ - id: end-of-file-fixer
18
+ - id: no-commit-to-branch
19
+ - id: requirements-txt-fixer
20
+ - id: trailing-whitespace
21
+ - id: fix-byte-order-marker
22
+ exclude: docs/CNAME
23
+ - id: fix-encoding-pragma
24
+ args: [--remove]
25
+ - id: mixed-line-ending
26
+ args: [--fix=lf]
27
+ - repo: https://gitlab.com/pycqa/flake8
28
+ rev: 3.7.9
29
+ hooks:
30
+ - id: flake8
31
+ - repo: https://github.com/psf/black
32
+ rev: 22.3.0
33
+ hooks:
34
+ - id: black
35
+ language_version: python3.8
36
+ - repo: https://github.com/codespell-project/codespell
37
+ rev: v2.1.0
38
+ hooks:
39
+ - id: codespell
40
+ exclude: >
41
+ (?x)^(
42
+ .*\.json|ignore.txt
43
+ )$
44
+ args: [--check-filenames, --check-hidden, --ignore-words=ignore.txt]
evaluation-pipeline/CODEOWNERS ADDED
@@ -0,0 +1 @@
 
 
1
+ * @jon-tow @leogao2 @StellaAthena
evaluation-pipeline/LICENSE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 EleutherAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
evaluation-pipeline/README.md ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BabyLM Evaluation Pipeline
2
+ ![BabyLM Challenge](assets/babylm.png)
3
+
4
+ ## Overview
5
+
6
+ This code provides the backend for the BabyLM Challenge's evaluation pipeline.
7
+
8
+ We provide support for zero-shot evaluations on BLiMP, as well as scripts for fine-tuning HuggingFace-based models on GLUE and MSGS tasks.
9
+
10
+ We also provide a [Colab demo](https://colab.research.google.com/drive/1HX2D3wztO81tKcqCeV_ecRcEUseBVuTc?usp=sharing) of the evaluation pipeline as a demonstration of how to use the code.
11
+
12
+ If you have questions about or suggestions for this code, please open an issue and consider [joining our Slack](https://join.slack.com/t/babylmchallenge/shared_invite/zt-1s8el4mro-qvVO447l3POBZcUNvMWQcg). We also welcome pull requests!
13
+
14
+ ## Installation
15
+
16
+ To install dependencies, run this:
17
+
18
+ ```bash
19
+ git clone https://github.com/babylm/evaluation-pipeline
20
+ cd evaluation-pipeline
21
+ pip install -e ".[dev]"
22
+ pip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 torchaudio==0.11.0 --extra-index-url https://download.pytorch.org/whl/cu113
23
+ ```
24
+
25
+ If your GPU is compatible with CUDA 10, replace all instances of `cu113` with `cu102`.
26
+
27
+ ### Data
28
+ We provide versions of BLiMP, GLUE, and MSGS which have been filtered according to the vocabulary of the `strict-small` dataset. We filter for examples where each word has appeared in our training set at least twice.
29
+
30
+ Unzip the dataset into the root directory of this repository: `unzip filter_data.zip`.
31
+
32
+ ## Usage
33
+ ### Zero-shot Evaluation
34
+ To evaluate a model on zero-shot tasks like BLiMP and the held-out BLiMP supplement tasks:
35
+
36
+ ```bash
37
+ python babylm_eval.py 'path/to/model_and_tokenizer' 'model_type'
38
+ ```
39
+
40
+ Where `model_type` is one of "encoder", "decoder" or "encoder-decoder".
41
+
42
+ ### Fine-tuning
43
+ To fine-tune and evaluate a model on tasks that require fine-tuning, like the (Super)GLUE tasks or held-out MSGS tasks:
44
+
45
+ ```bash
46
+ ./finetune_all_tasks.sh 'path/to/model_and_tokenizer'
47
+ ```
48
+
49
+ #### Hyperparameters
50
+ This script contains hyperparameter defaults that should work for a variety of model sizes, architectures, and tasks. You may adjust these hyperparameters as you wish, though we ask that you submit the best hyperparmeter settings in a README file if you don't use the defaults.
51
+
52
+ Here are the defaults that we use:
53
+ | Hyperparameter | Value |
54
+ | -------------- | ----- |
55
+ | Initial learning rate | 5e-5 |
56
+ | Batch size | 64 |
57
+ | Maximum epochs | 10 |
58
+ | Evaluate every (steps) | 200 |
59
+ | Patience | 10 |
60
+ | Random seed | 12 |
61
+
62
+ ## Uploading Results
63
+ We provide a shell script that will collect your results into a single file:
64
+
65
+ ```bash
66
+ ./collect_results.py path/to/model_and_tokenizer
67
+ ```
68
+
69
+ This will output a file called `all_predictions.json` in the root folder of this repository. We will ask you to upload this file to a submission portal.
70
+
71
+ We will also ask you to share a link where we can download your model and tokenizer.
72
+
73
+ ### Format of Predictions
74
+ If you wish to submit your results and you are not using the `collect_results.py` script, please ensure that your predictions file conforms to the submission format (example provided here as `sample_predictions.json`). This is a file consisting of line-separated JSON objects, where each line corresponds to a single subtask.
75
+
76
+ For each line, the JSON object includes a `task` field ("blimp", "glue", "supplement", or "msgs"), a `sub_task` field (the specific task, like "cola" or "anaphor_agreement"), and a `predictions` field, which is a list of JSON objects containing example IDs and predictions for those examples. Here is an example:
77
+
78
+ ```
79
+ {"task": "glue", "sub_task": "mnli", "predictions": [{"id": "mnli_0", "pred": 0}, {"id": "mnli_1": "pred": 1}, ..., {"id": "mnli_6561", "pred": 1}]}
80
+ ```
81
+
82
+ ### Age-of-acquisition prediction Evaluation
83
+ This evaluation is based on Portelance, Duan, Lupyan and Frank 2023 (see citation below).
84
+
85
+ If you want to run it, run the zero-shot evaluation script with the "--run_aoa" flag:
86
+
87
+ ```bash
88
+ python babylm_eval.py 'path/to/model_and_tokenizer' 'model_type' --run_aoa
89
+ ```
90
+
91
+ Note, the evaluation requires access to forward pass labels from your tokenizer. It currently expects the tokenizer to either produce them under the key "labels" if the model type is a "decoder" where labels represent the shifted "input_ids", or if no labels are provided, it will set the "labels" to be equal to the "input_ids" (this is done automatically for "encoder" and "encoder-decoder" type models. In the event that your labels are not equal to the input_ids, please make sure your tokenizer contains them under the key "labels".
92
+
93
+ Once it runs, it will produce two json files in a folder called "aoa_prediction" in the model directory provided. One of the files contains the estimated average surprisal of words for the model in child directed utterances taken from CHILDES. The other contains the results of the evaluation. Models are evaluated using leave-one-out cross validation. The results are Mean Absolute Deviation (MAD) scores in months between the actual average age-of-acquisition (AoA) of these words by American English speaking children and the predicted AoA based on the models average surprisal scores (the closer the MAD scores are to zero, the better). MAD scores are provided over all the words, over nouns, over predicates, and over function words. Previous work has found that models tend to do better at predicting the AoA of predicates and function words over nouns.
94
+
95
+ The better the fit, the better a model's predictions and the actual AoA of words in kids (the smaller the MAD scores), the more the order in which models learn words resembles the order in which children tend to learn words.
96
+
97
+ Note that, while we do not require you to run this evaluation or submit your score for our evaluation, we highly encourage you to compute this metric and discuss it in your paper!
98
+
99
+ ## Baselines
100
+ We provide a series of baseline models that we train on our strict or strict-small dataset. These are [hosted on HuggingFace](https://huggingface.co/babylm).
101
+
102
+ We simply take the hyperparameters used to pre-train the original versions of these models, and train them on our strict or strict-small datasets. While we do reduce the context length and, in some cases, the batch size, these are otherwise minimally modified.
103
+
104
+ Here are baseline scores. These are all accuracies, unless otherwise noted by (F1), where we use macro-F1. Random chance accuracy on all BLiMP tasks is 50.
105
+
106
+ **Strict-small Track**
107
+
108
+ *BLiMP*
109
+ | Model | Anaphor Agr. | Agr. Structure | Binding | Control/Raising | D-N Agr. | Ellipsis | Filler-Gap | Irregular Forms | Island Effects | NPI Licensing | Quantifiers | S-V Agr. |
110
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
111
+ | OPT-125m | 63.8 | 70.6 | 67.1 | 66.5 | 78.5 | 62 | 63.8 | 67.5 | 48.6 | 46.7 | 59.6 | 56.9 |
112
+ | RoBERTa-base | 81.5 | 67.1 | 67.3 | 67.9 | 90.8 | 76.4 | 63.5 | 87.4 | 39.9 | 55.9 | 70.5 | 65.4 |
113
+ | T5-base | 68.9 | 63.8 | 60.4 | 60.9 | 72.2 | 34.4 | 48.2 | 77.6 | 45.6 | 47.8 | 61.2 | 65.0 |
114
+
115
+ *BLiMP Supplement*
116
+ | Model | Hypernym | QA Congruence (easy) | QA Congruence (tricky) | Subj.-Aux. Inversion | Turn Taking |
117
+ | --- | --- | --- | --- | --- | --- |
118
+ | OPT-125m | 50.0 | 54.7 | 31.5 | 80.3 | 57.1 |
119
+ | RoBERTa-base | 49.4 | 31.3 | 32.1 | 71.7 | 53.2 |
120
+ | T5-base | 48.0 | 40.6 | 21.2 | 64.9 | 45.0 |
121
+
122
+ *(Super)GLUE*
123
+ | Model | CoLA | SST-2 | MRPC (F1) | QQP (F1) | MNLI | MNLI-mm | QNLI | RTE | BoolQ | MultiRC | WSC |
124
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
125
+ | *Majority label* | *69.5* | *50.2* | *82* | *53.1* | *35.7* | *35.7* | *35.4* | *53.1* | *50.5* | *59.9* | *53.2* | *61.4* |
126
+ | OPT-125m | 64.6 | 81.9 | 72.5 | 60.4 | 57.6 | 60.0 | 61.5 | 60.0 | 63.3 | 55.2 | 60.2 |
127
+ | RoBERTa-base | 70.8 | 87.0 | 79.2 | 73.7 | 73.2 | 74.0 | 77.0 | 61.6 | 66.3 | 61.4 | 61.4 |
128
+ | T5-base | 61.2 | 78.1 | 80.5 | 66.2 | 48.0 | 50.3 | 62.0 | 49.4 | 66.0 | 47.1 | 61.4 |
129
+
130
+ *MSGS*
131
+ | Model | CR (Control) | LC (Control) | MV (Control) | RP (Control) | SC (Control) | CR_LC | CR_RTP | MV_LC | MV_RTP | SC_LC | SC_RP |
132
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
133
+ | OPT-125m | 86.4 | 86.1 | 99.8 | 100.0 | 94.3 | 66.5 | 67.0 | 66.5 | 67.6 | 80.2 | 67.5 |
134
+ | RoBERTa-base | 84.1 | 100.0 | 99.4 | 93.5 | 96.4 | 67.7 | 68.6 | 66.7 | 68.6 | 84.2 | 65.7 |
135
+ | T5-base | 78.4 | 100.0 | 72.7 | 95.5 | 94.4 | 66.7 | 69.7 | 66.6 | 66.9 | 73.6 | 67.8 |
136
+
137
+ *Age-of-acquisition Prediction*
138
+ (Mean absolute deviation in months across LOO cross-validation folds)
139
+ | Model | Overall (591 words) | Nouns (322) | Predicates (167) | Function words (102) |
140
+ | --- | --- | --- | --- | --- |
141
+ | OPT-125m | 2.03 | 1.98 | 1.81 | 2.57 |
142
+ | RoBERTa-base | 2.06 | 1.99 | 1.85 | 2.65 |
143
+ | T5-base | 2.04 | 1.97 | 1.82 | 2.64 |
144
+
145
+ -------------
146
+
147
+ **Strict Track**
148
+
149
+ *BLiMP*
150
+ | Model | Anaphor Agr. | Agr. Structure | Binding | Control/Raising | D-N Agr. | Ellipsis | Filler-Gap | Irregular Forms | Island Effects | NPI Licensing | Quantifiers | S-V Agr. |
151
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
152
+ | OPT-125m | 94.9 | 73.8 | 73.8 | 72.2 | 93.1 | 80.5 | 73.6 | 80.8 | 57.8 | 51.6 | 74.5 | 77.3 |
153
+ | RoBERTa-base | 89.5 | 71.3 | 71 | 67.1 | 93.1 | 83.8 | 68.0 | 89.6 | 54.5 | 66.3 | 70.3 | 76.2 |
154
+ | T5-base | 66.7 | 61.2 | 59.4 | 59.8 | 53.8 | 49.1 | 70.0 | 75.5 | 43.6 | 45.6 | 34.2 | 53.2 |
155
+
156
+ *BLiMP Supplement*
157
+ | Model | Hypernym | QA Congruence (easy) | QA Congruence (tricky) | Subj.-Aux. Inversion | Turn Taking |
158
+ | --- | --- | --- | --- | --- | --- |
159
+ | OPT-125m | 46.3 | 76.5 | 47.9 | 85.3 | 82.9 |
160
+ | RoBERTa-base | 50.8 | 34.4 | 34.5 | 45.6 | 46.8 |
161
+ | T5-base | 51.1 | 45.3 | 25.5 | 69.2 | 48.9 |
162
+
163
+ *(Super)GLUE*
164
+ | Model | CoLA | SST-2 | MRPC (F1) | QQP (F1) | MNLI | MNLI-mm | QNLI | RTE | BoolQ | MultiRC | WSC |
165
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
166
+ | *Majority label* | *69.5* | *50.2* | *82* | *53.1* | *35.7* | *35.7* | *35.4* | *53.1* | *50.5* | *59.9* | *53.2* | *61.4* |
167
+ | OPT-125m | 73.7 | 86.6 | 82.1 | 77.8 | 70.1 | 71.9 | 80.1 | 67.7 | 66.0 | 61.1 | 59.0 |
168
+ | RoBERTa-base | 75.9 | 88.6 | 80.5 | 78.5 | 68.7 | 78.0 | 82.3 | 51.5 | 59.9 | 61.3 | 61.4 |
169
+ | T5-base | 76.3 | 88.0 | 85.9 | 79.7 | 71.5 | 74.0 | 83.1 | 60.6 | 69.0 | 62.4 | 60.2 |
170
+
171
+ *MSGS*
172
+ | Model | CR (Control) | LC (Control) | MV (Control) | RP (Control) | SC (Control) | CR_LC | CR_RTP | MV_LC | MV_RTP | SC_LC | SC_RP |
173
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
174
+ | OPT-125m | 97.2 | 82.6 | 100.0 | 99.8 | 88.1 | 75.3 | 67.1 | 66.3 | 66.8 | 84.8 | 62.0 |
175
+ | RoBERTa-base | 93.0 | 100.0 | 100.0 | 100.0 | 89.0 | 68.3 | 66.8 | 66.6 | 80.2 | 67.4 | 67.4 |
176
+ | T5-base | 95.1 | 100.0 | 100.0 | 99.8 | 88.7 | 76.7 | 69.4 | 67.0 | 67.7 | 72.7 | 68.0 |
177
+
178
+ -----------------------
179
+
180
+ These are naïve baselines that are meant to provide a starting point for investigation. We look forward to seeing how you will improve upon these!
181
+
182
+ ## Citation
183
+ If you use the datasets or code from this repository, please cite the BabyLM Call for Papers:
184
+
185
+ ```
186
+ @article{warstadt2023papers,
187
+ title = {Call for Papers -- The BabyLM Challenge: Sample-efficient pretraining on a developmentally plausible corpus},
188
+ author = {Warstadt, Alex and
189
+ Choshen, Leshem and
190
+ Mueller, Aaron and
191
+ Williams, Adina and
192
+ Wilcox, Ethan and
193
+ Zhuang, Chengxu},
194
+ year = {2023},
195
+ journal = {Computing Research Repository},
196
+ volume = {arXiv:2301.11796}
197
+ }
198
+ ```
199
+
200
+ Please also cite the lm-eval-harness paper:
201
+ ```
202
+ @software{eval-harness,
203
+ author = {Gao, Leo and
204
+ Tow, Jonathan and
205
+ Biderman, Stella and
206
+ Black, Sid and
207
+ DiPofi, Anthony and
208
+ Foster, Charles and
209
+ Golding, Laurence and
210
+ Hsu, Jeffrey and
211
+ McDonell, Kyle and
212
+ Muennighoff, Niklas and
213
+ Phang, Jason and
214
+ Reynolds, Laria and
215
+ Tang, Eric and
216
+ Thite, Anish and
217
+ Wang, Ben and
218
+ Wang, Kevin and
219
+ Zou, Andy},
220
+ title = {A framework for few-shot language model evaluation},
221
+ month = sep,
222
+ year = 2021,
223
+ publisher = {Zenodo},
224
+ version = {v0.0.1},
225
+ doi = {10.5281/zenodo.5371628},
226
+ url = {https://doi.org/10.5281/zenodo.5371628}
227
+ }
228
+ ```
229
+
230
+ Please cite the following if you choose to include the Age-of-acquisition prediction evaluation:
231
+ ```
232
+ @manuscript{portelance2023predicting,
233
+ author = {Portelance, Eva and Duan, Yuguang and Frank, Michael C. and Lupyan, Gary},
234
+ title = {Predicting age of acquisition for children’s early vocabulary in five languages using language model surprisal},
235
+ year = {2023},
236
+ url = {https://github.com/evaportelance/multilingual-aoa-prediction}
237
+ }
evaluation-pipeline/aoa_data/sent_words.json ADDED
The diff for this file is too large to render. See raw diff
 
evaluation-pipeline/aoa_data/word_list.csv ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ language,uni_lemma,lexical_category,category,definition,word_clean,aoa,concreteness,frequency
2
+ English (American),a,function_words,quantifiers,a,a,26.75657271813926,1.46,301773
3
+ English (American),a,function_words,quantifiers,an,an,26.75657271813926,1.46,13508
4
+ English (American),a lot,function_words,quantifiers,a lot,a lot,29.354943884668234,2.37,4807
5
+ English (American),about,function_words,locations,about,about,33.56541793707104,1.77,27478
6
+ English (American),above,function_words,locations,above,above,32.94888134846138,3.33,332
7
+ English (American),airplane,nouns,vehicles,airplane,airplane,20.14529714809586,4.96,1192
8
+ English (American),all,function_words,quantifiers,all,all,26.31156607337898,2.27,49585
9
+ English (American),all gone,predicates,descriptive_words,all gone,all gone,19.106125409049845,2.04,779
10
+ English (American),alligator,nouns,animals,alligator,alligator,25.74050182260553,4.96,404
11
+ English (American),am,predicates,helping_predicates,am,am,29.39866638780256,1.96,4070
12
+ English (American),and,function_words,connecting_words,and,and,27.669136574125037,1.52,217485
13
+ English (American),animal,nouns,animals,animal,animal,24.531890826243654,4.61,1523
14
+ English (American),ankle,nouns,body_parts,ankle,ankle,29.54373992549591,4.81,75
15
+ English (American),another,function_words,quantifiers,another,another,28.49498165323644,2.69,14222
16
+ English (American),ant,nouns,animals,ant,ant,24.632024173206105,4.86,182
17
+ English (American),any,function_words,quantifiers,any,any,30.168894359149128,1.72,12098
18
+ English (American),apple,nouns,food_drink,apple,apple,18.316415297779947,5,3736
19
+ English (American),applesauce,nouns,food_drink,applesauce,applesauce,25.18708208845118,4.96,127
20
+ English (American),are,function_words,helping_predicates,are,are,30.400848330016352,1.96,106583
21
+ English (American),arm,nouns,body_parts,arm,arm,21.679117916792883,4.96,1528
22
+ English (American),around,function_words,locations,around,around,29.73724069586142,1.96,6835
23
+ English (American),asleep,predicates,descriptive_words,asleep,asleep,24.95132838125333,3.71,1365
24
+ English (American),at,function_words,locations,at,at,28.44395214386389,2.07,52573
25
+ English (American),awake,predicates,descriptive_words,awake,awake,26.406667306484906,3.32,362
26
+ English (American),away,function_words,locations,away,away,27.268694284819865,2.23,11014
27
+ English (American),back (location),function_words,locations,back,back,26.041013448918488,4.33,26533
28
+ English (American),bad,predicates,descriptive_words,bad,bad,24.376033345405514,1.68,2576
29
+ English (American),ball,nouns,toys,ball,ball,14.051831559140178,5,8382
30
+ English (American),balloon,nouns,toys,balloon,balloon,17.252991342080126,4.92,1810
31
+ English (American),banana,nouns,food_drink,banana,banana,16.787250784202772,5,1615
32
+ English (American),basement,nouns,furniture_rooms,basement,basement,31.403406659378565,4.89,121
33
+ English (American),basket,nouns,household,basket,basket,25.32137110090939,5,1734
34
+ English (American),bat,nouns,toys,bat,bat,25.94740000625428,5,384
35
+ English (American),bathroom,nouns,furniture_rooms,bathroom,bathroom,23.22834292081228,4.52,1059
36
+ English (American),bathtub,nouns,furniture_rooms,bathtub,bathtub,21.86077443068652,4.92,410
37
+ English (American),be,function_words,helping_predicates,be,be,30.344096265123305,1.85,41097
38
+ English (American),beach,nouns,outside,beach,beach,26.078273320304067,4.79,991
39
+ English (American),beads,nouns,clothing,beads,beads,29.819752587655973,4.9,546
40
+ English (American),beans,nouns,food_drink,beans,beans,24.532090787380607,5,1249
41
+ English (American),bear,nouns,animals,bear,bear,19.290426322598368,4.88,5220
42
+ English (American),because,function_words,connecting_words,because,because,30.412366644638137,1.22,31730
43
+ English (American),bed,nouns,furniture_rooms,bed,bed,20.494046155718603,5,7584
44
+ English (American),bedroom,nouns,furniture_rooms,bedroom,bedroom,25.645644681903754,4.9,1119
45
+ English (American),bee,nouns,animals,bee,bee,21.306296871726428,4.88,1475
46
+ English (American),behind,function_words,locations,behind,behind,29.581051780523048,3.48,2954
47
+ English (American),belly button,nouns,body_parts,belly button,belly button,20.62619109370771,5,90
48
+ English (American),belt,nouns,clothing,belt,belt,25.39428676791078,4.9,307
49
+ English (American),bench,nouns,furniture_rooms,bench,bench,31.122752354523378,4.87,241
50
+ English (American),beside,function_words,locations,beside,beside,33.68775817791739,2.59,304
51
+ English (American),better,predicates,descriptive_words,better,better,27.197801378663197,1.91,9742
52
+ English (American),bib,nouns,clothing,bib,bib,23.648183674597796,4.79,639
53
+ English (American),bicycle,nouns,vehicles,bicycle,bicycle,21.77871249104521,4.89,660
54
+ English (American),big,predicates,descriptive_words,big,big,22.25931777062911,3.66,25182
55
+ English (American),bird,nouns,animals,bird,bird,17.224492119324236,5,2517
56
+ English (American),bite,predicates,action_words,bite,bite,21.93843222383973,4.44,2541
57
+ English (American),black,predicates,descriptive_words,black,black,26.65032453394826,3.76,2775
58
+ English (American),blanket,nouns,household,blanket,blanket,20.364584241108936,5,957
59
+ English (American),block,nouns,toys,block,block,21.47767824557252,4.48,1117
60
+ English (American),blow,predicates,action_words,blow,blow,24.100630216525534,3.74,2110
61
+ English (American),blue,predicates,descriptive_words,blue,blue,23.520465305593365,3.76,9232
62
+ English (American),boat,nouns,vehicles,boat,boat,20.384388304955454,4.93,2544
63
+ English (American),book,nouns,toys,book,book,16.378840412498462,4.9,15413
64
+ English (American),boots,nouns,clothing,boots,boots,22.762953333636315,5,792
65
+ English (American),bottle,nouns,household,bottle,bottle,18.109441114425163,4.91,3023
66
+ English (American),bowl,nouns,household,bowl,bowl,22.67450309415727,4.87,1967
67
+ English (American),box,nouns,household,box,box,22.36283488674821,4.9,8714
68
+ English (American),bread,nouns,food_drink,bread,bread,21.714838666180317,4.92,2959
69
+ English (American),break,predicates,action_words,break,break,24.498575833372556,3.71,2940
70
+ English (American),bring,predicates,action_words,bring,bring,27.00190998469981,2.55,5164
71
+ English (American),broken,predicates,descriptive_words,broken,broken,23.262899073559634,4.11,2733
72
+ English (American),broom,nouns,household,broom,broom,23.51056906797502,4.89,282
73
+ English (American),brown,predicates,descriptive_words,brown,brown,27.44722287259727,4.48,2294
74
+ English (American),brush (object),nouns,household,brush,brush,21.812402640756495,4.54,2162
75
+ English (American),bubbles,nouns,toys,bubbles,bubbles,18.447326266810368,4.6,1229
76
+ English (American),bucket,nouns,household,bucket,bucket,26.11855610121108,4.96,896
77
+ English (American),bug,nouns,animals,bug,bug,21.45346928441042,5,653
78
+ English (American),build,predicates,action_words,build,build,27.561167006392587,3.71,2552
79
+ English (American),bump,predicates,action_words,bump,bump,25.507631046994266,4.1,1008
80
+ English (American),bunny,nouns,animals,bunny,bunny,20.465056141535673,4.97,2386
81
+ English (American),bus,nouns,vehicles,bus,bus,21.261211792115443,4.9,3774
82
+ English (American),but,function_words,connecting_words,but,but,32.30802214785319,2.04,34537
83
+ English (American),butter,nouns,food_drink,butter,butter,24.566501758151283,4.9,1358
84
+ English (American),butterfly,nouns,animals,butterfly,butterfly,23.47450828971274,4.93,882
85
+ English (American),button,nouns,clothing,button,button,22.084011296770807,4.96,1602
86
+ English (American),buy,predicates,action_words,buy,buy,27.61820820612325,3.35,3593
87
+ English (American),by,function_words,locations,by,by,28.916261166336813,1.55,5847
88
+ English (American),cake,nouns,food_drink,cake,cake,21.93745596797483,4.81,3506
89
+ English (American),camera,nouns,household,camera,camera,25.73750398456283,5,1185
90
+ English (American),can (auxiliary),function_words,helping_predicates,can (auxiliary),can,27.82698008632811,4.55,175734
91
+ English (American),can (object),nouns,household,can (object),can,26.84891293682625,4.55,175734
92
+ English (American),candy,nouns,food_drink,candy,candy,22.10696542716163,4.83,704
93
+ English (American),car,nouns,vehicles,car,car,17.53434303192908,4.89,13476
94
+ English (American),careful,predicates,descriptive_words,careful,careful,26.43412690050291,1.86,6107
95
+ English (American),carrots,nouns,food_drink,carrots,carrots,24.037122543158606,5,802
96
+ English (American),carry,predicates,action_words,carry,carry,25.681963506798628,4.04,1148
97
+ English (American),cat,nouns,animals,cat,cat,17.67814164845057,4.86,5835
98
+ English (American),catch,predicates,action_words,catch,catch,25.556075994667953,4.11,2813
99
+ English (American),cereal,nouns,food_drink,cereal,cereal,22.086966073355658,4.83,1034
100
+ English (American),chair,nouns,furniture_rooms,chair,chair,20.747062695367397,4.58,6382
101
+ English (American),chalk,nouns,toys,chalk,chalk,27.572948668482248,4.9,246
102
+ English (American),chase,predicates,action_words,chase,chase,28.40000722125352,3.48,251
103
+ English (American),cheek,nouns,body_parts,cheek,cheek,23.639051249460564,4.83,159
104
+ English (American),cheerios,nouns,food_drink,cheerios,cheerios,23.30250911956345,4.35,59
105
+ English (American),cheese,nouns,food_drink,cheese,cheese,18.35624365220089,4.7,4215
106
+ English (American),chicken (animal),nouns,animals,chicken (animal),chicken,22.94116221978306,4.8,5636
107
+ English (American),chicken (food),nouns,food_drink,chicken (food),chicken,22.755311666095626,4.8,5636
108
+ English (American),chin,nouns,body_parts,chin,chin,23.932790792488237,4.89,444
109
+ English (American),chips,nouns,food_drink,potato chip,potato chip,23.914163430448284,4.9,23
110
+ English (American),chocolate,nouns,food_drink,chocolate,chocolate,25.207246056049254,4.72,2469
111
+ English (American),church,nouns,outside,church*,church,26.377623217552873,4.9,547
112
+ English (American),clap,predicates,action_words,clap,clap,23.57129610232303,4.16,1106
113
+ English (American),clean (action),predicates,action_words,clean (action),clean,24.56600009616096,3.07,7338
114
+ English (American),clean (description),predicates,descriptive_words,clean (description),clean,24.16485158037349,3.07,7338
115
+ English (American),climb,predicates,action_words,climb,climb,25.941366782032414,4.11,1076
116
+ English (American),clock,nouns,household,clock,clock,22.729118690605997,5,1709
117
+ English (American),close,predicates,action_words,close,close,24.612899480281406,3.2,3138
118
+ English (American),closet,nouns,furniture_rooms,closet,closet,26.33273273898802,4.83,289
119
+ English (American),cloud,nouns,outside,cloud,cloud,25.68327028006053,4.54,273
120
+ English (American),coat,nouns,clothing,coat,coat,22.77758807471102,4.97,1191
121
+ English (American),coffee,nouns,food_drink,coffee,coffee,24.733868049413292,4.81,2249
122
+ English (American),coke,nouns,food_drink,coke,coke,28.250686610987113,4.83,184
123
+ English (American),cold,predicates,descriptive_words,cold,cold,20.986347269894612,3.85,3891
124
+ English (American),comb (object),nouns,household,comb,comb,24.521530115219505,5,639
125
+ English (American),cook,predicates,action_words,cook,cook,25.20950610885458,4.32,1634
126
+ English (American),cookie,nouns,food_drink,cookie,cookie,18.05879104299356,5,2651
127
+ English (American),corn,nouns,food_drink,corn,corn,23.75808620462897,4.96,769
128
+ English (American),couch,nouns,furniture_rooms,couch,couch,24.81633921615295,4.71,505
129
+ English (American),could,function_words,helping_predicates,could,could,33.0915181485895,1.34,12880
130
+ English (American),cover (action),predicates,action_words,cover,cover,28.093896291699608,4.23,902
131
+ English (American),cow,nouns,animals,cow,cow,20.23330616534318,4.96,3496
132
+ English (American),cracker,nouns,food_drink,cracker,cracker,19.128739975548182,4.96,471
133
+ English (American),crayon,nouns,toys,crayon,crayon,22.958268446308498,4.87,1010
134
+ English (American),crib,nouns,furniture_rooms,crib,crib,25.54633696377014,4.86,306
135
+ English (American),cry,predicates,action_words,cry,cry,22.833033348617004,4,1408
136
+ English (American),cup,nouns,household,cup,cup,19.458761353171624,5,5361
137
+ English (American),cut,predicates,action_words,cut,cut,26.834383653830635,4.55,3650
138
+ English (American),cute,predicates,descriptive_words,cute,cute,26.878579973455473,2.76,1371
139
+ English (American),dance,predicates,action_words,dance,dance,23.594173710650814,4.32,1107
140
+ English (American),dark,predicates,descriptive_words,dark,dark,26.374254558849202,4.29,1494
141
+ English (American),deer,nouns,animals,deer,deer,26.28895723853603,4.86,374
142
+ English (American),diaper,nouns,clothing,diaper,diaper,19.45888352722782,4.82,1072
143
+ English (American),did,function_words,helping_predicates,did/did ya,did,28.236905169713484,2.45,57888
144
+ English (American),dirty,predicates,descriptive_words,dirty,dirty,22.183512254438906,4.23,2706
145
+ English (American),dish,nouns,household,dish,dish,26.369638755777036,4.9,312
146
+ English (American),do,function_words,helping_predicates,do,do,24.418127084458625,2.46,157341
147
+ English (American),does,function_words,helping_predicates,does,does,31.321420112088582,2.24,30079
148
+ English (American),dog,nouns,animals,dog,dog,14.594052719227676,4.85,5509
149
+ English (American),doll,nouns,toys,doll,doll,21.41564709887175,5,1830
150
+ English (American),don't,function_words,helping_predicates,don't,dont,25.29034229368797,2.46,89665
151
+ English (American),donkey,nouns,animals,donkey,donkey,27.89414096656381,5,575
152
+ English (American),donut,nouns,food_drink,donut,donut,26.088004339085252,4.93,98
153
+ English (American),door,nouns,furniture_rooms,door,door,20.2792407612697,4.81,6193
154
+ English (American),down,function_words,locations,down,down,19.778758085736765,3.52,31240
155
+ English (American),draw,predicates,action_words,draw,draw,26.127344086880825,3.97,4917
156
+ English (American),drawer,nouns,furniture_rooms,drawer,drawer,27.477050929051146,4.67,511
157
+ English (American),dress (object),nouns,clothing,dress (object),dress,25.175475858275057,4.93,2087
158
+ English (American),drink (action),predicates,action_words,drink (action),drink,21.405832133186447,3.77,12546
159
+ English (American),drink (beverage),nouns,food_drink,drink (beverage),drink,21.12191463243953,4.76,12546
160
+ English (American),drive,predicates,action_words,drive,drive,24.75429950810191,3.86,1883
161
+ English (American),drop,predicates,action_words,drop,drop,26.14791694487336,4.21,1105
162
+ English (American),dry (action),predicates,action_words,dry (action),dry,26.69818180786187,3.77,3410
163
+ English (American),dry (description),predicates,descriptive_words,dry (description),dry,26.486133398623007,3.77,3410
164
+ English (American),dryer,nouns,furniture_rooms,dryer,dryer,27.940244672930877,4.79,93
165
+ English (American),duck,nouns,animals,duck,duck,17.185401989712528,4.86,2872
166
+ English (American),dump,predicates,action_words,dump,dump,29.574191643049147,3.93,626
167
+ English (American),each,function_words,quantifiers,each,each,34.433173955126186,2.03,1275
168
+ English (American),ear,nouns,body_parts,ear,ear,18.42450761164981,5,1260
169
+ English (American),eat,predicates,action_words,eat,eat,19.996890077067878,4.44,18091
170
+ English (American),egg,nouns,food_drink,egg,egg,22.122988028871536,4.97,2550
171
+ English (American),elephant,nouns,animals,elephant,elephant,23.021554163445344,5,2858
172
+ English (American),empty,predicates,descriptive_words,empty,empty,26.56355703829002,3.43,1237
173
+ English (American),every,function_words,quantifiers,every,every,32.62625782784631,2.28,1932
174
+ English (American),eye,nouns,body_parts,eye,eye,17.19831986641664,4.9,1696
175
+ English (American),face,nouns,body_parts,face,face,23.386576805200583,4.87,4356
176
+ English (American),fall,predicates,action_words,fall,fall,23.05658646359307,4.04,4547
177
+ English (American),fast,predicates,descriptive_words,fast,fast,26.397899335243192,3.32,1814
178
+ English (American),feed,predicates,action_words,feed,feed,27.04318304347576,4.17,1696
179
+ English (American),find,predicates,action_words,find,find,25.911291431365097,2.63,11096
180
+ English (American),fine,predicates,descriptive_words,fine,fine,30.348259169087953,2.61,1791
181
+ English (American),finger,nouns,body_parts,finger,finger,21.846032665491855,5,2157
182
+ English (American),finish,predicates,action_words,finish,finish,28.14761497515676,2.89,2774
183
+ English (American),firetruck,nouns,vehicles,firetruck,firetruck,24.716233162853985,5,149
184
+ English (American),first,predicates,descriptive_words,first,first,28.530149212482925,2.76,8389
185
+ English (American),fish (animal),nouns,animals,fish (animal),fish,18.978116085220503,5,9298
186
+ English (American),fish (food),nouns,food_drink,fish (food),fish,22.085905665472275,5,9298
187
+ English (American),fit,predicates,action_words,fit,fit,29.08064200730688,2.7,3997
188
+ English (American),fix,predicates,action_words,fix,fix,25.32658824937031,2.93,2929
189
+ English (American),flag,nouns,outside,flag,flag,26.39411115381629,4.79,236
190
+ English (American),flower,nouns,outside,flower,flower,20.519981351232357,5,1361
191
+ English (American),food,nouns,food_drink,food,food,23.490400956729655,4.8,6233
192
+ English (American),foot,nouns,body_parts,foot,foot,20.351627730476352,4.9,3505
193
+ English (American),for,function_words,locations,for,for,29.21964285739064,1.63,60043
194
+ English (American),fork,nouns,household,fork,fork,21.912707160579416,4.9,782
195
+ English (American),french fries,nouns,food_drink,french fries,french fries,22.485372598777225,4.87,111
196
+ English (American),frog,nouns,animals,frog,frog,22.53087514553091,5,1734
197
+ English (American),full,predicates,descriptive_words,full,full,27.307650021326054,3.59,1585
198
+ English (American),game,nouns,toys,game,game,26.558324042448465,4.5,2813
199
+ English (American),garage,nouns,furniture_rooms,garage,garage,26.95193574573295,4.96,1135
200
+ English (American),garbage,nouns,household,garbage,garbage,25.263290629707857,4.69,493
201
+ English (American),garden,nouns,outside,garden,garden,28.814903721740233,4.73,1711
202
+ English (American),gentle,predicates,descriptive_words,gentle,gentle,27.53063486592105,2.53,955
203
+ English (American),get,predicates,action_words,get,get,24.203818250784888,2.38,55665
204
+ English (American),giraffe,nouns,animals,giraffe,giraffe,24.848340134105648,4.73,1156
205
+ English (American),give,predicates,action_words,give,give,26.131793055183277,2.83,13726
206
+ English (American),glass,nouns,household,glass,glass,25.377947756405593,4.82,1069
207
+ English (American),glasses,nouns,household,glasses,glasses,23.382539516196495,4.9,985
208
+ English (American),gloves,nouns,clothing,gloves,gloves,27.24887506361188,4.97,339
209
+ English (American),glue,nouns,toys,glue,glue,29.779166021342032,4.65,672
210
+ English (American),go,predicates,action_words,go,go,19.73419022328145,3.15,83559
211
+ English (American),good,predicates,descriptive_words,good,good,23.555059836026327,1.64,42780
212
+ English (American),goose,nouns,animals,goose,goose,26.868415336421975,4.81,522
213
+ English (American),grapes,nouns,food_drink,grapes,grapes,21.87000053388467,5,1148
214
+ English (American),grass,nouns,outside,grass,grass,23.421522474544503,4.93,1407
215
+ English (American),green,predicates,descriptive_words,green,green,24.864917218093773,4.07,8568
216
+ English (American),green beans,nouns,food_drink,green beans,green beans,28.18246325512689,4.9,224
217
+ English (American),gum,nouns,food_drink,gum,gum,25.6705889024626,4.89,374
218
+ English (American),hair,nouns,body_parts,hair,hair,19.550956015647447,4.97,6378
219
+ English (American),hamburger,nouns,food_drink,hamburger,hamburger,24.060486137223638,5,565
220
+ English (American),hammer,nouns,household,hammer,hammer,25.908134489269617,4.77,860
221
+ English (American),hand,nouns,body_parts,hand,hand,20.888392084906826,4.72,6426
222
+ English (American),happy,predicates,descriptive_words,happy,happy,24.111067699312272,2.56,3476
223
+ English (American),hard,predicates,descriptive_words,hard,hard,28.34690319460537,3.76,4563
224
+ English (American),hat,nouns,clothing,hat,hat,18.800006578327608,4.88,5643
225
+ English (American),hate,predicates,action_words,hate,hate,32.742713404389164,1.97,285
226
+ English (American),have,predicates,action_words,have,have,26.383343346266226,2.18,80189
227
+ English (American),he,function_words,pronouns,he,he,28.39328352610605,3.93,85599
228
+ English (American),head,nouns,body_parts,head,head,21.52867556120851,4.75,7286
229
+ English (American),hear,predicates,action_words,hear,hear,27.103048512621903,3.66,6278
230
+ English (American),heavy,predicates,descriptive_words,heavy,heavy,25.14874997804902,3.37,1182
231
+ English (American),helicopter,nouns,vehicles,helicopter,helicopter,24.90634156578962,4.62,729
232
+ English (American),help,predicates,action_words,help,help,22.819438880083318,2.56,8981
233
+ English (American),hen,nouns,animals,hen,hen,29.623281978610162,4.9,378
234
+ English (American),her,function_words,pronouns,her,her,30.0706499832329,3,32518
235
+ English (American),here,function_words,locations,here,here,25.0324996525398,3.13,74502
236
+ English (American),hers,function_words,pronouns,hers,hers,31.577356326543732,2.61,401
237
+ English (American),hide,predicates,action_words,hide,hide,25.6831882822722,3.21,1461
238
+ English (American),high,predicates,descriptive_words,high,high,27.021723647237135,3.46,1690
239
+ English (American),high chair,nouns,furniture_rooms,high chair,high chair,25.143576833379374,4.83,177
240
+ English (American),him,function_words,pronouns,him,him,30.171545513305684,3.54,24073
241
+ English (American),his,function_words,pronouns,his,his,30.86529830099037,3.14,25985
242
+ English (American),hit,predicates,action_words,hit,hit,24.176504122997176,4.11,2339
243
+ English (American),hold,predicates,action_words,hold,hold,25.28951191411586,3.68,6702
244
+ English (American),home,nouns,outside,home,home,21.55292850686028,4.11,9648
245
+ English (American),horse,nouns,animals,horse,horse,20.598917207238273,5,4162
246
+ English (American),hose,nouns,outside,hose,hose,26.925240566139266,4.87,264
247
+ English (American),hot,predicates,descriptive_words,hot,hot,17.886174346828543,4.31,4425
248
+ English (American),house,nouns,outside,house,house,22.949798098688984,5,12111
249
+ English (American),how,function_words,question_words,how,how,30.185466664457547,1.35,31682
250
+ English (American),hug,predicates,action_words,hug,hug,22.04054246795061,4.14,1172
251
+ English (American),hungry,predicates,descriptive_words,hungry,hungry,24.529656637397714,2.9,2717
252
+ English (American),hurry,predicates,action_words,hurry,hurry,27.48425052166916,2.63,865
253
+ English (American),hurt (description),predicates,descriptive_words,hurt,hurt,24.88161558121455,3.61,4613
254
+ English (American),i,function_words,pronouns,I,i,23.977441347865177,3.93,786
255
+ English (American),ice,nouns,food_drink,ice,ice,22.358270283361815,4.89,2197
256
+ English (American),ice cream,nouns,food_drink,ice cream,ice cream,21.580952159819738,5,1557
257
+ English (American),if,function_words,connecting_words,if,if,34.068154850176526,1.19,31526
258
+ English (American),in,function_words,locations,in,in,24.07962150691501,3,276036
259
+ English (American),in,function_words,locations,inside/in,inside,24.07962150691501,3,7888
260
+ English (American),inside,function_words,locations,inside,inside,28.910801367846076,3.67,7888
261
+ English (American),into,function_words,locations,into,into,32.328072400666066,2.3,7862
262
+ English (American),is,function_words,helping_predicates,is,is,28.508756906338796,1.59,183357
263
+ English (American),it,function_words,pronouns,it,it,25.985519116000557,2.81,297679
264
+ English (American),jacket,nouns,clothing,jacket,jacket,23.764267757552943,4.86,655
265
+ English (American),jar,nouns,household,jar,jar,30.036814769417507,5,389
266
+ English (American),jeans,nouns,clothing,jeans,jeans,27.85718213630826,5,160
267
+ English (American),jelly,nouns,food_drink,jelly,jelly,26.459272534245788,4.93,851
268
+ English (American),juice,nouns,food_drink,juice,juice,17.663424879988565,4.89,6380
269
+ English (American),jump,predicates,action_words,jump,jump,23.05187845463102,4.52,2396
270
+ English (American),keys,nouns,household,keys,keys,19.821178140120676,4.89,1273
271
+ English (American),kick,predicates,action_words,kick,kick,24.607244736468125,4.33,925
272
+ English (American),kiss,predicates,action_words,kiss,kiss,20.97729762630762,4.48,3370
273
+ English (American),kitchen,nouns,furniture_rooms,kitchen,kitchen,23.721678813935878,4.97,2439
274
+ English (American),kitty,nouns,animals,kitty,kitty,17.76353044822186,4.97,2807
275
+ English (American),knee,nouns,body_parts,knee,knee,22.83341234944545,5,1252
276
+ English (American),knife,nouns,household,knife,knife,25.180125523737622,4.9,749
277
+ English (American),knock,predicates,action_words,knock,knock,25.65520970263338,4.24,1500
278
+ English (American),ladder,nouns,outside,ladder,ladder,27.453139889383696,5,836
279
+ English (American),lamb,nouns,animals,lamb,lamb,26.77611745254101,4.97,762
280
+ English (American),lamp,nouns,household,lamp,lamp,27.707727325952707,4.97,286
281
+ English (American),last,predicates,descriptive_words,last,last,31.94810812999018,3.04,6041
282
+ English (American),lawn mower,nouns,outside,lawn mower,lawn mower,26.25206641047887,4.93,37
283
+ English (American),leg,nouns,body_parts,leg,leg,22.786751225180204,4.83,1696
284
+ English (American),lick,predicates,action_words,lick,lick,27.885918786410006,4.52,443
285
+ English (American),light (object),nouns,household,light,light,20.167269067810214,4.21,2752
286
+ English (American),like (action),predicates,action_words,like,like,25.712763627585442,1.89,80659
287
+ English (American),lion,nouns,animals,lion,lion,23.292560818293822,4.96,1972
288
+ English (American),listen,predicates,action_words,listen,listen,28.120047324042673,3.47,3194
289
+ English (American),little (description),predicates,descriptive_words,little (description),little,25.166304259548355,3.67,39012
290
+ English (American),living room,nouns,furniture_rooms,living room,living room,27.67343106925516,4.7,431
291
+ English (American),lollipop,nouns,food_drink,lollipop,lollipop,27.20359032793206,4.96,276
292
+ English (American),long,predicates,descriptive_words,long,long,30.43920077538411,3.18,5656
293
+ English (American),look,predicates,action_words,look,look,24.07200126089267,2.96,68469
294
+ English (American),loud,predicates,descriptive_words,loud,loud,27.096587104346657,3.73,1100
295
+ English (American),love,predicates,action_words,love,love,22.97930051104563,2.07,5139
296
+ English (American),mad,predicates,descriptive_words,mad,mad,28.322211878333118,2.76,839
297
+ English (American),make,predicates,action_words,make,make,27.26683722139889,2.67,22678
298
+ English (American),me,function_words,pronouns,me,me,21.782136908963487,4.33,58317
299
+ English (American),meat,nouns,food_drink,meat,meat,25.21618096142793,4.9,986
300
+ English (American),medicine,nouns,household,medicine,medicine,24.410637544584084,4.79,915
301
+ English (American),melon,nouns,food_drink,melon,melon,26.929946230882774,4.78,141
302
+ English (American),milk,nouns,food_drink,milk,milk,18.304538681163276,4.92,5537
303
+ English (American),mine,function_words,pronouns,mine,mine,20.0092783421445,3.56,2670
304
+ English (American),mittens,nouns,clothing,mittens,mittens,27.13676422394422,4.89,267
305
+ English (American),money,nouns,household,money,money,22.84702188801892,4.54,3251
306
+ English (American),monkey,nouns,animals,monkey,monkey,21.75146876358306,4.9,2316
307
+ English (American),moon,nouns,outside,moon,moon,21.064582625649372,4.9,1461
308
+ English (American),moose,nouns,animals,moose,moose,30.726348818983883,4.97,324
309
+ English (American),mop,nouns,household,mop,mop,28.697523528698856,4.97,158
310
+ English (American),more,function_words,quantifiers,more,more,19.934125196097916,2.37,23403
311
+ English (American),motorcycle,nouns,vehicles,motorcycle,motorcycle,25.424516980060698,4.97,366
312
+ English (American),mouse,nouns,animals,mouse,mouse,23.186364426729803,4.83,1784
313
+ English (American),mouth,nouns,body_parts,mouth,mouth,20.385274871125226,4.74,6017
314
+ English (American),much,function_words,quantifiers,much,much,31.135471437484984,1.69,7404
315
+ English (American),muffin,nouns,food_drink,muffin,muffin,26.053662526327358,4.78,219
316
+ English (American),my,function_words,pronouns,my,my,24.67561156823274,2.42,30474
317
+ English (American),myself,function_words,pronouns,myself,myself,30.826981734088697,2.97,674
318
+ English (American),nail (object),nouns,household,nail,nail,27.745919885712205,4.93,268
319
+ English (American),napkin,nouns,household,napkin,napkin,24.71066092570806,4.93,393
320
+ English (American),naughty,predicates,descriptive_words,naughty,naughty,30.45927863451864,2.04,2904
321
+ English (American),necklace,nouns,clothing,necklace,necklace,25.67583784602768,4.96,341
322
+ English (American),need,function_words,helping_predicates,need/need to,need,28.517326473959855,1.69,11101
323
+ English (American),new,predicates,descriptive_words,new,new,28.242927764036946,2.81,5522
324
+ English (American),nice,predicates,descriptive_words,nice,nice,24.731878757128417,2.18,20152
325
+ English (American),noisy,predicates,descriptive_words,noisy,noisy,28.238292864810433,3.56,903
326
+ English (American),none,function_words,quantifiers,none,none,30.075465085938674,2.59,494
327
+ English (American),nose,nouns,body_parts,nose,nose,17.50000892567104,4.89,5607
328
+ English (American),not,function_words,quantifiers,not,not,28.331503696333467,2.08,62788
329
+ English (American),of,function_words,locations,of,of,32.135421130600605,1.67,72422
330
+ English (American),off,function_words,locations,off,off,21.76331515371575,2.79,21580
331
+ English (American),old,predicates,descriptive_words,old,old,29.745205894423886,2.72,3975
332
+ English (American),on,function_words,locations,on,on,22.07453703332649,3.25,130164
333
+ English (American),open (action),predicates,action_words,open,open,21.70959024951605,3.21,8246
334
+ English (American),orange (description),predicates,descriptive_words,orange (description),orange,24.48307542955755,4.66,10036
335
+ English (American),orange (food),nouns,food_drink,orange (food),orange,22.862362842722305,4.66,10036
336
+ English (American),other,function_words,quantifiers,other,other,29.008003039766972,2.04,15644
337
+ English (American),our,function_words,pronouns,our,our,31.879580552349164,1.97,6116
338
+ English (American),out,function_words,locations,out,out,21.787538623492427,2.73,34288
339
+ English (American),outside,nouns,outside,outside,outside,20.10026304783487,4.25,5164
340
+ English (American),oven,nouns,furniture_rooms,oven,oven,26.959440376130473,4.97,718
341
+ English (American),over,function_words,locations,over,over,27.81126335036735,2.46,23641
342
+ English (American),owie,nouns,body_parts,owie/boo boo,owie,19.225364028172503,3.61,101
343
+ English (American),owl,nouns,animals,owl,owl,24.378811443862723,4.93,737
344
+ English (American),paint (action),predicates,action_words,paint,paint,26.7264001349599,4.79,1346
345
+ English (American),pajamas,nouns,clothing,pajamas,pajamas,23.01441672978766,4.73,776
346
+ English (American),pancake,nouns,food_drink,pancake,pancake,24.195947688413984,4.86,201
347
+ English (American),pants,nouns,clothing,pants,pants,21.997653199154513,4.86,2028
348
+ English (American),paper,nouns,household,paper,paper,22.40794784536237,4.93,4643
349
+ English (American),park,nouns,outside,park,park,23.44395480659095,4.74,1855
350
+ English (American),party,nouns,outside,party,party,26.48232416632208,3.89,2705
351
+ English (American),pasta,nouns,food_drink,noodles,noodles,22.2125626020018,4.86,209
352
+ English (American),pasta,nouns,food_drink,spaghetti,spaghetti,22.2125626020018,4.86,1466
353
+ English (American),peanut butter,nouns,food_drink,peanut butter,peanut butter,24.48646845168075,4.93,323
354
+ English (American),peas,nouns,food_drink,peas,peas,24.557921410443495,4.9,2307
355
+ English (American),pen,nouns,toys,pen,pen,23.51987496977609,4.92,1411
356
+ English (American),pencil,nouns,toys,pencil,pencil,25.06258390684458,4.88,1040
357
+ English (American),penguin,nouns,animals,penguin,penguin,27.293224141508716,5,658
358
+ English (American),penis,nouns,body_parts,penis*,penis,26.231902171762034,5,35
359
+ English (American),penny,nouns,household,penny,penny,26.32129034179081,4.83,575
360
+ English (American),pick,predicates,action_words,pick,pick,28.350959500123274,3.82,4884
361
+ English (American),pickle,nouns,food_drink,pickle,pickle,25.496142784956177,4.64,191
362
+ English (American),picture,nouns,household,picture,picture,24.228451852721275,4.52,6309
363
+ English (American),pig,nouns,animals,pig,pig,21.04970478014681,5,2423
364
+ English (American),pillow,nouns,household,pillow,pillow,22.179110907856753,5,683
365
+ English (American),pizza,nouns,food_drink,pizza,pizza,21.33010054090465,5,2650
366
+ English (American),plant,nouns,household,plant,plant,26.161845259337724,4.76,519
367
+ English (American),plate,nouns,household,plate,plate,24.38848139227323,4.77,2600
368
+ English (American),play,predicates,action_words,play,play,22.50225294745721,3.24,23148
369
+ English (American),play dough,nouns,toys,play dough,play dough,27.200019866322975,4.68,124
370
+ English (American),play pen,nouns,furniture_rooms,play pen,play pen,30.93414000000259,4.76,13
371
+ English (American),pony,nouns,animals,pony,pony,27.149124759679015,4.9,253
372
+ English (American),pool,nouns,outside,pool,pool,23.288489299463958,4.77,860
373
+ English (American),poor,predicates,descriptive_words,poor,poor,32.66767129734731,2.7,2640
374
+ English (American),popcorn,nouns,food_drink,popcorn,popcorn,23.68702745961217,5,195
375
+ English (American),popsicle,nouns,food_drink,popsicle,popsicle,25.14044583723922,4.93,120
376
+ English (American),porch,nouns,furniture_rooms,porch,porch,29.70353523171374,4.92,84
377
+ English (American),potato,nouns,food_drink,potato,potato,25.045299416217585,4.85,594
378
+ English (American),potty,nouns,furniture_rooms,potty,potty,21.163868967261262,4.12,991
379
+ English (American),pour,predicates,action_words,pour,pour,28.27835611871483,4.14,1410
380
+ English (American),present,nouns,toys,present,present,24.99147354255208,3.39,1400
381
+ English (American),pretend,predicates,action_words,pretend,pretend,31.275328228201392,2.11,3413
382
+ English (American),pretty,predicates,descriptive_words,pretty,pretty,23.70523132395096,2.4,6516
383
+ English (American),pretzel,nouns,food_drink,pretzel,pretzel,27.086772724245172,4.74,85
384
+ English (American),pudding,nouns,food_drink,pudding,pudding,28.336874661648956,4.9,306
385
+ English (American),pull,predicates,action_words,pull,pull,26.41351492122096,3.97,4797
386
+ English (American),pumpkin,nouns,food_drink,pumpkin,pumpkin,25.596056826431344,4.9,815
387
+ English (American),puppy,nouns,animals,puppy,puppy,20.642644342886626,4.78,1308
388
+ English (American),purse,nouns,household,purse,purse,24.680534115242512,4.9,487
389
+ English (American),push,predicates,action_words,push,push,24.884039995017684,4.21,5386
390
+ English (American),put,predicates,action_words,put,put,27.180432184212417,2.5,68322
391
+ English (American),puzzle,nouns,toys,puzzle,puzzle,24.603177970245078,4.75,2062
392
+ English (American),quiet,predicates,descriptive_words,quiet,quiet,27.05139131191479,2.76,1380
393
+ English (American),radio,nouns,household,radio,radio,26.613053034699238,4.74,355
394
+ English (American),rain,nouns,outside,rain,rain,22.05272569057193,4.97,1240
395
+ English (American),raisin,nouns,food_drink,raisin,raisin,23.922862069518597,4.97,169
396
+ English (American),read,predicates,action_words,read,read,22.864582930368915,3.56,9185
397
+ English (American),red,predicates,descriptive_words,red,red,24.476663524110176,4.24,9917
398
+ English (American),refrigerator,nouns,furniture_rooms,refrigerator,refrigerator,25.673848500166034,5,562
399
+ English (American),ride,predicates,action_words,ride,ride,24.3290998464415,3.75,2928
400
+ English (American),rip,predicates,action_words,rip,rip,30.898483534092605,3.79,375
401
+ English (American),rock (object),nouns,outside,rock,rock,22.092980833031184,4.91,875
402
+ English (American),rocking chair,nouns,furniture_rooms,rocking chair,rocking chair,26.286720661876167,4.93,184
403
+ English (American),roof,nouns,outside,roof,roof,29.380455204401983,4.79,941
404
+ English (American),room,nouns,furniture_rooms,room,room,24.7800417765674,4.79,5211
405
+ English (American),rooster,nouns,animals,rooster,rooster,27.785104097477404,4.75,422
406
+ English (American),run,predicates,action_words,run,run,23.547368180082476,4.31,2505
407
+ English (American),sad,predicates,descriptive_words,sad,sad,26.975730544989975,3.07,1405
408
+ English (American),salt,nouns,food_drink,salt,salt,28.441896714165853,4.89,431
409
+ English (American),same,function_words,quantifiers,same,same,30.94396519191967,2.64,3923
410
+ English (American),sandbox,nouns,outside,sandbox,sandbox,26.956125375322088,4.86,172
411
+ English (American),sandwich,nouns,food_drink,sandwich,sandwich,24.33836806143716,4.9,1683
412
+ English (American),sauce,nouns,food_drink,sauce,sauce,27.988140408941376,4.75,487
413
+ English (American),say,predicates,action_words,say,say,27.350714856102098,2.58,29942
414
+ English (American),scared,predicates,descriptive_words,scared,scared,27.284769726224756,2.5,1001
415
+ English (American),scarf,nouns,clothing,scarf,scarf,31.0680540145124,4.97,254
416
+ English (American),school,nouns,outside,school,school,23.424986892471757,4.79,6710
417
+ English (American),scissors,nouns,household,scissors,scissors,25.34069479638193,4.85,742
418
+ English (American),see,predicates,action_words,see,see,22.628651743930725,3.21,71442
419
+ English (American),shake,predicates,action_words,shake,shake,27.417577200447113,4.07,2018
420
+ English (American),share,predicates,action_words,share,share,26.777735575736017,2.96,1061
421
+ English (American),she,function_words,pronouns,she,she,29.293434421039155,3.36,53246
422
+ English (American),sheep,nouns,animals,sheep,sheep,23.925866583400786,4.9,2362
423
+ English (American),shirt,nouns,clothing,shirt,shirt,21.792127463554,4.94,2380
424
+ English (American),shoe,nouns,clothing,shoe,shoe,16.401616618833103,4.97,2169
425
+ English (American),shorts,nouns,clothing,shorts,shorts,24.909759184344438,4.82,425
426
+ English (American),shoulder,nouns,body_parts,shoulder,shoulder,27.357714981859722,4.93,225
427
+ English (American),shovel,nouns,outside,shovel,shovel,25.93264008363907,4.97,291
428
+ English (American),show,predicates,action_words,show,show,27.85277401420022,3.97,8568
429
+ English (American),shower,nouns,furniture_rooms,shower,shower,23.85617473782963,4.89,513
430
+ English (American),sick,predicates,descriptive_words,sick,sick,27.025423107263375,2.97,1207
431
+ English (American),sidewalk,nouns,outside,sidewalk,sidewalk,27.982232325403388,4.96,104
432
+ English (American),sing,predicates,action_words,sing,sing,24.699537103250435,4.34,3851
433
+ English (American),sink,nouns,furniture_rooms,sink,sink,25.65056395838028,4.74,560
434
+ English (American),sit,predicates,action_words,sit,sit,21.750618675138146,4.8,14108
435
+ English (American),skate,predicates,action_words,skate,skate,30.980023419231532,4.56,55
436
+ English (American),sky,nouns,outside,sky,sky,24.179550783288896,4.45,1303
437
+ English (American),sled,nouns,vehicles,sled,sled,29.4219079215242,5,90
438
+ English (American),sleep,predicates,action_words,sleep,sleep,22.7674333859663,4.44,5010
439
+ English (American),sleepy,predicates,descriptive_words,sleepy,sleepy,25.765911658239688,2.77,808
440
+ English (American),slide (action),predicates,action_words,slide (action),slide,24.394104047595913,4.48,3556
441
+ English (American),slide (object),nouns,outside,slide (object),slide,23.27441979107034,4.48,3556
442
+ English (American),slipper,nouns,clothing,slipper,slipper,25.90935922531163,4.86,266
443
+ English (American),slow,predicates,descriptive_words,slow,slow,29.462982166623352,3.28,515
444
+ English (American),smile,predicates,action_words,smile,smile,27.022198912378336,4.5,498
445
+ English (American),sneaker,nouns,clothing,sneaker,sneaker,28.458789287265894,4.69,22
446
+ English (American),snow,nouns,outside,snow,snow,25.263272056571832,4.85,1575
447
+ English (American),snowman,nouns,outside,snowman,snowman,27.67210714348651,4.64,577
448
+ English (American),snowsuit,nouns,clothing,snowsuit,snowsuit,32.10541910633961,5,14
449
+ English (American),so,function_words,connecting_words,so,so,31.12075549333711,1.42,44980
450
+ English (American),soap,nouns,household,soap,soap,22.217921774180518,4.93,709
451
+ English (American),sock,nouns,clothing,sock,sock,19.632046621854386,4.91,831
452
+ English (American),soda,nouns,food_drink,soda/pop,soda,24.87205183714649,4.97,226
453
+ English (American),sofa,nouns,furniture_rooms,sofa,sofa,29.394839148936164,4.9,450
454
+ English (American),soft,predicates,descriptive_words,soft,soft,26.4496476384763,3.88,1358
455
+ English (American),some,function_words,quantifiers,some,some,26.15437450894456,2.48,45706
456
+ English (American),soup,nouns,food_drink,soup,soup,24.537539621938286,4.72,1288
457
+ English (American),spill,predicates,action_words,spill,spill,26.85160156093012,4.07,741
458
+ English (American),splash,predicates,action_words,splash,splash,25.60191719014938,4.19,709
459
+ English (American),spoon,nouns,household,spoon,spoon,20.22002234723444,4.96,3524
460
+ English (American),sprinkler,nouns,outside,sprinkler,sprinkler,28.75113806495684,4.89,52
461
+ English (American),squirrel,nouns,animals,squirrel,squirrel,25.05065234245397,4.89,507
462
+ English (American),stairs,nouns,furniture_rooms,stairs,stairs,24.47753335085588,5,1063
463
+ English (American),stand,predicates,action_words,stand,stand,26.47937683978296,4.16,3558
464
+ English (American),star,nouns,outside,star,star,22.957358462903812,4.69,1068
465
+ English (American),stay,predicates,action_words,stay,stay,26.586593702088443,2.15,4403
466
+ English (American),stick,nouns,outside,stick,stick,24.363668955777232,4.59,2642
467
+ English (American),sticky,predicates,descriptive_words,sticky,sticky,26.569871206088944,3.59,1177
468
+ English (American),stone,nouns,outside,stone,stone,29.654573348257873,4.72,306
469
+ English (American),stop,predicates,action_words,stop,stop,22.813711423562257,3.68,5527
470
+ English (American),store,nouns,outside,store,store,23.347629882628436,4.5,1651
471
+ English (American),story,nouns,toys,story,story,24.92454125516168,3.3,5318
472
+ English (American),stove,nouns,furniture_rooms,stove,stove,26.381537023983125,4.96,520
473
+ English (American),strawberry,nouns,food_drink,strawberry,strawberry,24.304122215327734,5,840
474
+ English (American),street,nouns,outside,street,street,25.6074840807896,4.75,987
475
+ English (American),stroller,nouns,vehicles,stroller,stroller,24.603444785777125,4.96,227
476
+ English (American),stuck,predicates,descriptive_words,stuck,stuck,25.790527319514812,3.55,3519
477
+ English (American),sun,nouns,outside,sun,sun,23.386638497101277,4.83,1983
478
+ English (American),sweater,nouns,clothing,sweater,sweater,24.620590384363602,4.78,310
479
+ English (American),sweep,predicates,action_words,sweep,sweep,26.53419291818447,3.72,266
480
+ English (American),swim,predicates,action_words,swim,swim,24.83257594574256,4.43,986
481
+ English (American),swing (action),predicates,action_words,swing (action),swing,23.099517041407093,4.54,2158
482
+ English (American),swing (object),nouns,outside,swing (object),swing,21.97332053501421,4.54,2158
483
+ English (American),table,nouns,furniture_rooms,table,table,23.395064163035677,4.9,5798
484
+ English (American),take,predicates,action_words,take,take,27.354093799677152,3.06,20398
485
+ English (American),talk,predicates,action_words,talk,talk,26.172898281486297,4.07,4771
486
+ English (American),tape,nouns,household,tape,tape,25.98869069431121,4.9,2967
487
+ English (American),taste,predicates,action_words,taste,taste,28.306250651871636,4.07,1493
488
+ English (American),tear,predicates,action_words,tear,tear,30.110713846716816,4.56,352
489
+ English (American),teddybear,nouns,animals,teddybear,teddybear,22.457673785720814,4.87,513
490
+ English (American),telephone,nouns,household,telephone,telephone,20.80553350305347,4.96,1280
491
+ English (American),that,function_words,pronouns,that,that,24.03974924284265,1.54,219719
492
+ English (American),the,function_words,quantifiers,the,the,27.71532064680694,1.43,431031
493
+ English (American),their,function_words,pronouns,their,their,33.050453300967234,3.34,5083
494
+ English (American),them,function_words,pronouns,them,them,31.425327261028436,3.04,41587
495
+ English (American),then,function_words,connecting_words,then,then,32.94497320291506,1.44,43062
496
+ English (American),there,function_words,locations,there,there,25.554374013411266,2.2,106697
497
+ English (American),these,function_words,pronouns,these,these,28.91030410540727,2.03,20843
498
+ English (American),they,function_words,pronouns,they,they,31.558011791688703,2.93,53290
499
+ English (American),think,predicates,action_words,think,think,31.060977381002104,2.41,57446
500
+ English (American),thirsty,predicates,descriptive_words,thirsty,thirsty,25.9814458268787,3.86,776
501
+ English (American),this,function_words,pronouns,this,this,25.53668411833393,2.14,112409
502
+ English (American),those,function_words,pronouns,those,those,30.71305685632802,2.32,19370
503
+ English (American),throw,predicates,action_words,throw,throw,24.82027667799749,4.04,5585
504
+ English (American),tickle,predicates,action_words,tickle,tickle,23.030865141786716,3.85,2094
505
+ English (American),tiger,nouns,animals,tiger,tiger,23.97601642667219,5,2349
506
+ English (American),tights,nouns,clothing,tights,tights,30.49526782372822,4.62,89
507
+ English (American),tiny,predicates,descriptive_words,tiny,tiny,30.75118196119715,3.11,1454
508
+ English (American),tired,predicates,descriptive_words,tired,tired,26.126063847560406,3,3628
509
+ English (American),tissue,nouns,household,tissue/kleenex,tissue,24.881517554334437,4.93,915
510
+ English (American),to,function_words,locations,to,to,27.829074756482076,1.55,183409
511
+ English (American),toast,nouns,food_drink,toast,toast,22.957745051917446,4.93,2117
512
+ English (American),toe,nouns,body_parts,toe,toe,21.063402869488534,4.93,596
513
+ English (American),tongue,nouns,body_parts,tongue,tongue,23.578714641827492,4.93,776
514
+ English (American),too,function_words,quantifiers,too,too,25.97451456969294,1.7,21317
515
+ English (American),tooth,nouns,body_parts,tooth,tooth,21.390186244463926,4.89,351
516
+ English (American),toothbrush,nouns,household,toothbrush,toothbrush,21.327972861784076,5,330
517
+ English (American),touch,predicates,action_words,touch,touch,26.140740016873888,3.86,3096
518
+ English (American),towel,nouns,household,towel,towel,23.309359030136616,4.86,942
519
+ English (American),toy (object),nouns,toys,toy (object),toy,21.250379422750402,4.93,2764
520
+ English (American),tractor,nouns,vehicles,tractor,tractor,26.293460903708173,5,1903
521
+ English (American),train,nouns,vehicles,train,train,21.050773507323704,4.79,8225
522
+ English (American),trash,nouns,household,trash,trash,24.623003619992428,4.7,297
523
+ English (American),tray,nouns,household,tray,tray,31.297608014031766,4.74,570
524
+ English (American),tree,nouns,outside,tree,tree,20.395692984405432,5,4310
525
+ English (American),tricycle,nouns,vehicles,tricycle,tricycle,28.84180554601145,4.68,163
526
+ English (American),truck,nouns,vehicles,truck,truck,19.04437063778738,4.84,4906
527
+ English (American),try,function_words,helping_predicates,try/try to,try,28.751119300000134,2.22,8718
528
+ English (American),tummy,nouns,body_parts,tummy,tummy,21.281768482103764,4.68,1772
529
+ English (American),tuna,nouns,food_drink,tuna,tuna,28.649288768887633,4.89,208
530
+ English (American),turkey,nouns,animals,turkey,turkey,26.30455622910081,4.89,611
531
+ English (American),turtle,nouns,animals,turtle,turtle,23.014453310177558,5,792
532
+ English (American),tv,nouns,furniture_rooms,TV,tv,21.36643906838051,5,1285
533
+ English (American),under,function_words,locations,under,under,27.467319313886602,3.45,4364
534
+ English (American),underpants,nouns,clothing,underpants,underpants,27.702339180277328,4.89,111
535
+ English (American),up,function_words,locations,up,up,19.536229246282858,3.83,54966
536
+ English (American),us,function_words,pronouns,us,us,32.68418082412553,3.59,7432
537
+ English (American),vacuum,nouns,household,vacuum,vacuum,24.31715488103081,4.22,241
538
+ English (American),vagina,nouns,body_parts,vagina*,vagina,30.74482822160873,4.82,8
539
+ English (American),vanilla,nouns,food_drink,vanilla,vanilla,31.134282822644582,4.68,196
540
+ English (American),vitamins,nouns,food_drink,vitamins,vitamins,26.849949095931386,4.5,85
541
+ English (American),wait,predicates,action_words,wait,wait,26.620371092775404,2.68,7959
542
+ English (American),wake,predicates,action_words,wake,wake,27.154377902728353,3.11,1167
543
+ English (American),walk,predicates,action_words,walk,walk,22.817811861035416,4.07,3506
544
+ English (American),walker,nouns,household,walker,walker,31.785543166543064,4.42,60
545
+ English (American),wanna,function_words,helping_predicates,wanna/want to,wanna,25.18163215638973,1.93,45282
546
+ English (American),was,function_words,helping_predicates,was,was,31.797860743565355,1.69,47639
547
+ English (American),wash,predicates,action_words,wash,wash,23.987564663405482,4.35,3451
548
+ English (American),washing machine,nouns,furniture_rooms,washing machine,washing machine,27.543044986998385,4.89,239
549
+ English (American),watch (action),predicates,action_words,watch (action),watch,25.924613964341088,4.61,15632
550
+ English (American),watch (object),nouns,household,watch (object),watch,24.00259582021144,4.61,15632
551
+ English (American),water (beverage),nouns,food_drink,water (beverage),water,19.123463892055845,5,17388
552
+ English (American),water (not beverage),nouns,outside,water (not beverage),water,19.45099861331479,5,17388
553
+ English (American),we,function_words,pronouns,we,we,30.182434631151455,3.08,111064
554
+ English (American),were,function_words,helping_predicates,were,were,33.709463033181024,1.48,30396
555
+ English (American),wet (description),predicates,descriptive_words,wet,wet,22.298452425741512,4.46,2542
556
+ English (American),what,function_words,question_words,what,what,23.658782166516907,2,205010
557
+ English (American),when (question),function_words,question_words,when,when,31.814907045715227,1.6,27792
558
+ English (American),where (question),function_words,question_words,where,where,25.7164381182961,1.66,38793
559
+ English (American),which (question),function_words,question_words,which,which,33.63776900674318,1.54,10214
560
+ English (American),white,predicates,descriptive_words,white,white,27.648764293432254,3.89,3496
561
+ English (American),who,function_words,question_words,who,who,27.953549755744795,1.74,20283
562
+ English (American),why,function_words,question_words,why,why,27.262555741780712,1.86,22267
563
+ English (American),will,function_words,helping_predicates,will,will,30.909905381379183,2.64,14927
564
+ English (American),wind,nouns,outside,wind,wind,26.19931053900361,3.93,1298
565
+ English (American),window,nouns,furniture_rooms,window,window,24.48492597146611,4.86,2662
566
+ English (American),windy,predicates,descriptive_words,windy,windy,27.431143183092633,3.86,342
567
+ English (American),wipe,predicates,action_words,wipe,wipe,25.95723852087949,4,1809
568
+ English (American),wish,predicates,action_words,wish,wish,32.96609018388594,1.77,669
569
+ English (American),with,function_words,locations,with,with,28.56625914577001,2,64176
570
+ English (American),wolf,nouns,animals,wolf,wolf,28.251389709841927,4.79,431
571
+ English (American),work (action),predicates,action_words,work (action),work,24.762232083800356,3.48,12134
572
+ English (American),work (place),nouns,outside,work (place),work,24.024006606906344,3.48,12134
573
+ English (American),would,function_words,helping_predicates,would,would,34.17580948877974,1.12,22070
574
+ English (American),write,predicates,action_words,write,write,26.86079876248854,4.22,2971
575
+ English (American),yard,nouns,outside,backyard,backyard,26.10807276380005,4.82,105
576
+ English (American),yellow,predicates,descriptive_words,yellow,yellow,24.5595931762692,4.3,6782
577
+ English (American),yogurt,nouns,food_drink,yogurt,yogurt,23.91372922424347,4.9,589
578
+ English (American),you,function_words,pronouns,you,you,24.120602892947364,4.11,589501
579
+ English (American),your,function_words,pronouns,your,your,29.787082244817054,2.37,105998
580
+ English (American),yourself,function_words,pronouns,yourself,yourself,34.28546272279592,4.39,3279
581
+ English (American),yucky,predicates,descriptive_words,yucky,yucky,22.051017838612175,1.86,724
582
+ English (American),zebra,nouns,animals,zebra,zebra,25.31795862018206,4.86,902
583
+ English (American),zipper,nouns,clothing,zipper,zipper,24.84585073879806,4.83,421
584
+ English (American),zoo,nouns,outside,zoo,zoo,25.777390810890576,4.81,1804
585
+ English (American),butt,nouns,body_parts,buttocks/bottom*,bottom,21.98056796070707,4.75,2253
586
+ English (American),did,function_words,helping_predicates,did/did ya,did ya,28.236905169713484,2.45,195
587
+ English (American),in,function_words,locations,inside/in,in,24.07962150691501,3,276036
588
+ English (American),need,function_words,helping_predicates,need/need to,need to,28.517326473959855,1.69,829
589
+ English (American),soda,nouns,food_drink,soda/pop,pop,24.87205183714649,4.97,2512
590
+ English (American),tissue,nouns,household,tissue/kleenex,kleenex,24.881517554334437,4.93,91
591
+ English (American),try,function_words,helping_predicates,try/try to,try to,28.751119300000134,2.22,1273
592
+ English (American),wanna,function_words,helping_predicates,wanna/want to,want to,25.18163215638973,1.93,1415
evaluation-pipeline/assets/babylm.png ADDED

Git LFS Details

  • SHA256: 7785304abdfd889ca8f480e00d4b9630602d4926ba5cdd7aa190e15626581398
  • Pointer size: 131 Bytes
  • Size of remote file: 255 kB
evaluation-pipeline/babylm_eval.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import lm_eval
3
+ import os
4
+ import json
5
+
6
+ TASKS = {
7
+ "blimp": ["anaphor_agreement.json", "argument_structure.json", "binding.json",
8
+ "control_raising.json", "determiner_noun_agreement.json", "ellipsis.json",
9
+ "filler_gap.json", "irregular_forms.json", "island_effects.json",
10
+ "npi_licensing.json", "quantifiers.json", "subject_verb_agreement.json"],
11
+ "supplement": ["hypernym.json", "qa_congruence_easy.json", "qa_congruence_tricky.json",
12
+ "subject_aux_inversion.json", "turn_taking.json"]
13
+ }
14
+
15
+
16
+ def accuracy_on_task(task_name, eval_model, template_name, num_fewshot):
17
+ predictions_path = os.path.join(args.model_path, "zeroshot", task_title, "predictions.txt")
18
+ predictions_dir = os.path.dirname(predictions_path)
19
+ if not os.path.exists(predictions_dir):
20
+ os.makedirs(predictions_dir)
21
+
22
+ eval_task = lm_eval.get_task_list(task_name, template_names=[template_name])
23
+ results = lm_eval.evaluate(model=eval_model, tasks=eval_task, seed=12,
24
+ num_fewshot=num_fewshot, predictions_path=predictions_path)
25
+ accuracy = results['results'][0]['acc']
26
+ return accuracy
27
+
28
+
29
+ if __name__ == "__main__":
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument("model_path", type=str,
32
+ help="Path to huggingface model and tokenizer.")
33
+ parser.add_argument("model_type", type=str, choices=["decoder only", "decoder", "encoder only", "encoder", "encoder-decoder",],
34
+ help="Language model architecture.")
35
+ parser.add_argument("--tasks", "-t", type=str, choices=["blimp", "supplement", "all"], default="all",
36
+ help="Tasks on which we evaluate.")
37
+ parser.add_argument("--run_aoa", "-a", action="store_true",
38
+ help="Will run the additional AoA prediction task.")
39
+ parser.add_argument("--trust_remote_code", "-r", action="store_true",
40
+ help="Trust remote code (e.g. from huggingface) when loading model.")
41
+ parser.add_argument("--num_fewshot", "-n", type=int, default=0,
42
+ help="Number of few-shot examples to show the model for each test example.")
43
+ args = parser.parse_args()
44
+
45
+ MODEL_TYPE_REMAP = {"decoder only": "hf-causal", "decoder": "hf-causal",
46
+ "encoder only": "hf-mlm", "encoder": "hf-mlm",
47
+ "encoder-decoder": "hf-seq2seq",}
48
+ eval_model = lm_eval.get_model(MODEL_TYPE_REMAP[args.model_type],
49
+ pretrained=args.model_path,
50
+ trust_remote_code=args.trust_remote_code,
51
+ device="cuda")
52
+ tasks = []
53
+ if args.tasks == "all":
54
+ for task_type in TASKS.keys():
55
+ tasks.extend(TASKS[task_type])
56
+ else:
57
+ tasks = TASKS[args.tasks]
58
+
59
+ accuracies = {}
60
+ # Iterate through tasks, get accuracies
61
+ for task in tasks:
62
+ if task in TASKS["blimp"]:
63
+ template = None
64
+ task_title = task.split(".json")[0]
65
+ task = f"blimp_from_file:filter-data/blimp_filtered/{task}"
66
+ elif task in TASKS["supplement"]:
67
+ template = None
68
+ task_title = task.split(".json")[0]
69
+ task = f"blimp_from_file:filter-data/supplement_filtered/{task}"
70
+ else:
71
+ raise ValueError("Unrecognized task!")
72
+ accuracies[task_title] = accuracy_on_task(task, eval_model, template,
73
+ args.num_fewshot)
74
+ print(f"{task_title}:\t{accuracies[task_title] * 100:.2f}%")
75
+ # Write scores to file
76
+ out_path = os.path.join(args.model_path, "zeroshot", task_title, "eval_results.json")
77
+ out_dir = os.path.dirname(out_path)
78
+ if not os.path.exists(out_dir):
79
+ os.makedirs(out_dir)
80
+ with open(out_path, 'w') as out_file:
81
+ json.dump({"eval_accuracy": accuracies[task_title]}, out_file)
82
+
83
+ # Print scores
84
+ print("\nScores:")
85
+ for task in accuracies.keys():
86
+ print(f"{task}:\t{accuracies[task] * 100:.2f}%")
87
+
88
+ if args.run_aoa:
89
+ # Run AoA prediction evaluation
90
+ word_surprisals_n, mad_results = lm_eval.aoa_pred_eval(eval_model.model, eval_model.tokenizer, MODEL_TYPE_REMAP[args.model_type], batch_size = 32)
91
+ out_dir = os.path.join(args.model_path, "aoa_prediction")
92
+ if not os.path.exists(out_dir):
93
+ os.makedirs(out_dir)
94
+ with open(os.path.join(out_dir, "extracted_average_surprisals.json") , 'w') as out_file:
95
+ json.dump(word_surprisals_n, out_file)
96
+ with open(os.path.join(out_dir, "mean_absolute_deviation_results.json"), 'w') as out_file:
97
+ json.dump(mad_results, out_file)
evaluation-pipeline/collect_results.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import json
4
+
5
+ TASKS = {
6
+ "glue": ["cola", "sst2", "mrpc", "qqp", "mnli", "mnli-mm", "qnli", "rte",
7
+ "boolq", "multirc", "wsc"],
8
+ "blimp": ["anaphor_agreement", "argument_structure", "binding", "control_raising",
9
+ "determiner_noun_agreement", "ellipsis", "filler_gap", "irregular_forms",
10
+ "island_effects", "npi_licensing", "quantifiers", "subject_verb_agreement"],
11
+ "supplement": ["hypernym", "qa_congruence_easy", "qa_congruence_tricky",
12
+ "subject_aux_inversion", "turn_taking"],
13
+ "msgs": ["main_verb_control", "control_raising_control", "syntactic_category_control",
14
+ "relative_position_control", "lexical_content_the_control",
15
+ "main_verb_lexical_content_the", "main_verb_relative_token_position",
16
+ "control_raising_lexical_content_the", "control_raising_relative_token_position",
17
+ "syntactic_category_lexical_content_the", "syntactic_category_relative_position"]
18
+ }
19
+
20
+ def make_task_dict(task_name, preds_path):
21
+ def _add_to_dict(index, prediction, task_dict):
22
+ example_id = f"{task_name}_{index}"
23
+ prediction = prediction.replace("\\n", "\n")
24
+ task_dict["predictions"].append({"id": example_id, "pred": prediction})
25
+
26
+ if task_name in TASKS["glue"]:
27
+ task_type = "glue"
28
+ elif task_name in TASKS["blimp"]:
29
+ task_type = "blimp"
30
+ elif task_name in TASKS["supplement"]:
31
+ task_type = "supplement"
32
+ elif task_name in TASKS["msgs"]:
33
+ task_type = "msgs"
34
+ else:
35
+ raise ValueError(f"Invalid task: {task_name}!")
36
+
37
+ if not os.path.exists(preds_path):
38
+ raise FileNotFoundError(f"Warning: no predictions found for the \"{task_name}\" ({task_type}) task!")
39
+
40
+ task_dict = {"task": task_type, "sub_task": task_name, "predictions": []}
41
+ with open(preds_path, 'r') as predictions_file:
42
+ # skip header
43
+ next(predictions_file)
44
+ # collect predictions with ids
45
+ index = None
46
+ prediction = None
47
+ for line in predictions_file:
48
+ if "\t" in line:
49
+ # add to prediction list
50
+ if prediction:
51
+ _add_to_dict(index, prediction, task_dict)
52
+ # start new prediction
53
+ index, prediction = line.strip().split("\t")
54
+ else:
55
+ prediction += "\n" + line.strip()
56
+ # handle final prediction
57
+ _add_to_dict(index, prediction, task_dict)
58
+
59
+ return task_dict
60
+
61
+
62
+ if __name__ == "__main__":
63
+ parser = argparse.ArgumentParser()
64
+ parser.add_argument("model_path", type=str,
65
+ help="Path to huggingface model and tokenizer.")
66
+ args = parser.parse_args()
67
+
68
+ task_dicts = {}
69
+ for task in TASKS["glue"]:
70
+ preds_path = os.path.join(args.model_path, "finetune", task, "predict_results.txt")
71
+ task_dicts[task] = make_task_dict(task, preds_path)
72
+ for task in TASKS["msgs"]:
73
+ preds_path = os.path.join(args.model_path, "finetune", task, "predict_results.txt")
74
+ task_dicts[task] = make_task_dict(task, preds_path)
75
+ for task in TASKS["blimp"]:
76
+ preds_path = os.path.join(args.model_path, "zeroshot", task, "predictions.txt")
77
+ task_dicts[task] = make_task_dict(task, preds_path)
78
+ for task in TASKS["supplement"]:
79
+ preds_path = os.path.join(args.model_path, "zeroshot", task, "predictions.txt")
80
+ task_dicts[task] = make_task_dict(task, preds_path)
81
+
82
+ with open("all_predictions.json", "w") as predictions_out:
83
+ for task in task_dicts:
84
+ predictions_out.write(json.dumps(task_dicts[task]) + "\n")
85
+ print("Predictions output at `all_predictions.json`.")
evaluation-pipeline/docs/img/fewshot_example_gpt3.png ADDED

Git LFS Details

  • SHA256: 6af5dc2196248b29260ba443e882725dd6cfc51ef17ad5a4dbab4f8ce6850c75
  • Pointer size: 131 Bytes
  • Size of remote file: 316 kB
evaluation-pipeline/docs/task_guide.md ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `Task` Guide
2
+
3
+ The `Task` class is the foundation of all natural language tasks in the `lm-evaluation-harness` (harness). It encompasses everything you’d need to perform few-shot evaluation of an autoregressive language model. Here we’ll provide a step-by-step guide on how to subclass `Task` to create your very own task/s.
4
+
5
+ ## Setup
6
+
7
+ If you haven't already, go ahead and fork the main repo, clone it, create a branch with the name of your task, and install the project requirements in your environment:
8
+
9
+ ```sh
10
+ # After forking...
11
+ git clone https://github.com/<YOUR-USERNAME>/lm-evaluation-harness.git
12
+ cd lm-evaluation-harness
13
+ git checkout -b <task-name>
14
+ pip install -e ".[dev]"
15
+ ```
16
+
17
+ ## Creating Your Task File
18
+
19
+ From the `lm-evaluation-harness` project root, copy over the `new_task.py` template to `lm_eval/datasets`.
20
+
21
+ ```sh
22
+ cp templates/new_task.py lm_eval/tasks/<task-name>.py
23
+ ```
24
+
25
+ or if your task is **multiple-choice**, the `new_multiple_choice_task.py`:
26
+
27
+ ```sh
28
+ cp templates/new_multiple_choice_task.py lm_eval/tasks/<task-name>.py
29
+ ```
30
+
31
+ This will set you up with a few `TODO`s to fill-in which we'll now go over in detail.
32
+
33
+ ## Task Heading
34
+
35
+ Open the file you've just created and add a multiline docstring on the first line with the following contents:
36
+
37
+ ```python
38
+ """
39
+ <Paper title>
40
+ <Paper PDF URL>
41
+
42
+ <Short description of task>
43
+
44
+ Homepage: <URL to task's homepage>
45
+ """
46
+ ```
47
+
48
+ For example, take the QuAC dataset. We have:
49
+
50
+ ```python
51
+ """
52
+ QuAC: Question Answering in Context
53
+ https://arxiv.org/abs/1808.07036
54
+
55
+ Question Answering in Context (QuAC) is a dataset for modeling, understanding, and
56
+ participating in information seeking dialog. Data instances consist of an interactive
57
+ dialog between two crowd workers: (1) a student who poses a sequence of freeform
58
+ questions to learn as much as possible about a hidden Wikipedia text, and (2)
59
+ a teacher who answers the questions by providing short excerpts (spans) from the text.
60
+
61
+ Homepage: https://quac.ai/
62
+ """
63
+ ```
64
+
65
+ Next, at the module-level, create a constant variable named
66
+ `_CITATION` that contains the citation information for your task in BibTeX format.
67
+
68
+ Now let's walk through the actual implementation - from data handling to evaluation.
69
+
70
+ ## Data Handling
71
+
72
+ ### Downloading your Data
73
+
74
+ All data downloading and management is handled through the HuggingFace (**HF**) [`datasets`](https://github.com/huggingface/datasets) API. So, the first thing you should do is check to see if your task's dataset is already provided in their catalog [here](https://huggingface.co/datasets). If it's not in there, please consider adding it to their Hub to make it accessible to a wider user base by following their [new dataset guide](https://github.com/huggingface/datasets/blob/master/ADD_NEW_DATASET.md)
75
+ .
76
+ Now, that you have your HF dataset, you need to assign its path and name to your `Task` in the following fields:
77
+
78
+ ```python
79
+ class TaskName(...):
80
+ DATASET_PATH = "..."
81
+ DATASET_NAME = "..."
82
+ ```
83
+
84
+ where `DATASET_PATH` is the name of the dataset as listed by HF in the `datasets` Hub and `DATASET_NAME` is the name of, what HF calls, a “data instance” or sub-task of the benchmark. If your task does not contain any data instances, just set `DATASET_NAME = None`.
85
+ (If you're familiar with the HF `datasets.load_dataset` function, these are just the first 2 arguments to it.)
86
+
87
+ Next up, we have to set some “flags”:
88
+
89
+ ```python
90
+ def has_training_docs(self):
91
+ return # True/False
92
+
93
+ def has_validation_docs(self):
94
+ return # True/False
95
+
96
+ def has_test_docs(self):
97
+ return # True/False
98
+ ```
99
+
100
+ These methods return `True`/`False` whether or not your task dataset provides documents for each split type. __Note__: if the test set does not have publicly available answer labels, please do not put it down as having a test set - return False.
101
+
102
+ Lastly, we need to load the documents. In our terminology, a document (`doc`) is a single natural language data example stored in a Python `dict`. E.g.: `{“question”: “What is the capital of France?”, “answer”: “Paris”}`. Override the following methods to load your data splits from their storage location in `DATASET_PATH`:
103
+
104
+ ```python
105
+ def training_docs(self):
106
+ return #...
107
+
108
+ def validation_docs(self):
109
+ return #...
110
+
111
+ def test_docs(self):
112
+ return #...
113
+ ```
114
+
115
+ These should return a Python iterable (`list` or `generator`) of `dict`s that can be queried for individual `doc` examples.
116
+
117
+ #### Processing Documents
118
+
119
+ At this point, you can also process each individual document to, for example, strip whitespace or "detokenize" its fields. Put the processing logic into `_process_doc` and map the functions across training/validation/test docs inside of the respective functions.
120
+ 🔠 If your task is **multiple-choice**, we require you to format your documents such that they contain `gold` and `choices` fields. They can also have other fields, but those will be ignored by `MultipleChoiceTask`. `choices` should be a list of possible continuations, and `gold` should be an integer specifying the index of the correct completion.
121
+ See [this task](https://github.com/EleutherAI/lm-evaluation-harness/blob/6caa0afd96a7a7efb2ec4c1f24ad1756e48f3aa7/lm_eval/tasks/sat.py#L60) for an example. 🔠
122
+
123
+ ### Formatting your Few-Shot Examples
124
+
125
+ The harness is designed to facilitate task evaluations under the few-shot setting. Here we’ll format such examples.
126
+
127
+ Format your document into a single query prompt __without the answer__ here. This method takes a single `doc` example of type `dict` with `str` key-value members. You should concatenate these `doc` item values together into a neatly formatted prompt.
128
+
129
+ ```python
130
+ def doc_to_text(self, doc):
131
+ return ""
132
+ ```
133
+
134
+ <br>
135
+
136
+ ️🔠 **Multiple-Choice Formatting**
137
+
138
+ If your task is multiple-choice, you can now skip ahead to <a href="#Registering-Your-Task">registering your task</a>.
139
+
140
+ ️️🔠 **End Multiple-Choice Formatting**
141
+
142
+ <br>
143
+
144
+ Format the target answer from the contents of `doc`. Note that the prepended `" "` is required to space out the `doc_to_text` and `doc_to_target` strings.
145
+
146
+ ```python
147
+ def doc_to_target(self, doc):
148
+ target = ""
149
+ return " " + target
150
+ ```
151
+
152
+ Finally, be aware that the strings from `doc_to_text` and `doc_to_target` will be concatenated together to build up labeled examples in the k-shot setting where k > 0. Design with that in mind 👍.
153
+
154
+ ### Registering Your Task
155
+
156
+ Now's a good time to register your task to expose it for usage. All you'll need to do is import your task module in `lm_eval/tasks/__init__.py` and provide an entry in the `TASK_REGISTRY` dictionary with the key as the name of your benchmark task (in the form it'll be referred to in the command line) and the value as the task class. See how it's done for other tasks in the [file](https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/__init__.py).
157
+
158
+ ### Checking the Data
159
+
160
+ After registering your task, you can now check on your data downloading and verify that the few-shot samples look as intended. Run the following command with your desired args:
161
+
162
+ ```bash
163
+ python -m scripts.write_out \
164
+ --output_base_path <path> \
165
+ --tasks <your-task> \
166
+ --sets <train | val | test> \
167
+ --num_fewshot K \
168
+ --num_examples N \
169
+ ```
170
+
171
+ Open the file specified at the `--output_base_path <path>` and ensure it passes
172
+ a simple eye test.
173
+
174
+ ## Evaluation
175
+
176
+ **🛑** If your task is a single-true multiple-choice task and you've correctly inherited from `MultipleChoiceTask` then your job here is done; <a href="#Checking-the-Task-Performance">go ‘head and check on the task performance!</a> 🛑
177
+
178
+ Now comes evaluation. The methods you'll need to implement are:
179
+
180
+ ```python
181
+ def construct_requests(self, doc, ctx):
182
+ """Uses RequestFactory to construct Requests and returns an iterable of
183
+ Requests which will be sent to the LM.
184
+
185
+ Args:
186
+ doc (dict):
187
+ The document as returned from training_docs, validation_docs, or
188
+ test_docs.
189
+ ctx (str):
190
+ The context string, generated by fewshot_context. This includes
191
+ the natural language description, as well as the few shot examples,
192
+ and the question part of the document for `doc`.
193
+ args (dict):
194
+ The specifics of the context, including number of few shots.
195
+
196
+ Returns:
197
+ An iterable of `Request` objects.
198
+ """
199
+ return ...
200
+ ```
201
+ If your task requires generating text you'll need to return a `rf.greedy_until` request otherwise an `rf.loglikelihood` across all labels in a classification tasks will do.
202
+
203
+ ```python
204
+ def process_results(self, doc, results):
205
+ """Take a single document and the LM results and evaluates, returning a
206
+ dict where keys are the names of sub-metrics and values are the values of
207
+ the metric for that one document.
208
+
209
+ NOTE: This function automates processing by using the `promptsource`
210
+ metadata to determine the metric.
211
+
212
+ Args:
213
+ doc (dict):
214
+ The document as returned from training_docs, validation_docs, or
215
+ test_docs.
216
+ results (list):
217
+ The results of the requests created in construct_requests.
218
+
219
+ Returns:
220
+ A dict of metric results.
221
+ """
222
+ return {}
223
+ ```
224
+
225
+ ```python
226
+ def aggregation(self):
227
+ """
228
+ Returns:
229
+ A dictionary where keys are the names of sub-metrics and values are
230
+ functions that aggregate a list of metric scores.
231
+ {str: [metric_score] -> float}
232
+ """
233
+ return {}
234
+ ```
235
+
236
+ See `lm_eval/metrics.py` for a few "built-in" aggregate metrics you can easily import.
237
+
238
+ ```python
239
+ def higher_is_better(self):
240
+ """
241
+ Returns:
242
+ A dictionary where keys are the names of sub-metrics and values are
243
+ whether a higher value of the sub-metric is better.
244
+ {str: bool}
245
+ """
246
+ return {}
247
+ ```
248
+
249
+ Some tasks that are good examples of various ways evaluation can be implemented can be found here: [LAMBADA](https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/lambada.py), [TriviaQA](https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/triviaqa.py), [SQuAD](https://github.com/EleutherAI/lm-evaluation-harness/blob/master/lm_eval/tasks/squad.py).
250
+
251
+ Tip: Feel free to create your own helper-methods for your task!
252
+
253
+ ### Checking the Task Performance
254
+
255
+ ```sh
256
+ python main.py \
257
+ --model gpt2 \
258
+ --model_args device=<device-name> \
259
+ --tasks <task-name> \
260
+ --num_fewshot K
261
+ ```
262
+
263
+ Set the limit size, `N`, to a smallish number (e.g. 10) and try out the task under different `K`-shot settings. If you have an Nvidia GPU at your disposal, add the argument
264
+ `--model_args device=cuda:0`. If you have access to an OpenAI API key, you can also evaluate GPT-3 on various tasks with the following command:
265
+
266
+ ```sh
267
+ export OPENAI_API_SECRET_KEY=YOUR_KEY_HERE
268
+ python main.py \
269
+ --model gpt3 \
270
+ --tasks <task-name> \
271
+ --num_fewshot K
272
+ ```
273
+
274
+ ### Running Unit Tests
275
+
276
+ To run the entire test suite, use:
277
+
278
+ ```sh
279
+ pytest
280
+ ```
281
+
282
+ This is usually overkill; to run only the tests for your task, do:
283
+ ```sh
284
+ pytest -k <task name>
285
+ ```
286
+
287
+ ## Versioning
288
+
289
+ Lastly, we need to "version control". Tasks in the harness can always evolve. Metrics get updated, data sources change, etc. It’s important to mark each task with a version attribute so users can document which implementation version was used to obtain their results. Add a `VERSION` attribute to your task right below the class name and set it to `0` (this is the first version/implementation of your task):
290
+
291
+ ```python
292
+ class TaskName(...):
293
+ VERSION = 0
294
+ ```
295
+
296
+ ## Submitting your Task
297
+
298
+ Although we currently do not work behind a specific style guide, we'd appreciate if you tidy up your file/s with the `black` formatter (which should've been install through the `requirements.txt`). Keep things clean…ish 🙂.
299
+
300
+ Now push your work and make a pull request! Thanks for the contribution 👍. If there are any questions, leave a message in the `#lm-thunderdome` channel on the EAI discord.
evaluation-pipeline/filter_data.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8536705c9bb432cc84a9746fe19dacea457b7e2280602fab01431167123dd0b8
3
+ size 61762326
evaluation-pipeline/finetune_all_tasks.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH=$1
4
+ LR=${2:-5e-5}
5
+ PATIENCE=${3:-10}
6
+ BSZ=${4:-64}
7
+ EVAL_EVERY=${5:-200}
8
+ MAX_EPOCHS=${6:-10}
9
+ SEED=${7:-12}
10
+
11
+ # Fine-tune and evaluate on (Super)GLUE tasks
12
+ # If your system uses sbatch or qsub, consider using that to parallelize calls to finetune_model.sh
13
+ for subtask in {"cola","sst2","mrpc","qqp","mnli","mnli-mm","qnli","rte","boolq","multirc","wsc"}; do
14
+ ./finetune_model.sh $MODEL_PATH glue $subtask $LR $PATIENCE $BSZ $EVAL_EVERY $MAX_EPOCHS $SEED
15
+ done
16
+
17
+ # Fine-tune and evaluate on MSGS tasks
18
+ for subtask in {"main_verb_control","control_raising_control","syntactic_category_control","lexical_content_the_control","relative_position_control","main_verb_lexical_content_the","main_verb_relative_token_position","syntactic_category_lexical_content_the","syntactic_category_relative_position","control_raising_lexical_content_the","control_raising_relative_token_position"}; do
19
+ ./finetune_model.sh $MODEL_PATH msgs $subtask $LR $PATIENCE $BSZ $EVAL_EVERY $MAX_EPOCHS $SEED
20
+ done
evaluation-pipeline/finetune_classification.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ Finetuning the library models for sequence classification on GLUE."""
17
+ # You can also adapt this script on your own text classification task. Pointers for this are left as comments.
18
+
19
+ import logging
20
+ import os
21
+ import random
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from typing import Optional
25
+ import evaluate
26
+
27
+ import datasets
28
+ import numpy as np
29
+ from datasets import load_dataset
30
+ from sklearn.metrics import f1_score
31
+
32
+ import transformers
33
+ from transformers import (
34
+ AutoConfig,
35
+ AutoModelForSequenceClassification,
36
+ AutoTokenizer,
37
+ DataCollatorWithPadding,
38
+ EarlyStoppingCallback,
39
+ EvalPrediction,
40
+ HfArgumentParser,
41
+ IntervalStrategy,
42
+ PretrainedConfig,
43
+ Trainer,
44
+ TrainingArguments,
45
+ default_data_collator,
46
+ set_seed,
47
+ )
48
+ from transformers.trainer_utils import get_last_checkpoint
49
+ from transformers.utils import check_min_version, send_example_telemetry
50
+ from transformers.utils.versions import require_version
51
+
52
+
53
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
54
+ # check_min_version("4.27.0.dev0")
55
+
56
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
57
+
58
+ task_to_keys = {
59
+ "cola": ("sentence", None),
60
+ "mnli": ("premise", "hypothesis"),
61
+ "mrpc": ("sentence1", "sentence2"),
62
+ "qnli": ("question", "sentence"),
63
+ "qqp": ("question1", "question2"),
64
+ "rte": ("sentence1", "sentence2"),
65
+ "sst2": ("sentence", None),
66
+ "stsb": ("sentence1", "sentence2"),
67
+ "wnli": ("sentence1", "sentence2"),
68
+ }
69
+
70
+ logger = logging.getLogger(__name__)
71
+
72
+
73
+ @dataclass
74
+ class DataTrainingArguments:
75
+ """
76
+ Arguments pertaining to what data we are going to input our model for training and eval.
77
+
78
+ Using `HfArgumentParser` we can turn this class
79
+ into argparse arguments to be able to specify them on
80
+ the command line.
81
+ """
82
+
83
+ task_name: Optional[str] = field(
84
+ default=None,
85
+ metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())},
86
+ )
87
+ dataset_name: Optional[str] = field(
88
+ default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."}
89
+ )
90
+ dataset_config_name: Optional[str] = field(
91
+ default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
92
+ )
93
+ max_seq_length: int = field(
94
+ default=128,
95
+ metadata={
96
+ "help": (
97
+ "The maximum total input sequence length after tokenization. Sequences longer "
98
+ "than this will be truncated, sequences shorter will be padded."
99
+ )
100
+ },
101
+ )
102
+ overwrite_cache: bool = field(
103
+ default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
104
+ )
105
+ pad_to_max_length: bool = field(
106
+ default=True,
107
+ metadata={
108
+ "help": (
109
+ "Whether to pad all samples to `max_seq_length`. "
110
+ "If False, will pad the samples dynamically when batching to the maximum length in the batch."
111
+ )
112
+ },
113
+ )
114
+ max_train_samples: Optional[int] = field(
115
+ default=None,
116
+ metadata={
117
+ "help": (
118
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
119
+ "value if set."
120
+ )
121
+ },
122
+ )
123
+ max_eval_samples: Optional[int] = field(
124
+ default=None,
125
+ metadata={
126
+ "help": (
127
+ "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
128
+ "value if set."
129
+ )
130
+ },
131
+ )
132
+ max_predict_samples: Optional[int] = field(
133
+ default=None,
134
+ metadata={
135
+ "help": (
136
+ "For debugging purposes or quicker training, truncate the number of prediction examples to this "
137
+ "value if set."
138
+ )
139
+ },
140
+ )
141
+ patience: Optional[int] = field(
142
+ default=None,
143
+ metadata={
144
+ "help": (
145
+ "Number of evaluation steps without improvement > epsilon before stopping fine-tuning. "
146
+ "Requires the use of the --eval_every argument."
147
+ )
148
+ },
149
+ )
150
+ eval_every: Optional[int] = field(
151
+ default=None,
152
+ metadata = {
153
+ "help": (
154
+ "Number of steps between evaluations (MUST be set if patience is set)."
155
+ )
156
+ }
157
+ )
158
+ train_file: Optional[str] = field(
159
+ default=None, metadata={"help": "A csv or a json file containing the training data."}
160
+ )
161
+ validation_file: Optional[str] = field(
162
+ default=None, metadata={"help": "A csv or a json file containing the validation data."}
163
+ )
164
+ test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
165
+
166
+ def __post_init__(self):
167
+ if self.task_name is not None:
168
+ self.task_name = self.task_name.lower()
169
+ if self.task_name not in task_to_keys.keys():
170
+ raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys()))
171
+ elif self.dataset_name is not None:
172
+ pass
173
+ elif self.train_file is None or self.validation_file is None:
174
+ raise ValueError("Need either a GLUE task, a training/validation file or a dataset name.")
175
+ else:
176
+ train_extension = self.train_file.split(".")[-1]
177
+ assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
178
+ validation_extension = self.validation_file.split(".")[-1]
179
+ assert (
180
+ validation_extension == train_extension
181
+ ), "`validation_file` should have the same extension (csv or json) as `train_file`."
182
+
183
+
184
+ @dataclass
185
+ class ModelArguments:
186
+ """
187
+ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
188
+ """
189
+
190
+ model_name_or_path: str = field(
191
+ metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
192
+ )
193
+ freeze_model: bool = field(
194
+ default=False,
195
+ metadata={"help": "Whether to freeze the parameters of the base model."}
196
+ )
197
+ config_name: Optional[str] = field(
198
+ default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
199
+ )
200
+ tokenizer_name: Optional[str] = field(
201
+ default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
202
+ )
203
+ cache_dir: Optional[str] = field(
204
+ default=None,
205
+ metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
206
+ )
207
+ use_fast_tokenizer: bool = field(
208
+ default=True,
209
+ metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
210
+ )
211
+ model_revision: str = field(
212
+ default="main",
213
+ metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
214
+ )
215
+ use_auth_token: bool = field(
216
+ default=False,
217
+ metadata={
218
+ "help": (
219
+ "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
220
+ "with private models)."
221
+ )
222
+ },
223
+ )
224
+ ignore_mismatched_sizes: bool = field(
225
+ default=False,
226
+ metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."},
227
+ )
228
+
229
+
230
+ def main():
231
+ # See all possible arguments in src/transformers/training_args.py
232
+ # or by passing the --help flag to this script.
233
+ # We now keep distinct sets of args, for a cleaner separation of concerns.
234
+
235
+ parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
236
+ if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
237
+ # If we pass only one argument to the script and it's the path to a json file,
238
+ # let's parse it to get our arguments.
239
+ model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
240
+ else:
241
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
242
+
243
+ # Check for the use of early stopping
244
+ if data_args.patience:
245
+ training_args.eval_steps = data_args.eval_every
246
+ training_args.save_total_limit = 1
247
+ training_args.load_best_model_at_end = True
248
+ training_args.evaluation_strategy = "steps"
249
+ callbacks = [EarlyStoppingCallback(early_stopping_patience=data_args.patience,
250
+ early_stopping_threshold=0.001)]
251
+ else:
252
+ callbacks = None
253
+
254
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
255
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
256
+ send_example_telemetry("run_glue", model_args, data_args)
257
+
258
+ # Setup logging
259
+ logging.basicConfig(
260
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
261
+ datefmt="%m/%d/%Y %H:%M:%S",
262
+ handlers=[logging.StreamHandler(sys.stdout)],
263
+ )
264
+
265
+ log_level = training_args.get_process_log_level()
266
+ logger.setLevel(log_level)
267
+ datasets.utils.logging.set_verbosity(log_level)
268
+ transformers.utils.logging.set_verbosity(log_level)
269
+ transformers.utils.logging.enable_default_handler()
270
+ transformers.utils.logging.enable_explicit_format()
271
+
272
+ # Log on each process the small summary:
273
+ logger.warning(
274
+ f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
275
+ + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
276
+ )
277
+ logger.info(f"Training/evaluation parameters {training_args}")
278
+
279
+ # Detecting last checkpoint.
280
+ last_checkpoint = None
281
+ if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
282
+ last_checkpoint = get_last_checkpoint(training_args.output_dir)
283
+ if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
284
+ raise ValueError(
285
+ f"Output directory ({training_args.output_dir}) already exists and is not empty. "
286
+ "Use --overwrite_output_dir to overcome."
287
+ )
288
+ elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
289
+ logger.info(
290
+ f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
291
+ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."
292
+ )
293
+
294
+ # Set seed before initializing model.
295
+ set_seed(training_args.seed)
296
+
297
+ # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
298
+ # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
299
+ #
300
+ # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the
301
+ # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named
302
+ # label if at least two columns are provided.
303
+ #
304
+ # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
305
+ # single column. You can easily tweak this behavior (see below)
306
+ #
307
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
308
+ # download the dataset.
309
+ if data_args.task_name is not None:
310
+ # Downloading and loading a dataset from the hub.
311
+ raw_datasets = load_dataset(
312
+ "glue",
313
+ data_args.task_name,
314
+ cache_dir=model_args.cache_dir,
315
+ use_auth_token=True if model_args.use_auth_token else None,
316
+ )
317
+ elif data_args.dataset_name is not None:
318
+ # Downloading and loading a dataset from the hub.
319
+ raw_datasets = load_dataset(
320
+ data_args.dataset_name,
321
+ data_args.dataset_config_name,
322
+ cache_dir=model_args.cache_dir,
323
+ use_auth_token=True if model_args.use_auth_token else None,
324
+ )
325
+ else:
326
+ # Loading a dataset from your local files.
327
+ # CSV/JSON training and evaluation files are needed.
328
+ data_files = {"train": data_args.train_file, "validation": data_args.validation_file}
329
+
330
+ # Get the test dataset: you can provide your own CSV/JSON test file (see below)
331
+ # when you use `do_predict` without specifying a GLUE benchmark task.
332
+ if training_args.do_predict:
333
+ if data_args.test_file is not None:
334
+ train_extension = data_args.train_file.split(".")[-1]
335
+ test_extension = data_args.test_file.split(".")[-1]
336
+ assert (
337
+ test_extension == train_extension
338
+ ), "`test_file` should have the same extension (csv or json) as `train_file`."
339
+ data_files["test"] = data_args.test_file
340
+ else:
341
+ train_extension = data_args.train_file.split(".")[-1]
342
+ validation_extension = data_args.validation_file.split(".")[-1]
343
+ assert (
344
+ validation_extension == train_extension
345
+ ), "`validation_file` should have the same extension (csv or json) as `train_file`."
346
+ data_files["test"] = data_args.validation_file
347
+
348
+ for key in data_files.keys():
349
+ logger.info(f"load a local file for {key}: {data_files[key]}")
350
+
351
+ if data_args.train_file.endswith(".csv"):
352
+ # Loading a dataset from local csv files
353
+ raw_datasets = load_dataset(
354
+ "csv",
355
+ data_files=data_files,
356
+ cache_dir=model_args.cache_dir,
357
+ use_auth_token=True if model_args.use_auth_token else None,
358
+ )
359
+ else:
360
+ # Loading a dataset from local json files
361
+ raw_datasets = load_dataset(
362
+ "json",
363
+ data_files=data_files,
364
+ cache_dir=model_args.cache_dir,
365
+ use_auth_token=True if model_args.use_auth_token else None,
366
+ )
367
+ # See more about loading any type of standard or custom dataset at
368
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
369
+
370
+ # Labels
371
+ if data_args.task_name is not None:
372
+ is_regression = data_args.task_name == "stsb"
373
+ if not is_regression:
374
+ label_list = raw_datasets["train"].features["label"].names
375
+ num_labels = len(label_list)
376
+ else:
377
+ num_labels = 1
378
+ else:
379
+ # Trying to have good defaults here, don't hesitate to tweak to your needs.
380
+ is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"]
381
+ if is_regression:
382
+ num_labels = 1
383
+ else:
384
+ # A useful fast method:
385
+ # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique
386
+ label_list = raw_datasets["train"].unique("label")
387
+ label_list.sort() # Let's sort it for determinism
388
+ num_labels = len(label_list)
389
+
390
+ is_binary = (num_labels == 2)
391
+
392
+ # Load pretrained model and tokenizer
393
+ #
394
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
395
+ # download model & vocab.
396
+ config = AutoConfig.from_pretrained(
397
+ model_args.config_name if model_args.config_name else model_args.model_name_or_path,
398
+ num_labels=num_labels,
399
+ finetuning_task=data_args.task_name,
400
+ cache_dir=model_args.cache_dir,
401
+ revision=model_args.model_revision,
402
+ use_auth_token=True if model_args.use_auth_token else None,
403
+ )
404
+ tokenizer = AutoTokenizer.from_pretrained(
405
+ model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
406
+ cache_dir=model_args.cache_dir,
407
+ use_fast=model_args.use_fast_tokenizer,
408
+ revision=model_args.model_revision,
409
+ use_auth_token=True if model_args.use_auth_token else None,
410
+ )
411
+ try:
412
+ model = AutoModelForSequenceClassification.from_pretrained(
413
+ model_args.model_name_or_path,
414
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
415
+ config=config,
416
+ cache_dir=model_args.cache_dir,
417
+ revision=model_args.model_revision,
418
+ use_auth_token=True if model_args.use_auth_token else None,
419
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
420
+ )
421
+ except ValueError as e:
422
+ from transformers import T5Config
423
+ if isinstance(config, T5Config):
424
+ from transformers_modified.t5 import T5ForSequenceClassification
425
+ model = T5ForSequenceClassification.from_pretrained(
426
+ model_args.model_name_or_path,
427
+ from_tf=bool(".ckpt" in model_args.model_name_or_path),
428
+ config=config,
429
+ cache_dir=model_args.cache_dir,
430
+ revision=model_args.model_revision,
431
+ use_auth_token=True if model_args.use_auth_token else None,
432
+ ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,
433
+ )
434
+ else:
435
+ raise e
436
+
437
+ # Freeze all parameters (including embeddings) except the classifier head
438
+ if model_args.freeze_model:
439
+ for name, param in model.named_parameters():
440
+ if "classifier" not in name and not name.startswith("score"): # classifier layer
441
+ param.requires_grad = False
442
+
443
+ # Preprocessing the raw_datasets
444
+ template = None
445
+ if data_args.task_name is not None:
446
+ sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
447
+ else:
448
+ # Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
449
+ non_label_column_names = [name for name in raw_datasets["train"].column_names if name not in ("label", "idx")]
450
+ if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
451
+ sentence1_key, sentence2_key = "sentence1", "sentence2"
452
+ elif "question1" in non_label_column_names and "question2" in non_label_column_names:
453
+ sentence1_key, sentence2_key = "question1", "question2"
454
+ elif "premise" in non_label_column_names and "hypothesis" in non_label_column_names:
455
+ sentence1_key, sentence2_key = "premise", "hypothesis"
456
+ elif "question" in non_label_column_names and "passage" in non_label_column_names:
457
+ sentence1_key, sentence2_key = "question", "passage"
458
+ elif "question" in non_label_column_names and "sentence" in non_label_column_names:
459
+ sentence1_key, sentence2_key = "question", "sentence"
460
+ # special cases
461
+ elif "paragraph" in non_label_column_names and \
462
+ "question" in non_label_column_names and \
463
+ "answer" in non_label_column_names: # MultiRC
464
+ sentence1_key, sentence2_key = ["question", "answer"], "paragraph"
465
+ template = "Question: {} Answer: {}"
466
+ elif "text" in non_label_column_names and \
467
+ "span1_text" in non_label_column_names and \
468
+ "span2_text" in non_label_column_names: # WSC
469
+ sentence1_key, sentence2_key = ["span2_text", "span1_text"], "text"
470
+ template = "Does \"{}\" refer to \"{}\" in this passage?"
471
+ elif "sentence" in non_label_column_names and "linguistic_feature_type" in non_label_column_names:
472
+ sentence1_key, sentence2_key = "sentence", None
473
+ else:
474
+ if len(non_label_column_names) >= 2:
475
+ sentence1_key, sentence2_key = non_label_column_names[:2]
476
+ else:
477
+ sentence1_key, sentence2_key = non_label_column_names[0], None
478
+
479
+ # Padding strategy
480
+ if data_args.pad_to_max_length:
481
+ padding = "max_length"
482
+ else:
483
+ # We will pad later, dynamically at batch creation, to the max sequence length in each batch
484
+ padding = False
485
+
486
+ # Some models have set the order of the labels to use, so let's make sure we do use it.
487
+ label_to_id = None
488
+ if (
489
+ model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
490
+ and data_args.task_name is not None
491
+ and not is_regression
492
+ ):
493
+ # Some have all caps in their config, some don't.
494
+ label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()}
495
+ if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)):
496
+ label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
497
+ else:
498
+ logger.warning(
499
+ "Your model seems to have been trained with labels, but they don't match the dataset: ",
500
+ f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}."
501
+ "\nIgnoring the model labels as a result.",
502
+ )
503
+ elif data_args.task_name is None and not is_regression:
504
+ label_to_id = {v: i for i, v in enumerate(label_list)}
505
+
506
+ if label_to_id is not None:
507
+ model.config.label2id = label_to_id
508
+ model.config.id2label = {id: label for label, id in config.label2id.items()}
509
+ elif data_args.task_name is not None and not is_regression:
510
+ model.config.label2id = {l: i for i, l in enumerate(label_list)}
511
+ model.config.id2label = {id: label for label, id in config.label2id.items()}
512
+
513
+ if data_args.max_seq_length > tokenizer.model_max_length:
514
+ logger.warning(
515
+ f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
516
+ f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
517
+ )
518
+ max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
519
+
520
+ def preprocess_function(examples):
521
+ # Tokenize the texts
522
+ if isinstance(sentence1_key, list):
523
+ keya, keyb = examples[sentence1_key[0]], examples[sentence1_key[1]]
524
+ keys1 = [template.format(ka, kb) for ka, kb in zip(keya, keyb)]
525
+ args = (
526
+ (keys1, examples[sentence2_key])
527
+ )
528
+ else:
529
+ args = (
530
+ (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
531
+ )
532
+ result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
533
+
534
+ # Map labels to IDs (not necessary for GLUE tasks)
535
+ if label_to_id is not None and "label" in examples:
536
+ result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]]
537
+ return result
538
+
539
+ with training_args.main_process_first(desc="dataset map pre-processing"):
540
+ raw_datasets = raw_datasets.map(
541
+ preprocess_function,
542
+ batched=True,
543
+ load_from_cache_file=not data_args.overwrite_cache,
544
+ desc="Running tokenizer on dataset",
545
+ )
546
+ if training_args.do_train:
547
+ if "train" not in raw_datasets:
548
+ raise ValueError("--do_train requires a train dataset")
549
+ train_dataset = raw_datasets["train"]
550
+ if data_args.max_train_samples is not None:
551
+ max_train_samples = min(len(train_dataset), data_args.max_train_samples)
552
+ train_dataset = train_dataset.select(range(max_train_samples))
553
+
554
+ if training_args.do_eval:
555
+ if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
556
+ raise ValueError("--do_eval requires a validation dataset")
557
+ eval_dataset = raw_datasets["validation_matched" if data_args.task_name == "mnli" else "validation"]
558
+ if data_args.max_eval_samples is not None:
559
+ max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples)
560
+ eval_dataset = eval_dataset.select(range(max_eval_samples))
561
+
562
+ if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None:
563
+ if "test" not in raw_datasets and "test_matched" not in raw_datasets:
564
+ raise ValueError("--do_predict requires a test dataset")
565
+ predict_dataset = raw_datasets["test_matched" if data_args.task_name == "mnli" else "test"]
566
+ if data_args.max_predict_samples is not None:
567
+ max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples)
568
+ predict_dataset = predict_dataset.select(range(max_predict_samples))
569
+
570
+ # Log a few random samples from the training set:
571
+ if training_args.do_train:
572
+ for index in random.sample(range(len(train_dataset)), 3):
573
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
574
+
575
+ # Get the metric function
576
+ if data_args.task_name is not None:
577
+ metric = evaluate.load("glue", data_args.task_name)
578
+ else:
579
+ metric = evaluate.load("accuracy")
580
+
581
+ # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
582
+ # predictions and label_ids field) and has to return a dictionary string to float.
583
+ def compute_metrics(p: EvalPrediction):
584
+ preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
585
+ preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
586
+ if data_args.task_name is not None:
587
+ result = metric.compute(predictions=preds, references=p.label_ids)
588
+ if len(result) > 1:
589
+ result["combined_score"] = np.mean(list(result.values())).item()
590
+ return result
591
+ elif is_regression:
592
+ return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
593
+ elif is_binary:
594
+ return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item(),
595
+ "f1": f1_score(y_true=p.label_ids, y_pred=preds, average="binary")}
596
+ else:
597
+ return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}
598
+
599
+ # Data collator will default to DataCollatorWithPadding when the tokenizer is passed to Trainer, so we change it if
600
+ # we already did the padding.
601
+ if data_args.pad_to_max_length:
602
+ data_collator = default_data_collator
603
+ elif training_args.fp16:
604
+ data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
605
+ else:
606
+ data_collator = None
607
+
608
+ if is_regression:
609
+ training_args.metric_for_best_model = "mse"
610
+ elif is_binary:
611
+ training_args.metric_for_best_model = "f1"
612
+ training_args.greater_is_better = True
613
+ else:
614
+ training_args.metric_for_best_model = "accuracy"
615
+ training_args.greater_is_better = True
616
+
617
+ # Initialize our Trainer
618
+ trainer = Trainer(
619
+ model=model,
620
+ args=training_args,
621
+ train_dataset=train_dataset if training_args.do_train else None,
622
+ eval_dataset=eval_dataset if training_args.do_eval else None,
623
+ compute_metrics=compute_metrics,
624
+ tokenizer=tokenizer,
625
+ data_collator=data_collator,
626
+ callbacks = callbacks,
627
+ )
628
+
629
+ # Training
630
+ if training_args.do_train:
631
+ checkpoint = None
632
+ if training_args.resume_from_checkpoint is not None:
633
+ checkpoint = training_args.resume_from_checkpoint
634
+ elif last_checkpoint is not None:
635
+ checkpoint = last_checkpoint
636
+ train_result = trainer.train(resume_from_checkpoint=checkpoint)
637
+ metrics = train_result.metrics
638
+ max_train_samples = (
639
+ data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset)
640
+ )
641
+ metrics["train_samples"] = min(max_train_samples, len(train_dataset))
642
+
643
+ trainer.save_model() # Saves the tokenizer too for easy upload
644
+
645
+ trainer.log_metrics("train", metrics)
646
+ trainer.save_metrics("train", metrics)
647
+ trainer.save_state()
648
+
649
+ # Evaluation
650
+ if training_args.do_eval:
651
+ logger.info("*** Evaluate ***")
652
+
653
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
654
+ tasks = [data_args.task_name]
655
+ eval_datasets = [eval_dataset]
656
+ if data_args.task_name == "mnli":
657
+ tasks.append("mnli-mm")
658
+ valid_mm_dataset = raw_datasets["validation_mismatched"]
659
+ if data_args.max_eval_samples is not None:
660
+ max_eval_samples = min(len(valid_mm_dataset), data_args.max_eval_samples)
661
+ valid_mm_dataset = valid_mm_dataset.select(range(max_eval_samples))
662
+ eval_datasets.append(valid_mm_dataset)
663
+ combined = {}
664
+
665
+ for eval_dataset, task in zip(eval_datasets, tasks):
666
+ metrics = trainer.evaluate(eval_dataset=eval_dataset)
667
+
668
+ max_eval_samples = (
669
+ data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset)
670
+ )
671
+ metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset))
672
+
673
+ if task == "mnli-mm":
674
+ metrics = {k + "_mm": v for k, v in metrics.items()}
675
+ if task is not None and "mnli" in task:
676
+ combined.update(metrics)
677
+
678
+ trainer.log_metrics("eval", metrics)
679
+ trainer.save_metrics("eval", combined if task is not None and "mnli" in task else metrics)
680
+
681
+ if training_args.do_predict:
682
+ logger.info("*** Predict ***")
683
+
684
+ # Loop to handle MNLI double evaluation (matched, mis-matched)
685
+ # We do not use MNLI test data.
686
+ tasks = [data_args.task_name]
687
+ if data_args.task_name == "mnli":
688
+ tasks.append("mnli-mm")
689
+ predict_datasets.append(raw_datasets["test_mismatched"])
690
+
691
+ # Removing the `label` columns because it contains -1 and Trainer won't like that.
692
+ predict_dataset = predict_dataset.remove_columns("label")
693
+ predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions
694
+ predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1)
695
+
696
+ output_predict_file = os.path.join(training_args.output_dir, f"predict_results.txt")
697
+ if trainer.is_world_process_zero():
698
+ with open(output_predict_file, "w") as writer:
699
+ logger.info(f"***** Predict results *****")
700
+ writer.write("index\tprediction\n")
701
+ for index, item in enumerate(predictions):
702
+ if is_regression:
703
+ writer.write(f"{index}\t{item:3.3f}\n")
704
+ else:
705
+ item = label_list[item]
706
+ writer.write(f"{index}\t{item}\n")
707
+
708
+ kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-classification"}
709
+ if data_args.task_name is not None:
710
+ kwargs["language"] = "en"
711
+ kwargs["dataset_tags"] = "glue"
712
+ kwargs["dataset_args"] = data_args.task_name
713
+ kwargs["dataset"] = f"GLUE {data_args.task_name.upper()}"
714
+
715
+ """
716
+ if training_args.push_to_hub:
717
+ trainer.push_to_hub(**kwargs)
718
+ else:
719
+ trainer.create_model_card(**kwargs)
720
+ """
721
+
722
+ def _mp_fn(index):
723
+ # For xla_spawn (TPUs)
724
+ main()
725
+
726
+
727
+ if __name__ == "__main__":
728
+ main()
evaluation-pipeline/finetune_model.sh ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ MODEL_PATH=$1
4
+ TASK_NAME=$2
5
+ SUBTASK_NAME=$3
6
+ LR=${4:-5e-5} # default: 5e-5
7
+ PATIENCE=${5:-10} # default: 10
8
+ BSZ=${6:-64} # default: 64
9
+ EVAL_EVERY=${7:-200} # default: 200
10
+ MAX_EPOCHS=${8:-10} # default: 10
11
+ SEED=${9:-12} # default: 12
12
+
13
+ if [[ "$SUBTASK_NAME" = "mnli" ]]; then
14
+ VALID_NAME="validation_matched"
15
+ OUT_DIR="mnli"
16
+ elif [[ "$SUBTASK_NAME" = "mnli-mm" ]]; then
17
+ VALID_NAME="validation_mismatched"
18
+ SUBTASK_NAME="mnli"
19
+ OUT_DIR="mnli-mm"
20
+ else
21
+ VALID_NAME="validation"
22
+ OUT_DIR=$SUBTASK_NAME
23
+ fi
24
+
25
+ mkdir -p $MODEL_PATH/finetune/$OUT_DIR/
26
+
27
+ python finetune_classification.py \
28
+ --model_name_or_path $MODEL_PATH \
29
+ --output_dir $MODEL_PATH/finetune/$OUT_DIR/ \
30
+ --train_file filter-data/${TASK_NAME}_filtered/$SUBTASK_NAME.train.json \
31
+ --validation_file filter-data/${TASK_NAME}_filtered/$SUBTASK_NAME.$VALID_NAME.json \
32
+ --do_train \
33
+ --do_eval \
34
+ --do_predict \
35
+ --use_fast_tokenizer False \
36
+ --max_seq_length 128 \
37
+ --per_device_train_batch_size $BSZ \
38
+ --learning_rate $LR \
39
+ --num_train_epochs $MAX_EPOCHS \
40
+ --evaluation_strategy steps \
41
+ --patience $PATIENCE \
42
+ --eval_every $EVAL_EVERY \
43
+ --eval_steps $EVAL_EVERY \
44
+ --save_steps $EVAL_EVERY \
45
+ --overwrite_output_dir \
46
+ --seed $SEED
evaluation-pipeline/ignore.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ROUGE
2
+ rouge
3
+ nin
4
+ ond
5
+ som
6
+ tha
7
+ vie
8
+ FPR
9
+ fpr
evaluation-pipeline/lm_eval/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .evaluator import evaluate
2
+ from .models import get_model, list_model_apis
3
+ from .tasks import get_task, get_task_list, list_tasks, get_templates, list_templates, aoa_pred_eval
evaluation-pipeline/lm_eval/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (454 Bytes). View file
 
evaluation-pipeline/lm_eval/__pycache__/evaluator.cpython-310.pyc ADDED
Binary file (9.65 kB). View file
 
evaluation-pipeline/lm_eval/api/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
evaluation-pipeline/lm_eval/api/__pycache__/metric.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
evaluation-pipeline/lm_eval/api/__pycache__/model.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
evaluation-pipeline/lm_eval/api/__pycache__/request.cpython-310.pyc ADDED
Binary file (2.14 kB). View file
 
evaluation-pipeline/lm_eval/api/__pycache__/task.cpython-310.pyc ADDED
Binary file (27 kB). View file
 
evaluation-pipeline/lm_eval/api/__pycache__/utils.cpython-310.pyc ADDED
Binary file (11.2 kB). View file
 
evaluation-pipeline/lm_eval/api/metric.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+ import random
4
+ import numpy as np
5
+ import sacrebleu
6
+ import sklearn.metrics
7
+ from collections.abc import Iterable
8
+ from rouge_score import rouge_scorer
9
+ from typing import List, Mapping, Optional
10
+
11
+ from lm_eval.metrics import sari as sari_impl
12
+
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def mean(arr):
18
+ return sum(arr) / len(arr)
19
+
20
+
21
+ def pop_stddev(arr):
22
+ mu = mean(arr)
23
+ return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / len(arr))
24
+
25
+
26
+ def sample_stddev(arr):
27
+ mu = mean(arr)
28
+ if len(arr) == 1:
29
+ return 0
30
+ else:
31
+ return math.sqrt(sum([(x - mu) ** 2 for x in arr]) / (len(arr) - 1))
32
+
33
+
34
+ def mean_stderr(arr):
35
+ return sample_stddev(arr) / math.sqrt(len(arr))
36
+
37
+
38
+ def median(arr):
39
+ return arr[len(arr) // 2]
40
+
41
+
42
+ def matthews_corrcoef(items):
43
+ unzipped_list = list(zip(*items))
44
+ golds = unzipped_list[0]
45
+ preds = unzipped_list[1]
46
+ return sklearn.metrics.matthews_corrcoef(golds, preds)
47
+
48
+
49
+ def f1_score(items):
50
+ unzipped_list = list(zip(*items))
51
+ golds = unzipped_list[0]
52
+ preds = unzipped_list[1]
53
+ fscore = sklearn.metrics.f1_score(golds, preds)
54
+ return np.max(fscore)
55
+
56
+
57
+ def acc_all(items):
58
+ # Only count as correct if all answers are labeled correctly for each question
59
+ question_scoring_dict = {}
60
+ preds = list(zip(*items))[0]
61
+ docs = list(zip(*items))[1]
62
+
63
+ for doc, pred in zip(docs, preds):
64
+ paragraph_id = doc["idx"]["paragraph"]
65
+ question_id = doc["idx"]["question"]
66
+ if (paragraph_id, question_id) not in question_scoring_dict:
67
+ question_scoring_dict[(paragraph_id, question_id)] = []
68
+
69
+ gold_label = doc["label"] == 1
70
+
71
+ question_scoring_dict[(paragraph_id, question_id)].append(gold_label == pred)
72
+ acc = np.mean([int(all(x)) for x in question_scoring_dict.values()])
73
+ return acc
74
+
75
+
76
+ def acc_all_stderr(items):
77
+ # Only count as correct if all answers are labeled correctly for each question
78
+ question_scoring_dict = {}
79
+ preds = list(zip(*items))[0]
80
+ docs = list(zip(*items))[1]
81
+
82
+ for doc, pred in zip(docs, preds):
83
+ question_id = doc["idx"]["question"]
84
+ if question_id not in question_scoring_dict:
85
+ question_scoring_dict[question_id] = []
86
+
87
+ gold_label = doc["label"] == 1
88
+ question_scoring_dict[question_id].append(gold_label == pred)
89
+
90
+ acc = mean_stderr([int(all(x)) for x in question_scoring_dict.values()])
91
+ return acc
92
+
93
+
94
+ def compute_parity_scores(items):
95
+ # Parity checks whether predictions in subsequent pairs of examples are consistent.
96
+ # In WinogenderSchema those examples differ only in the gender of the pronoun in the hypothesis.
97
+ indices2predictions = {idx: pred for idx, pred in items}
98
+ parity_scores = []
99
+ for idx in indices2predictions.keys():
100
+ if (idx % 2) == 0 and (idx + 1) in indices2predictions:
101
+ parity_scores.append(
102
+ int(indices2predictions[idx] == indices2predictions[idx + 1])
103
+ )
104
+ return parity_scores
105
+
106
+
107
+ def parity(items):
108
+ parity_scores = compute_parity_scores(items)
109
+ if len(parity_scores) > 0:
110
+ acc = mean(parity_scores)
111
+ else:
112
+ acc = 0.0
113
+ return acc
114
+
115
+
116
+ def parity_stderr(items):
117
+ parity_scores = compute_parity_scores(items)
118
+ if len(parity_scores) > 0:
119
+ stderr = mean_stderr(parity_scores)
120
+ else:
121
+ stderr = 0.0
122
+ return stderr
123
+
124
+
125
+ def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
126
+ """Compute max metric between prediction and each ground truth."""
127
+ scores_for_ground_truths = []
128
+ for ground_truth in ground_truths:
129
+ score = metric_fn(prediction, ground_truth)
130
+ scores_for_ground_truths.append(score)
131
+ return max(scores_for_ground_truths)
132
+
133
+
134
+ def perplexity(items):
135
+ return math.exp(-mean(items))
136
+
137
+
138
+ def weighted_mean(items):
139
+ a, b = zip(*items)
140
+ return sum(a) / sum(b)
141
+
142
+
143
+ def weighted_perplexity(items):
144
+ return math.exp(-weighted_mean(items))
145
+
146
+
147
+ def bits_per_byte(items):
148
+ return -weighted_mean(items) / math.log(2)
149
+
150
+
151
+ def sari(sentence_to_simplifiy, generated_sentence, references):
152
+ """Implementation of SARI from the authors'."""
153
+ return sari_impl.SARIsent(sentence_to_simplifiy, generated_sentence, references)
154
+
155
+
156
+ def bleu(items):
157
+ """The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric
158
+ for evaluating a generated sentence to a reference sentence. It counts matching
159
+ n-grams in the candidate translation to n-grams in the reference text, where
160
+ 1-gram or uni-gram would be each token and a bi-gram comparison would be each
161
+ word pair. The comparison is made regardless of word order
162
+ Source: https://machinelearningmastery.com/calculate-bleu-score-for-text-python/
163
+ Paper: https://www.aclweb.org/anthology/P02-1040/
164
+
165
+ Higher is better
166
+ """
167
+ refs = list(zip(*items))[0]
168
+ preds = list(zip(*items))[1]
169
+ refs, preds = _sacreformat(refs, preds)
170
+ return sacrebleu.corpus_bleu(preds, refs).score
171
+
172
+
173
+ def chrf(items):
174
+ """chrF++ is a tool for automatic evaluation of machine translation output
175
+ based on character n-gram precision and recall enhanced with word n-grams.
176
+ Source: https://github.com/m-popovic/chrF
177
+ Paper: https://www.aclweb.org/anthology/W15-3049.pdf
178
+
179
+ Higher is better
180
+ """
181
+ refs = list(zip(*items))[0]
182
+ preds = list(zip(*items))[1]
183
+ refs, preds = _sacreformat(refs, preds)
184
+ return sacrebleu.corpus_chrf(preds, refs).score
185
+
186
+
187
+ def ter(items):
188
+ """Translation Error Rate is an error metric for machine translation that
189
+ measures the number of edits required to change a system output into one
190
+ of the references
191
+ Source: http://www.cs.umd.edu/~snover/tercom/
192
+ Paper: http://mt-archive.info/AMTA-2006-Snover.pdf
193
+
194
+ Lower is better
195
+ """
196
+ refs = list(zip(*items))[0]
197
+ preds = list(zip(*items))[1]
198
+ refs, preds = _sacreformat(refs, preds)
199
+ return sacrebleu.corpus_ter(preds, refs).score
200
+
201
+
202
+ def is_non_str_iterable(obj):
203
+ return isinstance(obj, Iterable) and not isinstance(obj, str)
204
+
205
+
206
+ def _sacreformat(refs, preds):
207
+ """Format refs and preds for sacrebleu corpus calculation. It is very particular"""
208
+ # Sacrebleu expects (List[str], List[List[str])
209
+ # e.g. sacrebleu.corpus_bleu([pred_t], [[ref1_stream], [ref2_stream], ...])
210
+
211
+ # Note [ref1_stream] is the first reference for each pred.
212
+ # So lists are size N and (M, N) for N preds and M possible refs for each pred
213
+ # This is a different order of dimensions that I would expect
214
+
215
+ # We expect refs to be List[str] or List[List[str]], the outer list corresponding to preds
216
+ # Must become List[List[str]] with the inner list corresponding to preds
217
+ if not is_non_str_iterable(refs):
218
+ refs = list(refs)
219
+ if not is_non_str_iterable(refs[0]):
220
+ refs = [[ref] for ref in refs]
221
+ refs = list(zip(*refs))
222
+ # Note the number of refs in each ref list much match the number of preds
223
+
224
+ # We expect preds to be List[str] or List[List[str]]. Must become List[str]
225
+ if not is_non_str_iterable(preds):
226
+ preds = list(preds)
227
+ if is_non_str_iterable(preds[0]):
228
+ assert len(preds[0]) == 1, f"Pred must be a str, was {preds[0]}"
229
+ preds = [pred[0] for pred in preds]
230
+
231
+ return refs, preds
232
+
233
+
234
+ def rouge(
235
+ refs: List[str],
236
+ pred: str,
237
+ rouge_types: Optional[List[str]] = ["rouge1", "rouge2", "rougeL", "rougeLsum"],
238
+ ) -> Mapping[str, float]:
239
+ """ROUGE with multi-reference support
240
+
241
+ Implementation based on GEM-metrics:
242
+ https://github.com/GEM-benchmark/GEM-metrics/blob/431a8174bd6b3637e8d6118bfad2983e39e99733/gem_metrics/rouge.py
243
+
244
+ Args:
245
+ refs (List[str]):
246
+ A `list` of reference `str`s.
247
+ pred (str):
248
+ A single prediction `str`s.
249
+ rouge_types (Optional[List[str]]):
250
+ An optional list of ROUGE types from the set:
251
+ ["rouge1", "rouge2", "rougeL", "rougeLsum"]
252
+
253
+ Returns:
254
+ A `dict` of ROUGE scores.
255
+ """
256
+
257
+ # Add newlines between sentences to correctly compute `rougeLsum`.
258
+ if "rougeLsum" in rouge_types:
259
+ # TODO: Adapt this to handle languages that do not support sentence endings by `.`.
260
+ # See GEM-metrics implementation with lang specific `nltk` tokenizers to
261
+ # split sentences.
262
+ pred = pred.replace(".", ".\n")
263
+ refs = [ref.replace(".", ".\n") for ref in refs]
264
+
265
+ scorer = rouge_scorer.RougeScorer(rouge_types=rouge_types, use_stemmer=True)
266
+ # ROUGE multi-ref jackknifing
267
+ if len(refs) > 1:
268
+ cur_scores = [scorer.score(ref, pred) for ref in refs]
269
+
270
+ # get best score for all leave-one-out sets
271
+ best_scores = []
272
+ for leave in range(len(refs)):
273
+ cur_scores_leave_one = [
274
+ cur_scores[s] for s in range(len(refs)) if s != leave
275
+ ]
276
+ best_scores.append(
277
+ {
278
+ rouge_type: max(
279
+ [s[rouge_type] for s in cur_scores_leave_one],
280
+ key=lambda s: s.fmeasure,
281
+ )
282
+ for rouge_type in rouge_types
283
+ }
284
+ )
285
+ # average the leave-one-out bests to produce the final score
286
+ score = {
287
+ rouge_type: rouge_scorer.scoring.Score(
288
+ np.mean([b[rouge_type].precision for b in best_scores]),
289
+ np.mean([b[rouge_type].recall for b in best_scores]),
290
+ np.mean([b[rouge_type].fmeasure for b in best_scores]),
291
+ )
292
+ for rouge_type in rouge_types
293
+ }
294
+ else:
295
+ score = scorer.score(refs[0], pred)
296
+ # convert the named tuples to plain nested dicts
297
+ score = {
298
+ rouge_type: {
299
+ "precision": score[rouge_type].precision,
300
+ "recall": score[rouge_type].recall,
301
+ "fmeasure": score[rouge_type].fmeasure,
302
+ }
303
+ for rouge_type in rouge_types
304
+ }
305
+ return score
306
+
307
+
308
+ # Standard Error Utils
309
+
310
+
311
+ class _BootstrapInternal:
312
+ def __init__(self, f, n):
313
+ self.f = f
314
+ self.n = n
315
+
316
+ def __call__(self, v):
317
+ i, xs = v
318
+ rnd = random.Random()
319
+ rnd.seed(i)
320
+ res = []
321
+ for _ in range(self.n):
322
+ res.append(self.f(rnd.choices(xs, k=len(xs))))
323
+ return res
324
+
325
+
326
+ def bootstrap_stderr(f, xs, iters):
327
+ import multiprocessing as mp
328
+
329
+ pool = mp.Pool(mp.cpu_count())
330
+ # this gives a biased estimate of the stderr (i.e w/ the mean, it gives something
331
+ # equivalent to stderr calculated without Bessel's correction in the stddev.
332
+ # Unfortunately, I haven't been able to figure out what the right correction is
333
+ # to make the bootstrap unbiased - I considered multiplying by sqrt(n/(n-1)) but
334
+ # that would be ad-hoc and I can't prove that that would actually be an unbiased estimator)
335
+ # Thankfully, shouldn't matter because our samples are usually pretty big.
336
+ res = []
337
+ chunk_size = min(1000, iters)
338
+ from tqdm import tqdm
339
+
340
+ logger.info("Bootstrapping for stddev:", f.__name__)
341
+ for bootstrap in tqdm(
342
+ pool.imap(
343
+ _BootstrapInternal(f, chunk_size),
344
+ [(i, xs) for i in range(iters // chunk_size)],
345
+ ),
346
+ total=iters // chunk_size,
347
+ ):
348
+ # sample w replacement
349
+ res.extend(bootstrap)
350
+
351
+ pool.close()
352
+ return sample_stddev(res)
353
+
354
+
355
+ def stderr_for_metric(metric, bootstrap_iters):
356
+ bootstrappable = [
357
+ median,
358
+ matthews_corrcoef,
359
+ f1_score,
360
+ perplexity,
361
+ bleu,
362
+ chrf,
363
+ ter,
364
+ ]
365
+
366
+ if metric in bootstrappable:
367
+ return lambda x: bootstrap_stderr(metric, x, iters=bootstrap_iters)
368
+
369
+ stderr = {mean: mean_stderr, acc_all: acc_all_stderr, parity: parity_stderr}
370
+
371
+ return stderr.get(metric, None)
evaluation-pipeline/lm_eval/api/model.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from tqdm import tqdm
8
+ from typing import Iterable, List, Optional, Tuple, Union
9
+ from transformers import BatchEncoding
10
+
11
+ from lm_eval.api import utils
12
+
13
+
14
+ class LM(abc.ABC):
15
+ def __init__(self):
16
+ self.cache_hook = CacheHook(None)
17
+
18
+ @abc.abstractmethod
19
+ def loglikelihood(
20
+ self, requests: List[Tuple[str, str]]
21
+ ) -> List[Tuple[float, bool]]:
22
+ """Compute log-likelihood of generating a continuation from a context.
23
+ Downstream tasks should attempt to use loglikelihood instead of other
24
+ LM calls whenever possible.
25
+
26
+ Args:
27
+ requests (List[Tuple[str, str]]):
28
+ A list of pairs (context, continuation):
29
+ context (str):
30
+ Context string. Implementations of LM must be able to handle
31
+ an empty context string.
32
+ continuation (str):
33
+ The continuation over which log likelihood will be calculated.
34
+ If there is a word boundary, the space should be in the
35
+ continuation. For example, context="hello" continuation=" world"
36
+ is correct.
37
+
38
+ Returns:
39
+ A list of pairs (logprob, isgreedy):
40
+ logprob (float):
41
+ The log probability of `continuation`.
42
+ isgreedy (bool):
43
+ Whether `continuation` would be generated by greedy
44
+ sampling from `context`.
45
+ """
46
+ pass
47
+
48
+ @abc.abstractmethod
49
+ def loglikelihood_rolling(self, requests: List[Tuple[str, str]]) -> List[float]:
50
+ """Compute full log-likelihood of a string, with no truncation, for perplexity computation
51
+ - We will use the full max context length of the model.
52
+ - For inputs that exceed the max context length, we divide the tokenized string into chunks of up to
53
+ the max context length.
54
+ - IMPORTANT: Each document's loglikelihood/perplexity is computed *separately*, unlike other implementations
55
+ which may simply concatenate multiple documents together.
56
+ - IMPORTANT: We maximize the amount of context for each prediction. Specifically, for inputs that we break into
57
+ multiple chunks, the last input will still a full-sized context.
58
+ Example:
59
+ Input tokens: [ 0 1 2 3 4 5 6 7 8 9 ]
60
+ Prefix: EOT
61
+ Max context length: 4
62
+ Resulting input/prediction pairs:
63
+
64
+ INPUT: EOT 0 1 2
65
+ PRED: 0 1 2 3
66
+
67
+ INPUT: 3 4 5 6
68
+ PRED: 4 5 6 7
69
+
70
+ INPUT: 5 6 7 8
71
+ PRED: 8 9
72
+
73
+ Observe that:
74
+ 1. Each token is predicted exactly once
75
+ 2. For the last pair, we provide the full context, but only score the last two tokens
76
+
77
+ Args:
78
+ requests (List[Tuple[str, str]]):
79
+ A list of paired strings.
80
+ string (str):
81
+ String for which we are computing per-token loglikelihood.
82
+
83
+ Returns:
84
+ A list of logprobs on the `continuation`.
85
+ """
86
+ pass
87
+
88
+ @abc.abstractmethod
89
+ def greedy_until(self, requests: List[Tuple[str, dict]]) -> List[str]:
90
+ """Generate greedily until a stopping sequence or max generation length.
91
+
92
+ Args:
93
+ requests (List[Tuple[str, dict]]):
94
+ A list of pairs (context, args):
95
+ context (str):
96
+ Context string.
97
+ args (dict):
98
+ A dictionary of generation arguments in the form:
99
+ {
100
+ stop_sequences: str,
101
+ max_generation_length: int,
102
+ num_fewshot: int
103
+ }
104
+
105
+ Returns:
106
+ A list of strings continuation:
107
+ continuation: str
108
+ The generated continuation.
109
+ """
110
+ pass
111
+
112
+ def set_cache_hook(self, cache_hook: "CacheHook"):
113
+ self.cache_hook = cache_hook
114
+
115
+
116
+ TokenSequence = Union[List[int], torch.LongTensor, torch.Tensor, BatchEncoding]
117
+
118
+
119
+ class TokenLM(LM):
120
+ """A language model that assumes inputs, and possibly outputs, are
121
+ tokenized text as opposed to language model APIs that only support
122
+ string-based input and output systems.
123
+ """
124
+
125
+ @abc.abstractmethod
126
+ def tok_encode(self, string: str):
127
+ pass
128
+
129
+ @abc.abstractmethod
130
+ def tok_decode(self, tokens: Iterable[int]) -> List[str]:
131
+ pass
132
+
133
+ @property
134
+ @abc.abstractmethod
135
+ def eot_token(self) -> str:
136
+ pass
137
+
138
+ @property
139
+ @abc.abstractmethod
140
+ def eot_token_id(self) -> int:
141
+ pass
142
+
143
+ @property
144
+ @abc.abstractmethod
145
+ def max_gen_toks(self) -> int:
146
+ """The maximum number of tokens to generate - not including context."""
147
+ pass
148
+
149
+ @property
150
+ @abc.abstractmethod
151
+ def max_length(self) -> int:
152
+ """The maximum sequence length of the model."""
153
+ pass
154
+
155
+ @property
156
+ @abc.abstractmethod
157
+ def batch_size(self) -> int:
158
+ pass
159
+
160
+ @property
161
+ @abc.abstractmethod
162
+ def device(self) -> Union[int, str, torch.device]:
163
+ pass
164
+
165
+ def loglikelihood(
166
+ self, requests: List[Tuple[str, str]]
167
+ ) -> List[Tuple[float, bool]]:
168
+ new_requests = []
169
+ for context, continuation in requests:
170
+ if context == "":
171
+ # End of text as context
172
+ context_enc = [self.eot_token_id]
173
+ else:
174
+ context_enc = self.tok_encode(context)
175
+ continuation_enc = self.tok_encode(continuation)
176
+ new_requests.append(
177
+ ((context, continuation), context_enc, continuation_enc)
178
+ )
179
+ return self._loglikelihood_tokens(new_requests)
180
+
181
+ def loglikelihood_rolling(self, requests: List[Tuple[str, str]]) -> List[float]:
182
+ # TODO: Implement caching once we've confirmed the perplexity implementation
183
+ # TODO: Automatic batch size detection for vectorization
184
+ loglikelihoods = []
185
+ for (string,) in tqdm(requests):
186
+ rolling_token_windows = list(
187
+ map(
188
+ utils.make_disjoint_window,
189
+ utils.get_rolling_token_windows(
190
+ token_list=self.tok_encode(string),
191
+ prefix_token=self.eot_token_id,
192
+ max_seq_len=self.max_length,
193
+ context_len=1,
194
+ ),
195
+ )
196
+ )
197
+ rolling_token_windows = [(None,) + x for x in rolling_token_windows]
198
+ # TODO: Extract out this call so it only gets called once and
199
+ # also somehow figure out partial caching for that.
200
+ string_nll = self._loglikelihood_tokens(
201
+ rolling_token_windows, disable_tqdm=True
202
+ )
203
+ # Discard `is_greedy`
204
+ string_nll = [x[0] for x in string_nll]
205
+ string_nll = sum(string_nll)
206
+ loglikelihoods.append(string_nll)
207
+ return loglikelihoods
208
+
209
+ def _loglikelihood_tokens(
210
+ self,
211
+ requests: List[Tuple[Tuple[str, str], TokenSequence, TokenSequence]],
212
+ disable_tqdm: Optional[bool] = False,
213
+ ) -> List[Tuple[float, bool]]:
214
+ """Helper method for computing log-likelihood of generating a
215
+ continuation from a context that have both been tokenized/encoded.
216
+
217
+ Args:
218
+ requests (List[Tuple[Tuple[str, str], TokenSequence, TokenSequence]]):
219
+ A list of pairs ((context, continuation), context_enc, continuation_enc):
220
+ context (str):
221
+ Context string. Implementations of LM must be able to handle
222
+ an empty context string.
223
+ continuation (str):
224
+ The continuation over which log likelihood will be calculated.
225
+ If there is a word boundary, the space should be in the
226
+ continuation. For example, context="hello" continuation=" world"
227
+ is correct.
228
+ context_enc (TokenSequence):
229
+ The tokenized/encoded context.
230
+ continuation_enc (TokenSequence):
231
+ The tokenized/encoded continuation.
232
+ disable_tqdm (bool, optional, defaults to False):
233
+ Whether to disable `tqdm` progress bar.
234
+
235
+ Returns:
236
+ A list of pairs (logprob, isgreedy):
237
+ logprob (float):
238
+ The log probability of `continuation`.
239
+ isgreedy (float):
240
+ Whether `continuation` would be generated by greedy sampling from `context`.
241
+ """
242
+
243
+ def _collate(x):
244
+ # The negative sign on len(tokens) sorts descending - this has a few advantages:
245
+ # - Time estimates will always be over not underestimates, which is more useful for planning
246
+ # - To know the size of a batch when going through the list, you know the first one is always the batch
247
+ # padded context length. this is useful to simplify the batching logic and more importantly to make
248
+ # automatic adaptive batches much easier to implement
249
+ # - Any OOMs will happen right away rather than near the end
250
+ tokens = x[1] + x[2]
251
+ return -len(tokens), tuple(tokens)
252
+
253
+ # TODO: Automatic (variable) batch size detection for vectorization
254
+ # TODO: Implement some kind of efficient-request-middleware that lumps together requests with the same context
255
+ results = []
256
+ reorder = utils.Reorderer(requests, _collate)
257
+ for chunk in utils.chunks(
258
+ tqdm(reorder.get_reordered(), disable=disable_tqdm), self.batch_size
259
+ ):
260
+ inputs = []
261
+ input_lens = []
262
+ cont_tokens_list = []
263
+ padding_length = None
264
+
265
+ # Because vectorizing is annoying, we first convert each (context, continuation) pair to padded
266
+ # tensors, then we pack them together into a batch, call the model, and then pick it all apart
267
+ # again because vectorizing is annoying
268
+ for _, context_enc, continuation_enc in chunk:
269
+ # sanity check
270
+ assert len(context_enc) > 0
271
+ assert len(continuation_enc) > 0
272
+ assert len(continuation_enc) <= self.max_length
273
+
274
+ # How this all works:
275
+ # CTX CONT
276
+ # inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
277
+ # gpt2 \ \
278
+ # logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
279
+ # cont_tokens 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
280
+
281
+ # When too long to fit in context, truncate from the left
282
+ _full_enc = context_enc + continuation_enc
283
+ input = torch.tensor(
284
+ _full_enc[-(self.max_length + 1) :][:-1],
285
+ dtype=torch.long,
286
+ ).to(self.device)
287
+ (input_len,) = input.shape
288
+
289
+ # Since in _collate we make sure length is descending, the longest is always the first one.
290
+ padding_length = (
291
+ padding_length if padding_length is not None else input_len
292
+ )
293
+
294
+ # Pad length from seq to padding_length
295
+ input = torch.cat(
296
+ [
297
+ input, # [seq]
298
+ torch.zeros(padding_length - input_len, dtype=torch.long).to(
299
+ input.device
300
+ ), # [padding_length - seq]
301
+ ],
302
+ dim=0,
303
+ )
304
+ inputs.append(input.unsqueeze(0)) # [1, padding_length]
305
+ cont_tokens_list.append(continuation_enc)
306
+ input_lens.append(input_len)
307
+
308
+ batched_inputs = torch.cat(inputs, dim=0) # [batch, padding_length]
309
+ multi_logits = F.log_softmax(
310
+ self._model_call(batched_inputs), dim=-1
311
+ ).cpu() # [batch, padding_length, vocab]
312
+
313
+ for (cache_key, _, _), logits, input, input_len, cont_tokens in zip(
314
+ chunk, multi_logits, inputs, input_lens, cont_tokens_list
315
+ ):
316
+ # Slice to original seq length
317
+ cont_len = len(cont_tokens)
318
+ # [1, seq, vocab]
319
+ logits = logits[input_len - cont_len : input_len].unsqueeze(0)
320
+ # Check if per-token argmax is exactly equal to continuation
321
+ greedy_tokens = logits.argmax(dim=-1)
322
+ # [1, seq]
323
+ cont_tokens = torch.tensor(cont_tokens, dtype=torch.long).unsqueeze(0)
324
+ max_equal = (greedy_tokens == cont_tokens).all()
325
+
326
+ # Obtain logprobs at the corresponding continuation token indices
327
+ # last_token_slice = logits[:, -1, :].squeeze(0).tolist()
328
+ # [1, seq]
329
+ logits = torch.gather(logits, 2, cont_tokens.unsqueeze(-1)).squeeze(-1)
330
+ # Answer: (log prob, is-exact-match)
331
+ answer = (float(logits.sum()), bool(max_equal))
332
+ # Partial caching
333
+ if cache_key is not None:
334
+ self.cache_hook.add_partial("loglikelihood", cache_key, answer)
335
+ results.append(answer)
336
+ return reorder.get_original(results)
337
+
338
+ @abc.abstractmethod
339
+ def _model_call(
340
+ self, inputs: TokenSequence, labels: Optional[TokenSequence] = None
341
+ ) -> TokenSequence:
342
+ """
343
+ Args:
344
+ inputs (TokenSequence):
345
+ A list of strings or torch tensor of shape [batch, sequence]
346
+ the size of sequence may vary from call to call.
347
+ labels (TokenSequence, optional, defaults to None):
348
+ A list of strings or torch tensor of shape [batch, sequence]
349
+ useful for sequence-to-sequence language models.
350
+
351
+ Returns:
352
+ A list of ints or torch tensor of shape [batch, sequence, vocab]
353
+ with the logits returned from the model.
354
+ """
355
+ pass
356
+
357
+ @abc.abstractmethod
358
+ def _model_generate(
359
+ self, inputs: TokenSequence, max_tokens: int, stop: Optional[List[str]] = None
360
+ ) -> Union[TokenSequence, List[str]]:
361
+ """
362
+ Args:
363
+ inputs (TokenSequence):
364
+ A list of strings/ints or torch tensor of shape [batch, sequence]
365
+ the size of sequence may vary from call to call.
366
+ max_tokens (int):
367
+ The maximum number of tokens to generate.
368
+ stop (List[str], optional, defaults to None):
369
+ A list of stopping sequences. If provided, the generation will
370
+ stop when any string sequence in the list is encountered.
371
+
372
+ Returns:
373
+ A list of ints/strings or a torch tensor of shape [batch, sequence, vocab]
374
+ with continuation tokens/string of the inputs.
375
+ """
376
+ pass
377
+
378
+
379
+ def hash_args(attr, args):
380
+ data = json.dumps([attr] + list(args))
381
+ return hashlib.sha256(data.encode("utf-8")).hexdigest()
382
+
383
+
384
+ class CachingLM:
385
+ def __init__(self, lm: LM, cache_db: str):
386
+ """LM wrapper that returns cached results if they exist, and uses the underlying LM if not.
387
+
388
+ Args:
389
+ lm (LM):
390
+ The underlying LM to use.
391
+ cache_db (str):
392
+ Path to the `cache` database.
393
+ """
394
+ from sqlitedict import SqliteDict
395
+
396
+ self.lm = lm
397
+ if os.path.dirname(cache_db):
398
+ os.makedirs(os.path.dirname(cache_db), exist_ok=True)
399
+ self.cache_db = cache_db
400
+ self.dbdict = SqliteDict(cache_db, autocommit=True)
401
+ # Add hook to lm
402
+ lm.set_cache_hook(self.get_cache_hook())
403
+
404
+ def __getattr__(self, attr):
405
+ def fn(requests):
406
+ res = []
407
+ remaining_reqs = []
408
+
409
+ # Figure out which ones are cached and which ones are new
410
+ for req in requests:
411
+ hsh = hash_args(attr, req)
412
+ if hsh in self.dbdict:
413
+ ob = self.dbdict[hsh]
414
+
415
+ assert ob is not None
416
+ res.append(ob)
417
+ else:
418
+ res.append(None)
419
+ remaining_reqs.append(req)
420
+
421
+ # Actually run the LM on the requests that do not have cached results
422
+ rem_res = getattr(self.lm, attr)(remaining_reqs)
423
+
424
+ # Stick the new ones back into the list and also cache any of the new ones
425
+ resptr = 0
426
+ for req, r in zip(remaining_reqs, rem_res):
427
+ while res[resptr] is not None:
428
+ resptr += 1
429
+
430
+ res[resptr] = r
431
+ # Caching
432
+ hsh = hash_args(attr, req)
433
+ self.dbdict[hsh] = r
434
+ self.dbdict.commit()
435
+ return res
436
+
437
+ return fn
438
+
439
+ def get_cache_hook(self):
440
+ return CacheHook(self)
441
+
442
+
443
+ class CacheHook:
444
+ def __init__(self, cachinglm: CachingLM):
445
+ if cachinglm is None:
446
+ self.dbdict = None
447
+ return
448
+ self.dbdict = cachinglm.dbdict
449
+
450
+ def add_partial(self, attr, req, res):
451
+ if self.dbdict is None:
452
+ return
453
+ hsh = hash_args(attr, req)
454
+ self.dbdict[hsh] = res
evaluation-pipeline/lm_eval/api/request.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+
4
+ REQUEST_RETURN_LENGTHS = {
5
+ "loglikelihood": 2,
6
+ "greedy_until": None,
7
+ "loglikelihood_rolling": None,
8
+ }
9
+
10
+
11
+ class Request:
12
+ def __init__(
13
+ self, request_type: str, args: Optional[Any] = None, index: Optional[int] = None
14
+ ):
15
+ if request_type not in REQUEST_RETURN_LENGTHS.keys():
16
+ raise NotImplementedError(
17
+ "The request type {} is not implemented!".format(request_type)
18
+ )
19
+ self.request_type = request_type
20
+ self.args = args
21
+ self.index = index
22
+
23
+ def __iter__(self):
24
+ if REQUEST_RETURN_LENGTHS[self.request_type] is None:
25
+ raise IndexError("This request type does not return multiple arguments!")
26
+ for i in range(REQUEST_RETURN_LENGTHS[self.request_type]):
27
+ yield Request(self.request_type, self.args, i)
28
+
29
+ def __getitem__(self, i: int):
30
+ if REQUEST_RETURN_LENGTHS[self.request_type] is None:
31
+ raise IndexError("This request type does not return multiple arguments!")
32
+ return Request(self.request_type, self.args, i)
33
+
34
+ def __eq__(self, other: "Request"):
35
+ return (
36
+ self.request_type == other.request_type
37
+ and self.args == other.args
38
+ and self.index == other.index
39
+ )
40
+
41
+ def __repr__(self):
42
+ return f"Req_{self.request_type}{self.args}[{self.index}]\n"
43
+
44
+
45
+ class RequestFactory:
46
+ def __getattr__(self, attr):
47
+ def fn(*args):
48
+ return Request(attr, args)
49
+
50
+ return fn
51
+
52
+
53
+ rf = RequestFactory()
evaluation-pipeline/lm_eval/api/task.py ADDED
@@ -0,0 +1,874 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import logging
3
+ import re
4
+ import datasets
5
+ import os
6
+ import numpy as np
7
+ import promptsource.templates
8
+ from abc import abstractmethod
9
+ from typing import Callable, List, Mapping, Optional, Tuple, Union
10
+
11
+ from lm_eval.api import utils
12
+ from lm_eval.api.metric import (
13
+ bits_per_byte,
14
+ bleu,
15
+ mean,
16
+ rouge,
17
+ sari,
18
+ weighted_perplexity,
19
+ )
20
+ from lm_eval.api.request import Request, rf
21
+
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ class Task(abc.ABC):
27
+ """A task represents an entire benchmark including its dataset, problems,
28
+ answers, and evaluation methods. See BoolQ for a simple example implementation
29
+
30
+ A `doc` can be any python object which represents one instance of evaluation.
31
+ This is usually a dictionary e.g.
32
+ {"question": ..., "answer": ...} or
33
+ {"question": ..., question, answer)
34
+ """
35
+
36
+ VERSION = 0
37
+
38
+ # The name of the `Task` benchmark as denoted in the HuggingFace datasets Hub
39
+ # or a path to a custom `datasets` loading script.
40
+ DATASET_PATH: str = None
41
+
42
+ # The name of a subset within `DATASET_PATH`.
43
+ DATASET_NAME: str = None
44
+
45
+ def __init__(
46
+ self,
47
+ data_dir: Optional[str] = None,
48
+ cache_dir: Optional[str] = None,
49
+ download_mode: Optional[str] = None,
50
+ file_path: Optional[str] = None,
51
+ ):
52
+ """
53
+ Args:
54
+ data_dir (str, optional, defaults to None):
55
+ Stores the path to a local folder containing the `Task`'s data
56
+ files. Use this to specify the path to manually downloaded data
57
+ (usually when the dataset is not publicly accessible).
58
+ cache_dir (str, optional, defaults to None):
59
+ The directory to read/write the `Task` dataset. This follows the
60
+ HuggingFace `datasets` API with the default cache directory located
61
+ at:
62
+ `~/.cache/huggingface/datasets`
63
+ NOTE: You can change the cache location globally for a given
64
+ process by setting the shell environment variable,
65
+ `HF_DATASETS_CACHE`, to another directory:
66
+ `export HF_DATASETS_CACHE="/path/to/another/directory"`
67
+ download_mode (datasets.DownloadMode, optional, defaults to None):
68
+ How to treat pre-existing `Task` downloads and data.
69
+ - `datasets.DownloadMode.REUSE_DATASET_IF_EXISTS`
70
+ Reuse download and reuse dataset.
71
+ - `datasets.DownloadMode.REUSE_CACHE_IF_EXISTS`
72
+ Reuse download with fresh dataset.
73
+ - `datasets.DownloadMode.FORCE_REDOWNLOAD`
74
+ Fresh download and fresh dataset.
75
+ """
76
+ if file_path:
77
+ self.load_from_file(file_path, cache_dir,
78
+ download_mode=datasets.DownloadMode.FORCE_REDOWNLOAD)
79
+ else:
80
+ self.download(data_dir, cache_dir, download_mode)
81
+ self._training_docs = None
82
+ self._fewshot_docs = None
83
+
84
+ def download(
85
+ self,
86
+ data_dir: Optional[str] = None,
87
+ cache_dir: Optional[str] = None,
88
+ download_mode: Optional[str] = None,
89
+ ):
90
+ """Downloads and returns the task dataset.
91
+
92
+ NOTE: Override this method to download the dataset from a custom API.
93
+ """
94
+ self.dataset = datasets.load_dataset(
95
+ path=self.DATASET_PATH,
96
+ name=self.DATASET_NAME,
97
+ data_dir=data_dir,
98
+ cache_dir=cache_dir,
99
+ download_mode=download_mode,
100
+ )
101
+
102
+ def load_from_file(
103
+ self,
104
+ file_path,
105
+ cache_dir: Optional[str] = None,
106
+ download_mode: Optional[str] = None,
107
+ ):
108
+ # get split names
109
+ splits = {}
110
+ dirname = os.path.dirname(file_path)
111
+ for filename in os.listdir(dirname):
112
+ if not filename.startswith(os.path.basename(file_path)):
113
+ continue
114
+ if filename.count(".") == 2:
115
+ splitname = filename.split(".")[1]
116
+ splits[splitname] = os.path.join(dirname, filename)
117
+ else:
118
+ splits["train"] = os.path.join(dirname, filename)
119
+
120
+ self.dataset = datasets.load_dataset(
121
+ "json",
122
+ data_files=splits,
123
+ cache_dir=cache_dir,
124
+ download_mode=download_mode,
125
+ )
126
+
127
+ @abstractmethod
128
+ def has_training_docs(self):
129
+ """Whether the task has a training set"""
130
+ pass
131
+
132
+ @abstractmethod
133
+ def has_validation_docs(self):
134
+ """Whether the task has a validation set"""
135
+ pass
136
+
137
+ @abstractmethod
138
+ def has_test_docs(self):
139
+ """Whether the task has a test set"""
140
+ pass
141
+
142
+ def training_docs(self) -> datasets.Dataset:
143
+ """
144
+ Returns:
145
+ A dataset of training documents.
146
+ """
147
+ return datasets.Dataset.from_dict({})
148
+
149
+ def validation_docs(self) -> datasets.Dataset:
150
+ """
151
+ Returns:
152
+ A dataset of validation documents.
153
+ """
154
+ return datasets.Dataset.from_dict({})
155
+
156
+ def test_docs(self) -> datasets.Dataset:
157
+ """
158
+ Returns:
159
+ A dataset of test documents.
160
+ """
161
+ return datasets.Dataset.from_dict({})
162
+
163
+ def _process_doc(self, doc):
164
+ """Override this to process (detokenize, strip, replace, etc.) individual
165
+ documents. This can be used in a map over documents of a data split.
166
+ E.g. `map(self._process_doc, self.dataset["validation"])`
167
+
168
+ Returns:
169
+ The processed version of the specified `doc`.
170
+ """
171
+ return doc
172
+
173
+ @abstractmethod
174
+ def doc_to_text(self, doc: dict) -> str:
175
+ pass
176
+
177
+ @abstractmethod
178
+ def doc_to_target(self, doc: dict) -> str:
179
+ pass
180
+
181
+ @abstractmethod
182
+ def construct_requests(self, doc: dict, ctx: str, args: dict) -> List[Request]:
183
+ """Uses RequestFactory to construct Requests and returns an iterable of
184
+ Requests which will be sent to the LM.
185
+
186
+ Args:
187
+ doc (dict):
188
+ The document as returned from training_docs, validation_docs, or
189
+ test_docs.
190
+ ctx (str):
191
+ The context string, generated by fewshot_context. This includes
192
+ the natural language description, as well as the few shot examples,
193
+ and the question part of the document for `doc`.
194
+ args (dict):
195
+ The specifics of the context, including number of few shots.
196
+
197
+ Returns:
198
+ An iterable of `Request` objects.
199
+ """
200
+ pass
201
+
202
+ @abstractmethod
203
+ def process_results(
204
+ self, doc: dict, results: list
205
+ ) -> Union[dict, Tuple[dict, dict]]:
206
+ """Take a single document and the LM results and evaluates, returning a
207
+ dict where keys are the names of sub-metrics and values are the values of
208
+ the metric for that one document.
209
+
210
+ Args:
211
+ doc (dict):
212
+ The document as returned from training_docs, validation_docs, or
213
+ test_docs.
214
+ results (list):
215
+ The results of the requests created in construct_requests.
216
+
217
+ Returns:
218
+ A dict of metric results.
219
+ """
220
+ pass
221
+
222
+ @abstractmethod
223
+ def aggregation(self) -> Mapping[str, Callable]:
224
+ """
225
+ Returns:
226
+ A dictionary where keys are the names of sub-metrics and values are
227
+ functions that aggregate a list of metric scores.
228
+ {str: [metric_score] -> float}
229
+ """
230
+ pass
231
+
232
+ @abstractmethod
233
+ def higher_is_better(self) -> Mapping[str, bool]:
234
+ """
235
+ Returns:
236
+ A dictionary where keys are the names of sub-metrics and values are
237
+ whether a higher value of the sub-metric is better.
238
+ {str: bool}
239
+ """
240
+ pass
241
+
242
+
243
+ class PromptSourceTask(Task):
244
+ """These are the metrics from promptsource that we have
245
+ added default behavior for. If you want to add default behavior for a new metric,
246
+ update the functions below. If you want to use one of the following metrics,
247
+ *and* add additional custom processing, override `process_results`, `higher_is_better`, and `aggregation`.
248
+ """
249
+
250
+ CONFIGURED_RANKED_CHOICE_PS_METRICS = {"Accuracy"}
251
+ CONFIGURED_GENERATION_PS_METRICS = {"BLEU", "ROUGE", "SARI"}
252
+ SPLIT = None
253
+
254
+ def __init__(
255
+ self,
256
+ data_dir: Optional[str] = None,
257
+ cache_dir: Optional[str] = None,
258
+ download_mode: Optional[str] = None,
259
+ prompt_template: Optional[promptsource.templates.Template] = None,
260
+ example_separator: Optional[str] = "\n###\n",
261
+ text_target_separator: Optional[str] = " ",
262
+ save_examples: Optional[bool] = True,
263
+ file_path: Optional[str] = None,
264
+ ):
265
+ """
266
+ Args:
267
+ save_examples (bool, optional, defaults to True):
268
+ Whether to save each example and corresponding model predictions
269
+ to an output `dict`.
270
+
271
+ > Few-shot prompting args
272
+
273
+ example_separator (str, optional, defaults to '\n###\n'):
274
+ The string that will be used to separate the few-shot examples
275
+ from the prompt example.
276
+ Default: '\n###\n'
277
+ See Webson & Pavlick (2022) https://arxiv.org/pdf/2109.01247.pdf
278
+ for justification of this separator.
279
+ text_target_separator (str, optional, defaults to ' '):
280
+ The string that will be used to separate the prompt example
281
+ from the target text.
282
+ NOTE: This is assumed to be some form of whitespace-only separation,
283
+ e.g. "\n\n", "\t", " ", etc. Otherwise, you should update
284
+ the Task's `promptsource` template with the appropriate
285
+ separator(s).
286
+ Example:
287
+ Q: Where is the Eiffel Tower located? A:{text_target_separator}Paris
288
+ """
289
+ assert isinstance(save_examples, bool), "`save_examples` must be a bool."
290
+ assert isinstance(example_separator, str) and isinstance(
291
+ text_target_separator, str
292
+ ), "Separator args must be strings."
293
+ assert (
294
+ text_target_separator.isspace()
295
+ ), f"`text_target_separator` must be whitespace only. Got: `{text_target_separator}`"
296
+
297
+ if file_path:
298
+ super().__init__(cache_dir=cache_dir, file_path=file_path,
299
+ download_mode=download_mode)
300
+ else:
301
+ super().__init__(data_dir, cache_dir, download_mode)
302
+ self.prompt_template = prompt_template
303
+ self.save_examples = save_examples
304
+ self.example_separator = example_separator
305
+ self.text_target_separator = text_target_separator
306
+
307
+ def stop_sequences(self) -> List[str]:
308
+ """Denote where the generation should end based on the few-shot example
309
+ separator.
310
+
311
+ NOTE: Override this if you want to use a sequence other than just the
312
+ task's few-shot example separator.
313
+ """
314
+ return [self.example_separator]
315
+
316
+ def max_generation_length(self) -> Optional[int]:
317
+ """Denote where the max length of the generation if it is obvious from the task."""
318
+ return None
319
+
320
+ def evaluation_docs(self) -> datasets.Dataset:
321
+ """Returns the `dataset` split to be used for evaluation."""
322
+ if self.has_test_docs():
323
+ return self.test_docs()
324
+ elif self.has_validation_docs():
325
+ return self.validation_docs()
326
+ else:
327
+ raise RuntimeError("Task has neither test_docs nor validation_docs")
328
+
329
+ def fewshot_docs(self) -> datasets.Dataset:
330
+ """Returns the `dataset` split that the few-shot examples should be sample
331
+ from. This prioritizes the `train_docs` split as the few-shot example
332
+ source, then `validation_docs`, and lastly `test_docs`.
333
+ """
334
+ if self.has_training_docs():
335
+ return self.training_docs()
336
+ elif self.has_validation_docs():
337
+ return self.validation_docs()
338
+ else:
339
+ return self.test_docs()
340
+
341
+ def doc_to_text(self, doc: dict) -> str:
342
+ """Returns the input string for a particular example, given the hf dict."""
343
+ if self.prompt_template is None:
344
+ return self.null_prompt_doc_to_text(doc)
345
+ # is just a string
346
+ text, _ = self.prompt_template.apply(doc)
347
+ return text
348
+
349
+ def null_prompt_doc_to_text(self, doc: dict) -> str:
350
+ return NotImplementedError("Override this method in your task!")
351
+
352
+ def doc_to_target(self, doc: dict) -> List[str]:
353
+ """Returns the target string for a particular example, given the hf dict."""
354
+ if self.prompt_template is None:
355
+ return self.null_prompt_doc_to_target(doc)
356
+ # is a list of strings where it usually only has one element: the correct answer
357
+ _, target = self.prompt_template.apply(doc)
358
+ return target
359
+
360
+ def null_prompt_doc_to_target(self, doc: dict) -> List[str]:
361
+ return NotImplementedError("Override this method in your task!")
362
+
363
+ def doc_to_rawtext(self, doc: dict) -> str:
364
+ """This should be used for selecting the raw text of the document.
365
+
366
+ The current use case is for computing SARI which requires the text
367
+ without the prompt. The `text` field is not standardized across tasks
368
+ so this is task specific.
369
+ """
370
+ raise NotImplementedError("This is task specific.")
371
+
372
+ def invalid_doc_for_prompt(self, doc) -> bool:
373
+ """Some prompts may not work for some documents.
374
+ Default: False
375
+ """
376
+ return False
377
+
378
+ def format_example(self, text: str, target: str, separator: str) -> str:
379
+ """Returns the text and target combined by the specified `separator`"""
380
+ return text + separator + target
381
+
382
+ def null_prompt_answer_choices(self, doc: dict) -> List[str]:
383
+ return NotImplementedError("Override this method in your task!")
384
+
385
+ def fewshot_examples(
386
+ self,
387
+ docs: datasets.Dataset,
388
+ k: int,
389
+ rng: np.random.Generator,
390
+ prompt: dict = None,
391
+ ) -> Tuple[List[dict], List[int]]:
392
+ """Returns `k` random examples from the set of documents in `docs`.
393
+
394
+ Args:
395
+ docs (datasets.Dataset):
396
+ The dataset of documents to sample few-shot examples from.
397
+ k (int):
398
+ The number of few-shot examples.
399
+ rng (np.random.Generator):
400
+ The pseudo-random number generator used to randomly sample examples.
401
+ prompt (Optional[dict]):
402
+ The prompt document. Specify this to ensure the prompt is not in
403
+ the set of few-shot examples.
404
+
405
+ Returns:
406
+ A tuple of two lists. The first list contains the few-shot examples
407
+ """
408
+ random_indices = np.arange(len(docs)).tolist()
409
+ rng.shuffle(random_indices)
410
+
411
+ i = 0
412
+ fewshot_examples, fewshot_idx = [], []
413
+ for idx in random_indices:
414
+ if i >= k: # Break when we have enough examples.
415
+ break
416
+ is_same_prompt = prompt is not None and all(
417
+ # Skips the `doc_id` key assigned to `prompt`s during eval pre-processing.
418
+ docs[idx][k] == prompt[k]
419
+ for k in docs[idx].keys()
420
+ )
421
+ if self.invalid_doc_for_prompt(docs[idx]) or is_same_prompt:
422
+ continue
423
+ fewshot_examples.append(docs[idx])
424
+ fewshot_idx.append(int(idx))
425
+ i += 1
426
+ return fewshot_examples, fewshot_idx
427
+
428
+ def fewshot_context(
429
+ self, doc: dict, num_fewshot: int, rng: Optional[np.random.Generator]
430
+ ) -> Tuple[str, dict]:
431
+ """Returns a few-shot context string made up of `num_fewshot` number of
432
+ labeled examples, and an appended prompt example without labeling.
433
+
434
+ Args:
435
+ doc (dict):
436
+ The document as returned from training_docs, validation_docs, or test_docs.
437
+ num_fewshot (int):
438
+ The number of fewshot examples to provide in the returned context string.
439
+ rng (numpy.random.Generator):
440
+ The pseudo-random number generator used to randomly sample few-shot examples.
441
+
442
+ Returns:
443
+ A few-shot context string and a dictionary containing few-shot context
444
+ logging information.
445
+ ctx (str):
446
+ The fewshot context.
447
+ logging_info (dict):
448
+ A `dict` of logging info that can be used to identify few-shot
449
+ sources.
450
+ """
451
+ assert (
452
+ rng is not None
453
+ ), "A `numpy.random.Generator` argument must be provided to `rng`"
454
+
455
+ if num_fewshot == 0:
456
+ labeled_examples = ""
457
+ fewshot_idx, fewshot_target_idx, fewshot_src = ([], [], None)
458
+ else:
459
+ # Construct few-shot labeled examples.
460
+ fewshot_docs = self.fewshot_docs()
461
+ fewshot_src = str(fewshot_docs.split)
462
+ fewshot_examples, fewshot_idx = self.fewshot_examples(
463
+ fewshot_docs, k=num_fewshot, rng=rng, prompt=doc
464
+ )
465
+ labeled_examples_list = []
466
+ fewshot_target_idx = []
467
+ for fewshot_example in fewshot_examples:
468
+ text = self.doc_to_text(fewshot_example)
469
+ targets = self.doc_to_target(fewshot_example)
470
+ # Choose 1 random target from multi-reference targets.
471
+ target_idx = int(rng.integers(0, len(targets)))
472
+ target = targets[target_idx].strip()
473
+ labeled_examples_list.append(
474
+ self.format_example(text, target, self.text_target_separator)
475
+ )
476
+ fewshot_target_idx.append(target_idx)
477
+ labeled_examples = self.example_separator.join(labeled_examples_list)
478
+ # Leave an extra `example_separator` right before the prompt.
479
+ labeled_examples += self.example_separator
480
+
481
+ prompt = self.doc_to_text(doc)
482
+ ctx = labeled_examples + prompt
483
+ logging_info = {
484
+ "fewshot_idx": fewshot_idx,
485
+ "fewshot_target_idx": fewshot_target_idx,
486
+ "fewshot_source": fewshot_src,
487
+ "fewshot_num": num_fewshot,
488
+ "ctx": ctx,
489
+ }
490
+ return ctx, logging_info
491
+
492
+ def construct_requests(self, doc: dict, ctx: str, args: dict) -> List[Request]:
493
+ """Uses RequestFactory to construct Requests and returns an iterable of
494
+ Requests which will be sent to the LM.
495
+
496
+ Args:
497
+ doc (dict):
498
+ The document as returned from training_docs, validation_docs, or
499
+ test_docs.
500
+ ctx (str):
501
+ The context string, generated by fewshot_context. This includes
502
+ the natural language description, as well as the few shot examples,
503
+ and the question part of the document for `doc`.
504
+ args (dict):
505
+ The specifics of the context, including number of few shots.
506
+
507
+ Returns:
508
+ An iterable of `Request` objects.
509
+ """
510
+ requests = []
511
+ if self.prompt_template is None:
512
+ answer_choices_list = self.null_prompt_answer_choices(doc)
513
+ else:
514
+ answer_choices_list = self.prompt_template.get_answer_choices_list(doc)
515
+ if answer_choices_list:
516
+ # If answer_choices_list, then this is a ranked choice prompt.
517
+ for answer_choice in answer_choices_list:
518
+ ll_answer_choice, _ = rf.loglikelihood(
519
+ ctx, self.text_target_separator + answer_choice
520
+ )
521
+ requests.append(ll_answer_choice)
522
+ else:
523
+ # If not, then this is a generation prompt.
524
+ request_args = {
525
+ "stop_sequences": self.stop_sequences(),
526
+ "max_generation_length": self.max_generation_length(),
527
+ "num_fewshot": args["num_fewshot"],
528
+ }
529
+ cont_request = rf.greedy_until(ctx, request_args)
530
+ requests.append(cont_request)
531
+ return requests
532
+
533
+ def process_results(
534
+ self, doc: dict, results: list
535
+ ) -> Union[dict, Tuple[dict, dict]]:
536
+ """Take a single document and the LM results and evaluates, returning a
537
+ dict where keys are the names of sub-metrics and values are the values of
538
+ the metric for that one document.
539
+
540
+ NOTE: This function automates processing by using the `promptsource`
541
+ metadata to determine the metric.
542
+
543
+ Args:
544
+ doc (dict):
545
+ The document as returned from training_docs, validation_docs, or
546
+ test_docs.
547
+ results (list):
548
+ The results of the requests created in construct_requests.
549
+
550
+ Returns:
551
+ A dict of metric results.
552
+ """
553
+ if self.prompt_template is None:
554
+ answer_choices_list = self.null_prompt_answer_choices(doc)
555
+ else:
556
+ answer_choices_list = self.prompt_template.get_answer_choices_list(doc)
557
+ target = self.doc_to_target(doc)
558
+ if answer_choices_list:
559
+ # If answer_choices_list, then this is a ranked choice prompt.
560
+ # NOTE: In the future, target could be a list of strings.
561
+ assert isinstance(target, list) and len(target) == 1
562
+ target = target[0].strip()
563
+ try:
564
+ target_idx = answer_choices_list.index(target)
565
+ except ValueError as e:
566
+ print("answer_choices_list:", answer_choices_list)
567
+ print("target:", target)
568
+ raise ValueError(e)
569
+
570
+ pred = answer_choices_list[np.argmax(results)]
571
+ out = {}
572
+ metric_list = ["Accuracy"] # TODO: CLI framework for specifying metrics
573
+
574
+ if self.prompt_template:
575
+ metric_list = self.prompt_template.metadata.metrics
576
+ for metric in metric_list:
577
+ if metric not in self.CONFIGURED_RANKED_CHOICE_PS_METRICS:
578
+ logger.warning(
579
+ f"Unexpected metric: `{metric}`. Add it, or use a task-specific solution."
580
+ )
581
+ if metric == "Accuracy":
582
+ out["acc"] = pred == target
583
+ # Byte-length normalization.
584
+ completion_len = np.array(
585
+ [float(len(i)) for i in answer_choices_list]
586
+ )
587
+ out["acc_norm"] = (
588
+ 1.0
589
+ if np.argmax(results / completion_len) == target_idx
590
+ else 0.0
591
+ )
592
+ # TODO: Add metrics here.
593
+ else:
594
+ # If not, then this is a generation prompt.
595
+ # NOTE: In the future, target will be a list of strings.
596
+ assert isinstance(target, list)
597
+ pred = results[0].strip()
598
+ out = {}
599
+ for metric in self.prompt_template.metadata.metrics:
600
+ if metric not in self.CONFIGURED_GENERATION_PS_METRICS:
601
+ logger.warning(
602
+ f"Unexpected metric: `{metric}`. Add it, or use a task-specific solution."
603
+ )
604
+ if metric == "BLEU":
605
+ out["bleu"] = (target, pred)
606
+ elif metric == "ROUGE":
607
+ # TODO: This computes all rouge sub-metrics. Find a generic
608
+ # way to handle user specified rouge sub-metrics to avoid extra
609
+ # compute.
610
+ rouge_scores = rouge(target, pred)
611
+ # Flatten rouge score dict.
612
+ rouge_scores = utils.flatten(rouge_scores)
613
+ # Merge all the rouge-type scores into the `out` dict.
614
+ out = {**out, **rouge_scores}
615
+ elif metric == "SARI":
616
+ out["sari"] = sari(self.doc_to_rawtext(doc), pred, target)
617
+
618
+ # TODO: Wrap process results s.t. override impl do not
619
+ # override the save examples.
620
+ if self.save_examples:
621
+ example = {
622
+ "pred": pred,
623
+ "target": target,
624
+ "answer_choices_list": answer_choices_list,
625
+ }
626
+ return out, example
627
+ return out
628
+
629
+ def aggregation(self) -> Mapping[str, Callable]:
630
+ out = {}
631
+ metric_list = ["Accuracy"]
632
+ if self.prompt_template:
633
+ metric_list = self.prompt_template.metadata.metrics
634
+ for metric in metric_list:
635
+ if metric == "Accuracy":
636
+ out["acc"] = mean
637
+ out["acc_norm"] = mean
638
+ elif metric == "BLEU":
639
+ out["bleu"] = bleu
640
+ elif metric == "ROUGE":
641
+ # TODO: Find a generic way to handle user specified rouge metrics.
642
+ out["rouge1_precision"] = mean
643
+ out["rouge1_recall"] = mean
644
+ out["rouge1_fmeasure"] = mean
645
+
646
+ out["rouge2_precision"] = mean
647
+ out["rouge2_recall"] = mean
648
+ out["rouge2_fmeasure"] = mean
649
+
650
+ out["rougeL_precision"] = mean
651
+ out["rougeL_recall"] = mean
652
+ out["rougeL_fmeasure"] = mean
653
+
654
+ out["rougeLsum_precision"] = mean
655
+ out["rougeLsum_recall"] = mean
656
+ out["rougeLsum_fmeasure"] = mean
657
+ elif metric == "SARI":
658
+ out["sari"] = mean
659
+ return out
660
+
661
+ def higher_is_better(self) -> Mapping[str, bool]:
662
+ out = {}
663
+ for metric in self.prompt_template.metadata.metrics:
664
+ if metric == "Accuracy":
665
+ out["acc"] = True
666
+ out["acc_norm"] = True
667
+ elif metric == "BLEU":
668
+ out["bleu"] = True
669
+ elif metric == "ROUGE":
670
+ # TODO: Find a generic way to handle user specified rouge metrics.
671
+ out["rouge1_precision"] = True
672
+ out["rouge1_recall"] = True
673
+ out["rouge1_fmeasure"] = True
674
+
675
+ out["rouge2_precision"] = True
676
+ out["rouge2_recall"] = True
677
+ out["rouge2_fmeasure"] = True
678
+
679
+ out["rougeL_precision"] = True
680
+ out["rougeL_recall"] = True
681
+ out["rougeL_fmeasure"] = True
682
+
683
+ out["rougeLsum_precision"] = True
684
+ out["rougeLsum_recall"] = True
685
+ out["rougeLsum_fmeasure"] = True
686
+ elif metric == "SARI":
687
+ out["sari"] = True
688
+ return out
689
+
690
+ def get_logging_info(self):
691
+ if self.prompt_template is None:
692
+ return self.null_prompt_get_logging_info()
693
+ return {
694
+ "fixed_answer_choice_list": self.prompt_template.get_fixed_answer_choices_list(),
695
+ "dataset_path": self.DATASET_PATH,
696
+ "dataset_name": self.DATASET_NAME,
697
+ "subset": self.SPLIT,
698
+ "prompt_name": self.prompt_template.get_name(),
699
+ "prompt_id": self.prompt_template.get_id(),
700
+ "prompt_jinja": self.prompt_template.jinja,
701
+ "prompt_original_task": self.prompt_template.metadata.original_task,
702
+ # Placeholder for comment in post-processing.
703
+ "comment": "",
704
+ }
705
+
706
+
707
+ class TranslationTask(PromptSourceTask):
708
+
709
+ # Language specific functions.
710
+ @classmethod
711
+ def zh_split(cls, zh_text: str) -> List[str]:
712
+ """Chinese splitting"""
713
+ import jieba
714
+
715
+ return [" ".join(jieba.cut(txt.strip())) for txt in zh_text]
716
+
717
+ @classmethod
718
+ def ja_split(cls, ja_text: str) -> List[str]:
719
+ """Japanese splitting"""
720
+ import nagisa
721
+
722
+ return [" ".join(nagisa.tagging(txt.strip()).words) for txt in ja_text]
723
+
724
+ NO_SPACE_LANG = {"zh": zh_split, "ja": ja_split}
725
+
726
+ def invalid_doc_for_prompt(self, doc) -> bool:
727
+ # Skip docs with empty references.
728
+ if self.doc_to_target(doc) == [""]:
729
+ return True
730
+ return False
731
+
732
+ def _get_src_ref_codes(self, template_name: str) -> Tuple[str, str]:
733
+ """Returns a 2-tuple of (src_lang, ref_lang) codes from the prompt template name."""
734
+ # Get the lang codes from the dataset name.
735
+ lang_pairs = self.DATASET_NAME.split("-")
736
+ # Template name ordering defines the src and ref lang codes.
737
+ if self.DATASET_NAME in template_name:
738
+ return lang_pairs[0], lang_pairs[1]
739
+ # Flip the lang pairs following the prompt source.
740
+ return lang_pairs[1], lang_pairs[0]
741
+
742
+ def process_results(
743
+ self, doc: dict, results: list
744
+ ) -> Union[dict, Tuple[dict, dict]]:
745
+ answer_choices_list = self.prompt_template.get_answer_choices_list(doc)
746
+ target = self.doc_to_target(doc)
747
+
748
+ # Add spaces between words for BLEU score calculation of target languages like Chinese
749
+ _, tar_lang_code = self._get_src_ref_codes(self.prompt_template.name)
750
+ if tar_lang_code in self.NO_SPACE_LANG:
751
+ target = [self.NO_SPACE_LANG[tar_lang_code]([t])[0] for t in target]
752
+ results = self.NO_SPACE_LANG[tar_lang_code](results)
753
+ pred = results[0].strip()
754
+
755
+ out = {}
756
+ for metric in self.prompt_template.metadata.metrics:
757
+ assert (
758
+ metric in self.CONFIGURED_GENERATION_PS_METRICS
759
+ ), "Unexpected metric. Add it, or use a task-specific solution."
760
+ if metric == "BLEU":
761
+ out["bleu"] = (target, pred)
762
+ elif metric == "ROUGE":
763
+ # TODO: This computes all rouge sub-metrics. Find a generic
764
+ # way to handle user specified rouge sub-metrics to avoid extra
765
+ # compute.
766
+ rouge_scores = rouge(target, pred)
767
+ # Flatten rouge score dict.
768
+ rouge_scores = utils.flatten(rouge_scores)
769
+ # Merge all the rouge-type scores into the `out` dict.
770
+ out = {**out, **rouge_scores}
771
+
772
+ # TODO: Wrap process results s.t. override impl do not
773
+ # override the save examples.
774
+ if self.save_examples:
775
+ example = {
776
+ "pred": pred,
777
+ "target": target,
778
+ "answer_choices_list": answer_choices_list,
779
+ }
780
+ return out, example
781
+ return out
782
+
783
+
784
+ class PerplexityTask(PromptSourceTask):
785
+ """NOTE: Prompts are ignored for perplexity tasks."""
786
+
787
+ def doc_to_text(self, doc: dict) -> str:
788
+ return ""
789
+
790
+ def doc_to_target(self, doc: dict) -> List[str]:
791
+ """Because prompts are ignored, return the relevant text from doc."""
792
+ raise NotImplementedError()
793
+
794
+ def fewshot_context(
795
+ self,
796
+ doc: dict,
797
+ num_fewshot: int,
798
+ rng: Optional[np.random.Generator],
799
+ ) -> Tuple[str, dict]:
800
+ assert (
801
+ num_fewshot == 0
802
+ ), "The number of fewshot examples must be 0 for perplexity tasks."
803
+ assert (
804
+ rng is not None
805
+ ), "A `numpy.random.Generator` argument must be provided to `rng`"
806
+ return (
807
+ "",
808
+ {
809
+ "fewshot_idx": [],
810
+ "fewshot_target_idx": [],
811
+ "fewshot_source": None,
812
+ "fewshot_num": 0,
813
+ "ctx": "",
814
+ },
815
+ )
816
+
817
+ def construct_requests(self, doc: dict, ctx: str, args: dict) -> List[Request]:
818
+ assert not ctx
819
+ string = self.doc_to_target(doc)[0]
820
+ req = rf.loglikelihood_rolling(string)
821
+ return req
822
+
823
+ def process_results(
824
+ self, doc: dict, results: list
825
+ ) -> Union[dict, Tuple[dict, dict]]:
826
+ (loglikelihood,) = results
827
+ target = self.doc_to_target(doc)[0]
828
+ words = self.count_words(target)
829
+ bytes_ = self.count_bytes(target)
830
+
831
+ out = {
832
+ "word_perplexity": (loglikelihood, words),
833
+ "byte_perplexity": (loglikelihood, bytes_),
834
+ "bits_per_byte": (loglikelihood, bytes_),
835
+ }
836
+ if self.save_examples:
837
+ return out, {
838
+ "word_perplexity_instance": weighted_perplexity(
839
+ [(loglikelihood, words)]
840
+ ),
841
+ "byte_perplexity_instance": weighted_perplexity(
842
+ [(loglikelihood, bytes_)]
843
+ ),
844
+ "bits_per_byte_instance": bits_per_byte([(loglikelihood, bytes_)]),
845
+ }
846
+ return out
847
+
848
+ def aggregation(self) -> Mapping[str, Callable]:
849
+ return {
850
+ "word_perplexity": weighted_perplexity,
851
+ "byte_perplexity": weighted_perplexity,
852
+ "bits_per_byte": bits_per_byte,
853
+ }
854
+
855
+ def higher_is_better(self) -> Mapping[str, bool]:
856
+ return {
857
+ "word_perplexity": False,
858
+ "byte_perplexity": False,
859
+ "bits_per_byte": False,
860
+ }
861
+
862
+ @classmethod
863
+ def count_bytes(cls, doc):
864
+ return len(doc.encode("utf-8"))
865
+
866
+ @classmethod
867
+ def count_words(cls, doc):
868
+ """Downstream tasks with custom word boundaries should override this!"""
869
+ return len(re.split(r"\s+", doc))
870
+
871
+ def get_logging_info(self):
872
+ return {
873
+ "prompt_name": None,
874
+ }
evaluation-pipeline/lm_eval/api/utils.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import pathlib
3
+ import re
4
+ import sys
5
+ import torch
6
+ from typing import Callable, Final, Iterable, List, Optional, Tuple, Union
7
+ from collections.abc import MutableMapping
8
+ from transformers import set_seed as transformers_set_seed
9
+
10
+
11
+ # General Utils
12
+
13
+
14
+ class ExitCodeError(Exception):
15
+ pass
16
+
17
+
18
+ # Reproducibility utils
19
+
20
+
21
+ DEFAULT_SEED: Final[int] = 1234
22
+
23
+
24
+ def set_seed(seed: Optional[int] = DEFAULT_SEED):
25
+ transformers_set_seed(seed)
26
+
27
+
28
+ # Token Utils
29
+
30
+
31
+ def general_detokenize(s: str) -> str:
32
+ s = s.replace(" n't", "n't")
33
+ s = s.replace(" )", ")")
34
+ s = s.replace("( ", "(")
35
+ s = s.replace('" ', '"')
36
+ s = s.replace(' "', '"')
37
+ s = re.sub(r" (['.,])", r"\1", s)
38
+ return s
39
+
40
+
41
+ def get_rolling_token_windows(
42
+ token_list: List[int], prefix_token: int, max_seq_len: int, context_len: int
43
+ ) -> Iterable[Tuple[List[int], List[int]]]:
44
+ """Returns a generator of rolling windows of length `max_seq_len` from a list of tokens.
45
+
46
+ Args:
47
+ token_list (List[int]):
48
+ List of tokens to be predicted.
49
+ prefix_token (int):
50
+ Dummy token like <eos> so the first token has something to condition
51
+ on.
52
+ max_seq_len (int):
53
+ The maximum sequence length of the model or a length we want to use.
54
+ context_len (int):
55
+ Amount of desired token context for prediction. Needs to be at least 1.
56
+ This allows for a rolling window context, letting each prediction
57
+ window to potentially condition on some context.
58
+
59
+ Returns:
60
+ Generator of tuples: (input_tokens, pred_tokens)
61
+ NOTE: Score only the last len(pred_tokens) logits of the LM.
62
+ """
63
+ assert 1 <= context_len <= max_seq_len
64
+ if not token_list:
65
+ return
66
+ # +1 offset, going from input->preds
67
+ pred_len = max_seq_len - context_len + 1
68
+ predicted = 0
69
+
70
+ # Special handling for first window: predict all tokens
71
+ first_seq_len = min(max_seq_len, len(token_list))
72
+ yield [prefix_token] + token_list[: first_seq_len - 1], token_list[:first_seq_len]
73
+ predicted += first_seq_len
74
+
75
+ while predicted < len(token_list):
76
+ window_pred_len = min(len(token_list) - predicted, pred_len)
77
+ window_end = predicted + window_pred_len
78
+
79
+ yield (
80
+ token_list[window_end - max_seq_len - 1 : window_end - 1],
81
+ token_list[window_end - window_pred_len : window_end],
82
+ )
83
+ predicted += window_pred_len
84
+
85
+
86
+ def split_and_pad_windows(
87
+ windows: List[Tuple[str, str]], pad_token_id: int, max_seq_len: int
88
+ ) -> Tuple[List[int], List[int]]:
89
+ """Splits and pads a sequence of rolling context and continuation windows
90
+ from `get_rolling_token_windows`.
91
+
92
+ Example:
93
+ [
94
+ ([1] , [23, 19, 3]), # (context, continuation)
95
+ ([43], [2, 4]])
96
+ ]
97
+
98
+ Output:
99
+ [
100
+ [[1],[43]], # Split & padded contexts.
101
+ [[23, 19, 3], [2, 4, 1]]` # Split & padded continuations.
102
+ ]
103
+ where `1` = `pad_token` id.
104
+
105
+ Args:
106
+ windows (List[Tuple[str, str]]):
107
+ A generator of rolling `(context, continuation)` token windows
108
+ (tuples).
109
+ pad_token_id (int):
110
+ The token id to pad with.
111
+ max_seq_len (int):
112
+ The maximum sequence length of the model or a length we want to use.
113
+
114
+ Returns:
115
+ A tuple of (context, continuation) padding windows.
116
+ """
117
+ contexts, continuations = zip(*windows)
118
+ contexts, continuations = list(contexts), list(continuations)
119
+
120
+ # Pad contexts:
121
+ rollover_context = contexts[-1]
122
+ rollover_context_size = len(rollover_context)
123
+ # Handle empty final context token list - just add 1 token.
124
+ if rollover_context_size == 0:
125
+ contexts[-1] += [pad_token_id]
126
+ elif rollover_context_size > 1:
127
+ for i in range(len(contexts[:-1])):
128
+ contexts[i] += [pad_token_id] * (rollover_context_size - len(contexts[i]))
129
+
130
+ # Pad continuations:
131
+ rollover_continuation = continuations[-1]
132
+ rollover_continuation_size = len(rollover_continuation)
133
+ is_multiple_windows = len(continuations) > 1
134
+ if rollover_continuation_size < max_seq_len and is_multiple_windows:
135
+ continuations[-1] = rollover_continuation + [pad_token_id] * (
136
+ max_seq_len - rollover_continuation_size
137
+ )
138
+ return contexts, continuations
139
+
140
+
141
+ def make_disjoint_window(pair):
142
+ """Takes output from get_rolling_token_windows and makes the context not
143
+ overlap with the continuation.
144
+ """
145
+ a, b = pair
146
+ return a[: -(len(b) - 1)], b
147
+
148
+
149
+ def select_continuation_from_batch_left_padding(
150
+ generations: Union[List[List[int]], torch.Tensor], max_context_size: int
151
+ ):
152
+ """Select the continuation from the batch, removing prompts of different lengths.
153
+
154
+ Args:
155
+ generations (Union[List[List[int]], torch.Tensor]):
156
+ A tensor or list-of-lists of shape [batch_size, sequence length].
157
+ max_context_size (int):
158
+ The size of the biggest context; generations will proceed from that
159
+ index.
160
+
161
+ Example:
162
+ PAD PAD Continue : The dog chased the cat [every day of the week]
163
+ Riddle me this : The dog chased the cat [yesterday] PAD PAD PAD PAD
164
+
165
+ Output:
166
+ [every day of the week]
167
+ [yesterday] PAD PAD PAD PAD
168
+ """
169
+ return generations[:, max_context_size:]
170
+
171
+
172
+ # Container Utils
173
+
174
+
175
+ class Reorderer:
176
+ def __init__(self, arr, fn):
177
+ self.size = len(arr)
178
+ arr = list(enumerate(arr))
179
+ arr = group(arr, lambda x: fn(x[1]))
180
+ arr = [([y[0] for y in x], x[0][1]) for x in arr]
181
+ arr.sort(key=lambda x: fn(x[1]))
182
+ self.arr = arr
183
+
184
+ def get_reordered(self):
185
+ return [x[1] for x in self.arr]
186
+
187
+ def get_original(self, newarr):
188
+ res = [None] * self.size
189
+ cov = [False] * self.size
190
+ for (inds, _), v in zip(self.arr, newarr):
191
+ for ind in inds:
192
+ res[ind] = v
193
+ cov[ind] = True
194
+ assert all(cov)
195
+ return res
196
+
197
+
198
+ def flatten(
199
+ d: Union[dict, MutableMapping],
200
+ parent_key: str = "",
201
+ sep: str = "_",
202
+ ) -> dict:
203
+ # From: https://stackoverflow.com/a/6027615
204
+ items = []
205
+ for k, v in d.items():
206
+ new_key = parent_key + sep + k if parent_key else k
207
+ if isinstance(v, MutableMapping):
208
+ items.extend(flatten(v, new_key, sep=sep).items())
209
+ else:
210
+ items.append((new_key, v))
211
+ return dict(items)
212
+
213
+
214
+ def join_iters(iterables: Iterable) -> List:
215
+ for iterable in iterables:
216
+ yield from iterable
217
+
218
+
219
+ def chunks(iterable: Iterable, n: int) -> List:
220
+ arr = []
221
+ for x in iterable:
222
+ arr.append(x)
223
+ if len(arr) == n:
224
+ yield arr
225
+ arr = []
226
+ if arr:
227
+ yield arr
228
+
229
+
230
+ def group(arr: Iterable, fn: Callable) -> List:
231
+ res = collections.defaultdict(list)
232
+ for ob in arr:
233
+ res[fn(ob)].append(ob)
234
+ return list(res.values())
235
+
236
+
237
+ # CLI utils
238
+
239
+
240
+ def cli_template_names(
241
+ task_name: str, template_names: str, template_idx: int = None
242
+ ) -> List[str]:
243
+ """Returns a selection of template names for a given task and comma-
244
+ separated string of template names.
245
+
246
+ Example:
247
+ cli_template_names("task", "A,B,C") -> ["A", "B", "C"]
248
+
249
+ Args:
250
+ task_name (str):
251
+ Name of the task from which to retrieve template names.
252
+ template_names (str):
253
+ A string of template names separated by a comma if multiple names
254
+ are given.
255
+ General Selectors:
256
+ "all_templates":
257
+ Returns all templates for the task.
258
+ "original_templates":
259
+ Returns all templates with formatting that matches the
260
+ original task design.
261
+ template_idx (int, optional, defaults to None):
262
+ If given, returns only the template at the given index.
263
+
264
+ Returns:
265
+ A list of template names.
266
+ """
267
+ import lm_eval.tasks
268
+
269
+ if template_names == "all_templates":
270
+ selections = lm_eval.tasks.list_templates(task_name)
271
+ elif template_names == "original_templates":
272
+ templates = lm_eval.tasks.get_templates(task_name)
273
+ selections = []
274
+ for name in templates.all_template_names:
275
+ if templates[name].metadata.original_task is True:
276
+ selections.append(name)
277
+ if not selections:
278
+ raise ValueError(f"No original task templates found for {task_name}")
279
+ else:
280
+ selections = template_names.split(",")
281
+ if template_idx is not None:
282
+ selections = [selections[template_idx]]
283
+ return selections
284
+
285
+
286
+ def parse_cli_args_string(args: str) -> dict:
287
+ """Parses a string in the following format to a kwargs dictionary.
288
+ "args1=val1,arg2=val2"
289
+ """
290
+ # Remove leading whitespace but not trailing in case a `val` contains necessary whitespace.
291
+ args = args.lstrip()
292
+ if not args:
293
+ return {}
294
+ arg_list = args.split(",")
295
+ args_dict = {}
296
+ for arg in arg_list:
297
+ # Split on the first `=` to allow for `=`s in `val`.
298
+ k, v = arg.split("=", 1)
299
+ args_dict[k] = str_to_builtin_type(v)
300
+ return args_dict
301
+
302
+
303
+ def str_to_builtin_type(s: str) -> str:
304
+ for fn in (to_bool, int, float):
305
+ try:
306
+ return fn(s)
307
+ except ValueError:
308
+ pass
309
+ return s
310
+
311
+
312
+ # https://stackoverflow.com/questions/7019283/automatically-type-cast-parameters-in-python
313
+ def to_bool(s: str):
314
+ if s == "True" or s == "true":
315
+ return True
316
+ if s == "False" or s == "false":
317
+ return False
318
+ raise ValueError(f"The input `{s}` is not of boolean form.")
319
+
320
+
321
+ # Test utils
322
+
323
+
324
+ def find_test_root(*, start_path: pathlib.Path) -> pathlib.Path:
325
+ """Search upward in the directory tree to a maximum of three layers
326
+ to find and return the package root (containing the 'tests' folder)
327
+ """
328
+ cur_path = start_path.resolve()
329
+ max_layers = 3
330
+ for _ in range(max_layers):
331
+ if (cur_path / "tests" / "test_version_stable.py").exists():
332
+ return cur_path
333
+ else:
334
+ cur_path = cur_path.parent.resolve()
335
+ raise FileNotFoundError(
336
+ f"Unable to find package root within {max_layers} upwards" + f"of {start_path}"
337
+ )
338
+
339
+
340
+ def run_task_tests(*, task_list: List[str]):
341
+ """Find the package root and run the tests for the given tasks."""
342
+ import pytest
343
+
344
+ package_root = find_test_root(start_path=pathlib.Path(__file__))
345
+ task_string = " or ".join(task_list)
346
+ args = [
347
+ f"{package_root}/tests/test_version_stable.py",
348
+ f"--rootdir={package_root}",
349
+ "-k",
350
+ f"{task_string}",
351
+ ]
352
+ sys.path.append(str(package_root))
353
+ pytest_return_val = pytest.main(args)
354
+ if pytest_return_val:
355
+ raise ValueError(
356
+ f"Not all tests for the specified tasks ({task_list}) ran successfully! Error code: {pytest_return_val}"
357
+ )
evaluation-pipeline/lm_eval/datasets/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # datasets
2
+
3
+ This directory contains custom EleutherAI datasets not available in the HuggingFace `datasets` hub.
4
+
5
+ In the rare case that you need to add a custom dataset to this collection, follow the
6
+ HuggingFace `datasets` guide found [here](https://huggingface.co/docs/datasets/dataset_script).
evaluation-pipeline/lm_eval/datasets/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/datasets/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
evaluation-pipeline/lm_eval/datasets/arithmetic/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/datasets/arithmetic/arithmetic.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """GPT-3 Arithmetic Test Dataset."""
15
+
16
+
17
+ import json
18
+
19
+ import datasets
20
+
21
+
22
+ _CITATION = """\
23
+ @inproceedings{NEURIPS2020_1457c0d6,
24
+ author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},
25
+ booktitle = {Advances in Neural Information Processing Systems},
26
+ editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},
27
+ pages = {1877--1901},
28
+ publisher = {Curran Associates, Inc.},
29
+ title = {Language Models are Few-Shot Learners},
30
+ url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},
31
+ volume = {33},
32
+ year = {2020}
33
+ }
34
+ """
35
+
36
+ _DESCRIPTION = """\
37
+ A small battery of 10 tests that involve asking language models a simple arithmetic
38
+ problem in natural language.
39
+ """
40
+
41
+ _HOMEPAGE = "https://github.com/openai/gpt-3/tree/master/data"
42
+
43
+ # TODO: Add the licence for the dataset here if you can find it
44
+ _LICENSE = ""
45
+
46
+
47
+ class ArithmeticConfig(datasets.BuilderConfig):
48
+ """BuilderConfig for GPT3 Arithmetic Test Dataset."""
49
+
50
+ def __init__(self, url, features, **kwargs):
51
+ """BuilderConfig for GPT3 Arithmetic dataset.
52
+
53
+ Args:
54
+ url: *string*, the url to the specific subset of the GPT3 Arithmetic dataset.
55
+ features: *list[string]*, list of the features that will appear in the
56
+ feature dict.
57
+ """
58
+ # Version history:
59
+ super().__init__(version=datasets.Version("0.0.1"), **kwargs)
60
+ self.url = url
61
+ self.features = features
62
+
63
+
64
+ class Arithmetic(datasets.GeneratorBasedBuilder):
65
+ """A small battery of 10 tests involving simple arithmetic problems."""
66
+
67
+ BUILDER_CONFIGS = [
68
+ ArithmeticConfig(
69
+ name="arithmetic_2da",
70
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_addition.jsonl",
71
+ features=datasets.Features(
72
+ {
73
+ "context": datasets.Value("string"),
74
+ "completion": datasets.Value("string"),
75
+ }
76
+ ),
77
+ description="2-digit addition",
78
+ ),
79
+ ArithmeticConfig(
80
+ name="arithmetic_2ds",
81
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_subtraction.jsonl",
82
+ features=datasets.Features(
83
+ {
84
+ "context": datasets.Value("string"),
85
+ "completion": datasets.Value("string"),
86
+ }
87
+ ),
88
+ description="2-digit subtraction",
89
+ ),
90
+ ArithmeticConfig(
91
+ name="arithmetic_3da",
92
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/three_digit_addition.jsonl",
93
+ features=datasets.Features(
94
+ {
95
+ "context": datasets.Value("string"),
96
+ "completion": datasets.Value("string"),
97
+ }
98
+ ),
99
+ description="3-digit addition",
100
+ ),
101
+ ArithmeticConfig(
102
+ name="arithmetic_3ds",
103
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/three_digit_subtraction.jsonl",
104
+ features=datasets.Features(
105
+ {
106
+ "context": datasets.Value("string"),
107
+ "completion": datasets.Value("string"),
108
+ }
109
+ ),
110
+ description="3-digit subtraction",
111
+ ),
112
+ ArithmeticConfig(
113
+ name="arithmetic_4da",
114
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/four_digit_addition.jsonl",
115
+ features=datasets.Features(
116
+ {
117
+ "context": datasets.Value("string"),
118
+ "completion": datasets.Value("string"),
119
+ }
120
+ ),
121
+ description="4-digit addition",
122
+ ),
123
+ ArithmeticConfig(
124
+ name="arithmetic_4ds",
125
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/four_digit_subtraction.jsonl",
126
+ features=datasets.Features(
127
+ {
128
+ "context": datasets.Value("string"),
129
+ "completion": datasets.Value("string"),
130
+ }
131
+ ),
132
+ description="4-digit subtraction",
133
+ ),
134
+ ArithmeticConfig(
135
+ name="arithmetic_5da",
136
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/five_digit_addition.jsonl",
137
+ features=datasets.Features(
138
+ {
139
+ "context": datasets.Value("string"),
140
+ "completion": datasets.Value("string"),
141
+ }
142
+ ),
143
+ description="5-digit addition",
144
+ ),
145
+ ArithmeticConfig(
146
+ name="arithmetic_5ds",
147
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/five_digit_subtraction.jsonl",
148
+ features=datasets.Features(
149
+ {
150
+ "context": datasets.Value("string"),
151
+ "completion": datasets.Value("string"),
152
+ }
153
+ ),
154
+ description="5-digit subtraction",
155
+ ),
156
+ ArithmeticConfig(
157
+ name="arithmetic_2dm",
158
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_multiplication.jsonl",
159
+ features=datasets.Features(
160
+ {
161
+ "context": datasets.Value("string"),
162
+ "completion": datasets.Value("string"),
163
+ }
164
+ ),
165
+ description="2-digit multiplication",
166
+ ),
167
+ ArithmeticConfig(
168
+ name="arithmetic_1dc",
169
+ url="https://raw.githubusercontent.com/openai/gpt-3/master/data/single_digit_three_ops.jsonl",
170
+ features=datasets.Features(
171
+ {
172
+ "context": datasets.Value("string"),
173
+ "completion": datasets.Value("string"),
174
+ }
175
+ ),
176
+ description="Single digit 3 operations",
177
+ ),
178
+ ]
179
+
180
+ def _info(self):
181
+ return datasets.DatasetInfo(
182
+ description=f"{_DESCRIPTION}\n{self.config.description}",
183
+ features=self.config.features,
184
+ homepage=_HOMEPAGE,
185
+ license=_LICENSE,
186
+ citation=_CITATION,
187
+ )
188
+
189
+ def _split_generators(self, dl_manager):
190
+ urls = self.config.url
191
+ data_dir = dl_manager.download_and_extract(urls)
192
+ return [
193
+ datasets.SplitGenerator(
194
+ name=datasets.Split.VALIDATION,
195
+ # These kwargs will be passed to _generate_examples
196
+ gen_kwargs={
197
+ "filepath": data_dir,
198
+ "split": datasets.Split.VALIDATION,
199
+ },
200
+ ),
201
+ ]
202
+
203
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
204
+ def _generate_examples(self, filepath, split):
205
+ with open(filepath, encoding="utf-8") as f:
206
+ for key, row in enumerate(f):
207
+ data = json.loads(row)
208
+ context = (
209
+ data["context"]
210
+ .strip()
211
+ .replace("\n\n", "\n")
212
+ .replace("Q:", "Question:")
213
+ .replace("A:", "Answer:")
214
+ )
215
+ completion = data["completion"]
216
+ yield key, {"context": context, "completion": completion}
evaluation-pipeline/lm_eval/datasets/arithmetic/dataset_infos.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"arithmetic_2da": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n2-digit addition", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_2da", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 96624, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_addition.jsonl": {"num_bytes": 138624, "checksum": "75a54b7a3db3b23369df74fe440c23025f3d3c51f664300bd3d56632b2617b3d"}}, "download_size": 138624, "post_processing_size": null, "dataset_size": 96624, "size_in_bytes": 235248}, "arithmetic_2ds": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n2-digit subtraction", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_2ds", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 98216, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_subtraction.jsonl": {"num_bytes": 140216, "checksum": "da956066ff108c00b341d360567472784f5fd872d6465071b44a14291205bc03"}}, "download_size": 140216, "post_processing_size": null, "dataset_size": 98216, "size_in_bytes": 238432}, "arithmetic_3da": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n3-digit addition", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_3da", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 102612, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/three_digit_addition.jsonl": {"num_bytes": 144612, "checksum": "124865e30efd2abfbc1855dd34c218fc02d32d780ace970ab9b4ea3fa74c798b"}}, "download_size": 144612, "post_processing_size": null, "dataset_size": 102612, "size_in_bytes": 247224}, "arithmetic_3ds": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n3-digit subtraction", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_3ds", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 104150, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/three_digit_subtraction.jsonl": {"num_bytes": 146150, "checksum": "7fc6aaedcb0e2bd17c398dd4147c5585b1e608278a8e98b914e69656707d6a29"}}, "download_size": 146150, "post_processing_size": null, "dataset_size": 104150, "size_in_bytes": 250300}, "arithmetic_4da": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n4-digit addition", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_4da", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 108570, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/four_digit_addition.jsonl": {"num_bytes": 150570, "checksum": "459c6f75baa2e8d7cf50bdd07db6d0ca9133a6b137d95d09267db85b6e07f391"}}, "download_size": 150570, "post_processing_size": null, "dataset_size": 108570, "size_in_bytes": 259140}, "arithmetic_4ds": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n4-digit subtraction", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_4ds", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 110150, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/four_digit_subtraction.jsonl": {"num_bytes": 152150, "checksum": "0c47db40a10c052ef0cf732a9ef2edaa53d66377d43eb47a9c382d33a8af7102"}}, "download_size": 152150, "post_processing_size": null, "dataset_size": 110150, "size_in_bytes": 262300}, "arithmetic_5da": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n5-digit addition", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_5da", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 114476, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/five_digit_addition.jsonl": {"num_bytes": 156476, "checksum": "30ada42efe315b958c6e9649274005d3b720e50298e92c3a2d321f8996e58f54"}}, "download_size": 156476, "post_processing_size": null, "dataset_size": 114476, "size_in_bytes": 270952}, "arithmetic_5ds": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n5-digit subtraction", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_5ds", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 116119, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/five_digit_subtraction.jsonl": {"num_bytes": 158119, "checksum": "8b98ccfc943cbf9193bcf1984954aa0b1a4527016072d972a2b055cc1482ca3c"}}, "download_size": 158119, "post_processing_size": null, "dataset_size": 116119, "size_in_bytes": 274238}, "arithmetic_2dm": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\n2-digit multiplication", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_2dm", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 100685, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/two_digit_multiplication.jsonl": {"num_bytes": 142685, "checksum": "5613d1d1cc3b2c03edc1990252247d34c10ec82944b2cdeb19e71b00f237f431"}}, "download_size": 142685, "post_processing_size": null, "dataset_size": 100685, "size_in_bytes": 243370}, "arithmetic_1dc": {"description": "A small battery of 10 tests that involve asking language models a simple arithmetic\nproblem in natural language.\n\nSingle digit 3 operations", "citation": "@inproceedings{NEURIPS2020_1457c0d6,\n author = {Brown, Tom and Mann, Benjamin and Ryder, Nick and Subbiah, Melanie and Kaplan, Jared D and Dhariwal, Prafulla and Neelakantan, Arvind and Shyam, Pranav and Sastry, Girish and Askell, Amanda and Agarwal, Sandhini and Herbert-Voss, Ariel and Krueger, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel and Wu, Jeffrey and Winter, Clemens and Hesse, Chris and Chen, Mark and Sigler, Eric and Litwin, Mateusz and Gray, Scott and Chess, Benjamin and Clark, Jack and Berner, Christopher and McCandlish, Sam and Radford, Alec and Sutskever, Ilya and Amodei, Dario},\n booktitle = {Advances in Neural Information Processing Systems},\n editor = {H. Larochelle and M. Ranzato and R. Hadsell and M. F. Balcan and H. Lin},\n pages = {1877--1901},\n publisher = {Curran Associates, Inc.},\n title = {Language Models are Few-Shot Learners},\n url = {https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Paper.pdf},\n volume = {33},\n year = {2020}\n}\n", "homepage": "https://github.com/openai/gpt-3/tree/master/data", "license": "", "features": {"context": {"dtype": "string", "id": null, "_type": "Value"}, "completion": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "arithmetic", "config_name": "arithmetic_1dc", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 97651, "num_examples": 2000, "dataset_name": "arithmetic"}}, "download_checksums": {"https://raw.githubusercontent.com/openai/gpt-3/master/data/single_digit_three_ops.jsonl": {"num_bytes": 139651, "checksum": "08b34e3272a8ff1d4932d63f251519d14c485c38d582366e1e323d0b859c3925"}}, "download_size": 139651, "post_processing_size": null, "dataset_size": 97651, "size_in_bytes": 237302}}
evaluation-pipeline/lm_eval/datasets/asdiv/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/datasets/asdiv/asdiv.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ASDIV dataset."""
15
+
16
+
17
+ import os
18
+ import xml.etree.ElementTree as ET
19
+
20
+ import datasets
21
+
22
+
23
+ _CITATION = """\
24
+ @misc{miao2021diverse,
25
+ title={A Diverse Corpus for Evaluating and Developing English Math Word Problem Solvers},
26
+ author={Shen-Yun Miao and Chao-Chun Liang and Keh-Yih Su},
27
+ year={2021},
28
+ eprint={2106.15772},
29
+ archivePrefix={arXiv},
30
+ primaryClass={cs.AI}
31
+ }
32
+ """
33
+
34
+ _DESCRIPTION = """\
35
+ ASDiv (Academia Sinica Diverse MWP Dataset) is a diverse (in terms of both language
36
+ patterns and problem types) English math word problem (MWP) corpus for evaluating
37
+ the capability of various MWP solvers. Existing MWP corpora for studying AI progress
38
+ remain limited either in language usage patterns or in problem types. We thus present
39
+ a new English MWP corpus with 2,305 MWPs that cover more text patterns and most problem
40
+ types taught in elementary school. Each MWP is annotated with its problem type and grade
41
+ level (for indicating the level of difficulty).
42
+ """
43
+
44
+ _HOMEPAGE = "https://github.com/chaochun/nlu-asdiv-dataset"
45
+
46
+ # TODO: Add the licence for the dataset here if you can find it
47
+ _LICENSE = ""
48
+
49
+ _URLS = "https://github.com/chaochun/nlu-asdiv-dataset/archive/55790e5270bb91ccfa5053194b25732534696b50.zip"
50
+
51
+
52
+ class ASDiv(datasets.GeneratorBasedBuilder):
53
+ """ASDiv: A Diverse Corpus for Evaluating and Developing English Math Word Problem Solvers"""
54
+
55
+ VERSION = datasets.Version("0.0.1")
56
+
57
+ BUILDER_CONFIGS = [
58
+ datasets.BuilderConfig(
59
+ name="asdiv",
60
+ version=VERSION,
61
+ description="A diverse corpus for evaluating and developing english math word problem solvers",
62
+ )
63
+ ]
64
+
65
+ def _info(self):
66
+ features = datasets.Features(
67
+ {
68
+ "body": datasets.Value("string"),
69
+ "question": datasets.Value("string"),
70
+ "solution_type": datasets.Value("string"),
71
+ "answer": datasets.Value("string"),
72
+ "formula": datasets.Value("string"),
73
+ }
74
+ )
75
+ return datasets.DatasetInfo(
76
+ description=_DESCRIPTION,
77
+ features=features,
78
+ homepage=_HOMEPAGE,
79
+ license=_LICENSE,
80
+ citation=_CITATION,
81
+ )
82
+
83
+ def _split_generators(self, dl_manager):
84
+ urls = _URLS
85
+ data_dir = dl_manager.download_and_extract(urls)
86
+ base_filepath = "nlu-asdiv-dataset-55790e5270bb91ccfa5053194b25732534696b50"
87
+ return [
88
+ datasets.SplitGenerator(
89
+ name=datasets.Split.VALIDATION,
90
+ # These kwargs will be passed to _generate_examples
91
+ gen_kwargs={
92
+ "filepath": os.path.join(
93
+ data_dir, base_filepath, "dataset", "ASDiv.xml"
94
+ ),
95
+ "split": datasets.Split.VALIDATION,
96
+ },
97
+ ),
98
+ ]
99
+
100
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
101
+ def _generate_examples(self, filepath, split):
102
+ tree = ET.parse(filepath)
103
+ root = tree.getroot()
104
+ for key, problem in enumerate(root.iter("Problem")):
105
+ yield key, {
106
+ "body": problem.find("Body").text,
107
+ "question": problem.find("Question").text,
108
+ "solution_type": problem.find("Solution-Type").text,
109
+ "answer": problem.find("Answer").text,
110
+ "formula": problem.find("Formula").text,
111
+ }
evaluation-pipeline/lm_eval/datasets/asdiv/dataset_infos.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"asdiv": {"description": "ASDiv (Academia Sinica Diverse MWP Dataset) is a diverse (in terms of both language\npatterns and problem types) English math word problem (MWP) corpus for evaluating\nthe capability of various MWP solvers. Existing MWP corpora for studying AI progress\nremain limited either in language usage patterns or in problem types. We thus present\na new English MWP corpus with 2,305 MWPs that cover more text patterns and most problem\ntypes taught in elementary school. Each MWP is annotated with its problem type and grade\nlevel (for indicating the level of difficulty).\n", "citation": "@misc{miao2021diverse,\n title={A Diverse Corpus for Evaluating and Developing English Math Word Problem Solvers},\n author={Shen-Yun Miao and Chao-Chun Liang and Keh-Yih Su},\n year={2021},\n eprint={2106.15772},\n archivePrefix={arXiv},\n primaryClass={cs.AI}\n}\n", "homepage": "https://github.com/chaochun/nlu-asdiv-dataset", "license": "", "features": {"body": {"dtype": "string", "id": null, "_type": "Value"}, "question": {"dtype": "string", "id": null, "_type": "Value"}, "solution_type": {"dtype": "string", "id": null, "_type": "Value"}, "answer": {"dtype": "string", "id": null, "_type": "Value"}, "formula": {"dtype": "string", "id": null, "_type": "Value"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "as_div", "config_name": "asdiv", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"validation": {"name": "validation", "num_bytes": 501489, "num_examples": 2305, "dataset_name": "as_div"}}, "download_checksums": {"https://github.com/chaochun/nlu-asdiv-dataset/archive/55790e5270bb91ccfa5053194b25732534696b50.zip": {"num_bytes": 440966, "checksum": "8f1fe4f6d5f170ec1e24ab78c244153c14c568b1bb2b1dad0324e71f37939a2d"}}, "download_size": 440966, "post_processing_size": null, "dataset_size": 501489, "size_in_bytes": 942455}}
evaluation-pipeline/lm_eval/datasets/coqa/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/datasets/coqa/coqa.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """CoQA dataset.
15
+
16
+ This `CoQA` adds the "additional_answers" feature that's missing in the original
17
+ datasets version:
18
+ https://github.com/huggingface/datasets/blob/master/datasets/coqa/coqa.py
19
+ """
20
+
21
+
22
+ import json
23
+
24
+ import datasets
25
+
26
+
27
+ _CITATION = """\
28
+ @misc{reddy2018coqa,
29
+ title={CoQA: A Conversational Question Answering Challenge},
30
+ author={Siva Reddy and Danqi Chen and Christopher D. Manning},
31
+ year={2018},
32
+ eprint={1808.07042},
33
+ archivePrefix={arXiv},
34
+ primaryClass={cs.CL}
35
+ }
36
+ """
37
+
38
+ _DESCRIPTION = """\
39
+ CoQA is a large-scale dataset for building Conversational Question Answering
40
+ systems. The goal of the CoQA challenge is to measure the ability of machines to
41
+ understand a text passage and answer a series of interconnected questions that
42
+ appear in a conversation.
43
+ """
44
+
45
+ _HOMEPAGE = "https://stanfordnlp.github.io/coqa/"
46
+
47
+ # TODO: Add the licence for the dataset here if you can find it
48
+ _LICENSE = ""
49
+
50
+ _URLS = {
51
+ "train": "https://nlp.stanford.edu/data/coqa/coqa-train-v1.0.json",
52
+ "validation": "https://nlp.stanford.edu/data/coqa/coqa-dev-v1.0.json",
53
+ }
54
+
55
+ # `additional_answers` are not available in the train set so we fill them with
56
+ # empty dicts of the same form.
57
+ _EMPTY_ADDITIONAL_ANSWER = {
58
+ "0": [
59
+ {
60
+ "span_start": -1,
61
+ "span_end": -1,
62
+ "span_text": "",
63
+ "input_text": "",
64
+ "turn_id": -1,
65
+ }
66
+ ],
67
+ "1": [
68
+ {
69
+ "span_start": -1,
70
+ "span_end": -1,
71
+ "span_text": "",
72
+ "input_text": "",
73
+ "turn_id": -1,
74
+ }
75
+ ],
76
+ "2": [
77
+ {
78
+ "span_start": -1,
79
+ "span_end": -1,
80
+ "span_text": "",
81
+ "input_text": "",
82
+ "turn_id": -1,
83
+ }
84
+ ],
85
+ }
86
+
87
+
88
+ class Coqa(datasets.GeneratorBasedBuilder):
89
+ """CoQA is a large-scale dataset for building Conversational Question Answering systems."""
90
+
91
+ VERSION = datasets.Version("0.0.1")
92
+
93
+ BUILDER_CONFIGS = [
94
+ datasets.BuilderConfig(
95
+ name="coqa", version=VERSION, description="The CoQA dataset."
96
+ ),
97
+ ]
98
+
99
+ def _info(self):
100
+ features = datasets.Features(
101
+ {
102
+ "id": datasets.Value("string"),
103
+ "source": datasets.Value("string"),
104
+ "story": datasets.Value("string"),
105
+ "questions": datasets.features.Sequence(
106
+ {
107
+ "input_text": datasets.Value("string"),
108
+ "turn_id": datasets.Value("int32"),
109
+ }
110
+ ),
111
+ "answers": datasets.features.Sequence(
112
+ {
113
+ "span_start": datasets.Value("int32"),
114
+ "span_end": datasets.Value("int32"),
115
+ "span_text": datasets.Value("string"),
116
+ "input_text": datasets.Value("string"),
117
+ "turn_id": datasets.Value("int32"),
118
+ }
119
+ ),
120
+ "additional_answers": {
121
+ "0": datasets.features.Sequence(
122
+ {
123
+ "span_start": datasets.Value("int32"),
124
+ "span_end": datasets.Value("int32"),
125
+ "span_text": datasets.Value("string"),
126
+ "input_text": datasets.Value("string"),
127
+ "turn_id": datasets.Value("int32"),
128
+ }
129
+ ),
130
+ "1": datasets.features.Sequence(
131
+ {
132
+ "span_start": datasets.Value("int32"),
133
+ "span_end": datasets.Value("int32"),
134
+ "span_text": datasets.Value("string"),
135
+ "input_text": datasets.Value("string"),
136
+ "turn_id": datasets.Value("int32"),
137
+ }
138
+ ),
139
+ "2": datasets.features.Sequence(
140
+ {
141
+ "span_start": datasets.Value("int32"),
142
+ "span_end": datasets.Value("int32"),
143
+ "span_text": datasets.Value("string"),
144
+ "input_text": datasets.Value("string"),
145
+ "turn_id": datasets.Value("int32"),
146
+ }
147
+ ),
148
+ },
149
+ }
150
+ )
151
+ return datasets.DatasetInfo(
152
+ description=_DESCRIPTION,
153
+ features=features,
154
+ homepage=_HOMEPAGE,
155
+ license=_LICENSE,
156
+ citation=_CITATION,
157
+ )
158
+
159
+ def _split_generators(self, dl_manager):
160
+ urls = {"train": _URLS["train"], "validation": _URLS["validation"]}
161
+ data_dirs = dl_manager.download_and_extract(urls)
162
+ return [
163
+ datasets.SplitGenerator(
164
+ name=datasets.Split.TRAIN,
165
+ # These kwargs will be passed to _generate_examples
166
+ gen_kwargs={
167
+ "filepath": data_dirs["train"],
168
+ "split": datasets.Split.TRAIN,
169
+ },
170
+ ),
171
+ datasets.SplitGenerator(
172
+ name=datasets.Split.VALIDATION,
173
+ # These kwargs will be passed to _generate_examples
174
+ gen_kwargs={
175
+ "filepath": data_dirs["validation"],
176
+ "split": datasets.Split.VALIDATION,
177
+ },
178
+ ),
179
+ ]
180
+
181
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
182
+ def _generate_examples(self, filepath, split):
183
+ with open(filepath, encoding="utf-8") as f:
184
+ data = json.load(f)
185
+ for row in data["data"]:
186
+ id = row["id"]
187
+ source = row["source"]
188
+ story = row["story"]
189
+ questions = [
190
+ {"input_text": q["input_text"], "turn_id": q["turn_id"]}
191
+ for q in row["questions"]
192
+ ]
193
+ answers = [
194
+ {
195
+ "span_start": a["span_start"],
196
+ "span_end": a["span_end"],
197
+ "span_text": a["span_text"],
198
+ "input_text": a["input_text"],
199
+ "turn_id": a["turn_id"],
200
+ }
201
+ for a in row["answers"]
202
+ ]
203
+ if split == datasets.Split.TRAIN:
204
+ additional_answers = _EMPTY_ADDITIONAL_ANSWER
205
+ else:
206
+ additional_answers = {
207
+ "0": [
208
+ {
209
+ "span_start": a0["span_start"],
210
+ "span_end": a0["span_end"],
211
+ "span_text": a0["span_text"],
212
+ "input_text": a0["input_text"],
213
+ "turn_id": a0["turn_id"],
214
+ }
215
+ for a0 in row["additional_answers"]["0"]
216
+ ],
217
+ "1": [
218
+ {
219
+ "span_start": a1["span_start"],
220
+ "span_end": a1["span_end"],
221
+ "span_text": a1["span_text"],
222
+ "input_text": a1["input_text"],
223
+ "turn_id": a1["turn_id"],
224
+ }
225
+ for a1 in row["additional_answers"]["1"]
226
+ ],
227
+ "2": [
228
+ {
229
+ "span_start": a2["span_start"],
230
+ "span_end": a2["span_end"],
231
+ "span_text": a2["span_text"],
232
+ "input_text": a2["input_text"],
233
+ "turn_id": a2["turn_id"],
234
+ }
235
+ for a2 in row["additional_answers"]["2"]
236
+ ],
237
+ }
238
+ yield row["id"], {
239
+ "id": id,
240
+ "story": story,
241
+ "source": source,
242
+ "questions": questions,
243
+ "answers": answers,
244
+ "additional_answers": additional_answers,
245
+ }
evaluation-pipeline/lm_eval/datasets/coqa/dataset_infos.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"coqa": {"description": "CoQA is a large-scale dataset for building Conversational Question Answering\nsystems. The goal of the CoQA challenge is to measure the ability of machines to\nunderstand a text passage and answer a series of interconnected questions that\nappear in a conversation.\n", "citation": "@misc{reddy2018coqa,\n title={CoQA: A Conversational Question Answering Challenge},\n author={Siva Reddy and Danqi Chen and Christopher D. Manning},\n year={2018},\n eprint={1808.07042},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "https://stanfordnlp.github.io/coqa/", "license": "", "features": {"id": {"dtype": "string", "id": null, "_type": "Value"}, "source": {"dtype": "string", "id": null, "_type": "Value"}, "story": {"dtype": "string", "id": null, "_type": "Value"}, "questions": {"feature": {"input_text": {"dtype": "string", "id": null, "_type": "Value"}, "turn_id": {"dtype": "int32", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}, "answers": {"feature": {"span_start": {"dtype": "int32", "id": null, "_type": "Value"}, "span_end": {"dtype": "int32", "id": null, "_type": "Value"}, "span_text": {"dtype": "string", "id": null, "_type": "Value"}, "input_text": {"dtype": "string", "id": null, "_type": "Value"}, "turn_id": {"dtype": "int32", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}, "additional_answers": {"0": {"feature": {"span_start": {"dtype": "int32", "id": null, "_type": "Value"}, "span_end": {"dtype": "int32", "id": null, "_type": "Value"}, "span_text": {"dtype": "string", "id": null, "_type": "Value"}, "input_text": {"dtype": "string", "id": null, "_type": "Value"}, "turn_id": {"dtype": "int32", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}, "1": {"feature": {"span_start": {"dtype": "int32", "id": null, "_type": "Value"}, "span_end": {"dtype": "int32", "id": null, "_type": "Value"}, "span_text": {"dtype": "string", "id": null, "_type": "Value"}, "input_text": {"dtype": "string", "id": null, "_type": "Value"}, "turn_id": {"dtype": "int32", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}, "2": {"feature": {"span_start": {"dtype": "int32", "id": null, "_type": "Value"}, "span_end": {"dtype": "int32", "id": null, "_type": "Value"}, "span_text": {"dtype": "string", "id": null, "_type": "Value"}, "input_text": {"dtype": "string", "id": null, "_type": "Value"}, "turn_id": {"dtype": "int32", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "coqa", "config_name": "coqa", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"train": {"name": "train", "num_bytes": 26250528, "num_examples": 7199, "dataset_name": "coqa"}, "validation": {"name": "validation", "num_bytes": 3765933, "num_examples": 500, "dataset_name": "coqa"}}, "download_checksums": {"https://nlp.stanford.edu/data/coqa/coqa-train-v1.0.json": {"num_bytes": 49001836, "checksum": "b0fdb2bc1bd38dd3ca2ce5fa2ac3e02c6288ac914f241ac409a655ffb6619fa6"}, "https://nlp.stanford.edu/data/coqa/coqa-dev-v1.0.json": {"num_bytes": 9090845, "checksum": "dfa367a9733ce53222918d0231d9b3bedc2b8ee831a2845f62dfc70701f2540a"}}, "download_size": 58092681, "post_processing_size": null, "dataset_size": 30016461, "size_in_bytes": 88109142}}
evaluation-pipeline/lm_eval/datasets/drop/__init__.py ADDED
File without changes
evaluation-pipeline/lm_eval/datasets/drop/dataset_infos.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"drop": {"description": "DROP is a QA dataset which tests comprehensive understanding of paragraphs. In \nthis crowdsourced, adversarially-created, 96k question-answering benchmark, a \nsystem must resolve multiple references in a question, map them onto a paragraph,\nand perform discrete operations over them (such as addition, counting, or sorting).\n", "citation": "@misc{dua2019drop,\n title={DROP: A Reading Comprehension Benchmark Requiring Discrete Reasoning Over Paragraphs}, \n author={Dheeru Dua and Yizhong Wang and Pradeep Dasigi and Gabriel Stanovsky and Sameer Singh and Matt Gardner},\n year={2019},\n eprint={1903.00161},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n", "homepage": "https://allenai.org/data/drop", "license": "", "features": {"section_id": {"dtype": "string", "id": null, "_type": "Value"}, "passage": {"dtype": "string", "id": null, "_type": "Value"}, "question": {"dtype": "string", "id": null, "_type": "Value"}, "query_id": {"dtype": "string", "id": null, "_type": "Value"}, "answer": {"number": {"dtype": "string", "id": null, "_type": "Value"}, "date": {"day": {"dtype": "string", "id": null, "_type": "Value"}, "month": {"dtype": "string", "id": null, "_type": "Value"}, "year": {"dtype": "string", "id": null, "_type": "Value"}}, "spans": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "worker_id": {"dtype": "string", "id": null, "_type": "Value"}, "hit_id": {"dtype": "string", "id": null, "_type": "Value"}}, "validated_answers": {"feature": {"number": {"dtype": "string", "id": null, "_type": "Value"}, "date": {"day": {"dtype": "string", "id": null, "_type": "Value"}, "month": {"dtype": "string", "id": null, "_type": "Value"}, "year": {"dtype": "string", "id": null, "_type": "Value"}}, "spans": {"feature": {"dtype": "string", "id": null, "_type": "Value"}, "length": -1, "id": null, "_type": "Sequence"}, "worker_id": {"dtype": "string", "id": null, "_type": "Value"}, "hit_id": {"dtype": "string", "id": null, "_type": "Value"}}, "length": -1, "id": null, "_type": "Sequence"}}, "post_processed": null, "supervised_keys": null, "task_templates": null, "builder_name": "drop", "config_name": "drop", "version": {"version_str": "0.0.1", "description": null, "major": 0, "minor": 0, "patch": 1}, "splits": {"train": {"name": "train", "num_bytes": 108858121, "num_examples": 77409, "dataset_name": "drop"}, "validation": {"name": "validation", "num_bytes": 12560739, "num_examples": 9536, "dataset_name": "drop"}}, "download_checksums": {"https://s3-us-west-2.amazonaws.com/allennlp/datasets/drop/drop_dataset.zip": {"num_bytes": 8308692, "checksum": "39d2278a29fd729de301b111a45f434c24834f40df8f4ff116d864589e3249d6"}}, "download_size": 8308692, "post_processing_size": null, "dataset_size": 121418860, "size_in_bytes": 129727552}}