chen459664 commited on
Commit
8409f53
·
verified ·
1 Parent(s): 027f073

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lm-evaluation-harness/lm_eval/models/__pycache__/hf_audiolm.cpython-311.pyc +0 -0
  2. lm-evaluation-harness/lm_eval/models/__pycache__/huggingface.cpython-311.pyc +0 -0
  3. lm-evaluation-harness/lm_eval/models/__pycache__/nemo_lm.cpython-310.pyc +0 -0
  4. lm-evaluation-harness/lm_eval/models/__pycache__/neuron_optimum.cpython-310.pyc +0 -0
  5. lm-evaluation-harness/lm_eval/models/__pycache__/optimum_lm.cpython-310.pyc +0 -0
  6. lm-evaluation-harness/lm_eval/models/__pycache__/optimum_lm.cpython-311.pyc +0 -0
  7. lm-evaluation-harness/lm_eval/models/huggingface.py +1480 -0
  8. lm-evaluation-harness/lm_eval/models/optimum_ipex.py +79 -0
  9. lm-evaluation-harness/lm_eval/models/optimum_lm.py +92 -0
  10. lm-evaluation-harness/lm_eval/models/textsynth.py +172 -0
  11. lm-evaluation-harness/lm_eval/prompts/__pycache__/__init__.cpython-311.pyc +0 -0
  12. lm-evaluation-harness/lm_eval/tasks/__pycache__/__init__.cpython-311.pyc +0 -0
  13. lm-evaluation-harness/lm_eval/tasks/aclue/_aclue.yaml +26 -0
  14. lm-evaluation-harness/lm_eval/tasks/aclue/_default_template_yaml +18 -0
  15. lm-evaluation-harness/lm_eval/tasks/aclue/aclue_basic_ancient_chinese.yaml +4 -0
  16. lm-evaluation-harness/lm_eval/tasks/aclue/aclue_poetry_appreciate.yaml +4 -0
  17. lm-evaluation-harness/lm_eval/tasks/aclue/aclue_polysemy_resolution.yaml +4 -0
  18. lm-evaluation-harness/lm_eval/tasks/acpbench/gen_2shot/reach.yaml +19 -0
  19. lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_twi.yaml +7 -0
  20. lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_wol.yaml +7 -0
  21. lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_xho.yaml +7 -0
  22. lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_yaml +36 -0
  23. lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_yor.yaml +7 -0
  24. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_hau.yaml +4 -0
  25. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_ibo.yaml +4 -0
  26. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_kin.yaml +4 -0
  27. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_orm.yaml +4 -0
  28. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_sna.yaml +4 -0
  29. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_swa.yaml +4 -0
  30. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_twi.yaml +4 -0
  31. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_wol.yaml +4 -0
  32. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_xho.yaml +4 -0
  33. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_yaml +32 -0
  34. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_yor.yaml +4 -0
  35. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_zul.yaml +4 -0
  36. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_amh.yaml +4 -0
  37. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_hau.yaml +4 -0
  38. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_kin.yaml +4 -0
  39. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_lug.yaml +4 -0
  40. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_orm.yaml +4 -0
  41. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_sna.yaml +4 -0
  42. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_sot.yaml +4 -0
  43. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_swa.yaml +4 -0
  44. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_twi.yaml +4 -0
  45. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_wol.yaml +4 -0
  46. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_xho.yaml +4 -0
  47. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_yaml +34 -0
  48. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_yor.yaml +4 -0
  49. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_zul.yaml +4 -0
  50. lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_3/afrimgsm_translate_amh.yaml +4 -0
lm-evaluation-harness/lm_eval/models/__pycache__/hf_audiolm.cpython-311.pyc ADDED
Binary file (12.4 kB). View file
 
lm-evaluation-harness/lm_eval/models/__pycache__/huggingface.cpython-311.pyc ADDED
Binary file (61.1 kB). View file
 
lm-evaluation-harness/lm_eval/models/__pycache__/nemo_lm.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
lm-evaluation-harness/lm_eval/models/__pycache__/neuron_optimum.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
lm-evaluation-harness/lm_eval/models/__pycache__/optimum_lm.cpython-310.pyc ADDED
Binary file (2.78 kB). View file
 
lm-evaluation-harness/lm_eval/models/__pycache__/optimum_lm.cpython-311.pyc ADDED
Binary file (4.27 kB). View file
 
lm-evaluation-harness/lm_eval/models/huggingface.py ADDED
@@ -0,0 +1,1480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import logging
3
+ import os
4
+ from datetime import timedelta
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List, Literal, Optional, Tuple, Union
7
+
8
+ import jinja2
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import transformers
12
+ from accelerate import (
13
+ Accelerator,
14
+ InitProcessGroupKwargs,
15
+ find_executable_batch_size,
16
+ )
17
+ from accelerate.utils import get_max_memory
18
+ from huggingface_hub import HfApi
19
+ from packaging import version
20
+ from peft import PeftModel
21
+ from peft import __version__ as PEFT_VERSION
22
+ from tqdm import tqdm
23
+ from transformers.models.auto.modeling_auto import (
24
+ MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
25
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
26
+ )
27
+
28
+ from lm_eval import utils
29
+ from lm_eval.api.instance import Instance
30
+ from lm_eval.api.model import TemplateLM
31
+ from lm_eval.api.registry import register_model
32
+ from lm_eval.models.utils import (
33
+ Collator,
34
+ clear_torch_cache,
35
+ configure_pad_token,
36
+ get_dtype,
37
+ handle_stop_sequences,
38
+ pad_and_concat,
39
+ stop_sequences_criteria,
40
+ )
41
+
42
+
43
+ eval_logger = logging.getLogger(__name__)
44
+
45
+
46
+ @register_model("hf-auto", "hf", "huggingface")
47
+ class HFLM(TemplateLM):
48
+ """
49
+ An abstracted Huggingface model class. Enables usage with both models of
50
+ `transformers.AutoModelForCausalLM` and `transformers.AutoModelForSeq2SeqLM` classes.
51
+
52
+ Supports data-parallel multi-GPU with HF Accelerate.
53
+ """
54
+
55
+ AUTO_MODEL_CLASS = None
56
+ _DEFAULT_MAX_LENGTH = 2048
57
+
58
+ def __init__(
59
+ self,
60
+ pretrained: Union[str, transformers.PreTrainedModel],
61
+ backend: Literal["default", "causal", "seq2seq"] = "default",
62
+ # override whether the model should be treated as decoder-only (causal) or encoder-decoder (seq2seq)
63
+ revision: Optional[str] = "main",
64
+ subfolder: Optional[str] = None,
65
+ tokenizer: Optional[
66
+ Union[
67
+ str,
68
+ transformers.PreTrainedTokenizer,
69
+ transformers.PreTrainedTokenizerFast,
70
+ ]
71
+ ] = None,
72
+ truncation: Optional[bool] = False,
73
+ logits_cache: bool = True,
74
+ max_length: Optional[int] = None,
75
+ device: Optional[str] = "cuda",
76
+ dtype: Optional[Union[str, torch.dtype]] = "auto",
77
+ softmax_dtype: Optional[Union[str, torch.dtype]] = None,
78
+ batch_size: Optional[Union[int, str]] = 1,
79
+ max_batch_size: Optional[int] = 64,
80
+ trust_remote_code: Optional[bool] = False,
81
+ use_fast_tokenizer: Optional[bool] = True,
82
+ add_bos_token: Optional[bool] = False,
83
+ prefix_token_id: Optional[int] = None,
84
+ # arguments used for splitting a model across GPUs naively.
85
+ # only used if `parallelize=True`.
86
+ parallelize: Optional[bool] = False,
87
+ max_memory_per_gpu: Optional[Union[int, str]] = None,
88
+ max_cpu_memory: Optional[Union[int, str]] = None,
89
+ offload_folder: Optional[Union[str, os.PathLike]] = "./offload",
90
+ # PEFT, delta weights and quantization options
91
+ peft: Optional[str] = None,
92
+ delta: Optional[str] = None,
93
+ autogptq: Optional[Union[bool, str]] = False,
94
+ gptqmodel: Optional[bool] = False,
95
+ gguf_file: Optional[str] = None,
96
+ **kwargs,
97
+ ) -> None:
98
+ super().__init__()
99
+ # optionally: take in an already-initialized transformers.PreTrainedModel
100
+ if not isinstance(pretrained, str):
101
+ eval_logger.warning(
102
+ "`pretrained` model kwarg is not of type `str`. Many other model arguments may be ignored. Please do not launch via accelerate or use `parallelize=True` if passing an existing model this way."
103
+ )
104
+ assert not parallelize, (
105
+ "`parallelize=True` is not compatible with passing pre-initialized model to `pretrained`"
106
+ )
107
+ self._model = pretrained
108
+ self._device = self._model.device
109
+ self._config = self._model.config
110
+ gpus = 0
111
+
112
+ else:
113
+ assert isinstance(device, str)
114
+ assert isinstance(pretrained, str)
115
+ assert isinstance(batch_size, (int, str))
116
+
117
+ gpus = torch.cuda.device_count()
118
+ accelerator_kwargs = InitProcessGroupKwargs(timeout=timedelta(weeks=52))
119
+ accelerator = Accelerator(kwargs_handlers=[accelerator_kwargs])
120
+ if accelerator.num_processes > 1:
121
+ self.accelerator = accelerator
122
+
123
+ if "npu" in accelerator.device.type:
124
+ gpus = torch.npu.device_count()
125
+
126
+ # using one process with no model parallelism
127
+ if not (parallelize or accelerator.num_processes > 1):
128
+ # use user-passed device
129
+ device_list = set(
130
+ ["cuda", "cpu"]
131
+ + [f"cuda:{i}" for i in range(gpus)]
132
+ + ["mps", "mps:0"]
133
+ + [f"npu:{i}" for i in range(gpus)]
134
+ )
135
+ if device and device in device_list:
136
+ self._device = torch.device(device)
137
+ eval_logger.info(f"Using device '{device}'")
138
+ if device in ("mps", "mps:0") and version.parse(
139
+ torch.__version__
140
+ ) < version.parse("2.1"):
141
+ raise RuntimeError(
142
+ f"mps requires torch >= 2.1. You have {torch.__version__}"
143
+ )
144
+ else:
145
+ eval_logger.info("Device not specified")
146
+ eval_logger.info(f"Cuda Available? {torch.cuda.is_available()}")
147
+ self._device = (
148
+ torch.device("cuda")
149
+ if torch.cuda.is_available()
150
+ else torch.device("cpu")
151
+ )
152
+ else: # Parallelism managed by accelerate
153
+ if device != "cuda":
154
+ eval_logger.info(
155
+ f"Using `accelerate launch` or `parallelize=True`, device '{device}' will be overridden when placing model."
156
+ )
157
+ # TODO: include in warning that `load_in_8bit` etc. affect this too
158
+ self._device = (
159
+ self.accelerator.device
160
+ if hasattr(self, "accelerator")
161
+ else torch.device(device)
162
+ )
163
+
164
+ revision = str(revision) # cast to string if not already one
165
+ # TODO: update this to be less of a hack once subfolder is fixed in HF
166
+ revision = revision + ("/" + subfolder if subfolder is not None else "")
167
+
168
+ self._get_config(
169
+ pretrained,
170
+ revision=revision,
171
+ trust_remote_code=trust_remote_code,
172
+ gguf_file=gguf_file,
173
+ )
174
+
175
+ # determine which of 'causal' and 'seq2seq' backends to use for HF models
176
+ self._get_backend(
177
+ config=self.config, backend=backend, trust_remote_code=trust_remote_code
178
+ )
179
+
180
+ # load tokenizer so we know tokenizer vocabulary size before loading model and PEFT
181
+ self._create_tokenizer(
182
+ pretrained,
183
+ tokenizer,
184
+ revision=revision,
185
+ trust_remote_code=trust_remote_code,
186
+ use_fast_tokenizer=use_fast_tokenizer,
187
+ gguf_file=gguf_file,
188
+ add_bos_token=add_bos_token,
189
+ )
190
+
191
+ # if we passed `pretrained` as a string, initialize our model now
192
+ if isinstance(pretrained, str):
193
+ self._create_model(
194
+ pretrained=pretrained,
195
+ revision=revision,
196
+ dtype=dtype,
197
+ trust_remote_code=trust_remote_code,
198
+ parallelize=parallelize,
199
+ gpus=gpus,
200
+ max_memory_per_gpu=max_memory_per_gpu,
201
+ max_cpu_memory=max_cpu_memory,
202
+ offload_folder=offload_folder,
203
+ peft=peft,
204
+ delta=delta,
205
+ autogptq=autogptq,
206
+ gptqmodel=gptqmodel,
207
+ gguf_file=gguf_file,
208
+ quantization_config=getattr(self.config, "quantization_config", None),
209
+ **kwargs,
210
+ )
211
+
212
+ # access self._model through self.model property outside this method
213
+ if isinstance(self.model, torch.nn.Module):
214
+ self.model.eval()
215
+ self.model.tie_weights()
216
+
217
+ self.truncation = truncation
218
+ self.logits_cache = logits_cache
219
+ self.vocab_size = self.tokenizer.vocab_size
220
+ # select (or create) a pad token to use
221
+ self.tokenizer = configure_pad_token(self.tokenizer, model_config=self.config)
222
+
223
+ self.add_bos_token = add_bos_token
224
+ if "gemma" in getattr(self.config, "model_type", ""):
225
+ self.add_bos_token = True
226
+ eval_logger.info(
227
+ f"Model type is '{self.config.model_type}', part of the Gemma family--a BOS token will be used as Gemma underperforms without it."
228
+ )
229
+
230
+ self._max_length = max_length
231
+ self.pretrained = pretrained
232
+ self.delta = delta
233
+ self.peft = peft
234
+ self.revision = revision
235
+ self.batch_schedule = 1
236
+ self.batch_sizes = {}
237
+ self.max_batch_size = max_batch_size
238
+ self.softmax_dtype = (
239
+ get_dtype(softmax_dtype) if softmax_dtype is not None else None
240
+ )
241
+
242
+ if str(batch_size).startswith("auto"):
243
+ batch_size = batch_size.split(":")
244
+ self.batch_size_per_gpu = batch_size[0]
245
+ self.batch_schedule = float(batch_size[1]) if len(batch_size) > 1 else 1
246
+ else:
247
+ self.batch_size_per_gpu = int(batch_size)
248
+
249
+ if isinstance(pretrained, str):
250
+ if gpus >= 1 or str(self.device) == "mps":
251
+ # TODO: can remove this whole snippet except in the mps case, perhaps?
252
+ if not (parallelize or autogptq or hasattr(self, "accelerator")):
253
+ # place model onto device requested manually,
254
+ # if not using HF Accelerate or device_map
255
+ # or any other option that preloads model onto device
256
+ try:
257
+ self.model.to(self.device)
258
+ except ValueError:
259
+ eval_logger.debug(
260
+ "Failed to place model onto specified device. This may be because the model is quantized via `bitsandbytes` or `device_map` is provided. If the desired GPU is being used, this message is safe to ignore."
261
+ )
262
+ # multigpu data-parallel support when launched with accelerate
263
+ if gpus > 1:
264
+ if accelerator.num_processes > 1:
265
+ if parallelize:
266
+ eval_logger.warning(
267
+ "You are both using a HF Accelerate `device_map` (`--model_args parallelize=True`) and launching via `accelerate launch`. This will attempt to do model and data parallelism depending on the resources available."
268
+ )
269
+ elif gpus > accelerator.num_processes:
270
+ eval_logger.warning(
271
+ "WARNING: The number of total system GPUs does not match the number of spawned processes. "
272
+ "If you would like to use data parallelism, please launch the script "
273
+ "with 'accelerate launch *script*'. "
274
+ f"Current run will proceed with {accelerator.num_processes} devices."
275
+ )
276
+ if self.accelerator.is_local_main_process:
277
+ eval_logger.info(
278
+ f"Using {gpus} devices with data parallelism"
279
+ )
280
+
281
+ self._device = torch.device(f"{accelerator.device}")
282
+ self.accelerator = accelerator
283
+
284
+ self._rank = self.accelerator.local_process_index
285
+ self._world_size = self.accelerator.num_processes
286
+ else:
287
+ # if we aren't launching via accelerate, ditch
288
+ self._rank = 0
289
+ self._world_size = 1
290
+ else:
291
+ # if a PreTrainedModel was passed into HFLM, we forgo distributed setup.
292
+ eval_logger.warning(
293
+ "Passed an already-initialized model through `pretrained`, assuming single-process call to evaluate() or custom distributed integration"
294
+ )
295
+ self._rank = 0
296
+ self._world_size = 1
297
+
298
+ self.custom_prefix_token_id = prefix_token_id
299
+ if prefix_token_id is not None:
300
+ eval_logger.info(
301
+ f"Loglikelihood prefix token id used in evaluation: {self.prefix_token_id}"
302
+ )
303
+
304
+ def _get_accelerate_args(
305
+ self,
306
+ parallelize: Optional[bool] = None,
307
+ device_map: Optional[str] = "auto",
308
+ max_memory_per_gpu: Optional[Union[int, str]] = None,
309
+ max_cpu_memory: Optional[Union[int, str]] = None,
310
+ offload_folder: Optional[str] = "./offload",
311
+ gpus: Optional[int] = None,
312
+ ) -> dict:
313
+ """Returns the kwargs needed to apply `accelerate` in `AutoModel.from_pretrained`."""
314
+ num_local_processes = int(os.environ.get("LOCAL_WORLD_SIZE", 1))
315
+ num_machines = int(os.environ.get("WORLD_SIZE", 0)) // num_local_processes
316
+ if (
317
+ num_machines == 0
318
+ and hasattr(self, "accelerator")
319
+ and self.accelerator is not None
320
+ ):
321
+ eval_logger.info(
322
+ "We are not in a distributed setting for accelerate. Setting model_parallel to False."
323
+ )
324
+ parallelize = False
325
+
326
+ if parallelize is None:
327
+ # If parallelism is unset by the user, we automatically assign model parallelism
328
+ # if enough extra GPUs are available
329
+ max_memory_all_gpus = get_max_memory()
330
+ # We just want gpu, not cpu, max memory
331
+ if "cpu" in max_memory_all_gpus:
332
+ del max_memory_all_gpus["cpu"]
333
+ parallelize = bool(num_local_processes < len(max_memory_all_gpus))
334
+ eval_logger.info(
335
+ f"Setting model parallel to {parallelize} since "
336
+ f"the number of local processes is {num_local_processes} "
337
+ f"and the number of GPUs is {len(max_memory_all_gpus)}"
338
+ )
339
+
340
+ args = {}
341
+ if parallelize: # Model parallelism will be used
342
+ max_memory = {}
343
+ if max_memory_per_gpu is not None: # Using the provided memory requirements
344
+ max_memory_per_gpu_map = {
345
+ device_idx: max_memory_per_gpu for device_idx in range(gpus)
346
+ }
347
+ else: # Estimating the possible memory requirements
348
+ max_memory_all_gpus = get_max_memory()
349
+ if "cpu" in max_memory_all_gpus:
350
+ del max_memory_all_gpus["cpu"]
351
+ if not hasattr(self, "accelerator"):
352
+ max_memory_per_gpu_map = {
353
+ k: v for k, v in max_memory_all_gpus.items()
354
+ }
355
+ else:
356
+ # use only 1 / num_processes of the GPUs if we are running under accelerate launch
357
+ max_memory_per_gpu_map = {
358
+ k: v
359
+ for k, v in max_memory_all_gpus.items()
360
+ if k % num_local_processes
361
+ == (self.accelerator.process_index % num_local_processes)
362
+ }
363
+ args["max_memory"] = max_memory_per_gpu_map
364
+ args["device_map"] = "auto" if device_map is None else device_map
365
+ eval_logger.info(
366
+ f"Model parallel was set to True, setting max memory per GPU to {max_memory_per_gpu_map} and device map to {args.get('device_map')}"
367
+ )
368
+
369
+ if max_cpu_memory is not None:
370
+ max_memory["cpu"] = max_cpu_memory
371
+
372
+ args["offload_folder"] = offload_folder
373
+ elif (
374
+ device_map is None
375
+ ): # No model parallelism, we use the default provided device for our model
376
+ if hasattr(self, "accelerator"):
377
+ device_map = {"": f"{self.accelerator.device}"}
378
+ else:
379
+ device_map = {"": str(self.device)}
380
+ args["max_memory"] = None
381
+ args["device_map"] = device_map
382
+ eval_logger.info(
383
+ f"Model parallel was set to False, max memory was not set, and device map was set to {device_map}"
384
+ )
385
+ else:
386
+ args["max_memory"] = None
387
+ args["device_map"] = None
388
+ eval_logger.info("Model parallel was set to False.")
389
+
390
+ return args
391
+
392
+ @property
393
+ def config(self):
394
+ # return the associated transformers.AutoConfig for the given pretrained model.
395
+ return self._config
396
+
397
+ @property
398
+ def model(self):
399
+ # returns the model, unwrapping it if using Accelerate
400
+ if hasattr(self, "accelerator"):
401
+ return self.accelerator.unwrap_model(self._model)
402
+ else:
403
+ return self._model
404
+
405
+ @property
406
+ def eot_token_id(self):
407
+ # we use EOT because end of *text* is more accurate for what we're doing than end of *sentence*
408
+ return self.tokenizer.eos_token_id
409
+
410
+ @property
411
+ def prefix_token_id(self):
412
+ # it is used as prefix for loglikelihood
413
+ if self.custom_prefix_token_id is not None:
414
+ return self.custom_prefix_token_id
415
+ if self.tokenizer.bos_token_id is not None:
416
+ return self.tokenizer.bos_token_id
417
+ return self.tokenizer.eos_token_id
418
+
419
+ @property
420
+ def max_length(self):
421
+ if self._max_length: # if max length manually set, return it
422
+ return self._max_length
423
+ seqlen_config_attrs = ("n_positions", "max_position_embeddings", "n_ctx")
424
+ for attr in seqlen_config_attrs:
425
+ if hasattr(self.model.config, attr):
426
+ return getattr(self.model.config, attr)
427
+ if hasattr(self.tokenizer, "model_max_length"):
428
+ if self.tokenizer.model_max_length == 1000000000000000019884624838656:
429
+ return self._DEFAULT_MAX_LENGTH
430
+ return self.tokenizer.model_max_length
431
+ return self._DEFAULT_MAX_LENGTH
432
+
433
+ @property
434
+ def max_gen_toks(self) -> int:
435
+ return 256
436
+
437
+ @property
438
+ def batch_size(self):
439
+ return self.batch_size_per_gpu
440
+
441
+ @property
442
+ def device(self):
443
+ return self._device
444
+
445
+ @property
446
+ def rank(self):
447
+ return self._rank
448
+
449
+ @property
450
+ def world_size(self):
451
+ return self._world_size
452
+
453
+ @property
454
+ def tokenizer_name(self) -> str:
455
+ return self.tokenizer.name_or_path.replace("/", "__")
456
+
457
+ def _get_backend(
458
+ self,
459
+ config: Union[transformers.PretrainedConfig, transformers.AutoConfig],
460
+ backend: Literal["default", "causal", "seq2seq"] = "default",
461
+ trust_remote_code: Optional[bool] = False,
462
+ ) -> None:
463
+ """
464
+ Helper method during initialization.
465
+ Determines the backend ("causal" (decoder-only) or "seq2seq" (encoder-decoder)) model type to be used.
466
+ sets `self.AUTO_MODEL_CLASS` appropriately if not already set.
467
+
468
+ **If not calling HFLM.__init__() or HFLM._get_backend() within a subclass of HFLM,
469
+ user must set `self.backend` to be either "causal" or "seq2seq" manually!**
470
+ """
471
+
472
+ assert backend in ["default", "causal", "seq2seq"]
473
+
474
+ if backend != "default":
475
+ # if we've settled on non-default backend, use that manually
476
+ if backend == "causal":
477
+ self.backend = backend
478
+ elif backend == "seq2seq":
479
+ self.backend = backend
480
+ eval_logger.info(
481
+ f"Overrode HF model backend type, and using type '{self.backend}'"
482
+ )
483
+ else:
484
+ # determine and use the default HF backend for this model, based on its config + metadata.
485
+ if (
486
+ getattr(config, "model_type")
487
+ in MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
488
+ ):
489
+ # first check if model type is listed under seq2seq models, since some
490
+ # models like MBart are listed in both seq2seq and causal mistakenly in HF transformers.
491
+ # these special cases should be treated as seq2seq models.
492
+ self.backend = "seq2seq"
493
+ eval_logger.debug(f"Using model type '{self.backend}'")
494
+ elif (
495
+ getattr(self.config, "model_type") in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
496
+ ):
497
+ self.backend = "causal"
498
+ eval_logger.debug(f"Using model type '{self.backend}'")
499
+ else:
500
+ if not trust_remote_code:
501
+ eval_logger.warning(
502
+ "HF model type is neither marked as CausalLM or Seq2SeqLM. \
503
+ This is expected if your model requires `trust_remote_code=True` but may be an error otherwise."
504
+ "Setting backend to causal"
505
+ )
506
+ # if model type is neither in HF transformers causal or seq2seq model registries
507
+ # then we default to assuming AutoModelForCausalLM
508
+ self.backend = "causal"
509
+ eval_logger.info(
510
+ f"Model type cannot be determined. Using default model type '{self.backend}'"
511
+ )
512
+
513
+ if self.AUTO_MODEL_CLASS is None:
514
+ if self.backend == "causal":
515
+ self.AUTO_MODEL_CLASS = transformers.AutoModelForCausalLM
516
+ elif self.backend == "seq2seq":
517
+ self.AUTO_MODEL_CLASS = transformers.AutoModelForSeq2SeqLM
518
+
519
+ def _get_config(
520
+ self,
521
+ pretrained: str,
522
+ revision: str = "main",
523
+ trust_remote_code: bool = False,
524
+ gguf_file: Optional[str] = None,
525
+ ) -> None:
526
+ """Return the model config for HuggingFace models"""
527
+ self._config = transformers.AutoConfig.from_pretrained(
528
+ pretrained,
529
+ revision=revision,
530
+ trust_remote_code=trust_remote_code,
531
+ gguf_file=gguf_file,
532
+ )
533
+
534
+ def _create_model(
535
+ self,
536
+ pretrained: str,
537
+ revision: Optional[str] = "main",
538
+ dtype: Optional[Union[str, torch.dtype]] = "auto",
539
+ trust_remote_code: Optional[bool] = False,
540
+ # arguments used for splitting a model across GPUs naively.
541
+ # only used if `parallelize=True`.
542
+ # (accelerate naive PP (device_map) options)
543
+ parallelize: Optional[bool] = False,
544
+ gpus: Optional[int] = None,
545
+ max_memory_per_gpu: Optional[Union[int, str]] = None,
546
+ max_cpu_memory: Optional[Union[int, str]] = None,
547
+ offload_folder: Optional[str] = "./offload",
548
+ # PEFT, delta weights and quantization options
549
+ peft: Optional[str] = None,
550
+ delta: Optional[str] = None,
551
+ autogptq: Optional[Union[bool, str]] = False,
552
+ gptqmodel: Optional[bool] = False,
553
+ gguf_file: Optional[str] = None,
554
+ quantization_config: Optional[Dict[str, Any]] = None,
555
+ **kwargs,
556
+ ) -> None:
557
+ """
558
+ Initializes an HF or HF-compatible PreTrainedModel from scratch
559
+ inside HFLM, using the kwargs passed into self.__init__().
560
+
561
+ Also handles functionality such as AutoGPTQ usage and PEFT wrapping.
562
+
563
+ For future similar extensions to AutoGPTQ that are not core to HF's ecosystem,
564
+ (such as PyTorch models that are nearly, but not quite, fully mirroring
565
+ HF's public interface relied on in this HFLM class)
566
+ please consider subclassing HFLM and overriding this and other methods as needed.
567
+ """
568
+
569
+ model_kwargs = kwargs if kwargs else {}
570
+
571
+ model_kwargs.update(
572
+ self._get_accelerate_args(
573
+ parallelize=parallelize,
574
+ device_map=kwargs.get("device_map", None),
575
+ max_memory_per_gpu=max_memory_per_gpu,
576
+ max_cpu_memory=max_cpu_memory,
577
+ offload_folder=offload_folder,
578
+ gpus=gpus,
579
+ )
580
+ )
581
+
582
+ if not autogptq and not gptqmodel:
583
+ if model_kwargs.get("load_in_4bit", None):
584
+ assert transformers.__version__ >= "4.30.0", (
585
+ "load_in_4bit requires transformers >= 4.30.0"
586
+ )
587
+ if transformers.__version__ >= "4.30.0":
588
+ if model_kwargs.get("load_in_4bit", None):
589
+ if model_kwargs.get("bnb_4bit_compute_dtype", None):
590
+ model_kwargs["bnb_4bit_compute_dtype"] = get_dtype(
591
+ model_kwargs["bnb_4bit_compute_dtype"]
592
+ )
593
+
594
+ self._model = self.AUTO_MODEL_CLASS.from_pretrained(
595
+ pretrained,
596
+ revision=revision,
597
+ torch_dtype=get_dtype(dtype),
598
+ trust_remote_code=trust_remote_code,
599
+ gguf_file=gguf_file,
600
+ quantization_config=quantization_config,
601
+ **model_kwargs,
602
+ )
603
+ else:
604
+ if autogptq and gptqmodel:
605
+ raise ValueError(
606
+ "Cannot use both 'autogptq' and 'gptqmodel' options at the same time."
607
+ )
608
+
609
+ if autogptq:
610
+ try:
611
+ from auto_gptq import AutoGPTQForCausalLM
612
+ except ModuleNotFoundError as exception:
613
+ raise type(exception)(
614
+ "Tried to load auto_gptq, but auto-gptq is not installed ",
615
+ "please install auto-gptq via pip install lm-eval[gptq] or pip install -e .[gptq]",
616
+ )
617
+
618
+ self._model = AutoGPTQForCausalLM.from_quantized(
619
+ pretrained,
620
+ trust_remote_code=trust_remote_code,
621
+ model_basename=None if autogptq is True else Path(autogptq).stem,
622
+ use_safetensors=True
623
+ if autogptq is True
624
+ else autogptq.endswith(".safetensors"),
625
+ **model_kwargs,
626
+ )
627
+
628
+ if gptqmodel:
629
+ try:
630
+ from gptqmodel import GPTQModel
631
+ except ModuleNotFoundError as exception:
632
+ raise type(exception)(
633
+ "Tried to load gptqmodel, but gptqmodel is not installed ",
634
+ "please install gptqmodel via `pip install gptqmodel --no-build-isolation` or `pip install lm-eval[gptqmodel] --no-build-isolation`",
635
+ )
636
+
637
+ self._model = GPTQModel.from_quantized(
638
+ pretrained, trust_remote_code=trust_remote_code, **model_kwargs
639
+ )
640
+
641
+ if peft and delta:
642
+ raise ValueError(
643
+ "Cannot use both 'peft' and 'delta' options at the same time."
644
+ )
645
+
646
+ if peft:
647
+ if model_kwargs.get("load_in_4bit", None):
648
+ if version.parse(PEFT_VERSION) < version.parse("0.4.0"):
649
+ raise AssertionError("load_in_4bit requires peft >= 0.4.0")
650
+ if self._model.config.vocab_size != len(self.tokenizer):
651
+ # resize model for LoRAs with added tokens
652
+ eval_logger.info(
653
+ f"Model config indicates vocab_size='{self._model.config.vocab_size}', but found tokenizer with vocab size '{len(self.tokenizer)}'. Resizing model embedding layer..."
654
+ )
655
+ self._model.resize_token_embeddings(len(self.tokenizer))
656
+ self._model = PeftModel.from_pretrained(
657
+ self._model, peft, revision=revision
658
+ )
659
+ elif delta:
660
+ if autogptq:
661
+ eval_logger.warning(
662
+ "Delta weights might trigger unexpected behavior when used with AutoGPTQ."
663
+ )
664
+ _model_delta = self.AUTO_MODEL_CLASS.from_pretrained(
665
+ delta,
666
+ revision=revision,
667
+ torch_dtype=get_dtype(dtype),
668
+ trust_remote_code=trust_remote_code,
669
+ **model_kwargs,
670
+ )
671
+ for name, param in self._model.state_dict().items():
672
+ try:
673
+ param.data += _model_delta.state_dict()[name]
674
+ except KeyError:
675
+ raise KeyError(f"Delta model is missing weights for layer: {name}")
676
+ except Exception as e:
677
+ raise RuntimeError(
678
+ f"Failed to add delta weights to layer {name}. Error: {e}"
679
+ )
680
+
681
+ del _model_delta
682
+
683
+ return None
684
+
685
+ def _create_tokenizer(
686
+ self,
687
+ pretrained: Union[str, transformers.PreTrainedModel],
688
+ tokenizer: Optional[
689
+ Union[
690
+ str,
691
+ transformers.PreTrainedTokenizer,
692
+ transformers.PreTrainedTokenizerFast,
693
+ ]
694
+ ],
695
+ revision: Optional[str] = "main",
696
+ trust_remote_code: Optional[bool] = False,
697
+ use_fast_tokenizer: Optional[bool] = True,
698
+ gguf_file: Optional[str] = None,
699
+ add_bos_token: Optional[bool] = False,
700
+ ) -> None:
701
+ """
702
+ Helper method during initialization.
703
+
704
+ Create a tokenizer object corresponding to the correct
705
+ tokenizer for value of `pretrained`, or use the pre-initialized tokenizer passed.
706
+ """
707
+ kwargs = {
708
+ "revision": revision,
709
+ "trust_remote_code": trust_remote_code,
710
+ }
711
+
712
+ # gguf format embeds tokenizer and is not compatible with hf tokenizer `use_fast` param
713
+ if gguf_file is not None:
714
+ kwargs["gguf_file"] = gguf_file
715
+ else:
716
+ kwargs["use_fast"] = use_fast_tokenizer
717
+
718
+ if add_bos_token:
719
+ kwargs["add_bos_token"] = True
720
+
721
+ if tokenizer:
722
+ if isinstance(tokenizer, str):
723
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
724
+ tokenizer, **kwargs
725
+ )
726
+ else:
727
+ assert isinstance(
728
+ tokenizer, transformers.PreTrainedTokenizer
729
+ ) or isinstance(tokenizer, transformers.PreTrainedTokenizerFast)
730
+ self.tokenizer = tokenizer
731
+ else:
732
+ # Get tokenizer based on 'pretrained'
733
+ if isinstance(pretrained, str):
734
+ model_name = pretrained
735
+ else:
736
+ # get the HF hub name via accessor on model
737
+ model_name = self.model.name_or_path
738
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
739
+ model_name, **kwargs
740
+ )
741
+ return None
742
+
743
+ def _detect_batch_size(self, requests=None, pos: int = 0):
744
+ if requests:
745
+ _, context_enc, continuation_enc = requests[pos]
746
+ max_length = len(
747
+ (context_enc + continuation_enc)[-(self.max_length + 1) :][:-1]
748
+ )
749
+ max_context_enc = len(context_enc[-(self.max_length + 1) :])
750
+ max_cont_enc = len(continuation_enc[-(self.max_length + 1) :])
751
+ else:
752
+ max_length = self.max_length
753
+ max_context_enc = max_length
754
+ max_cont_enc = max_length
755
+
756
+ # if OOM, then halves batch_size and tries again
757
+ @find_executable_batch_size(starting_batch_size=self.max_batch_size)
758
+ def forward_batch(batch_size):
759
+ if self.backend == "seq2seq":
760
+ length = max(max_context_enc, max_cont_enc)
761
+ batched_conts = torch.ones(
762
+ (batch_size, length), device=self.device
763
+ ).long()
764
+ test_batch = torch.ones((batch_size, length), device=self.device).long()
765
+ call_kwargs = {
766
+ "attn_mask": test_batch,
767
+ "labels": batched_conts,
768
+ }
769
+ else:
770
+ call_kwargs = {}
771
+ test_batch = torch.ones(
772
+ (batch_size, max_length), device=self.device
773
+ ).long()
774
+ for _ in range(5):
775
+ out = F.log_softmax( # noqa: F841
776
+ self._model_call(test_batch, **call_kwargs),
777
+ dim=-1,
778
+ dtype=self.softmax_dtype,
779
+ )
780
+
781
+ return batch_size
782
+
783
+ try:
784
+ batch_size = forward_batch()
785
+ except RuntimeError as e:
786
+ if "No executable batch size found" in str(e):
787
+ batch_size = 1
788
+ else:
789
+ raise
790
+
791
+ if self.world_size > 1:
792
+ # if multi-GPU, always take minimum over all selected batch sizes
793
+ max_rnk_bs = torch.tensor([batch_size], device=self.device)
794
+ gathered = (
795
+ self.accelerator.gather(max_rnk_bs).cpu().detach().numpy().tolist()
796
+ )
797
+ batch_size = min(gathered)
798
+ clear_torch_cache()
799
+ return batch_size
800
+
801
+ clear_torch_cache()
802
+ return batch_size
803
+
804
+ def tok_encode(
805
+ self, string: str, left_truncate_len=None, add_special_tokens=None
806
+ ) -> List[int]:
807
+ """ """
808
+ # default for None - empty dict, use predefined tokenizer param
809
+ # used for all models except for CausalLM or predefined value
810
+ special_tokens_kwargs = {}
811
+
812
+ # by default for CausalLM - false or self.add_bos_token is set
813
+ if add_special_tokens is None:
814
+ if self.backend == "causal":
815
+ special_tokens_kwargs = {
816
+ "add_special_tokens": False or self.add_bos_token
817
+ }
818
+ # otherwise the method explicitly defines the value
819
+ else:
820
+ special_tokens_kwargs = {"add_special_tokens": add_special_tokens}
821
+
822
+ encoding = self.tokenizer.encode(string, **special_tokens_kwargs)
823
+
824
+ # left-truncate the encoded context to be at most `left_truncate_len` tokens long
825
+ if left_truncate_len:
826
+ encoding = encoding[-left_truncate_len:]
827
+
828
+ return encoding
829
+
830
+ def tok_batch_encode(
831
+ self,
832
+ strings: List[str],
833
+ padding_side: str = "left",
834
+ left_truncate_len: int = None,
835
+ truncation: bool = False,
836
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
837
+ # encode a batch of strings. converts to tensors and pads automatically, unlike tok_encode.
838
+ old_padding_side = self.tokenizer.padding_side
839
+ self.tokenizer.padding_side = padding_side
840
+
841
+ add_special_tokens = {}
842
+ if self.backend == "causal":
843
+ add_special_tokens = {"add_special_tokens": False or self.add_bos_token}
844
+
845
+ encoding = self.tokenizer(
846
+ strings,
847
+ truncation=truncation,
848
+ padding="longest",
849
+ return_tensors="pt",
850
+ **add_special_tokens,
851
+ )
852
+ if left_truncate_len:
853
+ original_lengths = encoding["input_ids"].size(1)
854
+ if original_lengths > left_truncate_len:
855
+ eval_logger.warn(
856
+ f"Left truncation applied. Original sequence length was {original_lengths}, "
857
+ f"truncating to last {left_truncate_len} tokens. Some content will be lost.",
858
+ )
859
+ encoding["input_ids"] = encoding["input_ids"][:, -left_truncate_len:]
860
+ encoding["attention_mask"] = encoding["attention_mask"][
861
+ :, -left_truncate_len:
862
+ ]
863
+ self.tokenizer.padding_side = old_padding_side
864
+
865
+ return encoding["input_ids"], encoding["attention_mask"]
866
+
867
+ def tok_decode(self, tokens, skip_special_tokens=True):
868
+ return self.tokenizer.decode(tokens, skip_special_tokens=skip_special_tokens)
869
+
870
+ def _model_call(self, inps, attn_mask=None, labels=None):
871
+ """
872
+ :param inps: torch.Tensor
873
+ A torch tensor of shape [batch, (sequence_ctx + sequence_cont)] or of shape
874
+ [batch, sequence_ctx]. the size of sequence may vary from call to call
875
+ :param attn_mask: torch.Tensor, optional
876
+ A torch tensor of shape [batch, (sequence_ctx + sequence_cont)]. Only passed
877
+ (and must be passed) if self.AUTO_MODEL_CLASS is transformers.AutoModelForSeq2SeqLM
878
+ :param labels: torch.Tensor, optional
879
+ A torch tensor of shape [batch, (sequence_ctx + sequence_cont)]. Only passed
880
+ (and must be passed) if self.AUTO_MODEL_CLASS is transformers.AutoModelForSeq2SeqLM
881
+ :return
882
+ A torch tensor of shape [batch, sequence, vocab] with the
883
+ logits returned from the model's decoder
884
+ """
885
+ with torch.no_grad():
886
+ if attn_mask is not None or labels is not None:
887
+ assert attn_mask is not None and labels is not None
888
+ assert self.AUTO_MODEL_CLASS == transformers.AutoModelForSeq2SeqLM
889
+ return self.model(
890
+ input_ids=inps, attention_mask=attn_mask, labels=labels
891
+ ).logits
892
+ else:
893
+ assert self.AUTO_MODEL_CLASS in (
894
+ transformers.AutoModelForCausalLM,
895
+ transformers.AutoModelForVision2Seq,
896
+ )
897
+ return self.model(inps).logits
898
+
899
+ def _model_generate(self, context, max_length, stop, **generation_kwargs):
900
+ # temperature = 0.0 if not set
901
+ # if do_sample is false and temp==0.0:
902
+ # remove temperature, as do_sample=False takes care of this
903
+ # and we don't want a warning from HF
904
+ generation_kwargs["temperature"] = generation_kwargs.get("temperature", 0.0)
905
+ do_sample = generation_kwargs.get("do_sample", None)
906
+
907
+ # The temperature has to be a strictly positive float -- if it is 0.0, use greedy decoding strategies
908
+ if generation_kwargs.get("temperature") == 0.0 and do_sample is None:
909
+ generation_kwargs["do_sample"] = do_sample = False
910
+
911
+ if do_sample is False and generation_kwargs.get("temperature") == 0.0:
912
+ generation_kwargs.pop("temperature")
913
+ # build stopping criteria
914
+ stopping_criteria = stop_sequences_criteria(
915
+ self.tokenizer, stop, context.shape[1], context.shape[0]
916
+ )
917
+ return self.model.generate(
918
+ input_ids=context,
919
+ max_length=max_length,
920
+ stopping_criteria=stopping_criteria,
921
+ pad_token_id=self.tokenizer.pad_token_id,
922
+ use_cache=True,
923
+ **generation_kwargs,
924
+ )
925
+
926
+ def _select_cont_toks(
927
+ self, logits: torch.Tensor, contlen: int = None, inplen: int = None
928
+ ) -> torch.Tensor:
929
+ if self.backend == "causal":
930
+ assert contlen and inplen, (
931
+ "Must pass input len and cont. len to select scored logits for causal LM"
932
+ )
933
+ # discard right-padding.
934
+ # also discard the input/context tokens. we'll only score continuations.
935
+ logits = logits[inplen - contlen : inplen]
936
+ elif self.backend == "seq2seq":
937
+ assert contlen and not inplen, (
938
+ "Selecting scored logits for Seq2SeqLM requires only cont. len"
939
+ )
940
+ # only discard right-padding.
941
+ # the logits input to this fn only contain decoder-side tokens.
942
+ logits = logits[:contlen]
943
+
944
+ return logits
945
+
946
+ def loglikelihood_rolling(
947
+ self, requests: List[Instance], disable_tqdm: bool = False
948
+ ) -> List[float]:
949
+ adaptive_batch_size = None
950
+ if self.batch_size == "auto":
951
+ # using rolling window with maximum context
952
+ print("Passed argument batch_size = auto. Detecting largest batch size")
953
+ batch_size = self._detect_batch_size()
954
+ print(f"Determined Largest batch size: {batch_size}")
955
+ adaptive_batch_size = batch_size
956
+
957
+ # First, collect all windows from all requests
958
+ all_windows = [] # List of (request_idx, window) tuples
959
+ request_window_counts = [] # Track number of windows per request
960
+
961
+ for req_idx, (string,) in enumerate(
962
+ tqdm(
963
+ [req.args for req in requests],
964
+ disable=(disable_tqdm or (self.rank != 0)),
965
+ )
966
+ ):
967
+ rolling_token_windows: List[Tuple[List[int], List[int]]] = list(
968
+ map(
969
+ utils.make_disjoint_window,
970
+ utils.get_rolling_token_windows(
971
+ token_list=self.tok_encode(string),
972
+ prefix_token=self.prefix_token_id,
973
+ max_seq_len=self.max_length,
974
+ context_len=1,
975
+ ),
976
+ )
977
+ )
978
+
979
+ # TODO: Right now, we pass single EOT token to the Encoder and the full context to the decoder, in seq2seq case
980
+ windows = [(None,) + x for x in rolling_token_windows]
981
+
982
+ # Store windows with their request index
983
+ all_windows.extend((req_idx, window) for window in windows)
984
+ request_window_counts.append(len(windows))
985
+
986
+ # Handle distributed case padding
987
+ pad_amnt = 0
988
+ if self.world_size > 1:
989
+ mytensor = torch.tensor(len(all_windows), device=self.device)
990
+ gathered = self.accelerator.gather(mytensor).cpu().detach().numpy().tolist()
991
+ pad_amnt = max(gathered) - gathered[self.rank]
992
+ if pad_amnt > 0:
993
+ all_windows += pad_amnt * [all_windows[0]]
994
+
995
+ all_nlls = []
996
+ batch_size = adaptive_batch_size or self.batch_size
997
+ for i in range(0, len(all_windows), batch_size):
998
+ batch = all_windows[i : i + batch_size]
999
+ # Extract just the windows for processing, keeping track of request indices
1000
+ batch_indices, batch_windows = zip(*batch)
1001
+
1002
+ batch_nlls = self._loglikelihood_tokens(
1003
+ requests=batch_windows,
1004
+ disable_tqdm=False,
1005
+ override_bs=len(batch_windows),
1006
+ )
1007
+ # Store results with their request indices
1008
+ all_nlls.extend(zip(batch_indices, batch_nlls))
1009
+
1010
+ # Remove padding if necessary
1011
+ if (self.world_size > 1) and (pad_amnt > 0):
1012
+ all_nlls = all_nlls[:-pad_amnt]
1013
+
1014
+ # Reconstruct per-request loglikelihoods
1015
+ loglikelihoods = []
1016
+ current_idx = 0
1017
+ for window_count in request_window_counts:
1018
+ # Get all nlls for this request
1019
+ request_nlls = all_nlls[current_idx : current_idx + window_count]
1020
+ # Sum up the nlls for this request (discarding is_greedy)
1021
+ request_total = sum(nll[0] for _, nll in request_nlls)
1022
+ loglikelihoods.append(request_total)
1023
+ current_idx += window_count
1024
+
1025
+ string = requests[len(loglikelihoods) - 1].args[0]
1026
+ self.cache_hook.add_partial(
1027
+ "loglikelihood_rolling", (string,), request_total
1028
+ )
1029
+
1030
+ return loglikelihoods
1031
+
1032
+ def _batch_scheduler(self, pos, n_reordered_requests):
1033
+ sched = pos // int(len(n_reordered_requests) / self.batch_schedule)
1034
+ if sched in self.batch_sizes:
1035
+ return self.batch_sizes[sched]
1036
+ if (len(self.batch_sizes) > 1) and (
1037
+ self.batch_sizes[sched - 1] == self.max_batch_size
1038
+ ):
1039
+ # if previous batch size is already maximal, skip recomputation
1040
+ self.batch_sizes[sched] = self.max_batch_size
1041
+ return self.batch_sizes[sched]
1042
+ print(
1043
+ f"Passed argument batch_size = auto:{self.batch_schedule}. Detecting largest batch size"
1044
+ )
1045
+ self.batch_sizes[sched] = self._detect_batch_size(n_reordered_requests, pos)
1046
+ print(f"Determined largest batch size: {self.batch_sizes[sched]}")
1047
+ return self.batch_sizes[sched]
1048
+
1049
+ def _loglikelihood_tokens(
1050
+ self,
1051
+ requests: List[Tuple[Tuple[str, str], List[int], List[int]]],
1052
+ disable_tqdm: bool = False,
1053
+ override_bs: int = None,
1054
+ ) -> List[Tuple[float, bool]]:
1055
+ # TODO: implement some kind of efficient-request-middleware that lumps together requests with the same context
1056
+ res = []
1057
+
1058
+ def _collate(req: Tuple[Tuple[str, str], List[int], List[int]]):
1059
+ """Defines the key for the sorted method"""
1060
+ # the negative sign on len(toks) sorts descending - this has a few advantages:
1061
+ # - time estimates will always be over not underestimates, which is more useful for planning
1062
+ # - to know the size of a batch when going through the list, you know the first one is always the batch
1063
+ # padded context length. this is useful to simplify the batching logic and more importantly to make
1064
+ # automatic adaptive batches much much easier to implement
1065
+ # - any OOMs will happen right away rather than near the end
1066
+
1067
+ toks = req[1] + req[2]
1068
+ return -len(toks), tuple(toks)
1069
+
1070
+ def _lookup_one_token_cont(req: Tuple[Tuple[str, str], List[int], List[int]]):
1071
+ """Defines the key to group and lookup one-token continuations"""
1072
+ # Use with group_by="contexts" (optional)"
1073
+ # allows for the creation of a lookup, so we can reuse logits in case of one-token continuations.
1074
+ # speeds up some multiple-choice tasks proportionally to the number of choices.
1075
+ # groups requests by context+continuation[:-1] and infer on one request/group.
1076
+ return req[-2] + req[-1][:-1]
1077
+
1078
+ re_ord = Collator(
1079
+ requests,
1080
+ sort_fn=_collate,
1081
+ group_by="contexts"
1082
+ if self.backend == "causal" and self.logits_cache
1083
+ else None,
1084
+ group_fn=_lookup_one_token_cont,
1085
+ )
1086
+
1087
+ # automatic (variable) batch size detection for vectorization
1088
+ # pull longest context sample from request
1089
+ n_reordered_requests = len(re_ord)
1090
+ batch_size = (
1091
+ self.batch_size
1092
+ if self.batch_size != "auto"
1093
+ else override_bs
1094
+ if override_bs is not None
1095
+ else 0
1096
+ )
1097
+ batch_fn = (
1098
+ self._batch_scheduler
1099
+ if self.batch_size == "auto"
1100
+ and n_reordered_requests > 0
1101
+ and not override_bs
1102
+ else None
1103
+ )
1104
+
1105
+ chunks = re_ord.get_batched(n=batch_size, batch_fn=batch_fn)
1106
+ pbar = tqdm(
1107
+ total=len(requests),
1108
+ disable=(disable_tqdm or (self.rank != 0)),
1109
+ desc="Running loglikelihood requests",
1110
+ )
1111
+ for chunk in chunks:
1112
+ inps = []
1113
+ cont_toks_list = []
1114
+ inplens = []
1115
+
1116
+ conts = []
1117
+ encoder_attns = []
1118
+
1119
+ padding_len_inp = None
1120
+ padding_len_cont = None
1121
+ # because vectorizing is annoying, we first convert each (context, continuation) pair to padded
1122
+ # tensors, then we pack them together into a batch, call the model, and then pick it all apart
1123
+ # again because vectorizing is annoying
1124
+
1125
+ for _, context_enc, continuation_enc in chunk:
1126
+ # sanity check
1127
+ assert len(context_enc) > 0
1128
+ assert len(continuation_enc) > 0
1129
+ assert len(continuation_enc) <= self.max_length
1130
+
1131
+ # how this all works (illustrated on a causal decoder-only setup):
1132
+ # CTX CONT
1133
+ # inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
1134
+ # model \ \
1135
+ # logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
1136
+ # cont_toks 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
1137
+
1138
+ # when too long to fit in context, truncate from the left
1139
+ if self.backend == "causal":
1140
+ total_length = len(context_enc) + len(continuation_enc)
1141
+ if total_length > self.max_length + 1:
1142
+ eval_logger.warning(
1143
+ f"Combined length of context ({len(context_enc)}) and continuation ({len(continuation_enc)}) "
1144
+ f"exceeds model's maximum length ({self.max_length}). "
1145
+ f"Truncating {total_length - self.max_length + 1} tokens from the left."
1146
+ )
1147
+ inp = torch.tensor(
1148
+ (context_enc + continuation_enc)[-(self.max_length + 1) :][:-1],
1149
+ dtype=torch.long,
1150
+ device=self.device,
1151
+ )
1152
+ (inplen,) = inp.shape
1153
+ elif self.backend == "seq2seq":
1154
+ inp = torch.tensor(
1155
+ (context_enc)[-self.max_length :],
1156
+ dtype=torch.long,
1157
+ device=self.device,
1158
+ )
1159
+ (inplen,) = inp.shape
1160
+
1161
+ # build encoder attn masks
1162
+ encoder_attns.append(torch.ones_like(inp))
1163
+
1164
+ cont = torch.tensor(
1165
+ (continuation_enc)[-self.max_length :],
1166
+ # TODO: left-shift these?
1167
+ # TODO: our code assumes we never end up truncating conts for either model type
1168
+ dtype=torch.long,
1169
+ device=self.device,
1170
+ )
1171
+ (contlen,) = cont.shape
1172
+
1173
+ conts.append(cont)
1174
+
1175
+ padding_len_cont = (
1176
+ max(padding_len_cont, contlen)
1177
+ if padding_len_cont is not None
1178
+ else contlen
1179
+ )
1180
+
1181
+ padding_len_inp = (
1182
+ max(padding_len_inp, inplen)
1183
+ if padding_len_inp is not None
1184
+ else inplen
1185
+ )
1186
+
1187
+ inps.append(inp) # [1, inp_length]
1188
+ cont_toks_list.append(continuation_enc)
1189
+ inplens.append(inplen)
1190
+
1191
+ # create encoder attn mask and batched conts, if seq2seq
1192
+ call_kwargs = {}
1193
+ if self.backend == "causal":
1194
+ batched_inps = pad_and_concat(
1195
+ padding_len_inp, inps, padding_side="right"
1196
+ ) # [batch, padding_len_inp]
1197
+ elif self.backend == "seq2seq":
1198
+ # TODO: left-pad encoder inps and mask?
1199
+ batched_inps = pad_and_concat(
1200
+ padding_len_inp, inps
1201
+ ) # [batch, padding_len_inp]
1202
+ batched_conts = pad_and_concat(
1203
+ padding_len_cont, conts
1204
+ ) # [batch, padding_len_cont]
1205
+ batched_encoder_mask = pad_and_concat(
1206
+ padding_len_inp, encoder_attns
1207
+ ) # [batch, padding_len_inp]
1208
+ call_kwargs = {
1209
+ "attn_mask": batched_encoder_mask,
1210
+ "labels": batched_conts,
1211
+ }
1212
+
1213
+ multi_logits = F.log_softmax(
1214
+ self._model_call(batched_inps, **call_kwargs),
1215
+ dim=-1,
1216
+ dtype=self.softmax_dtype,
1217
+ ) # [batch, padding_length (inp or cont), vocab]
1218
+
1219
+ for (request_str, ctx_tokens, _), logits, inplen, cont_toks in zip(
1220
+ chunk, multi_logits, inplens, cont_toks_list
1221
+ ):
1222
+ # Slice to original seq length
1223
+ contlen = len(cont_toks)
1224
+ # take only logits in the continuation
1225
+ # (discard context toks if decoder-only ; discard right-padding)
1226
+ # also discards + checks for "virtual tokens" in the causal LM's input window
1227
+ # from prompt/prefix tuning tokens, if applicable
1228
+ ctx_len = (
1229
+ inplen + (logits.shape[0] - padding_len_inp)
1230
+ if self.backend == "causal"
1231
+ else None
1232
+ )
1233
+ logits = self._select_cont_toks(logits, contlen=contlen, inplen=ctx_len)
1234
+ logits = logits.unsqueeze(0) # [1, seq, vocab]
1235
+
1236
+ # Check if per-token argmax is exactly equal to continuation
1237
+ greedy_tokens = logits.argmax(dim=-1)
1238
+
1239
+ # check for one-token continuation cache hits.
1240
+ # noop in case group_by != "contexts" or no cache hit and returns the
1241
+ # original args. Otherwise, expands the logits batch dimension and yields each
1242
+ # batch along with matching continuation tokens and prompt strings.
1243
+ # logits -> [1, seq, vocab]
1244
+ for request_str, cont_toks, logits in re_ord.get_cache(
1245
+ req_str=request_str,
1246
+ cxt_toks=ctx_tokens,
1247
+ cont_toks=cont_toks,
1248
+ logits=logits,
1249
+ ):
1250
+ cont_toks = torch.tensor(
1251
+ cont_toks, dtype=torch.long, device=self.device
1252
+ ).unsqueeze(0) # [1, seq]
1253
+ # Use trailing slice [-cont_toks.shape[1]:] to handle variable length cont_len (but same ctx+cont[:-1]).
1254
+ # i.e. continuations can be sliced at diff points. Collator ensures we have sufficient greedy_tokens
1255
+ # by choosing key with longest cont if group_by="contexts".
1256
+ max_equal = (
1257
+ greedy_tokens[:, -cont_toks.shape[1] :] == cont_toks
1258
+ ).all()
1259
+
1260
+ # Obtain log-probs at the corresponding continuation token indices
1261
+ # last_token_slice = logits[:, -1, :].squeeze(0).tolist()
1262
+ logits = torch.gather(logits, 2, cont_toks.unsqueeze(-1)).squeeze(
1263
+ -1
1264
+ ) # [1, seq]
1265
+
1266
+ # Answer: (log prob, is-exact-match)
1267
+ answer = (float(logits.sum()), bool(max_equal))
1268
+
1269
+ res.append(answer)
1270
+
1271
+ if request_str is not None:
1272
+ # special case: loglikelihood_rolling produces a number of loglikelihood requests
1273
+ # all with cache key None. instead do add_partial on the per-example level
1274
+ # in the loglikelihood_rolling() function for those.
1275
+ self.cache_hook.add_partial(
1276
+ "loglikelihood", request_str, answer
1277
+ )
1278
+ pbar.update(1)
1279
+
1280
+ pbar.close()
1281
+
1282
+ return re_ord.get_original(res)
1283
+
1284
+ def generate_until(
1285
+ self, requests: List[Instance], disable_tqdm: bool = False
1286
+ ) -> List[str]:
1287
+ res = []
1288
+
1289
+ def _collate(req: Tuple[str, dict]):
1290
+ """Defines the key for the sorted method"""
1291
+ # the negative sign on len(toks) sorts descending - this has a few advantages:
1292
+ # - time estimates will always be over not underestimates, which is more useful for planning
1293
+ # - to know the size of a batch when going through the list, you know the first one is always the batch
1294
+ # padded context length. this is useful to simplify the batching logic and more importantly to make
1295
+ # automatic adaptive batches much much easier to implement
1296
+ # - any OOMs will happen right away rather than near the end
1297
+ toks = self.tok_encode(req[0])
1298
+ return -len(toks), req[0]
1299
+
1300
+ pbar = tqdm(
1301
+ total=len(requests),
1302
+ disable=(disable_tqdm or (self.rank != 0)),
1303
+ desc="Running generate_until requests",
1304
+ )
1305
+ adaptive_batch_size = None
1306
+ if self.batch_size == "auto":
1307
+ # using rolling window with maximum context
1308
+ print("Passed argument batch_size = auto. Detecting largest batch size")
1309
+ batch_size = self._detect_batch_size()
1310
+ print(f"Determined Largest batch size: {batch_size}")
1311
+ adaptive_batch_size = batch_size
1312
+ # for each different set of kwargs, we execute all requests, by batch.
1313
+ batch_size = (
1314
+ self.batch_size
1315
+ if self.batch_size != "auto"
1316
+ else adaptive_batch_size
1317
+ if adaptive_batch_size is not None
1318
+ else 0
1319
+ )
1320
+ batch_fn = (
1321
+ self._batch_scheduler
1322
+ if self.batch_size == "auto" and not adaptive_batch_size
1323
+ else None
1324
+ )
1325
+
1326
+ # we group requests by their generation_kwargs,
1327
+ # so that we don't try to execute e.g. greedy sampling and temp=0.8 sampling
1328
+ # in the same batch.
1329
+ # group_fn=lambda x: x[1] -> x=(context, gen_kwargs)
1330
+ re_ords = Collator(
1331
+ [reg.args for reg in requests],
1332
+ sort_fn=_collate,
1333
+ group_by="gen_kwargs",
1334
+ group_fn=lambda x: x[1],
1335
+ )
1336
+ chunks = re_ords.get_batched(n=batch_size, batch_fn=batch_fn)
1337
+ eos = self.tok_decode(self.eot_token_id, skip_special_tokens=False)
1338
+ for chunk in chunks:
1339
+ contexts, all_gen_kwargs = zip(*chunk)
1340
+ # we assume all gen kwargs in the batch are the same
1341
+ # this is safe to assume because the `grouper` object ensures it.
1342
+ gen_kwargs = all_gen_kwargs[0]
1343
+ # unpack our keyword arguments.
1344
+ if isinstance(gen_kwargs, dict):
1345
+ kwargs = copy.deepcopy(gen_kwargs) # edge case for repeats > 1
1346
+ # add EOS token to stop sequences
1347
+ until = handle_stop_sequences(kwargs.pop("until", None), eos=eos)
1348
+ else:
1349
+ raise ValueError(
1350
+ f"Expected `kwargs` to be of type `dict` but got {type(gen_kwargs)}"
1351
+ )
1352
+ if "max_gen_toks" in kwargs.keys():
1353
+ max_gen_toks = kwargs.pop("max_gen_toks")
1354
+ else:
1355
+ max_gen_toks = self.max_gen_toks
1356
+
1357
+ # set the max length in tokens of inputs ("context_enc")
1358
+ if self.backend == "causal":
1359
+ # max len for inputs = max length, minus room to generate the max new tokens
1360
+ max_ctx_len = self.max_length - max_gen_toks
1361
+ assert max_ctx_len > 0, (
1362
+ f"Invalid configuration: requested max tokens to generate ({max_gen_toks}) must be less than model's maximum sequence length ({self.max_length})."
1363
+ )
1364
+ elif self.backend == "seq2seq":
1365
+ # max len for inputs = encoder's whole max_length
1366
+ max_ctx_len = self.max_length
1367
+
1368
+ # encode, pad, and truncate contexts for this batch
1369
+ context_enc, attn_masks = self.tok_batch_encode(
1370
+ contexts,
1371
+ left_truncate_len=max_ctx_len,
1372
+ truncation=self.truncation,
1373
+ )
1374
+ context_enc = context_enc.to(self.device)
1375
+ attn_masks = attn_masks.to(self.device)
1376
+
1377
+ if "max_length" not in kwargs:
1378
+ kwargs["max_length"] = context_enc.shape[1] + max_gen_toks
1379
+
1380
+ # perform batched generation
1381
+ cont = self._model_generate(
1382
+ context=context_enc,
1383
+ attention_mask=attn_masks,
1384
+ stop=until,
1385
+ **kwargs,
1386
+ )
1387
+
1388
+ cont_toks_list = cont.tolist()
1389
+ for cont_toks, context in zip(cont_toks_list, contexts):
1390
+ # discard context + left-padding toks if using causal decoder-only LM
1391
+ if self.backend == "causal":
1392
+ cont_toks = cont_toks[context_enc.shape[1] :]
1393
+
1394
+ s = self.tok_decode(cont_toks)
1395
+
1396
+ # use secondary stop seqs to cut off should-have-been-stopped content post-hoc
1397
+ for term in until:
1398
+ if len(term) > 0:
1399
+ # ignore '' separator,
1400
+ # for seq2seq case where self.tok_decode(self.eot_token_id) = ''
1401
+ s = s.split(term)[0]
1402
+
1403
+ res.append(s)
1404
+
1405
+ self.cache_hook.add_partial("generate_until", (context, gen_kwargs), s)
1406
+ pbar.update(1)
1407
+ # reorder this group of results back to original unsorted form
1408
+ res = re_ords.get_original(res)
1409
+
1410
+ pbar.close()
1411
+
1412
+ return res
1413
+
1414
+ def apply_chat_template(
1415
+ self, chat_history: List[Dict[str, str]], add_generation_prompt: bool = True
1416
+ ) -> str:
1417
+ """
1418
+ Method to apply a chat template to a list of chat history between user and model.
1419
+ """
1420
+ try:
1421
+ chat_templated = self.tokenizer.apply_chat_template(
1422
+ chat_history,
1423
+ tokenize=False,
1424
+ add_generation_prompt=add_generation_prompt,
1425
+ continue_final_message=not add_generation_prompt,
1426
+ )
1427
+ except jinja2.exceptions.TemplateError:
1428
+ eval_logger.warning(
1429
+ "Failed to apply chat template. removing the system role in chat history."
1430
+ )
1431
+ chat_history = [msg for msg in chat_history if msg["role"] != "system"]
1432
+ chat_templated = self.tokenizer.apply_chat_template(
1433
+ chat_history,
1434
+ tokenize=False,
1435
+ add_generation_prompt=add_generation_prompt,
1436
+ continue_final_message=not add_generation_prompt,
1437
+ )
1438
+
1439
+ return chat_templated
1440
+
1441
+ def get_model_info(self) -> dict:
1442
+ """
1443
+ Method to get Hugging Face model information for experiment reproducibility.
1444
+ """
1445
+
1446
+ def get_model_num_params(model) -> int:
1447
+ if hasattr(model, "num_parameters"):
1448
+ return model.num_parameters()
1449
+ if hasattr(model, "parameters"):
1450
+ return sum(p.numel() for p in model.parameters())
1451
+ else:
1452
+ return -1
1453
+
1454
+ def get_model_dtype(model) -> str:
1455
+ if hasattr(model, "dtype"):
1456
+ return model.dtype
1457
+ else:
1458
+ return ""
1459
+
1460
+ def get_model_sha(pretrained: str, revision: str) -> str:
1461
+ try:
1462
+ model_info = HfApi().model_info(repo_id=pretrained, revision=revision)
1463
+ return model_info.sha
1464
+ except Exception as e:
1465
+ eval_logger.debug(
1466
+ f"Failed to get model SHA for {pretrained} at revision {revision}. Error: {e}"
1467
+ )
1468
+ return ""
1469
+
1470
+ model_info = {
1471
+ "model_num_parameters": get_model_num_params(self._model),
1472
+ "model_dtype": get_model_dtype(self._model),
1473
+ "model_revision": self.revision,
1474
+ "model_sha": get_model_sha(self.pretrained, self.revision),
1475
+ }
1476
+ if self.peft:
1477
+ model_info["peft_sha"] = get_model_sha(self.peft, self.revision)
1478
+ if self.delta:
1479
+ model_info["delta_sha"] = get_model_sha(self.delta, self.revision)
1480
+ return model_info
lm-evaluation-harness/lm_eval/models/optimum_ipex.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from importlib.util import find_spec
3
+
4
+ from lm_eval.api.registry import register_model
5
+ from lm_eval.models.huggingface import HFLM
6
+ from lm_eval.models.utils import get_dtype
7
+
8
+
9
+ eval_logger = logging.getLogger(__name__)
10
+
11
+
12
+ @register_model("ipex")
13
+ class IPEXLM(HFLM):
14
+ """
15
+ using the HuggingFace transformers + optimum-intel ipex backend, can run on intel cpu and intel gpu
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ **kwargs,
21
+ ) -> None:
22
+ if "backend" in kwargs:
23
+ # currently only supports causal models
24
+ assert kwargs["backend"] == "causal", (
25
+ "Currently, only IPEXModelForCausalLM is supported."
26
+ )
27
+
28
+ super().__init__(
29
+ backend=kwargs.pop("backend", "causal"),
30
+ **kwargs,
31
+ )
32
+
33
+ def _create_model(
34
+ self,
35
+ pretrained: str,
36
+ revision="main",
37
+ dtype="auto",
38
+ trust_remote_code=False,
39
+ # arguments used for splitting a model across GPUs naively.
40
+ # only used if `parallelize=True`.
41
+ # (accelerate naive PP (device_map) options)
42
+ parallelize=False,
43
+ gpus=None,
44
+ max_memory_per_gpu=None,
45
+ max_cpu_memory=None,
46
+ offload_folder="./offload",
47
+ # PEFT, delta weights and quantization options
48
+ peft=None,
49
+ delta=None,
50
+ autogptq=False,
51
+ gptqmodel=False,
52
+ **kwargs,
53
+ ) -> None:
54
+ if not find_spec("optimum"):
55
+ raise ModuleNotFoundError(
56
+ "package `optimum` is not installed. Please install it via `pip install optimum[ipex]`"
57
+ )
58
+ else:
59
+ from optimum.intel import IPEXModelForCausalLM
60
+
61
+ model_kwargs = kwargs if kwargs else {}
62
+ model_kwargs.update(
63
+ self._get_accelerate_args(
64
+ parallelize=parallelize,
65
+ device_map=kwargs.get("device_map", None),
66
+ max_memory_per_gpu=max_memory_per_gpu,
67
+ max_cpu_memory=max_cpu_memory,
68
+ offload_folder=offload_folder,
69
+ gpus=gpus,
70
+ )
71
+ )
72
+
73
+ self._model = IPEXModelForCausalLM.from_pretrained(
74
+ pretrained,
75
+ revision=revision,
76
+ torch_dtype=get_dtype(dtype),
77
+ trust_remote_code=trust_remote_code,
78
+ **model_kwargs,
79
+ )
lm-evaluation-harness/lm_eval/models/optimum_lm.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from importlib.util import find_spec
4
+ from pathlib import Path
5
+
6
+ from lm_eval.api.registry import register_model
7
+ from lm_eval.models.huggingface import HFLM
8
+
9
+
10
+ eval_logger = logging.getLogger(__name__)
11
+
12
+
13
+ @register_model("openvino")
14
+ class OptimumLM(HFLM):
15
+ """
16
+ Optimum Intel provides a simple interface to optimize Transformer models and convert them to \
17
+ OpenVINO™ Intermediate Representation (IR) format to accelerate end-to-end pipelines on \
18
+ Intel® architectures using OpenVINO™ runtime.
19
+
20
+ To use an OpenVINO config, use `--model_args ov_config` to point to a json file with an OpenVINO config:
21
+ `lm_eval --model openvino --model_args pretrained=gpt2,ov_config=config.json --task lambada_openai`
22
+ Example json file contents: {"INFERENCE_PRECISION_HINT": "f32", "CACHE_DIR": "model_cache"}
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ device="cpu",
28
+ **kwargs,
29
+ ) -> None:
30
+ if "backend" in kwargs:
31
+ # optimum currently only supports causal models
32
+ assert kwargs["backend"] == "causal", (
33
+ "Currently, only OVModelForCausalLM is supported."
34
+ )
35
+
36
+ self.openvino_device = device
37
+
38
+ super().__init__(
39
+ device=self.openvino_device,
40
+ backend=kwargs.pop("backend", "causal"),
41
+ **kwargs,
42
+ )
43
+
44
+ def _create_model(
45
+ self,
46
+ pretrained: str,
47
+ revision="main",
48
+ dtype="auto",
49
+ trust_remote_code=False,
50
+ **kwargs,
51
+ ) -> None:
52
+ if not find_spec("optimum"):
53
+ raise ModuleNotFoundError(
54
+ "package `optimum` is not installed. Please install it via `pip install optimum[openvino]`"
55
+ )
56
+ else:
57
+ from optimum.intel.openvino import OVModelForCausalLM
58
+
59
+ model_kwargs = kwargs if kwargs else {}
60
+ if "ov_config" in model_kwargs:
61
+ if not Path(model_kwargs["ov_config"]).exists():
62
+ raise ValueError(
63
+ "ov_config should point to a .json file containing an OpenVINO config"
64
+ )
65
+ with open(model_kwargs["ov_config"]) as f:
66
+ model_kwargs["ov_config"] = json.load(f)
67
+ eval_logger.info(
68
+ f"Using custom OpenVINO config: {model_kwargs['ov_config']}"
69
+ )
70
+
71
+ else:
72
+ model_kwargs["ov_config"] = {}
73
+ model_kwargs["ov_config"].setdefault("CACHE_DIR", "")
74
+ if "pipeline_parallel" in model_kwargs:
75
+ if model_kwargs["pipeline_parallel"]:
76
+ model_kwargs["ov_config"]["MODEL_DISTRIBUTION_POLICY"] = (
77
+ "PIPELINE_PARALLEL"
78
+ )
79
+ model_file = Path(pretrained) / "openvino_model.xml"
80
+ if model_file.exists():
81
+ export = False
82
+ else:
83
+ export = True
84
+
85
+ self._model = OVModelForCausalLM.from_pretrained(
86
+ pretrained,
87
+ revision=revision,
88
+ trust_remote_code=trust_remote_code,
89
+ export=export,
90
+ device=self.openvino_device.upper(),
91
+ **model_kwargs,
92
+ )
lm-evaluation-harness/lm_eval/models/textsynth.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TextSynth API
2
+ Implementation provided by Fabrice Bellard:
3
+ https://github.com/EleutherAI/lm-evaluation-harness/issues/295
4
+
5
+ In order to use the API, you must have a valid TextSynth account and
6
+ enough credits.
7
+
8
+ Example usage:
9
+
10
+ python main.py --model textsynth --model_args engine=gptj_6B --no_cache --tasks piqa
11
+
12
+ Homepage: https://textsynth.com/index.html
13
+ """
14
+
15
+ import logging
16
+ import os
17
+
18
+ import requests as _requests
19
+ from tqdm import tqdm
20
+
21
+ from lm_eval.api.model import LM
22
+ from lm_eval.api.registry import register_model
23
+ from lm_eval.models.utils import retry_on_specific_exceptions
24
+
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ def textsynth_completion(**kwargs):
30
+ """Query TextSynth API for completion.
31
+ Retry with back-off until they respond.
32
+ """
33
+
34
+ def _exception_callback(e: Exception, sleep_time: float) -> None:
35
+ import traceback
36
+
37
+ traceback.print_exc()
38
+
39
+ @retry_on_specific_exceptions(
40
+ on_exceptions=[_requests.exceptions.RequestException],
41
+ max_retries=None, # retry forever, consider changing
42
+ on_exception_callback=_exception_callback,
43
+ )
44
+ def completion():
45
+ return _requests.post(**kwargs)
46
+
47
+ return completion()
48
+
49
+
50
+ @register_model("textsynth")
51
+ class TextSynthLM(LM):
52
+ def __init__(self, engine, truncate: bool = False, **kwargs) -> None:
53
+ """
54
+ :param engine: str
55
+ TextSynth API engine (e.g. `gptj_6B`)
56
+ :param truncate: bool
57
+ Truncate input if too long (if False and input is too long, throw error)
58
+ """
59
+ super().__init__()
60
+
61
+ self.engine = engine
62
+ self.truncate = truncate
63
+ self.api_url = "https://api.textsynth.com"
64
+ # Read from environment variable TEXTSYNTH_API_SECRET_KEY
65
+ self.api_key = os.environ["TEXTSYNTH_API_SECRET_KEY"]
66
+
67
+ @property
68
+ def eot_token_id(self):
69
+ # Isn't used because we override loglikelihood, loglikelihood_rolling and generate_until
70
+ raise NotImplementedError()
71
+
72
+ @property
73
+ def max_length(self) -> int:
74
+ # NOTE: Turn on truncation to avoid errors on long inputs.
75
+ return 2048
76
+
77
+ @property
78
+ def max_gen_toks(self) -> int:
79
+ return 256
80
+
81
+ @property
82
+ def batch_size(self):
83
+ # Isn't used because we override loglikelihood, loglikelihood_rolling and generate_until
84
+ raise NotImplementedError()
85
+
86
+ @property
87
+ def device(self):
88
+ # Isn't used because we override loglikelihood, loglikelihood_rolling and generate_until
89
+ raise NotImplementedError()
90
+
91
+ def tok_encode(self, string: str):
92
+ # Isn't used because we override loglikelihood, loglikelihood_rolling and generate_until
93
+ raise NotImplementedError()
94
+
95
+ def tok_decode(self, tokens):
96
+ # Isn't used because we override loglikelihood, loglikelihood_rolling and generate_until
97
+ raise NotImplementedError()
98
+
99
+ def loglikelihood(self, requests, disable_tqdm: bool = False):
100
+ res = []
101
+ for context, continuation in tqdm(requests, disable=disable_tqdm):
102
+ response = textsynth_completion(
103
+ url=self.api_url + "/v1/engines/" + self.engine + "/logprob",
104
+ headers={"Authorization": "Bearer " + self.api_key},
105
+ json={"context": context, "continuation": continuation},
106
+ )
107
+ resp = response.json()
108
+ if "logprob" in resp:
109
+ logprob = resp["logprob"]
110
+ is_greedy = resp["is_greedy"]
111
+ res.append((logprob, is_greedy))
112
+
113
+ self.cache_hook.add_partial(
114
+ "loglikelihood", (context, continuation), (logprob, is_greedy)
115
+ )
116
+ else:
117
+ logger.error(
118
+ f"The following response does not contain `logprobs`. Got:\n{resp}"
119
+ )
120
+ assert False
121
+ return res
122
+
123
+ def loglikelihood_rolling(self, requests, disable_tqdm: bool = False):
124
+ # TODO: The TextSynth API does not support tokenized inputs so we cannot
125
+ # manually partition long contexts into smaller rolling windows as
126
+ # done for other models derived from `BaseLM`. Override this method
127
+ # with a windowing scheme that works for direct string inputs.
128
+ raise NotImplementedError(
129
+ "`loglikelihood_rolling` is currently not supported due to lack of "
130
+ "input tokenization support from TextSynth."
131
+ )
132
+
133
+ def generate_until(self, requests, disable_tqdm: bool = False):
134
+ if not requests:
135
+ return []
136
+
137
+ res = []
138
+ for request in tqdm(requests, disable=disable_tqdm):
139
+ inp = request[0]
140
+ request_args = request[1]
141
+ until = request_args["until"]
142
+ response = textsynth_completion(
143
+ url=self.api_url + "/v1/engines/" + self.engine + "/completions",
144
+ headers={"Authorization": "Bearer " + self.api_key},
145
+ json={
146
+ "prompt": inp,
147
+ "max_tokens": self.max_gen_toks,
148
+ "top_k": 1,
149
+ "stop": until,
150
+ },
151
+ )
152
+ resp = response.json()
153
+ if "text" in resp:
154
+ s = resp["text"]
155
+ res.append(s)
156
+
157
+ self.cache_hook.add_partial("generate_until", (inp, request_args), s)
158
+ else:
159
+ logger.error(
160
+ "The following response does not contain generated `text`. "
161
+ "Got:\n{resp}"
162
+ )
163
+ assert False
164
+ return res
165
+
166
+ def _model_call(self, inps):
167
+ # Isn't used because we override _loglikelihood_tokens
168
+ raise NotImplementedError()
169
+
170
+ def _model_generate(self, context, max_length, eos_token_id):
171
+ # Isn't used because we override generate_until
172
+ raise NotImplementedError()
lm-evaluation-harness/lm_eval/prompts/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (5.74 kB). View file
 
lm-evaluation-harness/lm_eval/tasks/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (31.3 kB). View file
 
lm-evaluation-harness/lm_eval/tasks/aclue/_aclue.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ group: aclue
2
+ task:
3
+ - aclue_ancient_chinese_culture
4
+ - aclue_ancient_literature
5
+ - aclue_ancient_medical
6
+ - aclue_ancient_phonetics
7
+ - aclue_basic_ancient_chinese
8
+ - aclue_couplet_prediction
9
+ - aclue_homographic_character_resolution
10
+ - aclue_named_entity_recognition
11
+ - aclue_poetry_appreciate
12
+ - aclue_poetry_context_prediction
13
+ - aclue_poetry_quality_assessment
14
+ - aclue_poetry_sentiment_analysis
15
+ - aclue_polysemy_resolution
16
+ - aclue_reading_comprehension
17
+ - aclue_sentence_segmentation
18
+ aggregate_metric_list:
19
+ - metric: acc
20
+ aggregation: mean
21
+ weight_by_size: true
22
+ - metric: acc_norm
23
+ aggregation: mean
24
+ weight_by_size: true
25
+ metadata:
26
+ version: 1.0
lm-evaluation-harness/lm_eval/tasks/aclue/_default_template_yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset_path: tyouisen/aclue
2
+ test_split: test
3
+ fewshot_split: dev
4
+ fewshot_config:
5
+ sampler: first_n
6
+ output_type: multiple_choice
7
+ doc_to_text: "{{Question.strip()}}\nA. {{A}}\nB. {{B}}\nC. {{C}}\nD. {{D}}\n答案:"
8
+ doc_to_choice: ["A", "B", "C", "D"]
9
+ doc_to_target: "{{['A', 'B', 'C', 'D'].index(Answer)}}"
10
+ metric_list:
11
+ - metric: acc
12
+ aggregation: mean
13
+ higher_is_better: true
14
+ - metric: acc_norm
15
+ aggregation: mean
16
+ higher_is_better: true
17
+ metadata:
18
+ version: 1.0
lm-evaluation-harness/lm_eval/tasks/aclue/aclue_basic_ancient_chinese.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ "dataset_name": "basic_ancient_chinese"
2
+ "description": "以下是关于古汉语知识的单项选择题,请直接给出正确答案的选项。\n\n"
3
+ "include": "_default_template_yaml"
4
+ "task": "aclue_basic_ancient_chinese"
lm-evaluation-harness/lm_eval/tasks/aclue/aclue_poetry_appreciate.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ "dataset_name": "poetry_appreciate"
2
+ "description": "以下是关于古诗词曲鉴赏的单项选择题,请直接给出正确答案的选项。\n\n"
3
+ "include": "_default_template_yaml"
4
+ "task": "aclue_poetry_appreciate"
lm-evaluation-harness/lm_eval/tasks/aclue/aclue_polysemy_resolution.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ "dataset_name": "polysemy_resolution"
2
+ "description": "以下是关于古文单字多义的单项选择题,请直接给出正确答案的选项。\n\n"
3
+ "include": "_default_template_yaml"
4
+ "task": "aclue_polysemy_resolution"
lm-evaluation-harness/lm_eval/tasks/acpbench/gen_2shot/reach.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ task: acp_reach_gen
2
+ dataset_name: acp_reach_gen
3
+ include: _gen_yaml_2shot
4
+ fewshot_config:
5
+ sampler: first_n
6
+ samples:
7
+ - context: "A robot is in a grid and can only move to places that are connected to its current position. The grid size is 5x5, and the locations are of the form fi-jf (e.g., f3-2f or f0-1f). The grid cells are connected to their neighbors (e.g., f1-2f is connected to the four neighbors f0-2f, f2-2f, f1-1f, and f1-3f). Some positions on the grid are locked and can be opened with a key of a matching shape. The robot has an arm that can pick up a key when the key is in same location as the robot and the arm is empty. There are 2 keys in 0 different shapes: Key key0-1 is of shape shape0, Key key0-0 is of shape shape0. Currently, the robot is at position f1-2f and its arm is empty. All the positions are open except the following: f4-2f has shape0 shaped lock. Key key0-0 is at position f1-0f. Key key0-1 is at position f1-3f. The available propositions are: (at ?r ?x) - Key ?r is at ?x location, (at-robot ?x) - Robot is at ?x location, (locked ?x) - Location ?x is locked, (holding ?k) - Robot is holding ?k, (open ?x) - Location ?x is open, and (arm-empty) - Robot's arm is empty."
8
+ question: "What proposition can never hold in any potentially reachable state?"
9
+ answer: "(locked f3-1f)"
10
+ - context: "There are several cities, each containing several locations, some of which are airports. There are also trucks, which can drive within a single city, and airplanes, which can fly between airports. The goal is to get some packages from various locations to various new locations. There are 2 trucks and 1 airplane, as well as 4 packages. There are 4 locations across 2 cities. The locations are in cities as follows: l0-0 and l0-1 are in c0; l1-0 and l1-1 are in c1. Currently, a0, p2, and t1 are at l1-0, p3 and p0 are at l0-0, t0 is at l0-1, p1 is in t1. The available propositions are: (at ?obj ?loc) - ?obj is at ?loc and (in ?obj1 ?obj2) - ?obj1 is in ?obj2."
11
+ question: "What proposition can never hold in any potentially reachable state?"
12
+ answer: "(at t0 l1-1)"
13
+ doc_to_text: "**Question**: {{context}} {{question}} Provide one proposition or None. **Final Answer**:"
14
+ filter_list:
15
+ - name: "acp_grammar_parse"
16
+ filter:
17
+ - function: "ACP_grammar_filter"
18
+ grammar_task: "act"
19
+ - function: "take_first"
lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_twi.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: twi
3
+ doc_to_text: "For mathematical questions provided in Twi language. Supply the accurate\
4
+ \ step by step answer to the provided question. \n\nQuestion: {{question}} \nStep\
5
+ \ by step answer: "
6
+ include: afrimgsm_cot_yaml
7
+ task: afrimgsm_cot_twi_prompt_5
lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_wol.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: wol
3
+ doc_to_text: "For mathematical questions provided in Wolof language. Supply the accurate\
4
+ \ step by step answer to the provided question. \n\nQuestion: {{question}} \nStep\
5
+ \ by step answer: "
6
+ include: afrimgsm_cot_yaml
7
+ task: afrimgsm_cot_wol_prompt_5
lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_xho.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: xho
3
+ doc_to_text: "For mathematical questions provided in isiXhosa language. Supply the\
4
+ \ accurate step by step answer to the provided question. \n\nQuestion: {{question}}\
5
+ \ \nStep by step answer: "
6
+ include: afrimgsm_cot_yaml
7
+ task: afrimgsm_cot_xho_prompt_5
lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tag:
2
+ - afrimgsm_cot_tasks
3
+ - afrimgsm_cot_tasks_prompt_5
4
+ dataset_path: masakhane/afrimgsm
5
+ dataset_name: null # Overridden by language-specific config.
6
+ output_type: generate_until
7
+ training_split: train
8
+ test_split: test
9
+ doc_to_target: '{% if answer is not none %}{{answer[21:]}}{% else %}{{answer_number|string}}{% endif %}'
10
+ generation_kwargs:
11
+ do_sample: false
12
+ until:
13
+ - 'Question:'
14
+ - </s>
15
+ - <|im_end|>
16
+ - <|eot_id|>
17
+ metric_list:
18
+ - metric: exact_match
19
+ aggregation: mean
20
+ higher_is_better: true
21
+ ignore_case: true
22
+ ignore_punctuation: true
23
+ filter_list:
24
+ - name: "strict-match"
25
+ filter:
26
+ - function: "regex"
27
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]+)"
28
+ - function: "take_first"
29
+ - filter:
30
+ - function: regex
31
+ group_select: -1
32
+ regex_pattern: (-?[$0-9.,]{2,})|(-?[0-9]+)
33
+ - function: take_first
34
+ name: flexible-extract
35
+ metadata:
36
+ version: 2.0
lm-evaluation-harness/lm_eval/tasks/afrimgsm/direct_cot/prompt_5/afrimgsm_cot_yor.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: yor
3
+ doc_to_text: "For mathematical questions provided in Yoruba language. Supply the accurate\
4
+ \ step by step answer to the provided question. \n\nQuestion: {{question}} \nStep\
5
+ \ by step answer: "
6
+ include: afrimgsm_cot_yaml
7
+ task: afrimgsm_cot_yor_prompt_5
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_hau.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: hau
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_hau_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_ibo.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: ibo
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_ibo_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_kin.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: kin
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_kin_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_orm.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: orm
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_orm_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_sna.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: sna
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_sna_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_swa.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: swa
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_swa_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_twi.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: twi
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_twi_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_wol.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: wol
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_wol_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_xho.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: xho
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_xho_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_yaml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tag: afrimgsm_tt_tasks
2
+ dataset_path: masakhane/afrimgsm-translate-test
3
+ output_type: generate_until
4
+ test_split: test
5
+ doc_to_target: '{% if answer is not none %}{{answer[21:]}}{% else %}{{answer_number|string}}{% endif %}'
6
+ doc_to_text: '{% if answer is not none %}{{question+"\nAnswer:"}}{% else %}{{"Question: "+question+"\nAnswer:"}}{% endif %}'
7
+ target_delimiter: ""
8
+ generation_kwargs:
9
+ do_sample: false
10
+ until:
11
+ - 'Question:'
12
+ - </s>
13
+ - <|im_end|>
14
+ filter_list:
15
+ - name: remove_whitespace
16
+ filter:
17
+ - function: remove_whitespace
18
+ - function: take_first
19
+ - filter:
20
+ - function: regex
21
+ group_select: -1
22
+ regex_pattern: (-?[$0-9.,]{2,})|(-?[0-9]+)
23
+ - function: take_first
24
+ name: flexible-extract
25
+ metric_list:
26
+ - metric: exact_match
27
+ aggregation: mean
28
+ higher_is_better: true
29
+ ignore_case: true
30
+ ignore_punctuation: true
31
+ metadata:
32
+ version: 2.0
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_yor.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: yor
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_yor_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_1/afrimgsm_translate_zul.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: zul
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_zul_prompt_1
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_amh.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: amh
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_amh_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_hau.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: hau
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_hau_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_kin.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: kin
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_kin_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_lug.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: lug
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_lug_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_orm.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: orm
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_orm_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_sna.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: sna
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_sna_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_sot.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: sot
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_sot_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_swa.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: swa
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_swa_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_twi.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: twi
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_twi_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_wol.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: wol
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_wol_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_xho.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: xho
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_xho_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_yaml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ tag: afrimgsm_tt_tasks
2
+ dataset_path: masakhane/afrimgsm-translate-test
3
+ output_type: generate_until
4
+ test_split: test
5
+ doc_to_target: '{% if answer is not none %}{{answer[21:]}}{% else %}{{answer_number|string}}{% endif %}'
6
+ doc_to_text: "Give direct numerical answers for the question provided. \n\nQuestion: {{question}} \nAnswer: "
7
+ target_delimiter: ""
8
+ generation_kwargs:
9
+ do_sample: false
10
+ until:
11
+ - 'Question:'
12
+ - </s>
13
+ - <|im_end|>
14
+ should_decontaminate: true
15
+ doc_to_decontamination_query: "Answer: "
16
+ filter_list:
17
+ - name: remove_whitespace
18
+ filter:
19
+ - function: remove_whitespace
20
+ - function: take_first
21
+ - filter:
22
+ - function: regex
23
+ group_select: -1
24
+ regex_pattern: (-?[$0-9.,]{2,})|(-?[0-9]+)
25
+ - function: take_first
26
+ name: flexible-extract
27
+ metric_list:
28
+ - metric: exact_match
29
+ aggregation: mean
30
+ higher_is_better: true
31
+ ignore_case: true
32
+ ignore_punctuation: true
33
+ metadata:
34
+ version: 2.0
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_yor.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: yor
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_yor_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_2/afrimgsm_translate_zul.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: zul
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_zul_prompt_2
lm-evaluation-harness/lm_eval/tasks/afrimgsm/translate/prompt_3/afrimgsm_translate_amh.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Generated by utils.py
2
+ dataset_name: amh
3
+ include: afrimgsm_translate_yaml
4
+ task: afrimgsm_translate_amh_prompt_3