EuroEval 15.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of EuroEval might be problematic. Click here for more details.

Files changed (40) hide show
  1. euroeval/__init__.py +72 -0
  2. euroeval/benchmark_config_factory.py +358 -0
  3. euroeval/benchmark_modules/__init__.py +7 -0
  4. euroeval/benchmark_modules/base.py +354 -0
  5. euroeval/benchmark_modules/fresh.py +286 -0
  6. euroeval/benchmark_modules/hf.py +1185 -0
  7. euroeval/benchmark_modules/litellm.py +905 -0
  8. euroeval/benchmark_modules/vllm.py +1171 -0
  9. euroeval/benchmarker.py +1074 -0
  10. euroeval/callbacks.py +72 -0
  11. euroeval/cli.py +281 -0
  12. euroeval/constants.py +50 -0
  13. euroeval/data_loading.py +96 -0
  14. euroeval/data_models.py +474 -0
  15. euroeval/dataset_configs.py +2001 -0
  16. euroeval/enums.py +144 -0
  17. euroeval/exceptions.py +191 -0
  18. euroeval/finetuning.py +324 -0
  19. euroeval/generation.py +296 -0
  20. euroeval/human_evaluation.py +737 -0
  21. euroeval/languages.py +200 -0
  22. euroeval/model_cache.py +253 -0
  23. euroeval/model_config.py +77 -0
  24. euroeval/model_loading.py +78 -0
  25. euroeval/scores.py +90 -0
  26. euroeval/speed_benchmark.py +124 -0
  27. euroeval/task_utils/__init__.py +1 -0
  28. euroeval/task_utils/multiple_choice_classification.py +176 -0
  29. euroeval/task_utils/question_answering.py +698 -0
  30. euroeval/task_utils/sequence_classification.py +237 -0
  31. euroeval/task_utils/text_to_text.py +150 -0
  32. euroeval/task_utils/token_classification.py +464 -0
  33. euroeval/tasks.py +202 -0
  34. euroeval/types.py +97 -0
  35. euroeval/utils.py +574 -0
  36. euroeval-15.2.0.dist-info/METADATA +234 -0
  37. euroeval-15.2.0.dist-info/RECORD +40 -0
  38. euroeval-15.2.0.dist-info/WHEEL +4 -0
  39. euroeval-15.2.0.dist-info/entry_points.txt +4 -0
  40. euroeval-15.2.0.dist-info/licenses/LICENSE +21 -0
euroeval/callbacks.py ADDED
@@ -0,0 +1,72 @@
1
+ """Callbacks for the Hugging Face Trainer."""
2
+
3
+ import sys
4
+ from collections.abc import Sized
5
+
6
+ from torch.utils.data import DataLoader
7
+ from tqdm.auto import tqdm
8
+ from transformers import TrainerControl, TrainerState, TrainingArguments
9
+ from transformers.trainer_callback import ProgressCallback
10
+
11
+
12
+ class NeverLeaveProgressCallback(ProgressCallback):
13
+ """Progress callback which never leaves the progress bar."""
14
+
15
+ def __init__(self, max_str_len: int = 100) -> None:
16
+ """Initialise the callback."""
17
+ super().__init__(max_str_len=max_str_len)
18
+ self.training_bar: tqdm | None = None
19
+ self.prediction_bar: tqdm | None = None
20
+
21
+ def on_train_begin(
22
+ self,
23
+ args: TrainingArguments,
24
+ state: TrainerState,
25
+ control: TrainerControl,
26
+ **kwargs: str,
27
+ ) -> None:
28
+ """Callback actions when training begins."""
29
+ if state.is_local_process_zero:
30
+ desc = "Finetuning model"
31
+ self.training_bar = tqdm(
32
+ total=None,
33
+ leave=False,
34
+ desc=desc,
35
+ disable=hasattr(sys, "_called_from_test"),
36
+ )
37
+ self.current_step = 0
38
+
39
+ def on_step_end(
40
+ self,
41
+ args: TrainingArguments,
42
+ state: TrainerState,
43
+ control: TrainerControl,
44
+ **kwargs: str,
45
+ ) -> None:
46
+ """Callback actions when a training step ends."""
47
+ if state.is_local_process_zero and self.training_bar is not None:
48
+ self.training_bar.update(state.global_step - self.current_step)
49
+ self.current_step = state.global_step
50
+
51
+ def on_prediction_step(
52
+ self,
53
+ args: TrainingArguments,
54
+ state: TrainerState,
55
+ control: TrainerControl,
56
+ eval_dataloader: DataLoader | None = None,
57
+ **kwargs: str,
58
+ ) -> None:
59
+ """Callback actions when a prediction step ends."""
60
+ if eval_dataloader is None:
61
+ return
62
+ correct_dtype = isinstance(eval_dataloader.dataset, Sized)
63
+ if state.is_local_process_zero and correct_dtype:
64
+ if self.prediction_bar is None:
65
+ desc = "Evaluating model"
66
+ self.prediction_bar = tqdm(
67
+ total=len(eval_dataloader),
68
+ leave=False,
69
+ desc=desc,
70
+ disable=hasattr(sys, "_called_from_test"),
71
+ )
72
+ self.prediction_bar.update(1)
euroeval/cli.py ADDED
@@ -0,0 +1,281 @@
1
+ """Command-line interface for benchmarking."""
2
+
3
+ import click
4
+
5
+ from .benchmarker import Benchmarker
6
+ from .dataset_configs import get_all_dataset_configs
7
+ from .enums import Device
8
+ from .languages import get_all_languages
9
+ from .tasks import get_all_tasks
10
+
11
+
12
+ @click.command()
13
+ @click.option(
14
+ "--model",
15
+ "-m",
16
+ required=True,
17
+ multiple=True,
18
+ help="The ID of the model to benchmark.",
19
+ )
20
+ @click.option(
21
+ "--task",
22
+ "-t",
23
+ default=None,
24
+ show_default=True,
25
+ multiple=True,
26
+ type=click.Choice(list(get_all_tasks().keys())),
27
+ help="The dataset tasks to benchmark the model(s) on.",
28
+ )
29
+ @click.option(
30
+ "--language",
31
+ "-l",
32
+ default=["all"],
33
+ show_default=True,
34
+ multiple=True,
35
+ metavar="ISO 639-1 LANGUAGE CODE",
36
+ type=click.Choice(["all"] + list(get_all_languages().keys())),
37
+ help="""The languages to benchmark, both for models and datasets. If "all" then all
38
+ models will be benchmarked on all datasets.""",
39
+ )
40
+ @click.option(
41
+ "--model-language",
42
+ "-ml",
43
+ default=None,
44
+ show_default=True,
45
+ multiple=True,
46
+ metavar="ISO 639-1 LANGUAGE CODE",
47
+ type=click.Choice(["all"] + list(get_all_languages().keys())),
48
+ help="""The model languages to benchmark. If not specified then this will use the
49
+ `language` value.""",
50
+ )
51
+ @click.option(
52
+ "--dataset-language",
53
+ "-dl",
54
+ default=None,
55
+ show_default=True,
56
+ multiple=True,
57
+ metavar="ISO 639-1 LANGUAGE CODE",
58
+ type=click.Choice(["all"] + list(get_all_languages().keys())),
59
+ help="""The dataset languages to benchmark. If "all" then the models will be
60
+ benchmarked on all datasets. If not specified then this will use the `language`
61
+ value.""",
62
+ )
63
+ @click.option(
64
+ "--dataset",
65
+ default=None,
66
+ show_default=True,
67
+ multiple=True,
68
+ type=click.Choice(list(get_all_dataset_configs().keys())),
69
+ help="""The name of the benchmark dataset. We recommend to use the `task` and
70
+ `language` options instead of this option.""",
71
+ )
72
+ @click.option(
73
+ "--batch-size",
74
+ default="32",
75
+ type=click.Choice(["1", "2", "4", "8", "16", "32"]),
76
+ help="The batch size to use.",
77
+ )
78
+ @click.option(
79
+ "--progress-bar/--no-progress-bar",
80
+ default=True,
81
+ show_default=True,
82
+ help="Whether to show a progress bar.",
83
+ )
84
+ @click.option(
85
+ "--raise-errors/--no-raise-errors",
86
+ default=False,
87
+ show_default=True,
88
+ help="Whether to raise errors instead of skipping the evaluation.",
89
+ )
90
+ @click.option(
91
+ "--verbose/--no-verbose",
92
+ "-v/-nv",
93
+ default=False,
94
+ show_default=True,
95
+ help="Whether extra input should be outputted during benchmarking",
96
+ )
97
+ @click.option(
98
+ "--save-results/--no-save-results",
99
+ "-s/-ns",
100
+ default=True,
101
+ show_default=True,
102
+ help="Whether results should not be stored to disk.",
103
+ )
104
+ @click.option(
105
+ "--cache-dir",
106
+ "-c",
107
+ default=".euroeval_cache",
108
+ show_default=True,
109
+ help="The directory where models are datasets are cached.",
110
+ )
111
+ @click.option(
112
+ "--api-key",
113
+ type=str,
114
+ default=None,
115
+ show_default=True,
116
+ help="""The API key to use for a given inference API. If you are benchmarking an "
117
+ "OpenAI model then this would be the OpenAI API key, if you are benchmarking a "
118
+ "model on the Hugging Face inference API then this would be the Hugging Face API "
119
+ "key, and so on.""",
120
+ )
121
+ @click.option(
122
+ "--force/--no-force",
123
+ "-f",
124
+ default=False,
125
+ show_default=True,
126
+ help="""Whether to force evaluation of models which have already been evaluated,
127
+ with scores lying in the 'euroeval_benchmark_results.jsonl' file.""",
128
+ )
129
+ @click.option(
130
+ "--device",
131
+ default=None,
132
+ show_default=True,
133
+ type=click.Choice([device.lower() for device in Device.__members__]),
134
+ help="""The device to use for evaluation. If not specified then the device will be
135
+ set automatically.""",
136
+ )
137
+ @click.option(
138
+ "--trust-remote-code/--no-trust-remote-code",
139
+ default=False,
140
+ show_default=True,
141
+ help="""Whether to trust remote code. Only set this flag if you trust the supplier
142
+ of the model.""",
143
+ )
144
+ @click.option(
145
+ "--use-flash-attention/--no-use-flash-attention",
146
+ default=None,
147
+ show_default=True,
148
+ help="""Whether to use Flash Attention. If not specified then the model will use
149
+ Flash Attention for generative models if a CUDA GPU is available and `flash-attn`
150
+ or `vllm-flash-attn` are installed.""",
151
+ )
152
+ @click.option(
153
+ "--clear-model-cache/--no-clear-model-cache",
154
+ default=False,
155
+ show_default=True,
156
+ help="""Whether to clear the model cache after benchmarking each model. Note that
157
+ this will only remove the model files, and not the cached model outputs (which
158
+ don't take up a lot of disk space). This is useful when benchmarking many models,
159
+ to avoid running out of disk space.""",
160
+ )
161
+ @click.option(
162
+ "--evaluate-test-split/--evaluate-val-split",
163
+ default=False,
164
+ show_default=True,
165
+ help="""Whether to only evaluate on the test split. Only use this for your final
166
+ evaluation, as the test split should not be used for development.""",
167
+ )
168
+ @click.option(
169
+ "--few-shot/--zero-shot",
170
+ default=True,
171
+ show_default=True,
172
+ help="Whether to only evaluate the model using few-shot evaluation. Only relevant "
173
+ "if the model is generative.",
174
+ )
175
+ @click.option(
176
+ "--num-iterations",
177
+ default=10,
178
+ show_default=True,
179
+ help="""The number of times each model should be evaluated. This is only meant to
180
+ be used for power users, and scores will not be allowed on the leaderboards if this
181
+ is changed.""",
182
+ )
183
+ @click.option(
184
+ "--api-base",
185
+ default=None,
186
+ show_default=True,
187
+ help="The base URL for a given inference API. Only relevant if `model` refers to a "
188
+ "model on an inference API.",
189
+ )
190
+ @click.option(
191
+ "--api-version",
192
+ default=None,
193
+ show_default=True,
194
+ help="The version of the API to use. Only relevant if `model` refers to a model on "
195
+ "an inference API.",
196
+ )
197
+ @click.option(
198
+ "--debug/--no-debug",
199
+ default=False,
200
+ show_default=True,
201
+ help="Whether to run the benchmark in debug mode. This prints out extra "
202
+ "information and stores all outputs to the current working directory. Only "
203
+ "relevant if the model is generative.",
204
+ )
205
+ @click.option(
206
+ "--only-allow-safetensors",
207
+ is_flag=True,
208
+ help="Only allow loading models that have safetensors weights available",
209
+ default=False,
210
+ )
211
+ def benchmark(
212
+ model: tuple[str],
213
+ dataset: tuple[str],
214
+ language: tuple[str],
215
+ model_language: tuple[str],
216
+ dataset_language: tuple[str],
217
+ raise_errors: bool,
218
+ task: tuple[str],
219
+ batch_size: str,
220
+ progress_bar: bool,
221
+ save_results: bool,
222
+ cache_dir: str,
223
+ api_key: str | None,
224
+ force: bool,
225
+ verbose: bool,
226
+ device: str | None,
227
+ trust_remote_code: bool,
228
+ use_flash_attention: bool | None,
229
+ clear_model_cache: bool,
230
+ evaluate_test_split: bool,
231
+ few_shot: bool,
232
+ num_iterations: int,
233
+ api_base: str | None,
234
+ api_version: str | None,
235
+ debug: bool,
236
+ only_allow_safetensors: bool,
237
+ ) -> None:
238
+ """Benchmark pretrained language models on language tasks."""
239
+ models = list(model)
240
+ datasets = None if len(dataset) == 0 else list(dataset)
241
+ languages: list[str] = list(language)
242
+ model_languages = None if len(model_language) == 0 else list(model_language)
243
+ dataset_languages = None if len(dataset_language) == 0 else list(dataset_language)
244
+ tasks = None if len(task) == 0 else list(task)
245
+ batch_size_int = int(batch_size)
246
+ device = Device[device.upper()] if device is not None else None
247
+
248
+ benchmarker = Benchmarker(
249
+ language=languages,
250
+ model_language=model_languages,
251
+ dataset_language=dataset_languages,
252
+ task=tasks,
253
+ dataset=datasets,
254
+ batch_size=batch_size_int,
255
+ progress_bar=progress_bar,
256
+ save_results=save_results,
257
+ raise_errors=raise_errors,
258
+ verbose=verbose,
259
+ api_key=api_key,
260
+ force=force,
261
+ cache_dir=cache_dir,
262
+ device=device,
263
+ trust_remote_code=trust_remote_code,
264
+ use_flash_attention=use_flash_attention,
265
+ clear_model_cache=clear_model_cache,
266
+ evaluate_test_split=evaluate_test_split,
267
+ few_shot=few_shot,
268
+ num_iterations=num_iterations,
269
+ api_base=api_base,
270
+ api_version=api_version,
271
+ debug=debug,
272
+ run_with_cli=True,
273
+ only_allow_safetensors=only_allow_safetensors,
274
+ )
275
+
276
+ # Perform the benchmark evaluation
277
+ benchmarker.benchmark(model=models)
278
+
279
+
280
+ if __name__ == "__main__":
281
+ benchmark()
euroeval/constants.py ADDED
@@ -0,0 +1,50 @@
1
+ """Constants used throughout the project."""
2
+
3
+ from .enums import TaskGroup
4
+ from .tasks import NER
5
+
6
+ # This is used as input to generative models; it cannot be a special token
7
+ DUMMY_FILL_VALUE = 100
8
+
9
+
10
+ # We need to raise the amount of tokens generated for reasoning models, to give them
11
+ # time to think
12
+ REASONING_MAX_TOKENS = 8_192
13
+
14
+
15
+ # The Hugging Face Hub pipeline tags used to classify models as generative
16
+ GENERATIVE_PIPELINE_TAGS = ["text-generation", "text2text-generation"]
17
+
18
+
19
+ # Used to disallow non-generative models to be evaluated on these task groups
20
+ GENERATIVE_DATASET_TASK_GROUPS = [TaskGroup.TEXT_TO_TEXT]
21
+
22
+
23
+ # Local models are required to have these files in their directory
24
+ LOCAL_MODELS_REQUIRED_FILES = ["config.json"]
25
+
26
+
27
+ # Tasks where we use structured generation for generative models
28
+ TASKS_USING_JSON = [NER]
29
+
30
+
31
+ # Tasks where we use log probabilities for generative models, rather than the raw
32
+ # completion
33
+ TASK_GROUPS_USING_LOGPROBS = [
34
+ TaskGroup.SEQUENCE_CLASSIFICATION,
35
+ TaskGroup.MULTIPLE_CHOICE_CLASSIFICATION,
36
+ ]
37
+
38
+
39
+ # The number of top log probabilities to return for generative models. For several APIs
40
+ # this is the maximum number of log probabilities that can be returned
41
+ MAX_LOGPROBS = 10
42
+
43
+
44
+ # We make sure to remove these metric attributed after each iteration, to avoid memory
45
+ # leaks
46
+ METRIC_ATTRIBUTES_TAKING_UP_MEMORY = ["cached_bertscorer"]
47
+
48
+
49
+ # Hugging Face Hub tags used to classify models as merge models
50
+ MERGE_TAGS = ["merge", "mergekit"]
@@ -0,0 +1,96 @@
1
+ """Functions related to the loading of the data."""
2
+
3
+ import logging
4
+ import sys
5
+ import time
6
+
7
+ from datasets import Dataset, DatasetDict, load_dataset
8
+ from datasets.exceptions import DatasetsError
9
+ from huggingface_hub.errors import HfHubHTTPError
10
+ from numpy.random import Generator
11
+
12
+ from .data_models import BenchmarkConfig, DatasetConfig
13
+ from .exceptions import InvalidBenchmark
14
+ from .utils import unscramble
15
+
16
+ logger = logging.getLogger("euroeval")
17
+
18
+
19
+ def load_data(
20
+ rng: Generator, dataset_config: "DatasetConfig", benchmark_config: "BenchmarkConfig"
21
+ ) -> list[DatasetDict]:
22
+ """Load the raw bootstrapped datasets.
23
+
24
+ Args:
25
+ rng:
26
+ The random number generator to use.
27
+ dataset_config:
28
+ The configuration for the dataset.
29
+ benchmark_config:
30
+ The configuration for the benchmark.
31
+
32
+ Returns:
33
+ A list of bootstrapped datasets, one for each iteration.
34
+ """
35
+ num_attempts = 5
36
+ for _ in range(num_attempts):
37
+ try:
38
+ dataset = load_dataset(
39
+ path=dataset_config.huggingface_id,
40
+ cache_dir=benchmark_config.cache_dir,
41
+ token=unscramble("HjccJFhIozVymqXDVqTUTXKvYhZMTbfIjMxG_"),
42
+ )
43
+ break
44
+ except (FileNotFoundError, DatasetsError):
45
+ logger.warning(
46
+ f"Failed to load dataset {dataset_config.huggingface_id!r}. Retrying..."
47
+ )
48
+ time.sleep(1)
49
+ continue
50
+ except HfHubHTTPError:
51
+ raise InvalidBenchmark("The Hugging Face Hub seems to be down.")
52
+ else:
53
+ raise InvalidBenchmark(
54
+ f"Failed to load dataset {dataset_config.huggingface_id!r} after "
55
+ f"{num_attempts} attempts."
56
+ )
57
+
58
+ assert isinstance(dataset, DatasetDict) # type: ignore[used-before-def]
59
+
60
+ dataset = DatasetDict({key: dataset[key] for key in ["train", "val", "test"]})
61
+
62
+ if not benchmark_config.evaluate_test_split:
63
+ dataset["test"] = dataset["val"]
64
+
65
+ # Remove empty examples from the datasets
66
+ for text_feature in ["tokens", "text"]:
67
+ if text_feature in dataset["train"].features:
68
+ dataset = dataset.filter(lambda x: len(x[text_feature]) > 0)
69
+
70
+ # If we are testing then truncate the test set
71
+ if hasattr(sys, "_called_from_test"):
72
+ dataset["test"] = dataset["test"].select(range(1))
73
+
74
+ # Bootstrap the splits
75
+ bootstrapped_splits: dict[str, list[Dataset]] = dict()
76
+ for split in ["train", "val", "test"]:
77
+ bootstrap_indices = rng.integers(
78
+ 0,
79
+ len(dataset[split]),
80
+ size=(benchmark_config.num_iterations, len(dataset[split])),
81
+ )
82
+ bootstrapped_splits[split] = [
83
+ dataset[split].select(bootstrap_indices[idx])
84
+ for idx in range(benchmark_config.num_iterations)
85
+ ]
86
+
87
+ datasets = [
88
+ DatasetDict(
89
+ {
90
+ split: bootstrapped_splits[split][idx]
91
+ for split in ["train", "val", "test"]
92
+ }
93
+ )
94
+ for idx in range(benchmark_config.num_iterations)
95
+ ]
96
+ return datasets