chen459664 commited on
Commit
8c6338f
·
verified ·
1 Parent(s): 93d45cc

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. llm-awq/tinychat/serve/README.md +27 -0
  2. llm-awq/tinychat/serve/controller.py +325 -0
  3. llm-awq/tinychat/stream_generators/NVILA_stream_gen.py +176 -0
  4. llm-awq/tinychat/stream_generators/__init__.py +1 -0
  5. llm-awq/tinychat/stream_generators/llava_stream_gen.py +301 -0
  6. llm-awq/tinychat/utils/constants.py +26 -0
  7. llm-awq/tinychat/utils/input_metadata.py +102 -0
  8. llm-awq/tinychat/utils/load_quant.py +171 -0
  9. llm-awq/tinychat/utils/log_utils.py +150 -0
  10. llm-awq/tinychat/utils/tune.py +81 -0
  11. lm-evaluation-harness/.coveragerc +28 -0
  12. lm-evaluation-harness/.flake8 +5 -0
  13. lm-evaluation-harness/.github/workflows/new_tasks.yml +71 -0
  14. lm-evaluation-harness/.github/workflows/publish.yml +97 -0
  15. lm-evaluation-harness/.github/workflows/unit_tests.yml +114 -0
  16. lm-evaluation-harness/CITATION.bib +10 -0
  17. lm-evaluation-harness/CODEOWNERS +1 -0
  18. lm-evaluation-harness/LICENSE.md +21 -0
  19. lm-evaluation-harness/MANIFEST.in +1 -0
  20. lm-evaluation-harness/README.md +625 -0
  21. lm-evaluation-harness/compute_score.py +155 -0
  22. lm-evaluation-harness/docs/API_guide.md +203 -0
  23. lm-evaluation-harness/docs/CONTRIBUTING.md +83 -0
  24. lm-evaluation-harness/docs/README.md +11 -0
  25. lm-evaluation-harness/docs/chat-template-readme.md +31 -0
  26. lm-evaluation-harness/docs/decontamination.md +76 -0
  27. lm-evaluation-harness/docs/footguns.md +58 -0
  28. lm-evaluation-harness/docs/interface.md +170 -0
  29. lm-evaluation-harness/docs/model_guide.md +192 -0
  30. lm-evaluation-harness/docs/new_task_guide.md +521 -0
  31. lm-evaluation-harness/docs/task_guide.md +335 -0
  32. lm-evaluation-harness/eval.log +0 -0
  33. lm-evaluation-harness/examples/lm-eval-overview.ipynb +1240 -0
  34. lm-evaluation-harness/examples/transformer-lens.py +59 -0
  35. lm-evaluation-harness/examples/visualize-wandb.ipynb +172 -0
  36. lm-evaluation-harness/examples/visualize-zeno.ipynb +115 -0
  37. lm-evaluation-harness/ignore.txt +8 -0
  38. lm-evaluation-harness/llama3-8b_eval.log +0 -0
  39. lm-evaluation-harness/lm_eval/__init__.py +7 -0
  40. lm-evaluation-harness/lm_eval/__main__.py +530 -0
  41. lm-evaluation-harness/lm_eval/__pycache__/__init__.cpython-310.pyc +0 -0
  42. lm-evaluation-harness/lm_eval/__pycache__/__init__.cpython-311.pyc +0 -0
  43. lm-evaluation-harness/lm_eval/__pycache__/__main__.cpython-310.pyc +0 -0
  44. lm-evaluation-harness/lm_eval/__pycache__/__main__.cpython-311.pyc +0 -0
  45. lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-310.pyc +0 -0
  46. lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-311.pyc +0 -0
  47. lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-310.pyc +0 -0
  48. lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-311.pyc +0 -0
  49. lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-310.pyc +0 -0
  50. lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-311.pyc +0 -0
llm-awq/tinychat/serve/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Gradio demo: VILA with TinyChat
2
+
3
+ We provide scripts for building your own gradio server to run VILA models with TinyChat. Please run the following commands to launch the server.
4
+
5
+ #### Launch a controller
6
+ ```bash
7
+ python -m tinychat.serve.controller --host 0.0.0.0 --port 10000
8
+ ```
9
+
10
+ #### Launch gradio web server.
11
+ ```bash
12
+ python -m tinychat.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload --share --auto-pad-image-token
13
+ ```
14
+ After launching this script, the web interface will be served on your machine and you can access it with a public URL (or localhost URL).
15
+
16
+ #### Launch a model worker
17
+
18
+ ```bash
19
+ python -m tinychat.serve.model_worker_new --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path <path-to-fp16-hf-model> --quant-path <path-to-awq-checkpoint>
20
+ # Please change tinychat.serve.model_worker_new to tinychat.serve.model_worker if you want to serve VILA rather than VILA-1.5
21
+ ```
22
+
23
+ Note: You can launch multiple model workers onto the same web server. And please remember to specify different ports for each model worker.
24
+
25
+ ### Acknowlegement
26
+
27
+ This demo is inspired by [LLaVA](https://github.com/haotian-liu/LLaVA). We thank LLaVA for providing an elegant way to build the Gradio Web UI.
llm-awq/tinychat/serve/controller.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/haotian-liu/LLaVA
2
+ # Copyright 2023 Haotian Liu
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ A controller manages distributed workers.
18
+ It sends worker addresses to clients.
19
+ """
20
+ import argparse
21
+ import asyncio
22
+ import dataclasses
23
+ from enum import Enum, auto
24
+ import json
25
+ import logging
26
+ import time
27
+ from typing import List, Union
28
+ import threading
29
+
30
+ from fastapi import FastAPI, Request
31
+ from fastapi.responses import StreamingResponse
32
+ import numpy as np
33
+ import requests
34
+ import uvicorn
35
+
36
+ from tinychat.utils.constants import CONTROLLER_HEART_BEAT_EXPIRATION
37
+ from tinychat.utils.log_utils import build_logger, server_error_msg
38
+
39
+
40
+ logger = build_logger("controller", "controller.log")
41
+
42
+
43
+ class DispatchMethod(Enum):
44
+ LOTTERY = auto()
45
+ SHORTEST_QUEUE = auto()
46
+
47
+ @classmethod
48
+ def from_str(cls, name):
49
+ if name == "lottery":
50
+ return cls.LOTTERY
51
+ elif name == "shortest_queue":
52
+ return cls.SHORTEST_QUEUE
53
+ else:
54
+ raise ValueError(f"Invalid dispatch method")
55
+
56
+
57
+ @dataclasses.dataclass
58
+ class WorkerInfo:
59
+ model_names: List[str]
60
+ speed: int
61
+ queue_length: int
62
+ check_heart_beat: bool
63
+ last_heart_beat: str
64
+
65
+
66
+ def heart_beat_controller(controller):
67
+ while True:
68
+ time.sleep(CONTROLLER_HEART_BEAT_EXPIRATION)
69
+ controller.remove_stable_workers_by_expiration()
70
+
71
+
72
+ class Controller:
73
+ def __init__(self, dispatch_method: str):
74
+ # Dict[str -> WorkerInfo]
75
+ self.worker_info = {}
76
+ self.dispatch_method = DispatchMethod.from_str(dispatch_method)
77
+
78
+ self.heart_beat_thread = threading.Thread(
79
+ target=heart_beat_controller, args=(self,)
80
+ )
81
+ self.heart_beat_thread.start()
82
+
83
+ logger.info("Init controller")
84
+
85
+ def register_worker(
86
+ self, worker_name: str, check_heart_beat: bool, worker_status: dict
87
+ ):
88
+ if worker_name not in self.worker_info:
89
+ logger.info(f"Register a new worker: {worker_name}")
90
+ else:
91
+ logger.info(f"Register an existing worker: {worker_name}")
92
+
93
+ if not worker_status:
94
+ worker_status = self.get_worker_status(worker_name)
95
+ if not worker_status:
96
+ return False
97
+
98
+ self.worker_info[worker_name] = WorkerInfo(
99
+ worker_status["model_names"],
100
+ worker_status["speed"],
101
+ worker_status["queue_length"],
102
+ check_heart_beat,
103
+ time.time(),
104
+ )
105
+
106
+ logger.info(f"Register done: {worker_name}, {worker_status}")
107
+ return True
108
+
109
+ def get_worker_status(self, worker_name: str):
110
+ try:
111
+ r = requests.post(worker_name + "/worker_get_status", timeout=5)
112
+ except requests.exceptions.RequestException as e:
113
+ logger.error(f"Get status fails: {worker_name}, {e}")
114
+ return None
115
+
116
+ if r.status_code != 200:
117
+ logger.error(f"Get status fails: {worker_name}, {r}")
118
+ return None
119
+
120
+ return r.json()
121
+
122
+ def remove_worker(self, worker_name: str):
123
+ del self.worker_info[worker_name]
124
+
125
+ def refresh_all_workers(self):
126
+ old_info = dict(self.worker_info)
127
+ self.worker_info = {}
128
+
129
+ for w_name, w_info in old_info.items():
130
+ if not self.register_worker(w_name, w_info.check_heart_beat, None):
131
+ logger.info(f"Remove stale worker: {w_name}")
132
+
133
+ def list_models(self):
134
+ model_names = set()
135
+
136
+ for w_name, w_info in self.worker_info.items():
137
+ model_names.update(w_info.model_names)
138
+
139
+ return list(model_names)
140
+
141
+ def get_worker_address(self, model_name: str):
142
+ if self.dispatch_method == DispatchMethod.LOTTERY:
143
+ worker_names = []
144
+ worker_speeds = []
145
+ for w_name, w_info in self.worker_info.items():
146
+ if model_name in w_info.model_names:
147
+ worker_names.append(w_name)
148
+ worker_speeds.append(w_info.speed)
149
+ worker_speeds = np.array(worker_speeds, dtype=np.float32)
150
+ norm = np.sum(worker_speeds)
151
+ if norm < 1e-4:
152
+ return ""
153
+ worker_speeds = worker_speeds / norm
154
+ if True: # Directly return address
155
+ pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
156
+ worker_name = worker_names[pt]
157
+ return worker_name
158
+
159
+ # Check status before returning
160
+ while True:
161
+ pt = np.random.choice(np.arange(len(worker_names)), p=worker_speeds)
162
+ worker_name = worker_names[pt]
163
+
164
+ if self.get_worker_status(worker_name):
165
+ break
166
+ else:
167
+ self.remove_worker(worker_name)
168
+ worker_speeds[pt] = 0
169
+ norm = np.sum(worker_speeds)
170
+ if norm < 1e-4:
171
+ return ""
172
+ worker_speeds = worker_speeds / norm
173
+ continue
174
+ return worker_name
175
+ elif self.dispatch_method == DispatchMethod.SHORTEST_QUEUE:
176
+ worker_names = []
177
+ worker_qlen = []
178
+ for w_name, w_info in self.worker_info.items():
179
+ if model_name in w_info.model_names:
180
+ worker_names.append(w_name)
181
+ worker_qlen.append(w_info.queue_length / w_info.speed)
182
+ if len(worker_names) == 0:
183
+ return ""
184
+ min_index = np.argmin(worker_qlen)
185
+ w_name = worker_names[min_index]
186
+ self.worker_info[w_name].queue_length += 1
187
+ logger.info(
188
+ f"names: {worker_names}, queue_lens: {worker_qlen}, ret: {w_name}"
189
+ )
190
+ return w_name
191
+ else:
192
+ raise ValueError(f"Invalid dispatch method: {self.dispatch_method}")
193
+
194
+ def receive_heart_beat(self, worker_name: str, queue_length: int):
195
+ if worker_name not in self.worker_info:
196
+ logger.info(f"Receive unknown heart beat. {worker_name}")
197
+ return False
198
+
199
+ self.worker_info[worker_name].queue_length = queue_length
200
+ self.worker_info[worker_name].last_heart_beat = time.time()
201
+ logger.info(f"Receive heart beat. {worker_name}")
202
+ return True
203
+
204
+ def remove_stable_workers_by_expiration(self):
205
+ expire = time.time() - CONTROLLER_HEART_BEAT_EXPIRATION
206
+ to_delete = []
207
+ for worker_name, w_info in self.worker_info.items():
208
+ if w_info.check_heart_beat and w_info.last_heart_beat < expire:
209
+ to_delete.append(worker_name)
210
+
211
+ for worker_name in to_delete:
212
+ self.remove_worker(worker_name)
213
+
214
+ def worker_api_generate_stream(self, params):
215
+ worker_addr = self.get_worker_address(params["model"])
216
+ if not worker_addr:
217
+ logger.info(f"no worker: {params['model']}")
218
+ ret = {
219
+ "text": server_error_msg,
220
+ "error_code": 2,
221
+ }
222
+ yield json.dumps(ret).encode() + b"\0"
223
+
224
+ try:
225
+ response = requests.post(
226
+ worker_addr + "/worker_generate_stream",
227
+ json=params,
228
+ stream=True,
229
+ timeout=5,
230
+ )
231
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
232
+ if chunk:
233
+ yield chunk + b"\0"
234
+ except requests.exceptions.RequestException as e:
235
+ logger.info(f"worker timeout: {worker_addr}")
236
+ ret = {
237
+ "text": server_error_msg,
238
+ "error_code": 3,
239
+ }
240
+ yield json.dumps(ret).encode() + b"\0"
241
+
242
+ # Let the controller act as a worker to achieve hierarchical
243
+ # management. This can be used to connect isolated sub networks.
244
+ def worker_api_get_status(self):
245
+ model_names = set()
246
+ speed = 0
247
+ queue_length = 0
248
+
249
+ for w_name in self.worker_info:
250
+ worker_status = self.get_worker_status(w_name)
251
+ if worker_status is not None:
252
+ model_names.update(worker_status["model_names"])
253
+ speed += worker_status["speed"]
254
+ queue_length += worker_status["queue_length"]
255
+
256
+ return {
257
+ "model_names": list(model_names),
258
+ "speed": speed,
259
+ "queue_length": queue_length,
260
+ }
261
+
262
+
263
+ app = FastAPI()
264
+
265
+
266
+ @app.post("/register_worker")
267
+ async def register_worker(request: Request):
268
+ data = await request.json()
269
+ controller.register_worker(
270
+ data["worker_name"], data["check_heart_beat"], data.get("worker_status", None)
271
+ )
272
+
273
+
274
+ @app.post("/refresh_all_workers")
275
+ async def refresh_all_workers():
276
+ models = controller.refresh_all_workers()
277
+
278
+
279
+ @app.post("/list_models")
280
+ async def list_models():
281
+ models = controller.list_models()
282
+ return {"models": models}
283
+
284
+
285
+ @app.post("/get_worker_address")
286
+ async def get_worker_address(request: Request):
287
+ data = await request.json()
288
+ addr = controller.get_worker_address(data["model"])
289
+ return {"address": addr}
290
+
291
+
292
+ @app.post("/receive_heart_beat")
293
+ async def receive_heart_beat(request: Request):
294
+ data = await request.json()
295
+ exist = controller.receive_heart_beat(data["worker_name"], data["queue_length"])
296
+ return {"exist": exist}
297
+
298
+
299
+ @app.post("/worker_generate_stream")
300
+ async def worker_api_generate_stream(request: Request):
301
+ params = await request.json()
302
+ generator = controller.worker_api_generate_stream(params)
303
+ return StreamingResponse(generator)
304
+
305
+
306
+ @app.post("/worker_get_status")
307
+ async def worker_api_get_status(request: Request):
308
+ return controller.worker_api_get_status()
309
+
310
+
311
+ if __name__ == "__main__":
312
+ parser = argparse.ArgumentParser()
313
+ parser.add_argument("--host", type=str, default="localhost")
314
+ parser.add_argument("--port", type=int, default=21001)
315
+ parser.add_argument(
316
+ "--dispatch-method",
317
+ type=str,
318
+ choices=["lottery", "shortest_queue"],
319
+ default="shortest_queue",
320
+ )
321
+ args = parser.parse_args()
322
+ logger.info(f"args: {args}")
323
+
324
+ controller = Controller(args.dispatch_method)
325
+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")
llm-awq/tinychat/stream_generators/NVILA_stream_gen.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gc
3
+ import time
4
+ from typing import Optional
5
+
6
+ from .llava_stream_gen import prepare_logits_processor
7
+
8
+ context_tokens = 0
9
+ context_time = 0.0
10
+ total_tokens = 0
11
+ generation_time_list = []
12
+
13
+
14
+ @torch.inference_mode()
15
+ def NVILAStreamGenerator(
16
+ model,
17
+ gen_params,
18
+ input: str,
19
+ media=None,
20
+ media_cfg=None,
21
+ start_pos: int = 0,
22
+ device: str = "cuda:0",
23
+ stream_interval: int = 2,
24
+ echo: bool = False,
25
+ stop_token_ids=[],
26
+ image_tensor: Optional[torch.FloatTensor] = None,
27
+ chunk_prefilling: bool = False,
28
+ quant_llm: bool = False,
29
+ ):
30
+ if chunk_prefilling and start_pos != 0:
31
+ input = "<|im_start|>" + input
32
+ input_ids = model.tokenizer(input)["input_ids"]
33
+ output_ids = list(input_ids)
34
+ input_echo_len = len(output_ids)
35
+ len_input = len(input)
36
+ if gen_params.top_k <= 0:
37
+ top_k = gen_params.n_vocab
38
+ else:
39
+ top_k = gen_params.top_k
40
+ logits_processor = prepare_logits_processor(
41
+ gen_params.temp, gen_params.repeat_penalty, gen_params.top_p, top_k
42
+ )
43
+ past_key_values = out = None
44
+ stop_token_ids.append(model.tokenizer.eos_token_id)
45
+ max_new_tokens = gen_params.n_predict
46
+
47
+ for i in range(max_new_tokens):
48
+ torch.cuda.synchronize()
49
+ t_st = time.time()
50
+
51
+ if i == 0:
52
+ inputs = torch.as_tensor([input_ids], device=device)
53
+ else:
54
+ inputs = torch.as_tensor([[token]], device=device)
55
+ out, length = model.stream_gen(
56
+ input_ids=inputs,
57
+ media=media,
58
+ media_cfg=media_cfg,
59
+ start_pos=start_pos,
60
+ chunk_prefilling=chunk_prefilling,
61
+ quant_llm=quant_llm,
62
+ )
63
+ start_pos += length
64
+ logits = out
65
+ torch.cuda.synchronize()
66
+ t_ed = time.time()
67
+ media = None
68
+ media_cfg = None
69
+ if torch.sum(torch.isinf(logits)):
70
+ print(
71
+ "{a} of {b}".format(
72
+ a=torch.sum(torch.isinf(logits)).item(), b=logits.numel()
73
+ )
74
+ )
75
+ print("{},{}".format(torch.max(logits), torch.min(logits)))
76
+ # Processing the logits
77
+ if logits_processor:
78
+ if gen_params.repeat_penalty > 1.0:
79
+ tmp_output_ids = torch.as_tensor([output_ids], device=logits.device)
80
+ # tmp_output_ids = output_ids[0].unsqueeze(0)
81
+ else:
82
+ tmp_output_ids = None
83
+ last_token_logits = logits_processor(tmp_output_ids, logits[:, -1, :])[0]
84
+ else:
85
+ last_token_logits = logits[:, -1, :]
86
+ if gen_params.temp < 1e-5 or gen_params.top_p < 1e-8: # greedy
87
+ token = int(torch.argmax(last_token_logits))
88
+ else:
89
+ probs = torch.softmax(last_token_logits.float(), dim=-1)
90
+ if torch.any(torch.isinf(probs)) or torch.any(torch.isnan(probs)):
91
+ print(
92
+ "[Error] Invalid probabilities detected (Inf/Nan exists). Saving the tensor and exiting..."
93
+ )
94
+ torch.save(last_token_logits, "last_token_logits.pt")
95
+ exit()
96
+ token = int(torch.multinomial(probs, num_samples=1))
97
+ output_ids.append(token)
98
+
99
+ global context_time
100
+ global context_tokens
101
+ global total_tokens
102
+ global generation_time_list
103
+ if i == 0:
104
+ context_time = t_ed - t_st
105
+ context_tokens = length
106
+ generation_time_list = []
107
+ else:
108
+ generation_time_list.append(t_ed - t_st)
109
+
110
+ if token in stop_token_ids:
111
+ stopped = True
112
+ else:
113
+ stopped = False
114
+
115
+ if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped:
116
+ if echo:
117
+ tmp_output_ids = output_ids
118
+ rfind_start = len_input
119
+ else:
120
+ tmp_output_ids = output_ids[input_echo_len:]
121
+ rfind_start = 0
122
+
123
+ output = model.tokenizer.decode(
124
+ tmp_output_ids,
125
+ skip_special_tokens=True,
126
+ spaces_between_special_tokens=False,
127
+ )
128
+
129
+ partially_stopped = False
130
+
131
+ # prevent yielding partial stop sequence
132
+ if not partially_stopped:
133
+ yield {
134
+ "text": output,
135
+ "usage": {
136
+ "prompt_tokens": input_echo_len,
137
+ "completion_tokens": i,
138
+ "total_tokens": input_echo_len + i,
139
+ },
140
+ "finish_reason": None,
141
+ "timing": None,
142
+ }
143
+
144
+ if stopped:
145
+ break
146
+
147
+ # finish stream event, which contains finish reason
148
+ if i == max_new_tokens - 1:
149
+ finish_reason = "length"
150
+ elif stopped:
151
+ finish_reason = "stop"
152
+ else:
153
+ finish_reason = None
154
+
155
+ total_tokens = context_tokens + len(generation_time_list)
156
+ yield {
157
+ "text": output,
158
+ "usage": {
159
+ "prompt_tokens": input_echo_len,
160
+ "completion_tokens": i,
161
+ "total_tokens": input_echo_len + i,
162
+ },
163
+ "finish_reason": finish_reason,
164
+ "timing": {
165
+ "context_tokens": context_tokens,
166
+ "context_time": context_time,
167
+ "total_tokens": total_tokens,
168
+ "generation_time_list": generation_time_list,
169
+ },
170
+ }
171
+
172
+ del past_key_values, out
173
+ gc.collect()
174
+ torch.cuda.empty_cache()
175
+
176
+ # return context_tokens, context_time, total_tokens, generation_time_list
llm-awq/tinychat/stream_generators/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .stream_gen import *
llm-awq/tinychat/stream_generators/llava_stream_gen.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gc
3
+ import time
4
+ from typing import Optional
5
+
6
+ import tinychat.utils.constants
7
+
8
+ from transformers.generation.logits_process import (
9
+ LogitsProcessorList,
10
+ RepetitionPenaltyLogitsProcessor,
11
+ TemperatureLogitsWarper,
12
+ TopKLogitsWarper,
13
+ TopPLogitsWarper,
14
+ )
15
+
16
+ # from llava.constants import (
17
+ # IMAGE_TOKEN_INDEX,
18
+ # )
19
+
20
+ context_tokens = 0
21
+ context_time = 0.0
22
+ total_tokens = 0
23
+ generation_time_list = []
24
+
25
+
26
+ def prepare_logits_processor(
27
+ temperature: float,
28
+ repetition_penalty: float,
29
+ top_p: float,
30
+ top_k: int,
31
+ min_tokens_to_keep: int = 1,
32
+ ) -> LogitsProcessorList:
33
+ processor_list = LogitsProcessorList()
34
+ # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases.
35
+ if temperature >= 1e-5 and temperature != 1.0:
36
+ processor_list.append(TemperatureLogitsWarper(temperature))
37
+ # Removed for the newest version of VILA
38
+ # if repetition_penalty > 1.0:
39
+ # processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty))
40
+ if 1e-8 <= top_p < 1.0:
41
+ processor_list.append(TopPLogitsWarper(top_p))
42
+ if top_k > 0:
43
+ processor_list.append(
44
+ TopKLogitsWarper(top_k=top_k, min_tokens_to_keep=min_tokens_to_keep)
45
+ )
46
+ return processor_list
47
+
48
+
49
+ # This function is inspired by https://github.com/haotian-liu/LLaVA/blob/main/llava/mm_utils.py#L185
50
+ def tokenizer_image_token(
51
+ prompt,
52
+ tokenizer,
53
+ image_token_index=tinychat.utils.constants.LLAVA_DEFAULT_IMAGE_TOKEN_IDX,
54
+ return_tensors=None,
55
+ ):
56
+ prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
57
+
58
+ def insert_separator(X, sep):
59
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
60
+
61
+ input_ids = []
62
+ offset = 0
63
+ if (
64
+ len(prompt_chunks) > 0
65
+ and len(prompt_chunks[0]) > 0
66
+ and prompt_chunks[0][0] == tokenizer.bos_token_id
67
+ ):
68
+ offset = 1
69
+ input_ids.append(prompt_chunks[0][0])
70
+
71
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
72
+ input_ids.extend(x[offset:])
73
+
74
+ if return_tensors is not None:
75
+ if return_tensors == "pt":
76
+ return torch.tensor(input_ids, dtype=torch.long)
77
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
78
+ return input_ids
79
+
80
+
81
+ @torch.inference_mode()
82
+ def LlavaStreamGenerator(
83
+ model,
84
+ tokenizer,
85
+ input: str,
86
+ start_pos: int,
87
+ gen_params: dict,
88
+ device: str = "cuda:0",
89
+ stream_interval: int = 1,
90
+ echo: bool = False,
91
+ stop_token_ids=[],
92
+ image_tensor: Optional[torch.FloatTensor] = None,
93
+ chunk_prefilling: bool = False,
94
+ ):
95
+ if chunk_prefilling and start_pos != 0: # </s>USER:2,11889 while USER:3148,1001
96
+ input = "</s>" + input
97
+ input_ids = (
98
+ tokenizer_image_token(
99
+ input,
100
+ tokenizer,
101
+ tinychat.utils.constants.LLAVA_DEFAULT_IMAGE_TOKEN_IDX,
102
+ return_tensors="pt",
103
+ )
104
+ .unsqueeze(0)
105
+ .to(device)
106
+ )
107
+ if chunk_prefilling and start_pos != 0:
108
+ input_ids = input_ids[
109
+ :, 2:
110
+ ] # tokenizer will add a <s> at the beginning, so to delete it
111
+ special_token = "<image>" in input
112
+ input_echo_len = len(input_ids)
113
+ output_ids = list(input_ids)
114
+ len_input = len(input)
115
+ if gen_params.top_k <= 0:
116
+ top_k = gen_params.n_vocab
117
+ else:
118
+ top_k = gen_params.top_k
119
+ logits_processor = prepare_logits_processor(
120
+ gen_params.temp, gen_params.repeat_penalty, gen_params.top_p, top_k
121
+ )
122
+
123
+ past_key_values = out = None
124
+ stop_token_ids.append(tokenizer.eos_token_id)
125
+ max_new_tokens = gen_params.n_predict
126
+
127
+ batch_size = 1 # TODO: support multi-batch
128
+ position_ids = [
129
+ torch.arange(
130
+ start_pos, start_pos + input_ids.numel(), dtype=torch.long, device=device
131
+ )
132
+ for i in range(batch_size)
133
+ ]
134
+ position_ids = torch.stack(position_ids)
135
+
136
+ for i in range(max_new_tokens):
137
+ torch.cuda.synchronize()
138
+ t_st = time.time()
139
+
140
+ if i == 0:
141
+ # inputs = torch.as_tensor([input_ids], device=device)
142
+ inputs = input_ids
143
+ else:
144
+ position_ids = (position_ids[:, -1] + 1).reshape(
145
+ 1, 1
146
+ ) # [Important] fixed the bug of positions
147
+ inputs = torch.as_tensor([[token]], device=device)
148
+
149
+ attention_mask = torch.ones(size=inputs.shape, dtype=torch.int, device=device)
150
+
151
+ if (
152
+ "llama" not in model.__class__.__name__.lower()
153
+ and "mpt" not in model.__class__.__name__.lower()
154
+ and "falcon" not in model.__class__.__name__.lower()
155
+ and "llava" not in model.__class__.__name__.lower()
156
+ # and "vila" not in model.__class__.__name__.lower() # VILA model reuses the model class of LLaVA
157
+ ):
158
+ if i == 0: # Context Stage
159
+ out = model(
160
+ input_ids=inputs,
161
+ attention_mask=attention_mask,
162
+ position_ids=position_ids,
163
+ use_cache=True,
164
+ output_attentions=False,
165
+ output_hidden_states=False,
166
+ images=image_tensor,
167
+ return_dict=True,
168
+ # special_token=special_token,
169
+ )
170
+ logits = out.logits
171
+ past_key_values = out.past_key_values
172
+ else:
173
+ out = model(
174
+ input_ids=inputs,
175
+ attention_mask=attention_mask,
176
+ position_ids=position_ids,
177
+ use_cache=True,
178
+ past_key_values=past_key_values,
179
+ output_attentions=False,
180
+ output_hidden_states=False,
181
+ images=image_tensor,
182
+ return_dict=True,
183
+ # special_token=special_token,
184
+ )
185
+ logits = out.logits
186
+ past_key_values = out.past_key_values
187
+ else:
188
+ out = model(
189
+ input_ids=inputs,
190
+ start_pos=start_pos,
191
+ images=image_tensor,
192
+ position_ids=position_ids,
193
+ attention_mask=attention_mask,
194
+ special_token=special_token,
195
+ chunk_prefilling=chunk_prefilling,
196
+ )
197
+ start_pos += (
198
+ inputs.shape[1] + 195 * torch.sum(inputs[0] == IMAGE_TOKEN_INDEX).item()
199
+ )
200
+ logits = out
201
+ torch.cuda.synchronize()
202
+ t_ed = time.time()
203
+
204
+ # Processing the logits
205
+ if logits_processor:
206
+ if gen_params.repeat_penalty > 1.0:
207
+ # tmp_output_ids = torch.as_tensor([output_ids], device=logits.device)
208
+ tmp_output_ids = output_ids[0].unsqueeze(0)
209
+ else:
210
+ tmp_output_ids = None
211
+ last_token_logits = logits_processor(tmp_output_ids, logits[:, -1, :])[0]
212
+ else:
213
+ last_token_logits = logits[:, -1, :]
214
+ if gen_params.temp < 1e-5 or gen_params.top_p < 1e-8: # greedy
215
+ token = int(torch.argmax(last_token_logits))
216
+ print(token)
217
+ else:
218
+ probs = torch.softmax(last_token_logits, dim=-1)
219
+ token = int(torch.multinomial(probs, num_samples=1))
220
+ output_ids.append(token)
221
+
222
+ global context_time
223
+ global context_tokens
224
+ global total_tokens
225
+ global generation_time_list
226
+ if i == 0:
227
+ context_time = t_ed - t_st
228
+ context_tokens = (
229
+ inputs.shape[1] + 195 * torch.sum(inputs[0] == IMAGE_TOKEN_INDEX).item()
230
+ )
231
+ generation_time_list = []
232
+ else:
233
+ generation_time_list.append(t_ed - t_st)
234
+
235
+ if token in stop_token_ids:
236
+ stopped = True
237
+ else:
238
+ stopped = False
239
+
240
+ if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped:
241
+ if echo:
242
+ tmp_output_ids = output_ids
243
+ rfind_start = len_input
244
+ else:
245
+ tmp_output_ids = output_ids[input_echo_len:]
246
+ rfind_start = 0
247
+
248
+ output = tokenizer.decode(
249
+ tmp_output_ids,
250
+ skip_special_tokens=True,
251
+ spaces_between_special_tokens=False,
252
+ )
253
+
254
+ partially_stopped = False
255
+
256
+ # prevent yielding partial stop sequence
257
+ if not partially_stopped:
258
+ yield {
259
+ "text": output,
260
+ "usage": {
261
+ "prompt_tokens": input_echo_len,
262
+ "completion_tokens": i,
263
+ "total_tokens": input_echo_len + i,
264
+ },
265
+ "finish_reason": None,
266
+ "timing": None,
267
+ }
268
+
269
+ if stopped:
270
+ break
271
+
272
+ # finish stream event, which contains finish reason
273
+ if i == max_new_tokens - 1:
274
+ finish_reason = "length"
275
+ elif stopped:
276
+ finish_reason = "stop"
277
+ else:
278
+ finish_reason = None
279
+
280
+ total_tokens = context_tokens + len(generation_time_list)
281
+ yield {
282
+ "text": output,
283
+ "usage": {
284
+ "prompt_tokens": input_echo_len,
285
+ "completion_tokens": i,
286
+ "total_tokens": input_echo_len + i,
287
+ },
288
+ "finish_reason": finish_reason,
289
+ "timing": {
290
+ "context_tokens": context_tokens,
291
+ "context_time": context_time,
292
+ "total_tokens": total_tokens,
293
+ "generation_time_list": generation_time_list,
294
+ },
295
+ }
296
+
297
+ del past_key_values, out
298
+ gc.collect()
299
+ torch.cuda.empty_cache()
300
+
301
+ # return context_tokens, context_time, total_tokens, generation_time_list
llm-awq/tinychat/utils/constants.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def init():
5
+ global max_seq_len, max_batch_size, llama_multiple_of, mem_efficient_load
6
+ max_seq_len = 8192
7
+ max_batch_size = 1
8
+ llama_multiple_of = 256
9
+ mem_efficient_load = False # Whether to load the checkpoint in a layer-wise manner. Activate this if you are facing OOM issues on edge devices (e.g., Jetson Orin).
10
+
11
+ # LLaVA Constants
12
+ global LLAVA_IGNORE_INDEX, LLAVA_DEFAULT_IMAGE_TOKEN, LLAVA_DEFAULT_IMAGE_TOKEN_IDX, LLAVA_DEFAULT_IMAGE_PATCH_TOKEN, LLAVA_DEFAULT_IMAGE_PATCH_TOKEN_IDX, LLAVA_DEFAULT_IM_START_TOKEN, LLAVA_DEFAULT_IM_END_TOKEN, LLAVA_DEFAULT_IM_TOKEN_PLACE_HOLDER, AUTO_FILL_IM_TOKEN_HOLDER
13
+ LLAVA_IGNORE_INDEX = -100
14
+ LLAVA_DEFAULT_IMAGE_TOKEN = "<image>"
15
+ LLAVA_DEFAULT_IMAGE_TOKEN_IDX = -200
16
+ LLAVA_DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
17
+ LLAVA_DEFAULT_IMAGE_PATCH_TOKEN_IDX = 32000
18
+ LLAVA_DEFAULT_IM_START_TOKEN = "<im_start>"
19
+ LLAVA_DEFAULT_IM_END_TOKEN = "<im_end>"
20
+ LLAVA_DEFAULT_IM_TOKEN_PLACE_HOLDER = "<image>"
21
+ AUTO_FILL_IM_TOKEN_HOLDER = "<im_holder>"
22
+
23
+ # gradio UI
24
+ global CONTROLLER_HEART_BEAT_EXPIRATION, WORKER_HEART_BEAT_INTERVAL
25
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
26
+ WORKER_HEART_BEAT_INTERVAL = 15
llm-awq/tinychat/utils/input_metadata.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File authors: Haotian Tang, Shang Yang, Yujun Lin, Song Han
2
+ # @article{lin2024awq,
3
+ # title={AWQ: Activation-aware Weight Quantization for On-Device LLM Compression and Acceleration},
4
+ # author={Lin, Ji and Tang, Jiaming and Tang, Haotian and Yang, Shang and Chen, Wei-Ming and Wang, Wei-Chen and Xiao, Guangxuan and Dang, Xingyu and Gan, Chuang and Han, Song},
5
+ # journal={Proceedings of Machine Learning and Systems},
6
+ # volume={6},
7
+ # pages={87--100},
8
+ # year={2024}
9
+ # }
10
+
11
+ import torch
12
+
13
+
14
+ class ActivationBuffer:
15
+ """
16
+ Pre-allocated Buffer for activation in the siglip model.
17
+
18
+ Args:
19
+ model: The input model
20
+ batched_seq_len: The batched sequence length. Sum of all the sequence lengths in the batch.
21
+ """
22
+
23
+ def __init__(self, model):
24
+ self.model_class = model.__class__.__name__
25
+
26
+ if self.model_class == "SiglipEncoder":
27
+ self.model_dtype = model.layers[0].self_attn.k_proj.weight.dtype
28
+
29
+ self.device = "cuda"
30
+ assert self.model_class in [
31
+ "SiglipEncoder",
32
+ ], f"model_class: {self.model_class} is currently not supported."
33
+ assert (
34
+ self.model_dtype == torch.float16
35
+ ), f"model_dtype is expected to be fp16. Current: {self.model_dtype}."
36
+
37
+ self.intermediate_size = model.config.intermediate_size
38
+ self.hidden_size = model.config.hidden_size
39
+
40
+ def allocate_activation_buffer(self, batched_seq_len):
41
+ if self.model_class == "SiglipEncoder":
42
+ self.__allocate_activation_buffer_siglip(batched_seq_len)
43
+ else:
44
+ raise NotImplementedError(
45
+ f"model_class: {self.model_class} is currently not supported."
46
+ )
47
+
48
+ def __allocate_activation_buffer_siglip(self, batched_seq_len):
49
+ # Allocate fp16 activation buffer.
50
+ self.act_buffer = torch.empty(
51
+ (batched_seq_len * max(self.hidden_size * 3, 2 * self.intermediate_size)),
52
+ device=self.device,
53
+ dtype=torch.float16,
54
+ )
55
+ self.qkv_proj_act_buffer = self.act_buffer[
56
+ : batched_seq_len * self.hidden_size * 3
57
+ ].view(
58
+ batched_seq_len, self.hidden_size * 3
59
+ ) # qkv
60
+
61
+ self.in_out_fc2_act_buffer = self.act_buffer[
62
+ : batched_seq_len * self.hidden_size
63
+ ].view(
64
+ batched_seq_len, self.hidden_size
65
+ ) # LN1, Wo_out, LN2, all_out
66
+
67
+ self.fc1_buffer = self.act_buffer[
68
+ : batched_seq_len * self.intermediate_size
69
+ ].view(batched_seq_len, self.intermediate_size)
70
+ self.actfn_buffer = self.act_buffer[
71
+ batched_seq_len
72
+ * self.intermediate_size : 2
73
+ * batched_seq_len
74
+ * self.intermediate_size
75
+ ].view(batched_seq_len, self.intermediate_size)
76
+
77
+ # Allocate quantized activation buffer.
78
+ self.quantized_act_buffer = torch.empty(
79
+ (batched_seq_len * max(self.hidden_size, self.intermediate_size)),
80
+ device=self.device,
81
+ dtype=torch.int8,
82
+ )
83
+ self.quantized_hidden_states_buffer = self.quantized_act_buffer[
84
+ : batched_seq_len * self.hidden_size
85
+ ].view(
86
+ batched_seq_len, self.hidden_size
87
+ ) # Wo_in,
88
+ self.quantized_mlp_act_buffer = self.quantized_act_buffer[
89
+ : batched_seq_len * self.intermediate_size
90
+ ].view(batched_seq_len, self.intermediate_size)
91
+
92
+ # per token
93
+ self.quantized_scale_buffer = torch.empty(
94
+ (batched_seq_len), device=self.device, dtype=torch.float16
95
+ )
96
+
97
+ # For faster act-quant implementation
98
+ self.tmp = torch.empty(
99
+ (batched_seq_len * self.intermediate_size),
100
+ device=self.device,
101
+ dtype=torch.float16,
102
+ )
llm-awq/tinychat/utils/load_quant.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import os
3
+ import re
4
+ from typing import Union, List
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from transformers import AutoModelForCausalLM
9
+ from accelerate import init_empty_weights, load_checkpoint_and_dispatch
10
+ from awq.quantize.quantizer import real_quantize_model_weight
11
+ from awq.quantize.qmodule import WQLinear
12
+ from tqdm import tqdm
13
+
14
+ import tinychat.utils.constants
15
+
16
+ version_message = """
17
+ [Warning] The awq quantized checkpoint seems to be in v1 format.
18
+ If the model cannot be loaded successfully, please use the latest awq library to re-quantized the model, or repack the current checkpoint with tinychat/offline-weight-repacker.py
19
+ """
20
+
21
+
22
+ def ckpt_version_check(quant_path):
23
+ if not quant_path.endswith("v2.pt"):
24
+ print(version_message)
25
+
26
+
27
+ def mem_efficient_load_checkpoint(
28
+ model: nn.Module,
29
+ ckpts_folder: Union[str, os.PathLike],
30
+ ):
31
+ checkpoint_files = [
32
+ ckpts_folder + "/" + f for f in os.listdir(ckpts_folder) if f.endswith(".pt")
33
+ ]
34
+
35
+ # Check if the ckpts match the model
36
+ model_keys = sorted((list(model.state_dict().keys())))
37
+ suffix = r"\.pt$"
38
+ ckpt_keys = sorted(
39
+ [re.sub(suffix, "", f) for f in os.listdir(ckpts_folder) if f.endswith(".pt")]
40
+ )
41
+ assert len(model_keys) == len(
42
+ ckpt_keys
43
+ ), f"The number of checkpoint files do not match the model. \n Model has {len(model_keys)} keys, while finding {len(ckpt_keys)} checkpoint files in the folder."
44
+ for key1, key2 in zip(model_keys, ckpt_keys):
45
+ assert (
46
+ key1 == key2
47
+ ), f"The checkpoint files do not match the model. \nmodel key {key1} != checkpoint key {key2}"
48
+
49
+ with tqdm(total=len(checkpoint_files)) as pbar:
50
+ pbar.set_description("Loading checkpoint shards")
51
+ for checkpoint_file in checkpoint_files:
52
+ checkpoint = torch.load(checkpoint_file, map_location=torch.device("cpu"))
53
+ model.load_state_dict(checkpoint, strict=False)
54
+ # Force Python to clean up.
55
+ del checkpoint
56
+ gc.collect()
57
+ pbar.update(1)
58
+ return model
59
+
60
+
61
+ def load_awq_model(model, checkpoint, w_bit, group_size, device):
62
+ q_config = {"zero_point": True, "q_group_size": group_size}
63
+ real_quantize_model_weight(model, w_bit, q_config, init_only=True)
64
+
65
+ if hasattr(model.config, "tie_encoder_decoder"):
66
+ model.config.tie_encoder_decoder = False
67
+ if hasattr(model.config, "tie_word_embeddings"):
68
+ model.config.tie_word_embeddings = False
69
+ if tinychat.utils.constants.mem_efficient_load:
70
+ assert os.path.isdir(
71
+ checkpoint
72
+ ), "You are in mem_efficient_load mode. \n Please set --load_quant the path to the folder containing all checkpoint files."
73
+ model = mem_efficient_load_checkpoint(
74
+ model,
75
+ checkpoint,
76
+ ).to(device)
77
+ else:
78
+ ckpt_version_check(checkpoint)
79
+ pbar = tqdm(range(1))
80
+ pbar.set_description("Loading checkpoint")
81
+ for i in pbar:
82
+ model = load_checkpoint_and_dispatch(
83
+ model,
84
+ checkpoint,
85
+ no_split_module_classes=[
86
+ "OPTDecoderLayer",
87
+ "LlamaDecoderLayer",
88
+ "BloomBlock",
89
+ "MPTBlock",
90
+ "DecoderLayer",
91
+ "CLIPEncoderLayer",
92
+ ],
93
+ ).to(device)
94
+ return model
95
+
96
+
97
+ def make_quant_linear(module, names, w_bit, groupsize, device, name=""):
98
+ if isinstance(module, WQLinear):
99
+ return
100
+ for attr in dir(module):
101
+ tmp = getattr(module, attr)
102
+ name1 = name + "." + attr if name != "" else attr
103
+ if name1 in names:
104
+ delattr(module, attr)
105
+ setattr(
106
+ module,
107
+ attr,
108
+ WQLinear(
109
+ w_bit,
110
+ groupsize,
111
+ tmp.in_features,
112
+ tmp.out_features,
113
+ tmp.bias is not None,
114
+ device,
115
+ dtype=tmp.weight.dtype,
116
+ ),
117
+ )
118
+ for name1, child in module.named_children():
119
+ make_quant_linear(
120
+ child,
121
+ names,
122
+ w_bit,
123
+ groupsize,
124
+ device,
125
+ name + "." + name1 if name != "" else name1,
126
+ )
127
+
128
+
129
+ def find_layers(module, layers=[nn.Linear], name=""):
130
+ if type(module) in layers:
131
+ return {name: module}
132
+ res = {}
133
+ for name1, child in module.named_children():
134
+ res.update(
135
+ find_layers(
136
+ child, layers=layers, name=name + "." + name1 if name != "" else name1
137
+ )
138
+ )
139
+ return res
140
+
141
+
142
+ def load_awq_llama_fast(model, checkpoint, w_bit, group_size, device):
143
+ layers = find_layers(model)
144
+ for name in ["lm_head"]:
145
+ if name in layers:
146
+ del layers[name]
147
+ make_quant_linear(model, layers, w_bit, group_size, device)
148
+ del layers
149
+
150
+ if tinychat.utils.constants.mem_efficient_load:
151
+ # TODO: mem-efficient load for llama
152
+ assert os.path.isdir(
153
+ checkpoint
154
+ ), "You are in mem_efficient_load mode. \n Please set --load_quant the path to the folder containing all checkpoint files."
155
+ model = mem_efficient_load_checkpoint(
156
+ model,
157
+ checkpoint,
158
+ )
159
+ else:
160
+ ckpt_version_check(checkpoint)
161
+ pbar = tqdm(range(1))
162
+ pbar.set_description("Loading checkpoint")
163
+ for i in pbar:
164
+ if checkpoint.endswith(".safetensors"):
165
+ from safetensors.torch import load_file as safe_load
166
+
167
+ model.load_state_dict(safe_load(checkpoint))
168
+ else:
169
+ model.load_state_dict(torch.load(checkpoint))
170
+
171
+ return model.to(device)
llm-awq/tinychat/utils/log_utils.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/haotian-liu/LLaVA
2
+ # Copyright 2023 Haotian Liu
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import datetime
17
+ import logging
18
+ import logging.handlers
19
+ import os
20
+ import sys
21
+
22
+ import requests
23
+
24
+ LOGDIR = "."
25
+
26
+ server_error_msg = (
27
+ "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
28
+ )
29
+ moderation_msg = (
30
+ "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
31
+ )
32
+
33
+ handler = None
34
+
35
+
36
+ def build_logger(logger_name, logger_filename):
37
+ global handler
38
+
39
+ formatter = logging.Formatter(
40
+ fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
41
+ datefmt="%Y-%m-%d %H:%M:%S",
42
+ )
43
+
44
+ # Set the format of root handlers
45
+ if not logging.getLogger().handlers:
46
+ logging.basicConfig(level=logging.INFO)
47
+ logging.getLogger().handlers[0].setFormatter(formatter)
48
+
49
+ # Redirect stdout and stderr to loggers
50
+ stdout_logger = logging.getLogger("stdout")
51
+ stdout_logger.setLevel(logging.INFO)
52
+ sl = StreamToLogger(stdout_logger, logging.INFO)
53
+ sys.stdout = sl
54
+
55
+ stderr_logger = logging.getLogger("stderr")
56
+ stderr_logger.setLevel(logging.ERROR)
57
+ sl = StreamToLogger(stderr_logger, logging.ERROR)
58
+ sys.stderr = sl
59
+
60
+ # Get logger
61
+ logger = logging.getLogger(logger_name)
62
+ logger.setLevel(logging.INFO)
63
+
64
+ # Add a file handler for all loggers
65
+ if handler is None:
66
+ os.makedirs(LOGDIR, exist_ok=True)
67
+ filename = os.path.join(LOGDIR, logger_filename)
68
+ handler = logging.handlers.TimedRotatingFileHandler(
69
+ filename, when="D", utc=True, encoding="UTF-8"
70
+ )
71
+ handler.setFormatter(formatter)
72
+
73
+ for name, item in logging.root.manager.loggerDict.items():
74
+ if isinstance(item, logging.Logger):
75
+ item.addHandler(handler)
76
+
77
+ return logger
78
+
79
+
80
+ class StreamToLogger(object):
81
+ """
82
+ Fake file-like stream object that redirects writes to a logger instance.
83
+ """
84
+
85
+ def __init__(self, logger, log_level=logging.INFO):
86
+ self.terminal = sys.stdout
87
+ self.logger = logger
88
+ self.log_level = log_level
89
+ self.linebuf = ""
90
+
91
+ def __getattr__(self, attr):
92
+ return getattr(self.terminal, attr)
93
+
94
+ def write(self, buf):
95
+ temp_linebuf = self.linebuf + buf
96
+ self.linebuf = ""
97
+ for line in temp_linebuf.splitlines(True):
98
+ # From the io.TextIOWrapper docs:
99
+ # On output, if newline is None, any '\n' characters written
100
+ # are translated to the system default line separator.
101
+ # By default sys.stdout.write() expects '\n' newlines and then
102
+ # translates them so this is still cross platform.
103
+ if line[-1] == "\n":
104
+ self.logger.log(self.log_level, line.rstrip())
105
+ else:
106
+ self.linebuf += line
107
+
108
+ def flush(self):
109
+ if self.linebuf != "":
110
+ self.logger.log(self.log_level, self.linebuf.rstrip())
111
+ self.linebuf = ""
112
+
113
+
114
+ def disable_torch_init():
115
+ """
116
+ Disable the redundant torch default initialization to accelerate model creation.
117
+ """
118
+ import torch
119
+
120
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
121
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
122
+
123
+
124
+ def violates_moderation(text):
125
+ """
126
+ Check whether the text violates OpenAI moderation API.
127
+ """
128
+ url = "https://api.openai.com/v1/moderations"
129
+ headers = {
130
+ "Content-Type": "application/json",
131
+ "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"],
132
+ }
133
+ text = text.replace("\n", "")
134
+ data = "{" + '"input": ' + f'"{text}"' + "}"
135
+ data = data.encode("utf-8")
136
+ try:
137
+ ret = requests.post(url, headers=headers, data=data, timeout=5)
138
+ flagged = ret.json()["results"][0]["flagged"]
139
+ except requests.exceptions.RequestException as e:
140
+ flagged = False
141
+ except KeyError as e:
142
+ flagged = False
143
+
144
+ return flagged
145
+
146
+
147
+ def pretty_print_semaphore(semaphore):
148
+ if semaphore is None:
149
+ return "None"
150
+ return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
llm-awq/tinychat/utils/tune.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import time
3
+ import torch
4
+ from awq.quantize.qmodule import WQLinear
5
+
6
+
7
+ __all__ = ["device_warmup", "tune_all_wqlinears"]
8
+
9
+
10
+ def device_warmup(device: str):
11
+ warm_up = torch.randn((8192, 8192)).to(device)
12
+ for i in range(100):
13
+ torch.mm(warm_up, warm_up)
14
+
15
+
16
+ def tune_llava_patch_embedding(vision_tower, device):
17
+ # run the llava_patch_embedding layer to pre-tune the kernel configuration
18
+ # Without this pre-tuning, the embedding layer can cause significant slowdown due to cuDNN tuning.
19
+ device = vision_tower.device
20
+ if "intern" not in vision_tower.__class__.__name__.lower():
21
+ patch_embedding = (
22
+ vision_tower.vision_tower.vision_model.embeddings.patch_embedding
23
+ )
24
+ else:
25
+ patch_embedding = vision_tower.vision_tower.embeddings.patch_embedding
26
+ patch_embedding = patch_embedding.to(device)
27
+ image = (
28
+ torch.randn((1, patch_embedding.in_channels, 336, 336))
29
+ .to(device)
30
+ .to(patch_embedding.weight.dtype)
31
+ )
32
+ for i in range(100):
33
+ patch_embedding(image)
34
+
35
+
36
+ def _time_module(module, inputs, measure_iters=1000):
37
+ time_lis = []
38
+ # Warmup
39
+ for i in range(measure_iters):
40
+ module(inputs)
41
+ for i in range(measure_iters):
42
+ torch.cuda.synchronize()
43
+ st = time.time()
44
+ module(inputs)
45
+ torch.cuda.synchronize()
46
+ ed = time.time()
47
+ time_lis.append((ed - st))
48
+ return np.median(time_lis)
49
+
50
+
51
+ def tune_wqlinear(module: WQLinear, measure_iters: int = 1000):
52
+ device_warmup(str(module.scales.device))
53
+ inputs = torch.randn(
54
+ 1, module.in_features, device=module.scales.device, dtype=module.scales.dtype
55
+ )
56
+ best_split_k_iter = None
57
+ best_latency = None
58
+ for split_k_iters in [1, 2, 4, 8, 16, 32]:
59
+ module.split_k_iters = split_k_iters
60
+ cur_latency = _time_module(module, inputs, measure_iters)
61
+ if best_split_k_iter is None or best_latency >= cur_latency:
62
+ best_split_k_iter = split_k_iters
63
+ best_latency = cur_latency
64
+ module.split_k_iters = best_split_k_iter
65
+ return best_split_k_iter
66
+
67
+
68
+ def tune_all_wqlinears(model, measure_iters: int = 1000):
69
+ tuned_results = dict()
70
+ for name, module in model.named_modules():
71
+ if isinstance(module, WQLinear):
72
+ ic, oc = module.in_features, module.out_features
73
+ if (ic, oc) not in tuned_results:
74
+ print(f"Tuning {(ic, oc)}...")
75
+ split_k_iters = tune_wqlinear(module)
76
+ tuned_results[(ic, oc)] = split_k_iters
77
+ # write configs to model
78
+ for name, module in model.named_modules():
79
+ if isinstance(module, WQLinear):
80
+ ic, oc = module.in_features, module.out_features
81
+ module.split_k_iters = tuned_results[(ic, oc)]
lm-evaluation-harness/.coveragerc ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+
3
+ # tasks that aren't wired up.
4
+ omit =
5
+ lm_eval/tasks/quac.py
6
+ lm_eval/tasks/storycloze.py
7
+ lm_eval/tasks/cbt.py
8
+ lm_eval/tasks/sat.py
9
+ lm_eval/tasks/triviaqa.py
10
+ lm_eval/tasks/naturalqs.py
11
+ lm_eval/models/dummy.py
12
+
13
+ [report]
14
+ exclude_lines =
15
+ # Skip any pass lines such as may be used for @abstractmethod
16
+ pass
17
+
18
+ # Have to re-enable the standard pragma
19
+ pragma: no cover
20
+
21
+ # Don't complain about missing debug-only code:
22
+ def __repr__
23
+ if self\.debug
24
+
25
+ # Don't complain if tests don't hit defensive assertion code:
26
+ raise AssertionError
27
+ raise NotImplementedError
28
+ return NotImplemented
lm-evaluation-harness/.flake8 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [flake8]
2
+ ignore = E203, E266, E501, W503, F403, F401, C901
3
+ max-line-length = 127
4
+ max-complexity = 10
5
+ select = B,C,E,F,W,T4,B9
lm-evaluation-harness/.github/workflows/new_tasks.yml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tasks Modified
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - 'main'
7
+ pull_request:
8
+ branches:
9
+ - 'main'
10
+ workflow_dispatch:
11
+ # comment/edit out the above to stop/change the triggers
12
+ jobs:
13
+ changed_files:
14
+ runs-on: ubuntu-latest # windows-latest || macos-latest
15
+ timeout-minutes: 120
16
+ name: Scan for changed tasks
17
+ steps:
18
+ - name: checkout
19
+ uses: actions/checkout@v4
20
+ with:
21
+ fetch-depth: 2 # OR "2" -> To retrieve the preceding commit.
22
+
23
+ # Uses the tj-actions/changed-files action to check for changes.
24
+ # The `files_yaml` input optionally takes a yaml string to specify filters,
25
+ # and prepends the filter name to the standard output names.
26
+ - name: Check task folders
27
+ id: changed-tasks
28
+ uses: tj-actions/changed-files@v46.0.5
29
+ with:
30
+ # tasks checks the tasks folder and api checks the api folder for changes
31
+ files_yaml: |
32
+ tasks:
33
+ - lm_eval/tasks/**
34
+ api:
35
+ - lm_eval/api/**
36
+ write_output_files: true
37
+
38
+ # The next step is optional; the files are written to the workspace by default (above).
39
+ # so it's just for debugging
40
+ - name: Run Tests
41
+ if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
42
+ run: |
43
+ echo .github/outputs/tasks_all_changed_and_modified_files.txt >> 'GITHUB_ENV'
44
+ echo "One or more test file(s) has changed."
45
+ echo "List of all the files that have changed: ${{ steps.changed-tasks.outputs.tasks_all_modified_files }}"
46
+
47
+ - name: Set up Python 3.9
48
+ if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
49
+ uses: actions/setup-python@v5
50
+ with:
51
+ python-version: 3.9
52
+ cache: 'pip'
53
+ cache-dependency-path: setup.py
54
+ - name: Install dependencies
55
+ if: steps.changed-tasks.outputs.tasks_any_modified == 'true' || steps.changed-tasks.outputs.api_any_modified == 'true'
56
+ run: |
57
+ python -m pip install --upgrade pip
58
+ pip install -e '.[dev,ifeval]' --extra-index-url https://download.pytorch.org/whl/cpu
59
+ # Install optional git dependencies
60
+ # pip install bleurt@https://github.com/google-research/bleurt/archive/b610120347ef22b494b6d69b4316e303f5932516.zip#egg=bleurt
61
+ # if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
62
+ - name: Test with pytest
63
+ # if new tasks are added, run tests on them
64
+ if: steps.changed-tasks.outputs.tasks_any_modified == 'true'
65
+ run: python -m pytest tests/test_tasks.py -s -vv
66
+ # if api is modified, run tests on it
67
+ - name: Test more tasks with pytest
68
+ env:
69
+ API: true
70
+ if: steps.changed-tasks.outputs.api_any_modified == 'true'
71
+ run: python -m pytest tests/test_tasks.py -s -vv
lm-evaluation-harness/.github/workflows/publish.yml ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish Python distribution to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - '*'
7
+
8
+ jobs:
9
+ build:
10
+ name: Build distribution
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - name: Set up Python
16
+ uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.x"
19
+
20
+ - name: Check version consistency
21
+ run: |
22
+ # Extract version from pyproject.toml
23
+ PYPROJECT_VERSION=$(grep 'version = ' pyproject.toml | head -1 | cut -d'"' -f2)
24
+
25
+ # Extract version from __init__.py
26
+ INIT_VERSION=$(grep '__version__ = ' lm_eval/__init__.py | head -1 | cut -d'"' -f2)
27
+
28
+ echo "Version in pyproject.toml: $PYPROJECT_VERSION"
29
+ echo "Version in __init__.py: $INIT_VERSION"
30
+
31
+ # Check if versions match
32
+ if [ "$PYPROJECT_VERSION" != "$INIT_VERSION" ]; then
33
+ echo "Error: Version mismatch between pyproject.toml ($PYPROJECT_VERSION) and __init__.py ($INIT_VERSION)"
34
+ exit 1
35
+ fi
36
+
37
+ echo "Version check passed: $PYPROJECT_VERSION"
38
+
39
+ - name: Install pypa/build
40
+ run: >-
41
+ python3 -m
42
+ pip install
43
+ build
44
+ --user
45
+ - name: Build a binary wheel and a source tarball
46
+ run: python3 -m build
47
+ - name: Store the distribution packages
48
+ uses: actions/upload-artifact@v4
49
+ with:
50
+ name: python-package-distributions
51
+ path: dist/
52
+
53
+ publish-to-pypi:
54
+ name: >-
55
+ Publish Python distribution to PyPI
56
+ if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes
57
+ needs:
58
+ - build
59
+ runs-on: ubuntu-latest
60
+ environment:
61
+ name: pypi
62
+ url: https://pypi.org/p/lm_eval
63
+ permissions:
64
+ id-token: write # IMPORTANT: mandatory for trusted publishing
65
+
66
+ steps:
67
+ - name: Download all the dists
68
+ uses: actions/download-artifact@v4
69
+ with:
70
+ name: python-package-distributions
71
+ path: dist/
72
+ - name: Publish distribution to PyPI
73
+ uses: pypa/gh-action-pypi-publish@release/v1
74
+
75
+ publish-to-testpypi:
76
+ name: Publish Python distribution to TestPyPI
77
+ needs:
78
+ - build
79
+ runs-on: ubuntu-latest
80
+
81
+ environment:
82
+ name: testpypi
83
+ url: https://test.pypi.org/p/lm_eval
84
+
85
+ permissions:
86
+ id-token: write # IMPORTANT: mandatory for trusted publishing
87
+
88
+ steps:
89
+ - name: Download all the dists
90
+ uses: actions/download-artifact@v4
91
+ with:
92
+ name: python-package-distributions
93
+ path: dist/
94
+ - name: Publish distribution to TestPyPI
95
+ uses: pypa/gh-action-pypi-publish@release/v1
96
+ with:
97
+ repository-url: https://test.pypi.org/legacy/
lm-evaluation-harness/.github/workflows/unit_tests.yml ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
3
+ # just comment out unwanted steps to turn off the test.
4
+ name: Unit Tests
5
+
6
+ on:
7
+ push:
8
+ branches:
9
+ - 'main'
10
+ pull_request:
11
+ branches:
12
+ - 'main'
13
+ workflow_dispatch:
14
+ # Jobs run concurrently and steps run sequentially within a job.
15
+ # jobs: linter and cpu_tests. Add more jobs/steps as required.
16
+ jobs:
17
+ linter:
18
+ name: Linters
19
+ runs-on: ubuntu-latest
20
+ timeout-minutes: 5
21
+
22
+ steps:
23
+ - name: Checkout Code
24
+ uses: actions/checkout@v4
25
+ - name: Set up Python 3.9
26
+ uses: actions/setup-python@v5
27
+ with:
28
+ python-version: 3.9
29
+ cache: pip
30
+ cache-dependency-path: pyproject.toml
31
+ - name: Pre-Commit
32
+ env:
33
+ SKIP: "no-commit-to-branch,mypy"
34
+ uses: pre-commit/action@v3.0.1
35
+ # Job 2
36
+ testcpu:
37
+ name: CPU Tests
38
+ runs-on: ubuntu-latest
39
+ strategy:
40
+ fail-fast: true
41
+ matrix:
42
+ python-version: ["3.9", "3.10", "3.11"]
43
+ timeout-minutes: 30
44
+ steps:
45
+ - name: Checkout Code
46
+ uses: actions/checkout@v4
47
+ - name: Set up Python ${{ matrix.python-version }}
48
+ uses: actions/setup-python@v5
49
+ with:
50
+ python-version: ${{ matrix.python-version }}
51
+ cache: pip
52
+ cache-dependency-path: pyproject.toml
53
+
54
+ # Cache HuggingFace cache directory for CPU tests
55
+ - name: Cache HuggingFace cache (CPU tests)
56
+ uses: actions/cache@v3
57
+ id: cache-hf-cpu
58
+ with:
59
+ path: ~/.cache/huggingface
60
+ key: ${{ runner.os }}-hf-cache-cpu
61
+ restore-keys: |
62
+ ${{ runner.os }}-hf-cache-cpu
63
+
64
+ - name: Install dependencies
65
+ run: |
66
+ python -m pip install --upgrade pip
67
+ pip install -e '.[dev]' --extra-index-url https://download.pytorch.org/whl/cpu
68
+ pip install hf_xet
69
+
70
+ - name: Test with pytest
71
+ run: python -m pytest --showlocals -s -vv -n=auto --ignore=tests/models/test_neuralmagic.py --ignore=tests/models/test_openvino.py --ignore=tests/models/test_hf_steered.py
72
+ continue-on-error: true # Continue workflow even if tests fail
73
+
74
+ # Save test artifacts
75
+ - name: Archive test artifacts
76
+ uses: actions/upload-artifact@v4
77
+ with:
78
+ name: output_testcpu${{ matrix.python-version }}
79
+ path: |
80
+ test_logs/*
81
+
82
+ # testmodels:
83
+ # name: External LM Tests
84
+ # runs-on: ubuntu-latest
85
+ # timeout-minutes: 30
86
+ # steps:
87
+ # - name: Checkout Code
88
+ # uses: actions/checkout@v4
89
+ # - name: Set up Python 3.9
90
+ # uses: actions/setup-python@v5
91
+ # with:
92
+ # python-version: 3.9
93
+ # cache: pip
94
+ # cache-dependency-path: pyproject.toml
95
+ #
96
+ # # Cache HuggingFace cache directory for External LM tests
97
+ # - name: Cache HuggingFace cache (External LM tests)
98
+ # uses: actions/cache@v3
99
+ # id: cache-hf-lm
100
+ # with:
101
+ # path: ~/.cache/huggingface
102
+ # key: ${{ runner.os }}-hf-cache-external-lm
103
+ # restore-keys: |
104
+ # ${{ runner.os }}-hf-cache-external-lm
105
+ #
106
+ # - name: Install dependencies
107
+ # run: |
108
+ # python -m pip install --upgrade pip
109
+ # pip install -e '.[dev,optimum,deepsparse,sparseml,api]' --extra-index-url https://download.pytorch.org/whl/cpu
110
+ # pip install -U transformers peft accelerate
111
+ #
112
+ # - name: Test with pytest
113
+ # run: python -m pytest tests/models --showlocals -s -vv
114
+ # continue-on-error: true # Continue workflow even if tests fail
lm-evaluation-harness/CITATION.bib ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ @misc{eval-harness,
2
+ author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy},
3
+ title = {A framework for few-shot language model evaluation},
4
+ month = 12,
5
+ year = 2023,
6
+ publisher = {Zenodo},
7
+ version = {v0.4.0},
8
+ doi = {10.5281/zenodo.10256836},
9
+ url = {https://zenodo.org/records/10256836}
10
+ }
lm-evaluation-harness/CODEOWNERS ADDED
@@ -0,0 +1 @@
 
 
1
+ * @baberabb @stellaathena
lm-evaluation-harness/LICENSE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 EleutherAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
lm-evaluation-harness/MANIFEST.in ADDED
@@ -0,0 +1 @@
 
 
1
+ recursive-include tests
lm-evaluation-harness/README.md ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Language Model Evaluation Harness
2
+
3
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10256836.svg)](https://doi.org/10.5281/zenodo.10256836)
4
+
5
+ ---
6
+
7
+ ## Latest News 📣
8
+
9
+ - [2025/03] Added support for steering HF models!
10
+ - [2025/02] Added [SGLang](https://docs.sglang.ai/) support!
11
+ - [2024/09] We are prototyping allowing users of LM Evaluation Harness to create and evaluate on text+image multimodal input, text output tasks, and have just added the `hf-multimodal` and `vllm-vlm` model types and `mmmu` task as a prototype feature. We welcome users to try out this in-progress feature and stress-test it for themselves, and suggest they check out [`lmms-eval`](https://github.com/EvolvingLMMs-Lab/lmms-eval), a wonderful project originally forking off of the lm-evaluation-harness, for a broader range of multimodal tasks, models, and features.
12
+ - [2024/07] [API model](docs/API_guide.md) support has been updated and refactored, introducing support for batched and async requests, and making it significantly easier to customize and use for your own purposes. **To run Llama 405B, we recommend using VLLM's OpenAI-compliant API to host the model, and use the `local-completions` model type to evaluate the model.**
13
+ - [2024/07] New Open LLM Leaderboard tasks have been added ! You can find them under the [leaderboard](lm_eval/tasks/leaderboard/README.md) task group.
14
+
15
+ ---
16
+
17
+ ## Announcement
18
+
19
+ **A new v0.4.0 release of lm-evaluation-harness is available** !
20
+
21
+ New updates and features include:
22
+
23
+ - **New Open LLM Leaderboard tasks have been added ! You can find them under the [leaderboard](lm_eval/tasks/leaderboard/README.md) task group.**
24
+ - Internal refactoring
25
+ - Config-based task creation and configuration
26
+ - Easier import and sharing of externally-defined task config YAMLs
27
+ - Support for Jinja2 prompt design, easy modification of prompts + prompt imports from Promptsource
28
+ - More advanced configuration options, including output post-processing, answer extraction, and multiple LM generations per document, configurable fewshot settings, and more
29
+ - Speedups and new modeling libraries supported, including: faster data-parallel HF model usage, vLLM support, MPS support with HuggingFace, and more
30
+ - Logging and usability changes
31
+ - New tasks including CoT BIG-Bench-Hard, Belebele, user-defined task groupings, and more
32
+
33
+ Please see our updated documentation pages in `docs/` for more details.
34
+
35
+ Development will be continuing on the `main` branch, and we encourage you to give us feedback on what features are desired and how to improve the library further, or ask questions, either in issues or PRs on GitHub, or in the [EleutherAI discord](https://discord.gg/eleutherai)!
36
+
37
+ ---
38
+
39
+ ## Overview
40
+
41
+ This project provides a unified framework to test generative language models on a large number of different evaluation tasks.
42
+
43
+ **Features:**
44
+
45
+ - Over 60 standard academic benchmarks for LLMs, with hundreds of subtasks and variants implemented.
46
+ - Support for models loaded via [transformers](https://github.com/huggingface/transformers/) (including quantization via [GPTQModel](https://github.com/ModelCloud/GPTQModel) and [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)), [GPT-NeoX](https://github.com/EleutherAI/gpt-neox), and [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/), with a flexible tokenization-agnostic interface.
47
+ - Support for fast and memory-efficient inference with [vLLM](https://github.com/vllm-project/vllm).
48
+ - Support for commercial APIs including [OpenAI](https://openai.com), and [TextSynth](https://textsynth.com/).
49
+ - Support for evaluation on adapters (e.g. LoRA) supported in [HuggingFace's PEFT library](https://github.com/huggingface/peft).
50
+ - Support for local models and benchmarks.
51
+ - Evaluation with publicly available prompts ensures reproducibility and comparability between papers.
52
+ - Easy support for custom prompts and evaluation metrics.
53
+
54
+ The Language Model Evaluation Harness is the backend for 🤗 Hugging Face's popular [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard), has been used in [hundreds of papers](https://scholar.google.com/scholar?oi=bibs&hl=en&authuser=2&cites=15052937328817631261,4097184744846514103,1520777361382155671,17476825572045927382,18443729326628441434,14801318227356878622,7890865700763267262,12854182577605049984,15641002901115500560,5104500764547628290), and is used internally by dozens of organizations including NVIDIA, Cohere, BigScience, BigCode, Nous Research, and Mosaic ML.
55
+
56
+ ## Install
57
+
58
+ To install the `lm-eval` package from the github repository, run:
59
+
60
+ ```bash
61
+ git clone --depth 1 https://github.com/EleutherAI/lm-evaluation-harness
62
+ cd lm-evaluation-harness
63
+ pip install -e .
64
+ ```
65
+
66
+ We also provide a number of optional dependencies for extended functionality. A detailed table is available at the end of this document.
67
+
68
+ ## Basic Usage
69
+
70
+ ### User Guide
71
+
72
+ A user guide detailing the full list of supported arguments is provided [here](./docs/interface.md), and on the terminal by calling `lm_eval -h`. Alternatively, you can use `lm-eval` instead of `lm_eval`.
73
+
74
+ A list of supported tasks (or groupings of tasks) can be viewed with `lm-eval --tasks list`. Task descriptions and links to corresponding subfolders are provided [here](./lm_eval/tasks/README.md).
75
+
76
+ ### Hugging Face `transformers`
77
+
78
+ To evaluate a model hosted on the [HuggingFace Hub](https://huggingface.co/models) (e.g. GPT-J-6B) on `hellaswag` you can use the following command (this assumes you are using a CUDA-compatible GPU):
79
+
80
+ ```bash
81
+ lm_eval --model hf \
82
+ --model_args pretrained=EleutherAI/gpt-j-6B \
83
+ --tasks hellaswag \
84
+ --device cuda:0 \
85
+ --batch_size 8
86
+ ```
87
+
88
+ Additional arguments can be provided to the model constructor using the `--model_args` flag. Most notably, this supports the common practice of using the `revisions` feature on the Hub to store partially trained checkpoints, or to specify the datatype for running a model:
89
+
90
+ ```bash
91
+ lm_eval --model hf \
92
+ --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \
93
+ --tasks lambada_openai,hellaswag \
94
+ --device cuda:0 \
95
+ --batch_size 8
96
+ ```
97
+
98
+ Models that are loaded via both `transformers.AutoModelForCausalLM` (autoregressive, decoder-only GPT style models) and `transformers.AutoModelForSeq2SeqLM` (such as encoder-decoder models like T5) in Huggingface are supported.
99
+
100
+ Batch size selection can be automated by setting the ```--batch_size``` flag to ```auto```. This will perform automatic detection of the largest batch size that will fit on your device. On tasks where there is a large difference between the longest and shortest example, it can be helpful to periodically recompute the largest batch size, to gain a further speedup. To do this, append ```:N``` to above flag to automatically recompute the largest batch size ```N``` times. For example, to recompute the batch size 4 times, the command would be:
101
+
102
+ ```bash
103
+ lm_eval --model hf \
104
+ --model_args pretrained=EleutherAI/pythia-160m,revision=step100000,dtype="float" \
105
+ --tasks lambada_openai,hellaswag \
106
+ --device cuda:0 \
107
+ --batch_size auto:4
108
+ ```
109
+
110
+ > [!Note]
111
+ > Just like you can provide a local path to `transformers.AutoModel`, you can also provide a local path to `lm_eval` via `--model_args pretrained=/path/to/model`
112
+
113
+ #### Multi-GPU Evaluation with Hugging Face `accelerate`
114
+
115
+ We support three main ways of using Hugging Face's [accelerate 🚀](https://github.com/huggingface/accelerate) library for multi-GPU evaluation.
116
+
117
+ To perform *data-parallel evaluation* (where each GPU loads a **separate full copy** of the model), we leverage the `accelerate` launcher as follows:
118
+
119
+ ```bash
120
+ accelerate launch -m lm_eval --model hf \
121
+ --tasks lambada_openai,arc_easy \
122
+ --batch_size 16
123
+ ```
124
+
125
+ (or via `accelerate launch --no-python lm_eval`).
126
+
127
+ For cases where your model can fit on a single GPU, this allows you to evaluate on K GPUs K times faster than on one.
128
+
129
+ **WARNING**: This setup does not work with FSDP model sharding, so in `accelerate config` FSDP must be disabled, or the NO_SHARD FSDP option must be used.
130
+
131
+ The second way of using `accelerate` for multi-GPU evaluation is when your model is *too large to fit on a single GPU.*
132
+
133
+ In this setting, run the library *outside the `accelerate` launcher*, but passing `parallelize=True` to `--model_args` as follows:
134
+
135
+ ```bash
136
+ lm_eval --model hf \
137
+ --tasks lambada_openai,arc_easy \
138
+ --model_args parallelize=True \
139
+ --batch_size 16
140
+ ```
141
+
142
+ This means that your model's weights will be split across all available GPUs.
143
+
144
+ For more advanced users or even larger models, we allow for the following arguments when `parallelize=True` as well:
145
+
146
+ - `device_map_option`: How to split model weights across available GPUs. defaults to "auto".
147
+ - `max_memory_per_gpu`: the max GPU memory to use per GPU in loading the model.
148
+ - `max_cpu_memory`: the max amount of CPU memory to use when offloading the model weights to RAM.
149
+ - `offload_folder`: a folder where model weights will be offloaded to disk if needed.
150
+
151
+ The third option is to use both at the same time. This will allow you to take advantage of both data parallelism and model sharding, and is especially useful for models that are too large to fit on a single GPU.
152
+
153
+ ```bash
154
+ accelerate launch --multi_gpu --num_processes {nb_of_copies_of_your_model} \
155
+ -m lm_eval --model hf \
156
+ --tasks lambada_openai,arc_easy \
157
+ --model_args parallelize=True \
158
+ --batch_size 16
159
+ ```
160
+
161
+ To learn more about model parallelism and how to use it with the `accelerate` library, see the [accelerate documentation](https://huggingface.co/docs/transformers/v4.15.0/en/parallelism)
162
+
163
+ **Warning: We do not natively support multi-node evaluation using the `hf` model type! Please reference [our GPT-NeoX library integration](https://github.com/EleutherAI/gpt-neox/blob/main/eval.py) for an example of code in which a custom multi-machine evaluation script is written.**
164
+
165
+ **Note: we do not currently support multi-node evaluations natively, and advise using either an externally hosted server to run inference requests against, or creating a custom integration with your distributed framework [as is done for the GPT-NeoX library](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py).**
166
+
167
+ ### Steered Hugging Face `transformers` models
168
+
169
+ To evaluate a Hugging Face `transformers` model with steering vectors applied, specify the model type as `steered` and provide the path to either a PyTorch file containing pre-defined steering vectors, or a CSV file that specifies how to derive steering vectors from pretrained `sparsify` or `sae_lens` models (you will need to install the corresponding optional dependency for this method).
170
+
171
+ Specify pre-defined steering vectors:
172
+
173
+ ```python
174
+ import torch
175
+
176
+ steer_config = {
177
+ "layers.3": {
178
+ "steering_vector": torch.randn(1, 768),
179
+ "bias": torch.randn(1, 768),
180
+ "steering_coefficient": 1,
181
+ "action": "add"
182
+ },
183
+ }
184
+ torch.save(steer_config, "steer_config.pt")
185
+ ```
186
+
187
+ Specify derived steering vectors:
188
+
189
+ ```python
190
+ import pandas as pd
191
+
192
+ pd.DataFrame({
193
+ "loader": ["sparsify"],
194
+ "action": ["add"],
195
+ "sparse_model": ["EleutherAI/sae-pythia-70m-32k"],
196
+ "hookpoint": ["layers.3"],
197
+ "feature_index": [30],
198
+ "steering_coefficient": [10.0],
199
+ }).to_csv("steer_config.csv", index=False)
200
+ ```
201
+
202
+ Run the evaluation harness with steering vectors applied:
203
+
204
+ ```bash
205
+ lm_eval --model steered \
206
+ --model_args pretrained=EleutherAI/pythia-160m,steer_path=steer_config.pt \
207
+ --tasks lambada_openai,hellaswag \
208
+ --device cuda:0 \
209
+ --batch_size 8
210
+ ```
211
+
212
+ ### NVIDIA `nemo` models
213
+
214
+ [NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo) is a generative AI framework built for researchers and pytorch developers working on language models.
215
+
216
+ To evaluate a `nemo` model, start by installing NeMo following [the documentation](https://github.com/NVIDIA/NeMo?tab=readme-ov-file#installation). We highly recommended to use the NVIDIA PyTorch or NeMo container, especially if having issues installing Apex or any other dependencies (see [latest released containers](https://github.com/NVIDIA/NeMo/releases)). Please also install the lm evaluation harness library following the instructions in [the Install section](https://github.com/EleutherAI/lm-evaluation-harness/tree/main?tab=readme-ov-file#install).
217
+
218
+ NeMo models can be obtained through [NVIDIA NGC Catalog](https://catalog.ngc.nvidia.com/models) or in [NVIDIA's Hugging Face page](https://huggingface.co/nvidia). In [NVIDIA NeMo Framework](https://github.com/NVIDIA/NeMo/tree/main/scripts/nlp_language_modeling) there are conversion scripts to convert the `hf` checkpoints of popular models like llama, falcon, mixtral or mpt to `nemo`.
219
+
220
+ Run a `nemo` model on one GPU:
221
+
222
+ ```bash
223
+ lm_eval --model nemo_lm \
224
+ --model_args path=<path_to_nemo_model> \
225
+ --tasks hellaswag \
226
+ --batch_size 32
227
+ ```
228
+
229
+ It is recommended to unpack the `nemo` model to avoid the unpacking inside the docker container - it may overflow disk space. For that you can run:
230
+
231
+ ```bash
232
+ mkdir MY_MODEL
233
+ tar -xvf MY_MODEL.nemo -c MY_MODEL
234
+ ```
235
+
236
+ #### Multi-GPU evaluation with NVIDIA `nemo` models
237
+
238
+ By default, only one GPU is used. But we do support either data replication or tensor/pipeline parallelism during evaluation, on one node.
239
+
240
+ 1) To enable data replication, set the `model_args` of `devices` to the number of data replicas to run. For example, the command to run 8 data replicas over 8 GPUs is:
241
+
242
+ ```bash
243
+ torchrun --nproc-per-node=8 --no-python lm_eval \
244
+ --model nemo_lm \
245
+ --model_args path=<path_to_nemo_model>,devices=8 \
246
+ --tasks hellaswag \
247
+ --batch_size 32
248
+ ```
249
+
250
+ 1) To enable tensor and/or pipeline parallelism, set the `model_args` of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. In addition, you also have to set up `devices` to be equal to the product of `tensor_model_parallel_size` and/or `pipeline_model_parallel_size`. For example, the command to use one node of 4 GPUs with tensor parallelism of 2 and pipeline parallelism of 2 is:
251
+
252
+ ```bash
253
+ torchrun --nproc-per-node=4 --no-python lm_eval \
254
+ --model nemo_lm \
255
+ --model_args path=<path_to_nemo_model>,devices=4,tensor_model_parallel_size=2,pipeline_model_parallel_size=2 \
256
+ --tasks hellaswag \
257
+ --batch_size 32
258
+ ```
259
+
260
+ Note that it is recommended to substitute the `python` command by `torchrun --nproc-per-node=<number of devices> --no-python` to facilitate loading the model into the GPUs. This is especially important for large checkpoints loaded into multiple GPUs.
261
+
262
+ Not supported yet: multi-node evaluation and combinations of data replication with tensor or pipeline parallelism.
263
+
264
+ #### Multi-GPU evaluation with OpenVINO models
265
+
266
+ Pipeline parallelism during evaluation is supported with OpenVINO models
267
+
268
+ To enable pipeline parallelism, set the `model_args` of `pipeline_parallel`. In addition, you also have to set up `device` to value `HETERO:<GPU index1>,<GPU index2>` for example `HETERO:GPU.1,GPU.0` For example, the command to use pipeline parallelism of 2 is:
269
+
270
+ ```bash
271
+ lm_eval --model openvino \
272
+ --tasks wikitext \
273
+ --model_args pretrained=<path_to_ov_model>,pipeline_parallel=True \
274
+ --device HETERO:GPU.1,GPU.0
275
+ ```
276
+
277
+ ### Tensor + Data Parallel and Optimized Inference with `vLLM`
278
+
279
+ We also support vLLM for faster inference on [supported model types](https://docs.vllm.ai/en/latest/models/supported_models.html), especially faster when splitting a model across multiple GPUs. For single-GPU or multi-GPU — tensor parallel, data parallel, or a combination of both — inference, for example:
280
+
281
+ ```bash
282
+ lm_eval --model vllm \
283
+ --model_args pretrained={model_name},tensor_parallel_size={GPUs_per_model},dtype=auto,gpu_memory_utilization=0.8,data_parallel_size={model_replicas} \
284
+ --tasks lambada_openai \
285
+ --batch_size auto
286
+ ```
287
+
288
+ To use vllm, do `pip install lm_eval[vllm]`. For a full list of supported vLLM configurations, please reference our [vLLM integration](https://github.com/EleutherAI/lm-evaluation-harness/blob/e74ec966556253fbe3d8ecba9de675c77c075bce/lm_eval/models/vllm_causallms.py) and the vLLM documentation.
289
+
290
+ vLLM occasionally differs in output from Huggingface. We treat Huggingface as the reference implementation, and provide a [script](./scripts/model_comparator.py) for checking the validity of vllm results against HF.
291
+
292
+ > [!Tip]
293
+ > For fastest performance, we recommend using `--batch_size auto` for vLLM whenever possible, to leverage its continuous batching functionality!
294
+
295
+ > [!Tip]
296
+ > Passing `max_model_len=4096` or some other reasonable default to vLLM through model args may cause speedups or prevent out-of-memory errors when trying to use auto batch size, such as for Mistral-7B-v0.1 which defaults to a maximum length of 32k.
297
+
298
+ ### Tensor + Data Parallel and Fast Offline Batching Inference with `SGLang`
299
+
300
+ We support SGLang for efficient offline batch inference. Its **[Fast Backend Runtime](https://docs.sglang.ai/index.html)** delivers high performance through optimized memory management and parallel processing techniques. Key features include tensor parallelism, continuous batching, and support for various quantization methods (FP8/INT4/AWQ/GPTQ).
301
+
302
+ To use SGLang as the evaluation backend, please **install it in advance** via SGLang documents [here](https://docs.sglang.ai/start/install.html#install-sglang).
303
+
304
+ > [!Tip]
305
+ > Due to the installing method of [`Flashinfer`](https://docs.flashinfer.ai/)-- a fast attention kernel library, we don't include the dependencies of `SGLang` within [pyproject.toml](pyproject.toml). Note that the `Flashinfer` also has some requirements on `torch` version.
306
+
307
+ SGLang's server arguments are slightly different from other backends, see [here](https://docs.sglang.ai/backend/server_arguments.html) for more information. We provide an example of the usage here:
308
+
309
+ ```bash
310
+ lm_eval --model sglang \
311
+ --model_args pretrained={model_name},dp_size={data_parallel_size},tp_size={tensor_parallel_size},dtype=auto \
312
+ --tasks gsm8k_cot \
313
+ --batch_size auto
314
+ ```
315
+
316
+ > [!Tip]
317
+ > When encountering out of memory (OOM) errors (especially for multiple-choice tasks), try these solutions:
318
+ >
319
+ > 1. Use a manual `batch_size`, rather than `auto`.
320
+ > 2. Lower KV cache pool memory usage by adjusting `mem_fraction_static` - Add to your model arguments for example `--model_args pretrained=...,mem_fraction_static=0.7`.
321
+ > 3. Increase tensor parallel size `tp_size` (if using multiple GPUs).
322
+
323
+ ### Model APIs and Inference Servers
324
+
325
+ Our library also supports the evaluation of models served via several commercial APIs, and we hope to implement support for the most commonly used performant local/self-hosted inference servers.
326
+
327
+ To call a hosted model, use:
328
+
329
+ ```bash
330
+ export OPENAI_API_KEY=YOUR_KEY_HERE
331
+ lm_eval --model openai-completions \
332
+ --model_args model=davinci-002 \
333
+ --tasks lambada_openai,hellaswag
334
+ ```
335
+
336
+ We also support using your own local inference server with servers that mirror the OpenAI Completions and ChatCompletions APIs.
337
+
338
+ ```bash
339
+ lm_eval --model local-completions --tasks gsm8k --model_args model=facebook/opt-125m,base_url=http://{yourip}:8000/v1/completions,num_concurrent=1,max_retries=3,tokenized_requests=False,batch_size=16
340
+ ```
341
+
342
+ Note that for externally hosted models, configs such as `--device` which relate to where to place a local model should not be used and do not function. Just like you can use `--model_args` to pass arbitrary arguments to the model constructor for local models, you can use it to pass arbitrary arguments to the model API for hosted models. See the documentation of the hosting service for information on what arguments they support.
343
+
344
+ | API or Inference Server | Implemented? | `--model <xxx>` name | Models supported: | Request Types: |
345
+ | --------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|-----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------|
346
+ | OpenAI Completions | :heavy_check_mark: | `openai-completions`, `local-completions` | All OpenAI Completions API models | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
347
+ | OpenAI ChatCompletions | :heavy_check_mark: | `openai-chat-completions`, `local-chat-completions` | [All ChatCompletions API models](https://platform.openai.com/docs/guides/gpt) | `generate_until` (no logprobs) |
348
+ | Anthropic | :heavy_check_mark: | `anthropic` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/reference/selecting-a-model) | `generate_until` (no logprobs) |
349
+ | Anthropic Chat | :heavy_check_mark: | `anthropic-chat`, `anthropic-chat-completions` | [Supported Anthropic Engines](https://docs.anthropic.com/claude/docs/models-overview) | `generate_until` (no logprobs) |
350
+ | Textsynth | :heavy_check_mark: | `textsynth` | [All supported engines](https://textsynth.com/documentation.html#engines) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
351
+ | Cohere | [:hourglass: - blocked on Cohere API bug](https://github.com/EleutherAI/lm-evaluation-harness/pull/395) | N/A | [All `cohere.generate()` engines](https://docs.cohere.com/docs/models) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
352
+ | [Llama.cpp](https://github.com/ggerganov/llama.cpp) (via [llama-cpp-python](https://github.com/abetlen/llama-cpp-python)) | :heavy_check_mark: | `gguf`, `ggml` | [All models supported by llama.cpp](https://github.com/ggerganov/llama.cpp) | `generate_until`, `loglikelihood`, (perplexity evaluation not yet implemented) |
353
+ | vLLM | :heavy_check_mark: | `vllm` | [Most HF Causal Language Models](https://docs.vllm.ai/en/latest/models/supported_models.html) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
354
+ | Mamba | :heavy_check_mark: | `mamba_ssm` | [Mamba architecture Language Models via the `mamba_ssm` package](https://huggingface.co/state-spaces) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
355
+ | Huggingface Optimum (Causal LMs) | :heavy_check_mark: | `openvino` | Any decoder-only AutoModelForCausalLM converted with Huggingface Optimum into OpenVINO™ Intermediate Representation (IR) format | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
356
+ | Huggingface Optimum-intel IPEX (Causal LMs) | :heavy_check_mark: | `ipex` | Any decoder-only AutoModelForCausalLM | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
357
+ | Neuron via AWS Inf2 (Causal LMs) | :heavy_check_mark: | `neuronx` | Any decoder-only AutoModelForCausalLM supported to run on [huggingface-ami image for inferentia2](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
358
+ | [Neural Magic DeepSparse](https://github.com/neuralmagic/deepsparse) | :heavy_check_mark: | `deepsparse` | Any LM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub with the "deepsparse" tag](https://huggingface.co/models?other=deepsparse) | `generate_until`, `loglikelihood` |
359
+ | [Neural Magic SparseML](https://github.com/neuralmagic/sparseml) | :heavy_check_mark: | `sparseml` | Any decoder-only AutoModelForCausalLM from [SparseZoo](https://sparsezoo.neuralmagic.com/) or on [HF Hub](https://huggingface.co/neuralmagic). Especially useful for models with quantization like [`zoo:llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized`](https://sparsezoo.neuralmagic.com/models/llama2-7b-gsm8k_llama2_pretrain-pruned60_quantized) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
360
+ | NVIDIA NeMo | :heavy_check_mark: | `nemo_lm` | [All supported models](https://docs.nvidia.com/nemo-framework/user-guide/24.09/nemotoolkit/core/core.html#nemo-models) | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
361
+ | Watsonx.ai | :heavy_check_mark: | `watsonx_llm` | [Supported Watsonx.ai Engines](https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-models.html?context=wx) | `generate_until` `loglikelihood` |
362
+ | [Your local inference server!](docs/API_guide.md) | :heavy_check_mark: | `local-completions` or `local-chat-completions` | Support for OpenAI API-compatible servers, with easy customization for other APIs. | `generate_until`, `loglikelihood`, `loglikelihood_rolling` |
363
+
364
+ Models which do not supply logits or logprobs can be used with tasks of type `generate_until` only, while local models, or APIs that supply logprobs/logits of their prompts, can be run on all task types: `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`.
365
+
366
+ For more information on the different task `output_types` and model request types, see [our documentation](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/model_guide.md#interface).
367
+
368
+ > [!Note]
369
+ > For best performance with closed chat model APIs such as Anthropic Claude 3 and GPT-4, we recommend carefully looking at a few sample outputs using `--limit 10` first to confirm answer extraction and scoring on generative tasks is performing as expected. providing `system="<some system prompt here>"` within `--model_args` for anthropic-chat-completions, to instruct the model what format to respond in, may be useful.
370
+
371
+ ### Other Frameworks
372
+
373
+ A number of other libraries contain scripts for calling the eval harness through their library. These include [GPT-NeoX](https://github.com/EleutherAI/gpt-neox/blob/main/eval_tasks/eval_adapter.py), [Megatron-DeepSpeed](https://github.com/microsoft/Megatron-DeepSpeed/blob/main/examples/MoE/readme_evalharness.md), and [mesh-transformer-jax](https://github.com/kingoflolz/mesh-transformer-jax/blob/master/eval_harness.py).
374
+
375
+ To create your own custom integration you can follow instructions from [this tutorial](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md#external-library-usage).
376
+
377
+ ### Additional Features
378
+
379
+ > [!Note]
380
+ > For tasks unsuitable for direct evaluation — either due risks associated with executing untrusted code or complexities in the evaluation process — the `--predict_only` flag is available to obtain decoded generations for post-hoc evaluation.
381
+
382
+ If you have a Metal compatible Mac, you can run the eval harness using the MPS back-end by replacing `--device cuda:0` with `--device mps` (requires PyTorch version 2.1 or higher). **Note that the PyTorch MPS backend is still in early stages of development, so correctness issues or unsupported operations may exist. If you observe oddities in model performance on the MPS back-end, we recommend first checking that a forward pass of your model on `--device cpu` and `--device mps` match.**
383
+
384
+ > [!Note]
385
+ > You can inspect what the LM inputs look like by running the following command:
386
+ >
387
+ > ```bash
388
+ > python write_out.py \
389
+ > --tasks <task1,task2,...> \
390
+ > --num_fewshot 5 \
391
+ > --num_examples 10 \
392
+ > --output_base_path /path/to/output/folder
393
+ > ```
394
+ >
395
+ > This will write out one text file for each task.
396
+
397
+ To verify the data integrity of the tasks you're performing in addition to running the tasks themselves, you can use the `--check_integrity` flag:
398
+
399
+ ```bash
400
+ lm_eval --model openai \
401
+ --model_args engine=davinci-002 \
402
+ --tasks lambada_openai,hellaswag \
403
+ --check_integrity
404
+ ```
405
+
406
+ ## Advanced Usage Tips
407
+
408
+ For models loaded with the HuggingFace `transformers` library, any arguments provided via `--model_args` get passed to the relevant constructor directly. This means that anything you can do with `AutoModel` can be done with our library. For example, you can pass a local path via `pretrained=` or use models finetuned with [PEFT](https://github.com/huggingface/peft) by taking the call you would run to evaluate the base model and add `,peft=PATH` to the `model_args` argument:
409
+
410
+ ```bash
411
+ lm_eval --model hf \
412
+ --model_args pretrained=EleutherAI/gpt-j-6b,parallelize=True,load_in_4bit=True,peft=nomic-ai/gpt4all-j-lora \
413
+ --tasks openbookqa,arc_easy,winogrande,hellaswag,arc_challenge,piqa,boolq \
414
+ --device cuda:0
415
+ ```
416
+
417
+ Models provided as delta weights can be easily loaded using the Hugging Face transformers library. Within --model_args, set the delta argument to specify the delta weights, and use the pretrained argument to designate the relative base model to which they will be applied:
418
+
419
+ ```bash
420
+ lm_eval --model hf \
421
+ --model_args pretrained=Ejafa/llama_7B,delta=lmsys/vicuna-7b-delta-v1.1 \
422
+ --tasks hellaswag
423
+ ```
424
+
425
+ GPTQ quantized models can be loaded using [GPTQModel](https://github.com/ModelCloud/GPTQModel) (faster) or [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ)
426
+
427
+ GPTQModel: add `,gptqmodel=True` to `model_args`
428
+
429
+ ```bash
430
+ lm_eval --model hf \
431
+ --model_args pretrained=model-name-or-path,gptqmodel=True \
432
+ --tasks hellaswag
433
+ ```
434
+
435
+ AutoGPTQ: add `,autogptq=True` to `model_args`:
436
+
437
+ ```bash
438
+ lm_eval --model hf \
439
+ --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \
440
+ --tasks hellaswag
441
+ ```
442
+
443
+ We support wildcards in task names, for example you can run all of the machine-translated lambada tasks via `--task lambada_openai_mt_*`.
444
+
445
+ ## Saving & Caching Results
446
+
447
+ To save evaluation results provide an `--output_path`. We also support logging model responses with the `--log_samples` flag for post-hoc analysis.
448
+
449
+ > [!TIP]
450
+ > Use `--use_cache <DIR>` to cache evaluation results and skip previously evaluated samples when resuming runs of the same (model, task) pairs. Note that caching is rank-dependent, so restart with the same GPU count if interrupted. You can also use --cache_requests to save dataset preprocessing steps for faster evaluation resumption.
451
+
452
+ To push results and samples to the Hugging Face Hub, first ensure an access token with write access is set in the `HF_TOKEN` environment variable. Then, use the `--hf_hub_log_args` flag to specify the organization, repository name, repository visibility, and whether to push results and samples to the Hub - [example dataset on the HF Hub](https://huggingface.co/datasets/KonradSzafer/lm-eval-results-demo). For instance:
453
+
454
+ ```bash
455
+ lm_eval --model hf \
456
+ --model_args pretrained=model-name-or-path,autogptq=model.safetensors,gptq_use_triton=True \
457
+ --tasks hellaswag \
458
+ --log_samples \
459
+ --output_path results \
460
+ --hf_hub_log_args hub_results_org=EleutherAI,hub_repo_name=lm-eval-results,push_results_to_hub=True,push_samples_to_hub=True,public_repo=False \
461
+ ```
462
+
463
+ This allows you to easily download the results and samples from the Hub, using:
464
+
465
+ ```python
466
+ from datasets import load_dataset
467
+
468
+ load_dataset("EleutherAI/lm-eval-results-private", "hellaswag", "latest")
469
+ ```
470
+
471
+ For a full list of supported arguments, check out the [interface](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md) guide in our documentation!
472
+
473
+ ## Visualizing Results
474
+
475
+ You can seamlessly visualize and analyze the results of your evaluation harness runs using both Weights & Biases (W&B) and Zeno.
476
+
477
+ ### Zeno
478
+
479
+ You can use [Zeno](https://zenoml.com) to visualize the results of your eval harness runs.
480
+
481
+ First, head to [hub.zenoml.com](https://hub.zenoml.com) to create an account and get an API key [on your account page](https://hub.zenoml.com/account).
482
+ Add this key as an environment variable:
483
+
484
+ ```bash
485
+ export ZENO_API_KEY=[your api key]
486
+ ```
487
+
488
+ You'll also need to install the `lm_eval[zeno]` package extra.
489
+
490
+ To visualize the results, run the eval harness with the `log_samples` and `output_path` flags.
491
+ We expect `output_path` to contain multiple folders that represent individual model names.
492
+ You can thus run your evaluation on any number of tasks and models and upload all of the results as projects on Zeno.
493
+
494
+ ```bash
495
+ lm_eval \
496
+ --model hf \
497
+ --model_args pretrained=EleutherAI/gpt-j-6B \
498
+ --tasks hellaswag \
499
+ --device cuda:0 \
500
+ --batch_size 8 \
501
+ --log_samples \
502
+ --output_path output/gpt-j-6B
503
+ ```
504
+
505
+ Then, you can upload the resulting data using the `zeno_visualize` script:
506
+
507
+ ```bash
508
+ python scripts/zeno_visualize.py \
509
+ --data_path output \
510
+ --project_name "Eleuther Project"
511
+ ```
512
+
513
+ This will use all subfolders in `data_path` as different models and upload all tasks within these model folders to Zeno.
514
+ If you run the eval harness on multiple tasks, the `project_name` will be used as a prefix and one project will be created per task.
515
+
516
+ You can find an example of this workflow in [examples/visualize-zeno.ipynb](examples/visualize-zeno.ipynb).
517
+
518
+ ### Weights and Biases
519
+
520
+ With the [Weights and Biases](https://wandb.ai/site) integration, you can now spend more time extracting deeper insights into your evaluation results. The integration is designed to streamline the process of logging and visualizing experiment results using the Weights & Biases (W&B) platform.
521
+
522
+ The integration provide functionalities
523
+
524
+ - to automatically log the evaluation results,
525
+ - log the samples as W&B Tables for easy visualization,
526
+ - log the `results.json` file as an artifact for version control,
527
+ - log the `<task_name>_eval_samples.json` file if the samples are logged,
528
+ - generate a comprehensive report for analysis and visualization with all the important metric,
529
+ - log task and cli specific configs,
530
+ - and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc.
531
+
532
+ First you'll need to install the lm_eval[wandb] package extra. Do `pip install lm_eval[wandb]`.
533
+
534
+ Authenticate your machine with an your unique W&B token. Visit https://wandb.ai/authorize to get one. Do `wandb login` in your command line terminal.
535
+
536
+ Run eval harness as usual with a `wandb_args` flag. Use this flag to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments.
537
+
538
+ ```bash
539
+ lm_eval \
540
+ --model hf \
541
+ --model_args pretrained=microsoft/phi-2,trust_remote_code=True \
542
+ --tasks hellaswag,mmlu_abstract_algebra \
543
+ --device cuda:0 \
544
+ --batch_size 8 \
545
+ --output_path output/phi-2 \
546
+ --limit 10 \
547
+ --wandb_args project=lm-eval-harness-integration \
548
+ --log_samples
549
+ ```
550
+
551
+ In the stdout, you will find the link to the W&B run page as well as link to the generated report. You can find an example of this workflow in [examples/visualize-wandb.ipynb](examples/visualize-wandb.ipynb), and an example of how to integrate it beyond the CLI.
552
+
553
+ ## How to Contribute or Learn More?
554
+
555
+ For more information on the library and how everything fits together, check out all of our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)! We plan to post a larger roadmap of desired + planned library improvements soon, with more information on how contributors can help.
556
+
557
+ ### Implementing new tasks
558
+
559
+ To implement a new task in the eval harness, see [this guide](./docs/new_task_guide.md).
560
+
561
+ In general, we follow this priority list for addressing concerns about prompting and other eval details:
562
+
563
+ 1. If there is widespread agreement among people who train LLMs, use the agreed upon procedure.
564
+ 2. If there is a clear and unambiguous official implementation, use that procedure.
565
+ 3. If there is widespread agreement among people who evaluate LLMs, use the agreed upon procedure.
566
+ 4. If there are multiple common implementations but not universal or widespread agreement, use our preferred option among the common implementations. As before, prioritize choosing from among the implementations found in LLM training papers.
567
+
568
+ These are guidelines and not rules, and can be overruled in special circumstances.
569
+
570
+ We try to prioritize agreement with the procedures used by other groups to decrease the harm when people inevitably compare runs across different papers despite our discouragement of the practice. Historically, we also prioritized the implementation from [Language Models are Few Shot Learners](https://arxiv.org/abs/2005.14165) as our original goal was specifically to compare results with that paper.
571
+
572
+ ### Support
573
+
574
+ The best way to get support is to open an issue on this repo or join the [EleutherAI Discord server](https://discord.gg/eleutherai). The `#lm-thunderdome` channel is dedicated to developing this project and the `#release-discussion` channel is for receiving support for our releases. If you've used the library and have had a positive (or negative) experience, we'd love to hear from you!
575
+
576
+ ## Optional Extras
577
+
578
+ Extras dependencies can be installed via `pip install -e ".[NAME]"`
579
+
580
+ | Name | Use |
581
+ | -------------------- | ----------------------------------------------------- |
582
+ | api | For using api models (Anthropic, OpenAI API) |
583
+ | audiolm_qwen | For running Qwen2 audio models |
584
+ | deepsparse | For running NM's DeepSparse models |
585
+ | dev | For linting PRs and contributions |
586
+ | gptq | For loading models with AutoGPTQ |
587
+ | gptqmodel | For loading models with GPTQModel |
588
+ | hf_transfer | For speeding up HF Hub file downloads |
589
+ | ibm_watsonx_ai | For using IBM watsonx.ai model apis |
590
+ | ifeval | For running the IFEval task |
591
+ | ipex | For running on optimum-intel ipex backend |
592
+ | japanese_leaderboard | For running Japanese LLM Leaderboard tasks |
593
+ | longbench | For running LongBench tasks |
594
+ | mamba | For loading Mamba SSM models |
595
+ | math | For running math task answer checking |
596
+ | multilingual | For multilingual tokenizers |
597
+ | neuronx | For running on AWS inf2 instances |
598
+ | optimum | For running Intel OpenVINO models |
599
+ | promptsource | For using PromptSource prompts |
600
+ | ruler | For running RULER tasks |
601
+ | sae_lens | For using SAELens to steer models |
602
+ | sentencepiece | For using the sentencepiece tokenizer |
603
+ | sparseml | For using NM's SparseML models |
604
+ | sparsify | For using Sparsify to steer models |
605
+ | testing | For running library test suite |
606
+ | vllm | For loading models with vLLM |
607
+ | wandb | For integration with `Weights and Biases` platform |
608
+ | zeno | For visualizing results with Zeno |
609
+ | -------------------- | ----------------------------------------------------- |
610
+ | all | Loads all extras (not recommended) |
611
+
612
+ ## Cite as
613
+
614
+ ```text
615
+ @misc{eval-harness,
616
+ author = {Gao, Leo and Tow, Jonathan and Abbasi, Baber and Biderman, Stella and Black, Sid and DiPofi, Anthony and Foster, Charles and Golding, Laurence and Hsu, Jeffrey and Le Noac'h, Alain and Li, Haonan and McDonell, Kyle and Muennighoff, Niklas and Ociepa, Chris and Phang, Jason and Reynolds, Laria and Schoelkopf, Hailey and Skowron, Aviya and Sutawika, Lintang and Tang, Eric and Thite, Anish and Wang, Ben and Wang, Kevin and Zou, Andy},
617
+ title = {The Language Model Evaluation Harness},
618
+ month = 07,
619
+ year = 2024,
620
+ publisher = {Zenodo},
621
+ version = {v0.4.3},
622
+ doi = {10.5281/zenodo.12608602},
623
+ url = {https://zenodo.org/records/12608602}
624
+ }
625
+ ```
lm-evaluation-harness/compute_score.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from typing import Dict, Any, Optional, List, Union, Tuple
3
+
4
+ import re
5
+
6
+ def extract_number_before_year(file_path: str) -> str | None:
7
+ """
8
+ 从文件路径中提取年份(四位数字)前的数字
9
+
10
+ Args:
11
+ file_path: 待处理的文件路径字符串
12
+
13
+ Returns:
14
+ 提取到的数字字符串(如"0");若未找到匹配项,返回None
15
+
16
+ Example:
17
+ >>> path = "/xxx/self_attn_Llama-2-7b-hf_0_2025-11-27.json"
18
+ >>> extract_number_before_year(path)
19
+ '0'
20
+ """
21
+ # 正则模式解释:
22
+ # _(\d+)_ 匹配下划线+一串数字+下划线(括号捕获数字)
23
+ # \d{4} 匹配四位数字(年份,如2025、2024)
24
+ pattern = r'_(\d+)_\d{4}'
25
+
26
+ # 执行正则匹配
27
+ match = re.search(pattern, file_path)
28
+
29
+ # 返回结果:有匹配则返回捕获的数字,否则返回None
30
+ return match.group(1) if match else None
31
+
32
+
33
+
34
+ def read_json_acc_scores(
35
+ file_path: str,
36
+ target_keys: Optional[Union[str, List[str]]] = None
37
+ ) -> Union[float, Tuple[Dict[str, float], float]]:
38
+ """
39
+ 读取JSON文件中的results数据,提取并计算acc,none分数
40
+
41
+ Args:
42
+ file_path: JSON文件的路径
43
+ target_keys: 要提取的key(单个字符串或字符串列表),为None时处理全部results
44
+
45
+ Returns:
46
+ - 单个key时:返回对应的acc,none分数(float)
47
+ - 多个key/全部时:返回(各key的acc分数字典, 平均分)
48
+
49
+ Raises:
50
+ FileNotFoundError: 文件不存在时抛出
51
+ json.JSONDecodeError: JSON格式错误时抛出
52
+ KeyError: 指定的key不存在或缺少acc,none字段时抛出
53
+ """
54
+
55
+ benchmark_metrics = {
56
+ "piqa": "acc,none",
57
+ "hellaswag": "acc_norm,none",
58
+ "arc_challenge": "acc_norm,none",
59
+ "boolq": "acc,none",
60
+ "winogrande": "acc,none",
61
+ }
62
+ try:
63
+ # 打开并读取JSON文件
64
+ with open(file_path, 'r', encoding='utf-8') as f:
65
+ data = json.load(f)
66
+
67
+ # 提取results部分
68
+ results = data.get('results', {})
69
+ if not results:
70
+ raise KeyError("JSON文件中未找到'results'字段")
71
+
72
+ # 确定要处理的keys
73
+ if target_keys is None:
74
+ process_keys = list(results.keys()) # 全部keys
75
+ elif isinstance(target_keys, str):
76
+ process_keys = [target_keys] # 单个key转为列表处理
77
+ elif isinstance(target_keys, list):
78
+ process_keys = target_keys # 列表keys
79
+ else:
80
+ raise TypeError("target_keys参数必须是字符串、列表或None")
81
+
82
+ # 验证keys是否存在并提取acc,none分数
83
+ acc_scores = {}
84
+ conc_ans = 0
85
+ for key in benchmark_metrics:
86
+ if key not in results:
87
+ continue
88
+
89
+ acc_scores[key] = results[key][benchmark_metrics[key]]
90
+ conc_ans += results[key][benchmark_metrics[key]]
91
+
92
+ # 多个key或全部,返回分数字典和平均分
93
+ # average_score = sum(acc_scores.values()) / len(acc_scores)
94
+ return acc_scores, conc_ans
95
+
96
+ except FileNotFoundError:
97
+ raise FileNotFoundError(f"文件不存在: {file_path}")
98
+ except json.JSONDecodeError:
99
+ raise json.JSONDecodeError("JSON文件格式错误", file_path, 0)
100
+
101
+ import os
102
+ def get_all_paths(folder):
103
+ """用os模块获取路径下所有文件/目录的完整路径"""
104
+ all_paths = []
105
+ # 先获取当前目录下的所有内容
106
+ for name in os.listdir(folder):
107
+ full_path = os.path.join(folder, name)
108
+ all_paths.append(full_path)
109
+ # 如果是目录,递归进去继续获取
110
+ return all_paths
111
+
112
+ dir_path = \
113
+ "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Qwen2.5-14B-quantization-layer"
114
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results3/Llama-3.1-8B-quantization-layer-mlp"
115
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Llama-3.1-8B-quantization-layer"
116
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Qwen2.5-7B-quantization-layer"
117
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results3/Llama-3.1-8B-quantization-layer-mlp"
118
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Llama-3.1-8B-quantization-layer"
119
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Qwen2.5-7B-quantization-layer"
120
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results3/Llama-3.1-8B-quantization-layer-mlp"
121
+ # "/mnt/bn/life-mllm/users/cxr/quantization/lm-evaluation-harness/results2/Qwen2.5-7B-quantization-layer"
122
+
123
+ mode = "self_attn"
124
+
125
+
126
+ paths = get_all_paths(dir_path)
127
+
128
+ filter_paths = [path for path in paths if mode in path]
129
+ print(filter_paths)
130
+ total_score = [0 for _ in range(len(filter_paths)-1)]
131
+ for filter_path in filter_paths:
132
+ final_paths = get_all_paths(filter_path)
133
+ idx = filter_path.split("/")[-1]
134
+ ans = []
135
+ for final_path in final_paths:
136
+ acc_scores, conc_ans = read_json_acc_scores(final_path)
137
+ # print(acc_scores)
138
+ if conc_ans !=0:
139
+ ans.append(conc_ans)
140
+ print(idx, sum(ans)/len(ans))
141
+ if int(idx.split("_")[-1]) != -1:
142
+ total_score[int(idx.split("_")[-1])] = sum(ans)/len(ans)
143
+ print("total_score:", total_score)
144
+
145
+ index_value_pairs = list(enumerate(total_score))
146
+ # 步骤2:按数值从大到小排序(key=lambda x: x[1] 取元组的第二个值作为排序依据,reverse=True 降序)
147
+ sorted_pairs = sorted(index_value_pairs, key=lambda x: x[1], reverse=True)
148
+
149
+ # 步骤3:提取排序后的索引
150
+ sorted_indices = [pair[0] for pair in sorted_pairs]
151
+ print(sorted_indices)
152
+ print(' '.join(str(num) for num in sorted_indices[:14]))
153
+ # acc_scores, average_score = read_json_acc_scores(path, "piqa")
154
+ # print(average_score)
155
+
lm-evaluation-harness/docs/API_guide.md ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TemplateAPI Usage Guide
2
+
3
+ The `TemplateAPI` class is a versatile superclass designed to facilitate the integration of various API-based language models into the lm-evaluation-harness framework. This guide will explain how to use and extend the `TemplateAPI` class to implement your own API models. If your API implements the OpenAI API you can use the `local-completions` or the `local-chat-completions` (defined [here](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/models/openai_completions.py)) model types, which can also serve as examples of how to effectively subclass this template.
4
+
5
+ ## Overview
6
+
7
+ The `TemplateAPI` class provides a template for creating API-based model implementations. It handles common functionalities such as:
8
+
9
+ - Tokenization (optional)
10
+ - Batch processing
11
+ - Caching
12
+ - Retrying failed requests
13
+ - Parsing API responses
14
+
15
+ To use this class, you typically need to subclass it and implement specific methods for your API.
16
+
17
+ ## Key Methods to Implement
18
+
19
+ When subclassing `TemplateAPI`, you need to implement the following methods:
20
+
21
+ 1. `_create_payload`: Creates the JSON payload for API requests.
22
+ 2. `parse_logprobs`: Parses log probabilities from API responses.
23
+ 3. `parse_generations`: Parses generated text from API responses.
24
+ 4. `headers`: Returns the headers for the API request.
25
+
26
+ You may also need to override other methods or properties depending on your API's specific requirements.
27
+
28
+ > [!NOTE]
29
+ > Currently loglikelihood and MCQ based tasks (such as MMLU) are only supported for completion endpoints. Not for chat-completion — those that expect a list of dicts — endpoints! Completion APIs which support instruct tuned models can be evaluated with the `--apply_chat_template` option in order to simultaneously evaluate models using a chat template format while still being able to access the model logits needed for loglikelihood-based tasks.
30
+
31
+ ## TemplateAPI Arguments
32
+
33
+ When initializing a `TemplateAPI` instance or a subclass, you can provide several arguments to customize its behavior. Here's a detailed explanation of some important arguments:
34
+
35
+ - `model` or `pretrained` (str):
36
+ - The name or identifier of the model to use.
37
+ - `model` takes precedence over `pretrained` when both are provided.
38
+
39
+ - `base_url` (str):
40
+ - The base URL for the API endpoint.
41
+
42
+ - `tokenizer` (str, optional):
43
+ - The name or path of the tokenizer to use.
44
+ - If not provided, it defaults to using the same tokenizer name as the model.
45
+
46
+ - `num_concurrent` (int):
47
+ - Number of concurrent requests to make to the API.
48
+ - Useful for APIs that support parallel processing.
49
+ - Default is 1 (sequential processing).
50
+
51
+ - `timeout` (int, optional):
52
+ - Timeout for API requests in seconds.
53
+ - Default is 30.
54
+
55
+ - `tokenized_requests` (bool):
56
+ - Determines whether the input is pre-tokenized. Defaults to `True`.
57
+ - Requests can be sent in either tokenized form (`list[list[int]]`) or as text (`list[str]`, or `str` for batch_size=1).
58
+ - For loglikelihood-based tasks, prompts require tokenization to calculate the context length. If `False` prompts are decoded back to text before being sent to the API.
59
+ - Not as important for `generate_until` tasks.
60
+ - Ignored for chat formatted inputs (list[dict...]) or if tokenizer_backend is None.
61
+
62
+ - `tokenizer_backend` (str, optional):
63
+ - Required for loglikelihood-based or MCQ tasks.
64
+ - Specifies the tokenizer library to use. Options are "tiktoken", "huggingface", or None.
65
+ - Default is "huggingface".
66
+
67
+ - `max_length` (int, optional):
68
+ - Maximum length of input + output.
69
+ - Default is 2048.
70
+
71
+ - `max_retries` (int, optional):
72
+ - Maximum number of retries for failed API requests.
73
+ - Default is 3.
74
+
75
+ - `max_gen_toks` (int, optional):
76
+ - Maximum number of tokens to generate in completion tasks.
77
+ - Default is 256 or set in task yaml.
78
+
79
+ - `batch_size` (int or str, optional):
80
+ - Number of requests to batch together (if the API supports batching).
81
+ - Can be an integer or "auto" (which defaults to 1 for API models).
82
+ - Default is 1.
83
+
84
+ - `seed` (int, optional):
85
+ - Random seed for reproducibility.
86
+ - Default is 1234.
87
+
88
+ - `add_bos_token` (bool, optional):
89
+ - Whether to add the beginning-of-sequence token to inputs (when tokenizing).
90
+ - Default is False.
91
+
92
+ - `custom_prefix_token_id` (int, optional):
93
+ - Custom token ID to use as a prefix for inputs.
94
+ - If not provided, uses the model's default BOS or EOS token (if `add_bos_token` is True).
95
+
96
+ - `verify_certificate` (bool, optional):
97
+ - Whether to validate the certificate of the API endpoint (if HTTPS).
98
+ - Default is True.
99
+
100
+ Example usage:
101
+
102
+ ```python
103
+ class MyAPIModel(TemplateAPI):
104
+ def __init__(self, **kwargs):
105
+ super().__init__(
106
+ model="my-model",
107
+ base_url="https://api.mymodel.com/v1/completions",
108
+ tokenizer_backend="huggingface",
109
+ num_concurrent=5,
110
+ max_retries=5,
111
+ batch_size=10,
112
+ **kwargs
113
+ )
114
+
115
+ # Implement other required methods...
116
+ ```
117
+
118
+ When subclassing `TemplateAPI`, you can override these arguments in your `__init__` method to set default values specific to your API. You can also add additional (potentially user-specified) arguments as needed for your specific implementation.
119
+
120
+ ## Example Implementation: OpenAI API
121
+
122
+ The `OpenAICompletionsAPI` and `OpenAIChatCompletion` ([here](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/models/openai_completions.py) classes demonstrate how to implement API models using the `TemplateAPI` class. Here's a breakdown of the key components:
123
+
124
+ ### 1. Subclassing and Initialization
125
+
126
+ ```python
127
+ @register_model("openai-completions")
128
+ class OpenAICompletionsAPI(LocalCompletionsAPI):
129
+ def __init__(
130
+ self,
131
+ base_url="https://api.openai.com/v1/completions",
132
+ tokenizer_backend="tiktoken",
133
+ **kwargs,
134
+ ):
135
+ super().__init__(
136
+ base_url=base_url, tokenizer_backend=tokenizer_backend, **kwargs
137
+ )
138
+ ```
139
+
140
+ ### 2. Implementing API Key Retrieval
141
+
142
+ ```python
143
+ @cached_property
144
+ def api_key(self):
145
+ key = os.environ.get("OPENAI_API_KEY", None)
146
+ if key is None:
147
+ raise ValueError(
148
+ "API key not found. Please set the OPENAI_API_KEY environment variable."
149
+ )
150
+ return key
151
+ ```
152
+
153
+ ### 3. Creating the Payload
154
+
155
+ ```python
156
+ def _create_payload(
157
+ self,
158
+ messages: Union[List[List[int]], List[dict], List[str], str],
159
+ generate=False,
160
+ gen_kwargs: Optional[dict] = None,
161
+ **kwargs,
162
+ ) -> dict:
163
+ if generate:
164
+ # ... (implementation for generation)
165
+ else:
166
+ # ... (implementation for log likelihood)
167
+ ```
168
+
169
+ ### 4. Parsing API Responses
170
+
171
+ ```python
172
+ @staticmethod
173
+ def parse_logprobs(
174
+ outputs: Union[Dict, List[Dict]],
175
+ tokens: List[List[int]] = None,
176
+ ctxlens: List[int] = None,
177
+ **kwargs,
178
+ ) -> List[Tuple[float, bool]]:
179
+ # ... (implementation)
180
+
181
+ @staticmethod
182
+ def parse_generations(outputs: Union[Dict, List[Dict]], **kwargs) -> List[str]:
183
+ # ... (implementation)
184
+ ```
185
+
186
+ The requests are initiated in the `model_call` or the `amodel_call` methods.
187
+
188
+ ## Implementing Your Own API Model
189
+
190
+ To implement your own API model:
191
+
192
+ 1. Subclass `TemplateAPI` or one of its subclasses (e.g., `LocalCompletionsAPI`).
193
+ 2. Override the `__init__` method if you need to set specific parameters.
194
+ 3. Implement the `_create_payload` and `header` methods to create the appropriate payload for your API.
195
+ 4. Implement the `parse_logprobs` and `parse_generations` methods to parse your API's responses.
196
+ 5. Override the `api_key` property if your API requires authentication.
197
+ 6. Override any other methods as necessary to match your API's behavior.
198
+
199
+ ## Best Practices
200
+
201
+ 1. Use the `@register_model` decorator to register your model with the framework (and import it in `lm_eval/models/__init__.py`!).
202
+ 2. Use environment variables for sensitive information like API keys.
203
+ 3. Properly handle batching and concurrent requests if supported by your API.
lm-evaluation-harness/docs/CONTRIBUTING.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to LM Evaluation Harness
2
+
3
+ Welcome and thank you for your interest in the LM Evaluation Harness! We welcome contributions and feedback and appreciate your time spent with our library, and hope you find it useful!
4
+
5
+ ## Important Resources
6
+
7
+ There are several places information about LM Evaluation Harness is located:
8
+
9
+ - Our [documentation pages](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs)
10
+ - We occasionally use [GitHub Milestones](https://github.com/EleutherAI/lm-evaluation-harness/milestones) to track progress toward specific near-term version releases.
11
+ - We maintain a [Project Board](https://github.com/orgs/EleutherAI/projects/25) for tracking current work items and PRs, and for future roadmap items or feature requests.
12
+ - Further discussion and support conversations are located in the #lm-thunderdome channel of the [EleutherAI discord](https://discord.gg/eleutherai).
13
+
14
+ ## Code Style
15
+
16
+ LM Evaluation Harness uses [ruff](https://github.com/astral-sh/ruff) for linting via [pre-commit](https://pre-commit.com/).
17
+
18
+ You can install linters and dev tools via
19
+
20
+ ```pip install lm_eval[dev]``` or ```pip install -e ".[dev]"```
21
+
22
+ Then, run
23
+
24
+ ```pre-commit install```
25
+
26
+ in order to ensure linters and other checks will be run upon committing.
27
+
28
+ ## Testing
29
+
30
+ We use [pytest](https://docs.pytest.org/en/latest/) for running unit tests. All library unit tests can be run via:
31
+
32
+ ```bash
33
+ python -m pytest --showlocals -s -vv -n=auto --ignore=tests/models/test_neuralmagic.py --ignore=tests/models/test_openvino.py
34
+ ```
35
+
36
+ ## Contributor License Agreement
37
+
38
+ We ask that new contributors agree to a Contributor License Agreement affirming that EleutherAI has the rights to use your contribution to our library.
39
+ First-time pull requests will have a reply added by @CLAassistant containing instructions for how to confirm this, and we require it before merging your PR.
40
+
41
+ ## Contribution Best Practices
42
+
43
+ We recommend a few best practices to make your contributions or reported errors easier to assist with.
44
+
45
+ **For Pull Requests:**
46
+
47
+ - PRs should be titled descriptively, and be opened with a brief description of the scope and intent of the new contribution.
48
+ - New features should have appropriate documentation added alongside them.
49
+ - Aim for code maintainability, and minimize code copying.
50
+ - If opening a task, try to share test results on the task using a publicly-available model, and if any public results are available on the task, compare to them.
51
+
52
+ **For Feature Requests:**
53
+
54
+ - Provide a short paragraph's worth of description. What is the feature you are requesting? What is its motivation, and an example use case of it? How does this differ from what is currently supported?
55
+
56
+ **For Bug Reports**:
57
+
58
+ - Provide a short description of the bug.
59
+ - Provide a *reproducible example*--what is the command you run with our library that results in this error? Have you tried any other steps to resolve it?
60
+ - Provide a *full error traceback* of the error that occurs, if applicable. A one-line error message or small screenshot snippet is unhelpful without the surrounding context.
61
+ - Note what version of the codebase you are using, and any specifics of your environment and setup that may be relevant.
62
+
63
+ **For Requesting New Tasks**:
64
+
65
+ - Provide a 1-2 sentence description of what the task is and what it evaluates.
66
+ - Provide a link to the paper introducing the task.
67
+ - Provide a link to where the dataset can be found.
68
+ - Provide a link to a paper containing results on an open-source model on the task, for use in comparisons and implementation validation.
69
+ - If applicable, link to any codebase that has implemented the task (especially the original publication's codebase, if existent).
70
+
71
+ ## How Can I Get Involved?
72
+
73
+ To quickly get started, we maintain a list of good first issues, which can be found [on our project board](https://github.com/orgs/EleutherAI/projects/25/views/8) or by [filtering GH Issues](https://github.com/EleutherAI/lm-evaluation-harness/issues?q=is%3Aopen+label%3A%22good+first+issue%22+label%3A%22help+wanted%22). These are typically smaller code changes or self-contained features which can be added without extensive familiarity with library internals, and we recommend new contributors consider taking a stab at one of these first if they are feeling uncertain where to begin.
74
+
75
+ There are a number of distinct ways to contribute to LM Evaluation Harness, and all are extremely helpful! A sampling of ways to contribute include:
76
+
77
+ - **Implementing and verifying new evaluation tasks**: Is there a task you'd like to see LM Evaluation Harness support? Consider opening an issue requesting it, or helping add it! Verifying and cross-checking task implementations with their original versions is also a very valuable form of assistance in ensuring standardized evaluation.
78
+ - **Improving documentation** - Improvements to the documentation, or noting pain points / gaps in documentation, are helpful in order for us to improve the user experience of the library and clarity + coverage of documentation.
79
+ - **Testing and devops** - We are very grateful for any assistance in adding tests for the library that can be run for new PRs, and other devops workflows.
80
+ - **Adding new modeling / inference library integrations** - We hope to support a broad range of commonly-used inference libraries popular among the community, and welcome PRs for new integrations, so long as they are documented properly and maintainable.
81
+ - **Proposing or Contributing New Features** - We want LM Evaluation Harness to support a broad range of evaluation usecases. If you have a feature that is not currently supported but desired, feel free to open an issue describing the feature and, if applicable, how you intend to implement it. We would be happy to give feedback on the cleanest way to implement new functionalities and are happy to coordinate with interested contributors via GH discussions or via discord.
82
+
83
+ We hope that this has been helpful, and appreciate your interest in contributing! Further questions can be directed to [our Discord](discord.gg/eleutherai).
lm-evaluation-harness/docs/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Eval Harness Documentation
2
+
3
+ Welcome to the docs for the LM Evaluation Harness!
4
+
5
+ ## Table of Contents
6
+
7
+ * To learn about the public interface of the library, as well as how to evaluate via the command line or as integrated into an external library, see the [Interface](./interface.md).
8
+ * To learn how to add a new library, API, or model type to the library, as well as a quick explainer on the types of ways to evaluate an LM, see the [Model Guide](./model_guide.md).
9
+ * For an extended description of how to extend the library to new model classes served over an API, see the [API Guide](./API_guide.md).
10
+ * For a crash course on adding new tasks to the library, see our [New Task Guide](./new_task_guide.md).
11
+ * To learn more about pushing the limits of task configuration that the Eval Harness supports, see the [Task Configuration Guide](./task_guide.md).
lm-evaluation-harness/docs/chat-template-readme.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chat Template Delimiter Handling Update
2
+
3
+ ## Overview
4
+
5
+ This change modifies how delimiters are handled when applying chat templates in the request construction process for likelihood and multiple-choice based tasks. When `apply_chat_template` is set to `True`, the target delimiter is now set to an empty string instead of using the configured delimiter.
6
+
7
+ ## Background
8
+
9
+ By default, the system uses a target delimiter (typically a whitespace " ") between the context and target text when constructing prompts. The full string is constructed as:
10
+
11
+ ```text
12
+ doc_to_text(doc) + target_delimiter + doc_to_target(doc)
13
+ ```
14
+
15
+ While this worked well for base models where we wanted the model to predict a single whitespace followed by the answer, chat models have their own formatting conventions that handle spacing differently.
16
+
17
+ ## The Change
18
+
19
+ - When `apply_chat_template=True`, the target delimiter is now empty ("") instead of the default whitespace
20
+ - This prevents interference between chat template formatting and the default delimiter system
21
+ - Particularly important for multiple choice tasks where the template itself handles spacing
22
+
23
+ ## Example
24
+
25
+ ```text
26
+ # Before (with default delimiter " ")
27
+ <user>Question: What color is the sky?\nAnswer:<assistant> blue
28
+
29
+ # After
30
+ <user>Question: What color is the sky?\nAnswer:<assistant>blue
31
+ ```
lm-evaluation-harness/docs/decontamination.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Decontamination
2
+
3
+ ## Usage
4
+
5
+ The provided directory should contain
6
+ the ngram files and info.json produced in "Pile Ngram Generation" further down.
7
+
8
+ ```bash
9
+ python -m lm_eval \
10
+ --model gpt2 \
11
+ --device 0 \
12
+ --tasks sciq
13
+ ```
14
+
15
+ ## Background
16
+
17
+ Downstream evaluations test model generalization, and are less useful when test set data also exists in the training set, referred to as leakage or contamination.
18
+
19
+ Filtering your training set against the test set is a good first step, however this isn't always possible, as in the case of a new benchmark or one that wasn't considered prior to model training. When training set filtering isn't possible, it is useful to measure the impact of test set leakage by detecting the contaminated test examples and producing a clean version of the benchmark.
20
+
21
+ The basis for our decontamination procedure can be found in Appendix C of "Language Models are Few-Shot Learners". OpenAI defined a test document as contaminated if any N-gram overlap existed with any training document. They used a range of N values between 8 and 13 depending on dataset, while we just used 13 for simplicity.
22
+
23
+ ## Implementation
24
+
25
+ Contamination detection can be found in `lm_eval/decontaminate.py` with supporting code in `lm_eval/decontamination/`.
26
+
27
+ decontaminate.py does the following:
28
+
29
+ 1. Build dictionaries of all ngrams and their corresponding evaluation/document ids.
30
+ 2. Scan through sorted files containing training set n-grams.
31
+ 3. If a match is found, the corresponding evaluation/document combinations are marked as contaminated.
32
+
33
+ `lm_eval/evaluator.py` can then produce a clean version of the benchmark by excluding the results of contaminated documents. For each metric, a clean version will be shown in the results with a "decontaminate" suffix.
34
+
35
+ This is disabled by default for new tasks, to support decontamination on a task override the "should_decontaminate" and "doc_to_decontamination_query" methods. For more details see the [task guide](task_guide.md).
36
+
37
+ ## Pile Ngram Generation
38
+
39
+ The relevant scripts can be found in `scripts/clean_training_data`, which also import from
40
+ `lm_eval/decontamination/`
41
+
42
+ 1. git clone https://github.com/EleutherAI/lm-evaluation-harness.git
43
+ 2. pip install -r requirements.txt
44
+ 3. Download The Pile from [The Eye](https://the-eye.eu/public/AI/pile/train/)
45
+ 4. Place pile files in "pile" directory under "lm-evaluation-harness" (or create a symlink)
46
+ 5. Run generate_13_grams.
47
+
48
+ ```bash
49
+ export PYTHONHASHSEED=0
50
+ python -m scripts/clean_training_data/generate_13_grams \
51
+ -dir path/to/working/directory \
52
+ -n 13 \
53
+ -buckets 500
54
+ ```
55
+
56
+ Took approximately 4 days for us. We had the time to wait, but this could be scaled out by doing partial pile scans on multiple instances of this script and merging the relevant buckets. We fixed PYTHONHASHSEED to ensure reproducibility of bucket hashing in case you need to stop and start.
57
+
58
+ 6. Sort the generated 13-grams.
59
+
60
+ ```bash
61
+ python -m scripts/clean_training_data/sort_13_gram_buckets \
62
+ -dir path/to/working/directory/output
63
+ ```
64
+
65
+ Took approximately 5 days for us. You could speed this up by spreading the files around to different machines and running the sort script before gathering them together.
66
+
67
+ 7. Compress the sorted 13 grams files and place them together with info.json.
68
+
69
+ This step only takes a few hours.
70
+
71
+ ```bash
72
+ python -m scripts/clean_training_data/compress_and_package \
73
+ -dir path/to/working/directory \
74
+ -output path/to/final/directory \
75
+ -procs 8
76
+ ```
lm-evaluation-harness/docs/footguns.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Common Pitfalls and Troubleshooting Guide
2
+
3
+ This document highlights common pitfalls and troubleshooting tips when using this library. We'll continue to add more tips as we discover them.
4
+
5
+ ## YAML Configuration Issues
6
+
7
+ ### Newline Characters in YAML (`\n`)
8
+
9
+ **Problem:** When specifying newline characters in YAML, they may be interpreted incorrectly depending on how you format them.
10
+
11
+ ```yaml
12
+ # ❌ WRONG: Single quotes don't process escape sequences
13
+ generation_kwargs:
14
+ until: ['\n'] # Gets parsed as the literal characters '\' and 'n' i.e "\\n"
15
+
16
+ ```
17
+ ```yaml
18
+ # ✅ RIGHT: Use double quotes for escape sequences
19
+ generation_kwargs:
20
+ until: ["\n"] # Gets parsed as an actual newline character
21
+
22
+ ```
23
+
24
+ **Solutions:**
25
+ - Use double quotes for strings containing escape sequences
26
+ - For multiline content, use YAML's block scalars (`|` or `>`)
27
+ - When generating YAML programmatically, be careful with how template engines handle escape sequences
28
+
29
+ ### Quoting in YAML
30
+
31
+ **When to use different types of quotes:**
32
+
33
+ - **No quotes**: Simple values (numbers, booleans, alphanumeric strings without special characters)
34
+ ```yaml
35
+ simple_value: plain text
36
+ number: 42
37
+
38
+ ```
39
+
40
+ - **Single quotes (')**:
41
+ - Preserves literal values
42
+ - Use when you need special characters to be treated literally
43
+ - Escape single quotes by doubling them: `'It''s working'`
44
+ ```yaml
45
+ literal_string: 'The newline character \n is not processed here'
46
+ path: 'C:\Users\name' # Backslashes preserved
47
+
48
+ ```
49
+
50
+ - **Double quotes (")**:
51
+ - Processes escape sequences like `\n`, `\t`, etc.
52
+ - Use for strings that need special characters interpreted
53
+ - Escape double quotes with backslash: `"He said \"Hello\""`
54
+ ```yaml
55
+ processed_string: "First line\nSecond line" # Creates actual newline
56
+ unicode: "Copyright symbol: \u00A9" # Unicode character
57
+
58
+ ```
lm-evaluation-harness/docs/interface.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # User Guide
2
+
3
+ This document details the interface exposed by `lm-eval` and provides details on what flags are available to users.
4
+
5
+ ## Command-line Interface
6
+
7
+ A majority of users run the library by cloning it from Github, installing the package as editable, and running the `python -m lm_eval` script.
8
+
9
+ Equivalently, running the library can be done via the `lm-eval` entrypoint at the command line.
10
+
11
+ This mode supports a number of command-line arguments, the details of which can also be seen via running with `-h` or `--help`:
12
+
13
+ - `--model` : Selects which model type or provider is evaluated. Must be a string corresponding to the name of the model type/provider being used. See [the main README](https://github.com/EleutherAI/lm-evaluation-harness/tree/main#model-apis-and-inference-servers) for a full list of enabled model names and supported libraries or APIs.
14
+
15
+ - `--model_args` : Controls parameters passed to the model constructor. Accepts a string containing comma-separated keyword arguments to the model class of the format `"arg1=val1,arg2=val2,..."`, such as, for example `--model_args pretrained=EleutherAI/pythia-160m,dtype=float32`. For a full list of what keyword arguments, see the initialization of the `lm_eval.api.model.LM` subclass, e.g. [`HFLM`](https://github.com/EleutherAI/lm-evaluation-harness/blob/365fcda9b85bbb6e0572d91976b8daf409164500/lm_eval/models/huggingface.py#L66)
16
+
17
+ - `--tasks` : Determines which tasks or task groups are evaluated. Accepts a comma-separated list of task names or task group names. Must be solely comprised of valid tasks/groups. A list of supported tasks can be viewed with `--tasks list`.
18
+
19
+ - `--num_fewshot` : Sets the number of few-shot examples to place in context. Must be an integer.
20
+
21
+ - `--gen_kwargs` : takes an arg string in same format as `--model_args` and creates a dictionary of keyword arguments. These will be passed to the models for all called `generate_until` (free-form or greedy generation task) tasks, to set options such as the sampling temperature or `top_p` / `top_k`. For a list of what args are supported for each model type, reference the respective library's documentation (for example, the documentation for `transformers.AutoModelForCausalLM.generate()`.) These kwargs will be applied to all `generate_until` tasks called--we do not currently support unique gen_kwargs or batch_size values per task in a single run of the library. To control these on a per-task level, set them in that task's YAML file.
22
+
23
+ - `--batch_size` : Sets the batch size used for evaluation. Can be a positive integer or `"auto"` to automatically select the largest batch size that will fit in memory, speeding up evaluation. One can pass `--batch_size auto:N` to re-select the maximum batch size `N` times during evaluation. This can help accelerate evaluation further, since `lm-eval` sorts documents in descending order of context length.
24
+
25
+ - `--max_batch_size` : Sets the maximum batch size to try to fit in memory, if `--batch_size auto` is passed.
26
+
27
+ - `--device` : Sets which device to place the model onto. Must be a string, for example, `"cuda", "cuda:0", "cpu", "mps"`. Defaults to "cuda", and can be ignored if running multi-GPU or running a non-local model type.
28
+
29
+ - `--output_path` : A string of the form `dir/file.jsonl` or `dir/`. Provides a path where high-level results will be saved, either into the file named or into the directory named. If `--log_samples` is passed as well, then per-document outputs and metrics will be saved into the directory as well.
30
+
31
+ - `--log_samples` : If this flag is passed, then the model's outputs, and the text fed into the model, will be saved at per-document granularity. Must be used with `--output_path`.
32
+
33
+ - `--limit` : Accepts an integer, or a float between 0.0 and 1.0 . If passed, will limit the number of documents to evaluate to the first X documents (if an integer) per task or first X% of documents per task. Useful for debugging, especially on costly API models.
34
+
35
+ - `--use_cache` : Should be a path where a sqlite db file can be written to. Takes a string of format `/path/to/sqlite_cache_` in order to create a cache db at `/path/to/sqlite_cache_rank{i}.db` for each process (0-NUM_GPUS). This allows results of prior runs to be cached, so that there is no need to re-run results in order to re-score or re-run a given (model, task) pair again.
36
+
37
+ - `--cache_requests` : Can be "true", "refresh", or "delete". "true" means that the cache should be used. "refresh" means that you wish to regenerate the cache, which you should run if you change your dataset configuration for a given task. "delete" will delete the cache. Cached files are stored under lm_eval/cache/.cache unless you specify a different path via the environment variable: `LM_HARNESS_CACHE_PATH`. e.g. `LM_HARNESS_CACHE_PATH=~/Documents/cache_for_lm_harness`.
38
+
39
+ - `--check_integrity` : If this flag is used, the library tests for each task selected are run to confirm task integrity.
40
+
41
+ - `--write_out` : Used for diagnostic purposes to observe the format of task documents passed to a model. If this flag is used, then prints the prompt and gold target string for the first document of each task.
42
+
43
+ - `--show_config` : If used, prints the full `lm_eval.api.task.TaskConfig` contents (non-default settings the task YAML file) for each task which was run, at the completion of an evaluation. Useful for when one is modifying a task's configuration YAML locally to transmit the exact configurations used for debugging or for reproducibility purposes.
44
+
45
+ - `--include_path` : Accepts a path to a folder. If passed, then all YAML files containing `lm-eval` compatible task configurations will be added to the task registry as available tasks. Used for when one is writing config files for their own task in a folder other than `lm_eval/tasks/`.
46
+
47
+ - `--system_instruction`: Specifies a system instruction string to prepend to the prompt.
48
+
49
+ - `--apply_chat_template` : This flag specifies whether to apply a chat template to the prompt. It can be used in the following ways:
50
+ - `--apply_chat_template` : When used without an argument, applies the only available chat template to the prompt. For Hugging Face models, if no dedicated chat template exists, the default chat template will be applied.
51
+ - `--apply_chat_template template_name` : If the model has multiple chat templates, apply the specified template to the prompt.
52
+
53
+ For Hugging Face models, the default chat template can be found in the [`default_chat_template`](https://github.com/huggingface/transformers/blob/fc35907f95459d7a6c5281dfadd680b6f7b620e3/src/transformers/tokenization_utils_base.py#L1912) property of the Transformers Tokenizer.
54
+
55
+ - `--fewshot_as_multiturn` : If this flag is on, the Fewshot examples are treated as a multi-turn conversation. Questions are provided as user content and answers are provided as assistant responses. Requires `--num_fewshot` to be set to be greater than 0, and `--apply_chat_template` to be on.
56
+
57
+ - `--predict_only`: Generates the model outputs without computing metrics. Use with `--log_samples` to retrieve decoded results.
58
+
59
+ - `--seed`: Set seed for python's random, numpy and torch. Accepts a comma-separated list of 3 values for python's random, numpy, and torch seeds, respectively, or a single integer to set the same seed for all three. The values are either an integer or 'None' to not set the seed. Default is `0,1234,1234` (for backward compatibility). E.g. `--seed 0,None,8` sets `random.seed(0)` and `torch.manual_seed(8)`. Here numpy's seed is not set since the second value is `None`. E.g, `--seed 42` sets all three seeds to 42.
60
+
61
+ - `--wandb_args`: Tracks logging to Weights and Biases for evaluation runs and includes args passed to `wandb.init`, such as `project` and `job_type`. Full list [here](https://docs.wandb.ai/ref/python/init). e.g., ```--wandb_args project=test-project,name=test-run```. Also allows for the passing of the step to log things at (passed to `wandb.run.log`), e.g., `--wandb_args step=123`.
62
+
63
+ - `--hf_hub_log_args` : Logs evaluation results to Hugging Face Hub. Accepts a string with the arguments separated by commas. Available arguments:
64
+ - `hub_results_org` - organization name on Hugging Face Hub, e.g., `EleutherAI`. If not provided, the results will be pushed to the owner of the Hugging Face token,
65
+ - `hub_repo_name` - repository name on Hugging Face Hub (deprecated, `details_repo_name` and `results_repo_name` should be used instead), e.g., `lm-eval-results`,
66
+ - `details_repo_name` - repository name on Hugging Face Hub to store details, e.g., `lm-eval-results`,
67
+ - `results_repo_name` - repository name on Hugging Face Hub to store results, e.g., `lm-eval-results`,
68
+ - `push_results_to_hub` - whether to push results to Hugging Face Hub, can be `True` or `False`,
69
+ - `push_samples_to_hub` - whether to push samples results to Hugging Face Hub, can be `True` or `False`. Requires `--log_samples` to be set,
70
+ - `public_repo` - whether the repository is public, can be `True` or `False`,
71
+ - `leaderboard_url` - URL to the leaderboard, e.g., `https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard`.
72
+ - `point_of_contact` - Point of contact for the results dataset, e.g., `yourname@example.com`.
73
+ - `gated` - whether to gate the details dataset, can be `True` or `False`.
74
+
75
+ - `--metadata`: JSON string to pass to TaskConfig. Used for some tasks which require additional metadata to be passed for processing. E.g., `--metadata '{"key": "value"}'`.
76
+
77
+ ## External Library Usage
78
+
79
+ We also support using the library's external API for use within model training loops or other scripts.
80
+
81
+ `lm_eval` supplies two functions for external import and use: `lm_eval.evaluate()` and `lm_eval.simple_evaluate()`.
82
+
83
+ `simple_evaluate()` can be used by simply creating an `lm_eval.api.model.LM` subclass that implements the methods described in the [Model Guide](https://github.com/EleutherAI/lm-evaluation-harness/tree/main/docs/model_guide.md), and wrapping your custom model in that class as follows:
84
+
85
+ ```python
86
+ import lm_eval
87
+ from lm_eval.utils import setup_logging
88
+ ...
89
+ # initialize logging
90
+ setup_logging("DEBUG") # optional, but recommended; or you can set up logging yourself
91
+ my_model = initialize_my_model() # create your model (could be running finetuning with some custom modeling code)
92
+ ...
93
+ # instantiate an LM subclass that takes your initialized model and can run
94
+ # - `Your_LM.loglikelihood()`
95
+ # - `Your_LM.loglikelihood_rolling()`
96
+ # - `Your_LM.generate_until()`
97
+ lm_obj = Your_LM(model=my_model, batch_size=16)
98
+
99
+ # indexes all tasks from the `lm_eval/tasks` subdirectory.
100
+ # Alternatively, you can set `TaskManager(include_path="path/to/my/custom/task/configs")`
101
+ # to include a set of tasks in a separate directory.
102
+ task_manager = lm_eval.tasks.TaskManager()
103
+
104
+ # Setting `task_manager` to the one above is optional and should generally be done
105
+ # if you want to include tasks from paths other than ones in `lm_eval/tasks`.
106
+ # `simple_evaluate` will instantiate its own task_manager if it is set to None here.
107
+ results = lm_eval.simple_evaluate( # call simple_evaluate
108
+ model=lm_obj,
109
+ tasks=["taskname1", "taskname2"],
110
+ num_fewshot=0,
111
+ task_manager=task_manager,
112
+ ...
113
+ )
114
+ ```
115
+
116
+ See the `simple_evaluate()` and `evaluate()` functions in [lm_eval/evaluator.py](../lm_eval/evaluator.py#:~:text=simple_evaluate) for a full description of all arguments available. All keyword arguments to simple_evaluate share the same role as the command-line flags described previously.
117
+
118
+ Additionally, the `evaluate()` function offers the core evaluation functionality provided by the library, but without some of the special handling and simplification + abstraction provided by `simple_evaluate()`.
119
+
120
+ As a brief example usage of `evaluate()`:
121
+
122
+ ```python
123
+ import lm_eval
124
+
125
+ # suppose you've defined a custom lm_eval.api.Task subclass in your own external codebase
126
+ from my_tasks import MyTask1
127
+ ...
128
+
129
+ # create your model (could be running finetuning with some custom modeling code)
130
+ my_model = initialize_my_model()
131
+ ...
132
+
133
+ # instantiate an LM subclass that takes your initialized model and can run
134
+ # - `Your_LM.loglikelihood()`
135
+ # - `Your_LM.loglikelihood_rolling()`
136
+ # - `Your_LM.generate_until()`
137
+ lm_obj = Your_LM(model=my_model, batch_size=16)
138
+
139
+ # optional: the task_manager indexes tasks including ones
140
+ # specified by the user through `include_path`.
141
+ task_manager = lm_eval.tasks.TaskManager(
142
+ include_path="/path/to/custom/yaml"
143
+ )
144
+
145
+ # To get a task dict for `evaluate`
146
+ task_dict = lm_eval.tasks.get_task_dict(
147
+ [
148
+ "mmlu", # A stock task
149
+ "my_custom_task", # A custom task
150
+ {
151
+ "task": ..., # A dict that configures a task
152
+ "doc_to_text": ...,
153
+ },
154
+ MyTask1 # A task object from `lm_eval.task.Task`
155
+ ],
156
+ task_manager # A task manager that allows lm_eval to
157
+ # load the task during evaluation.
158
+ # If none is provided, `get_task_dict`
159
+ # will instantiate one itself, but this
160
+ # only includes the stock tasks so users
161
+ # will need to set this if including
162
+ # custom paths is required.
163
+ )
164
+
165
+ results = evaluate(
166
+ lm=lm_obj,
167
+ task_dict=task_dict,
168
+ ...
169
+ )
170
+ ```
lm-evaluation-harness/docs/model_guide.md ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # New Model Guide
2
+
3
+ This guide may be of special interest to users who are using the library outside of the repository, via installing the library via pypi and calling `lm_eval.evaluator.evaluate()` to evaluate an existing model.
4
+
5
+ In order to properly evaluate a given LM, we require implementation of a wrapper class subclassing the `lm_eval.api.model.LM` class, that defines how the Evaluation Harness should interface with your model. This guide walks through how to write this `LM` subclass via adding it to the library!
6
+
7
+ ## Setup
8
+
9
+ To get started contributing, go ahead and fork the main repo, clone it, create a branch with the name of your model, and install the project requirements in your environment:
10
+
11
+ ```sh
12
+ # After forking...
13
+ git clone https://github.com/<YOUR-USERNAME>/lm-evaluation-harness.git
14
+ cd lm-evaluation-harness
15
+ git checkout -b <model-type>
16
+ pip install -e ".[dev]"
17
+ ```
18
+
19
+ Now, we'll create a new file where we'll be adding our model:
20
+
21
+ ```sh
22
+ touch lm_eval/models/<my_model_filename>.py
23
+ ```
24
+
25
+ **Tip: this filename should not shadow package names! For example, naming your file `anthropic.py` is disallowed since the API's name on pypi is `anthropic`, but naming it `anthropic_llms.py` works with no problems.**
26
+
27
+ ## Interface
28
+
29
+ All models must subclass the `lm_eval.api.model.LM` class.
30
+
31
+ The LM class enforces a common interface via which we can extract responses from a model:
32
+
33
+ ```python
34
+ class MyCustomLM(LM):
35
+ #...
36
+ def loglikelihood(self, requests: list[Instance]) -> list[tuple[float, bool]]:
37
+ #...
38
+
39
+
40
+ def loglikelihood_rolling(self, requests: list[Instance]) -> list[tuple[float, bool]]:
41
+ #...
42
+
43
+
44
+ def generate_until(self, requests: list[Instance]) -> list[str]:
45
+ #...
46
+ #...
47
+ ```
48
+
49
+ Where `Instance` is a dataclass defined in [`lm_eval.api.instance`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/api/instance.py) with property `args` of request-dependent type signature described below.
50
+
51
+ We support three types of requests, consisting of different interactions / measurements with an autoregressive LM.
52
+
53
+ All three request types take as input `requests` of type `list[Instance]` that have a matching `Instance.request_type` to the method name.
54
+
55
+ - `generate_until`
56
+ - Each request contains `Instance.args : Tuple[str, dict]` containing 1. an input string to the LM and 2. a dictionary of keyword arguments used to control generation parameters.
57
+ - Using this input and these generation parameters, text will be sampled from the language model (typically until a maximum output length or specific stopping string sequences--for example, `{"until": ["\n\n", "."], "max_gen_toks": 128}`).
58
+ - The generated output text from the model will then be returned.
59
+
60
+ - `loglikelihood`
61
+ - Each request contains `Instance.args : Tuple[str, str]` containing 1. an input string to the LM and 2. a target string on which the loglikelihood of the LM producing this target, conditioned on the input, will be returned.
62
+ - Each request will have, as result, `(ll, is_greedy): Tuple[float, int]` returned, where `ll` is a floating point number representing the log probability of generating the target string conditioned on the input, and `is_greedy` being either the value `0` or `1`, with it being `1` if and only if the target string *would be generated by greedy sampling from the LM* (that is, if the target string is the *most likely* N-token string to be output by the LM given the input. )
63
+
64
+ - `loglikelihood_rolling`
65
+ - Each request contains `Instance.args : Tuple[str]`, which is an input string to the model whose *entire* loglikelihood, conditioned on purely the EOT token, will be calculated.
66
+ - This is used to evaluate *perplexity* on a data distribution.
67
+ - It should return `(ll,) : Tuple[float]` , a.k.a. solely the *loglikelihood* of producing each piece of text given no starting input.
68
+
69
+ To allow a model to be evaluated on all types of tasks, you will need to implement these three types of measurements (note that `loglikelihood_rolling` is a special case of `loglikelihood`). For a reference implementation, check out `lm_eval/models/huggingface.py` ! Additionally, check out `lm_eval.api.model.TemplateLM` for a class that abstracts away some commonly used functions across LM subclasses, or see if your model would lend itself well to subclassing the `lm_eval.models.huggingface.HFLM` class and overriding just the initialization or a couple methods!
70
+
71
+ **Tip: be careful of indexing in loglikelihood!**
72
+
73
+ LMs take in tokens in position `[0 1 2 ... N]` and output a probability distribution for token position `N+1`. We provide a simplified graphic here, excerpted from `huggingface.py`:
74
+
75
+ ```text
76
+ # how this all works (illustrated on a causal decoder-only setup):
77
+ # CTX CONT
78
+ # inp 0 1 2 3|4 5 6 7 8 9 <- last token is deleted by inp[:, :-1]
79
+ # model \ \
80
+ # logits 1 2 3|4 5 6 7 8 9 <- the ctx half gets tossed out by the
81
+ # cont_toks 4 5 6 7 8 9 [:, -len(continuation_enc):, :self.vocab_size] slice
82
+ ```
83
+
84
+ The final token of the target is not passed into the LM, because we want the LM's predictions *up to but not past* that final target token. For more information, check out https://github.com/EleutherAI/lm-evaluation-harness/issues/942 .
85
+
86
+ ## Registration
87
+
88
+ Congrats on implementing your model! Now it's time to test it out.
89
+
90
+ To make your model usable via the command line interface to `lm-eval` using `python -m lm_eval`, you'll need to tell `lm-eval` what your model's name is.
91
+
92
+ This is done via a *decorator*, `lm_eval.api.registry.register_model`. Using `register_model()`, one can both tell the package what the model's name(s) to be used are when invoking it with `python -m lm_eval --model <name>` and alert `lm-eval` to the model's existence.
93
+
94
+ ```python
95
+ from lm_eval.api.registry import register_model
96
+
97
+ @register_model("<name1>", "<name2>")
98
+ class MyCustomLM(LM):
99
+ ```
100
+
101
+ Using this decorator results in the class being added to an accounting of the usable LM types maintained internally to the library at `lm_eval.api.registry.MODEL_REGISTRY`. See `lm_eval.api.registry` for more detail on what sorts of registries and decorators exist in the library!
102
+
103
+ **Tip: be sure to import your model in `lm_eval/models/__init__.py!`**
104
+
105
+ ## Testing
106
+
107
+ We also recommend that new model contributions be accompanied by short tests of their 3 core functionalities, at minimum. To see an example of such tests, look at https://github.com/EleutherAI/lm-evaluation-harness/blob/35bdecd379c0cefad6897e67db892f4a6026a128/tests/test_ggml.py .
108
+
109
+ ## Chat Templating
110
+
111
+ Many models are fine-tuned with a [Chat Template](https://huggingface.co/docs/transformers/main/en/chat_templating) in order to enable back-and-forth interaction between a "User"'s queries and the model (often called "Assistant")'s responses. It can be desirable to evaluate fine-tuned models on evaluation tasks while wrapped in the conversational format they expect.
112
+
113
+ In order to make your model optionally compatible with a chat format, three additional methods must be implemented:
114
+
115
+ ```python
116
+ class MyCustomLM(LM):
117
+ #...
118
+ @property
119
+ def tokenizer_name(self) -> str:
120
+ """
121
+ Return the name of the model's tokenizer and/or the accompanying chat template.
122
+ The returned string is used to cache requests.
123
+
124
+ Returns:
125
+ str: The name of the model's tokenizer and/or chat template.
126
+ """
127
+
128
+ def chat_template(self, chat_template: Union[bool, str] = False) -> str:
129
+ """
130
+ Get the appropriate chat template for the model based on the `chat_template` argument.
131
+
132
+ This method returns the chat template string to build the prompt from a chat history.
133
+ The chat template is saved in the evaluation results for reproducibility.
134
+ Boolean arguments should be used with models that have only one chat template,
135
+ while string arguments are used with models that have multiple chat templates.
136
+ For the reference implementation, see HFLM class in `lm_eval.models.huggingface`.
137
+
138
+ Args:
139
+ chat_template (Union[bool, str]): Specifies whether to apply a chat template:
140
+ - If False: Do not apply any chat template.
141
+ - If True: Apply the default chat template.
142
+ - If str: Apply the specified chat template by name.
143
+
144
+ Returns:
145
+ str: The selected chat template in Jinja format.
146
+ """
147
+
148
+ def apply_chat_template(self, chat_history: List[Dict[str, str]]) -> str:
149
+ """
150
+ Process a chat history to create a string that can be tokenized and input into the model.
151
+
152
+ Args:
153
+ chat_history (List[Dict[str, str]]): A list of dictionaries representing the chat history,
154
+ where each dictionary has "role" and "content" keys.
155
+
156
+ Returns:
157
+ str: A string representing the chat history that can be tokenized and fed into the model.
158
+ """
159
+ ```
160
+
161
+ - `apply_chat_template`
162
+ - This method performs the bulk of the work required for chat-formatting.
163
+ - As input, a `chat_history: List[Dict[str, str]]` is passed in. This is a transcript of a conversation of a form similar to
164
+
165
+ ```text
166
+ [
167
+ {"system": <user-provided system message such as "You are a helpful math-focused chatbot">},
168
+ {"user": <task example - a few-shot example 'input'>}
169
+ {"assistant": <correct response to the above example>},
170
+ # ... more few-shot examples, potentially
171
+ {"user": <test set query--response on which we will evaluate>},
172
+ ]
173
+ ```
174
+
175
+ which can then be converted into a string input.
176
+ - The output is a string representing this conversation that can be fed into the model.
177
+ - For example, this consists of simply calling `tokenizer.apply_chat_template` for HFLM--see the implementation there for reference.
178
+ - `tokenizer_name`
179
+ - LM Eval Harness supports [caching requests](https://github.com/EleutherAI/lm-evaluation-harness/blob/4902aaaf1f374682f95ac25fe2e13b23faddc91a/lm_eval/__main__.py#L140) that are sent to a model, for faster setup when repeating an already-performed evaluation.
180
+ - However, we don't want to use the cache of chat transcripts rendered using one chat template or system prompt to send to a model with a different template! So, we use this `lm.tokenizer_name` string to distinguish caches for a given model (and chat template) from one another.
181
+ - `chat_template`
182
+ - Chat templates are typically provided as a Jinja template string or a string formatted with str.format to include user and assistant messages in a single prompt. This template string is saved in the evaluation results to ensure reproducibility.
183
+
184
+ If not implemented for a given model type, the flags `--apply_chat_template` , `--fewshot_as_multiturn`, and `--system_instruction` cannot be used.
185
+
186
+ ## Other
187
+
188
+ **Pro tip**: In order to make the Evaluation Harness overestimate total runtimes rather than underestimate it, HuggingFace models come in-built with the ability to provide responses on data points in *descending order by total input length* via `lm_eval.utils.Reorderer`. Take a look at `lm_eval.models.hf_causal.HFLM` to see how this is done, and see if you can implement it in your own model!
189
+
190
+ ## Conclusion
191
+
192
+ After reading this guide, you should be able to add new model APIs or implementations to the Eval Harness library!
lm-evaluation-harness/docs/new_task_guide.md ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # New Task Guide
2
+
3
+ `lm-evaluation-harness` is a framework that strives to support a wide range of zero- and few-shot evaluation tasks on autoregressive language models (LMs).
4
+
5
+ This documentation page provides a walkthrough to get started creating your own task, in `lm-eval` versions v0.4.0 and later.
6
+
7
+ A more interactive tutorial is available as a Jupyter notebook [here](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/examples/lm-eval-overview.ipynb).
8
+
9
+ ## Setup
10
+
11
+ If you haven't already, go ahead and fork the main repo, clone it, create a branch with the name of your task, and install the project requirements in your environment:
12
+
13
+ ```sh
14
+ # After forking...
15
+ git clone https://github.com/<YOUR-USERNAME>/lm-evaluation-harness.git
16
+ cd lm-evaluation-harness
17
+ git checkout -b <task-name>
18
+ pip install -e ".[dev]"
19
+ ```
20
+
21
+ In this document, we'll walk through the basics of implementing a static benchmark evaluation in two formats: a *generative* task which requires sampling text from a model, such as [`gsm8k`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k.yaml), and a *discriminative*, or *multiple choice*, task where the model picks the most likely of several fixed answer choices, such as [`sciq`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/sciq/sciq.yaml).
22
+
23
+ ## Creating a YAML file
24
+
25
+ To implement a new standard task, we'll need to write a YAML file which configures our task logic. We start by making a new empty YAML file. This file can have any name, but we recommend placing it in a subfolder of `lm_eval/tasks` titled by the dataset or task's shorthand name: for example,
26
+
27
+ ```sh
28
+ touch lm_eval/tasks/<dataset_name>/<my_new_task_name>.yaml
29
+ ```
30
+
31
+ Or, copy the template subfolder we provide from `templates/new_yaml_task`:
32
+
33
+ ```sh
34
+ cp -r templates/new_yaml_task lm_eval/tasks/
35
+ ```
36
+
37
+ and rename the folders and YAML file(s) as desired.
38
+
39
+ ### Selecting and configuring a dataset
40
+
41
+ All data downloading and management is handled through the HuggingFace (**HF**) [`datasets`](https://github.com/huggingface/datasets) API. So, the first thing you should do is check to see if your task's dataset is already provided in their catalog [here](https://huggingface.co/datasets). If it's not in there, please consider adding it to their Hub to make it accessible to a wider user base by following their [new dataset guide](https://github.com/huggingface/datasets/blob/main/ADD_NEW_DATASET.md)
42
+ .
43
+ > [!TIP]
44
+ > To test your task, we recommend using verbose logging using `export LOGLEVEL = DEBUG` in your shell before running the evaluation script. This will help you debug any issues that may arise.
45
+ Once you have a HuggingFace dataset prepared for your task, we want to assign our new YAML to use this dataset:
46
+
47
+ ```yaml
48
+ dataset_path: ... # the name of the dataset on the HF Hub.
49
+ dataset_name: ... # the dataset configuration to use. Leave `null` if your dataset does not require a config to be passed. See https://huggingface.co/docs/datasets/load_hub#configurations for more info.
50
+ dataset_kwargs: null # any extra keyword arguments that should be passed to the dataset constructor, e.g. `data_dir`.
51
+ ```
52
+
53
+ Next, we'd like to tell our task what the dataset's train, validation, and test splits are named, if they exist:
54
+
55
+ ```yaml
56
+ training_split: <split name of training set, or `null`>
57
+ validation_split: <split name of val. set, or `null`>
58
+ test_split: <split name of test set, or `null`>
59
+ ```
60
+
61
+ Tests will run on the `test_split` if it is available, and otherwise evaluate on the `validation_split`.
62
+
63
+ We can also specify from which split the task should retrieve few-shot examples via:
64
+
65
+ ```yaml
66
+ fewshot_split: <split name to draw fewshot examples from, or `null`>
67
+ ```
68
+
69
+ or by hardcoding them, either using the following in the yaml file:
70
+
71
+ ```yaml
72
+ fewshot_config:
73
+ sampler: first_n
74
+ samples: [
75
+ {<sample 1>},
76
+ {<sample 2>},
77
+ ]
78
+ ```
79
+
80
+ or by adding the function `list_fewshot_samples` in the associated utils.py file:
81
+
82
+ ```python
83
+ def list_fewshot_samples() -> list[dict]:
84
+ return [{<sample 1>}, {<sample 2>}]
85
+ ```
86
+
87
+ See `lm_eval/tasks/minerva_math/minerva_math_algebra.yaml` for an example of the latter, and `lm_eval/tasks/gsm8k/gsm8k-cot.yaml` for an example of the former.
88
+
89
+ In this case, each sample must contain the same fields as the samples in the above sets--for example, if `doc_to_text` expects an `input` field when rendering input prompts, these provided samples must include an `input` key.
90
+
91
+ If neither above options are not set, we will default to train/validation/test sets, in that order.
92
+
93
+ Finally, our dataset may not be already in the exact format we want. Maybe we have to strip whitespace and special characters via a regex from our dataset's "question" field! Or maybe we just want to rename its columns to match a convention we'll be using for our prompts.
94
+
95
+ Let's create a python file in the directory where we're writing our YAML file:
96
+
97
+ ```bash
98
+ touch lm_eval/tasks/<dataset_name>/utils.py
99
+ ```
100
+
101
+ Now, in `utils.py` we'll write a function to process each split of our dataset (the following example is drawn from [the `hellaswag` task](../lm_eval/tasks/hellaswag/utils.py)):
102
+
103
+ ```python
104
+ def process_docs(dataset: datasets.Dataset) -> datasets.Dataset:
105
+ def _process_doc(doc):
106
+ ctx = doc["ctx_a"] + " " + doc["ctx_b"].capitalize()
107
+ out_doc = {
108
+ "query": preprocess(doc["activity_label"] + ": " + ctx),
109
+ "choices": [preprocess(ending) for ending in doc["endings"]],
110
+ "gold": int(doc["label"]),
111
+ }
112
+ return out_doc
113
+
114
+ return dataset.map(_process_doc)
115
+ ```
116
+
117
+ Now, in our YAML config file we'll use the `!function` constructor, and tell the config where our imported Python function will come from. At runtime, before doing anything else we will preprocess our dataset according to this function!
118
+
119
+ ```yaml
120
+ process_docs: !function utils.process_docs
121
+ ```
122
+
123
+ ### Using Local Datasets
124
+
125
+ To load a local dataset for evaluation, you can specify data files in the `dataset_kwargs` field, such as the following for JSON files:
126
+
127
+ ```yaml
128
+ dataset_path: json
129
+ dataset_name: null
130
+ dataset_kwargs:
131
+ data_files: /path/to/my/json
132
+ ```
133
+
134
+ Or with files already split into separate directories:
135
+
136
+ ```yaml
137
+ dataset_path: arrow
138
+ dataset_kwargs:
139
+ data_files:
140
+ train: /path/to/arrow/train/data-00000-of-00001.arrow
141
+ validation: /path/to/arrow/validation/data-00000-of-00001.arrow
142
+ ```
143
+
144
+ Alternatively, if you have previously downloaded a dataset from huggingface hub (using `save_to_disk()`) and wish to use the local files, you will need to use `data_dir` under `dataset_kwargs` to point to where the directory is.
145
+
146
+ ```yaml
147
+ dataset_path: hellaswag
148
+ dataset_kwargs:
149
+ data_dir: hellaswag_local/
150
+ ```
151
+
152
+ You can also set `dataset_path` as a directory path in your local system. This will assume that there is a loading script with the same name as the directory. [See datasets docs](https://huggingface.co/docs/datasets/loading#local-loading-script).
153
+
154
+ ## Writing a Prompt Template
155
+
156
+ The next thing we need to do is decide what format to use when presenting the data to the LM. This is our **prompt**, where we'll define both an input and output format.
157
+
158
+ To write a prompt, users will use `doc_to_text`, `doc_to_target`, and `doc_to_choice` (Optional when certain conditions are met).
159
+
160
+ `doc_to_text` defines the input string a model will be given while `doc_to_target` and `doc_to_choice` will be used to generate the target text. `doc_to_target` can be either a text string that refers to the target string or an integer that refers to the index of the correct label. When it is set as an index, `doc_to_choice` must also be set with the appropriate list of possible choice strings.
161
+
162
+ ### Basic prompts
163
+
164
+ If a dataset is straightforward enough, users can enter the feature name directly. This assumes that no preprocessing is required. For example in [Swag](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/swag/swag.yaml#L10-L11), `doc_to_text` and `doc_to_target` given the name of one of the feature each.
165
+
166
+ ```yaml
167
+ doc_to_text: startphrase
168
+ doc_to_target: label
169
+ ```
170
+
171
+ Hard-coding is also possible as is the case in [SciQ](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/sciq/sciq.yaml#L11).
172
+
173
+ ```yaml
174
+ doc_to_target: 3
175
+ ```
176
+
177
+ `doc_to_choice` can be directly given a list of text as option (See [Toxigen](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/toxigen/toxigen.yaml#L11))
178
+
179
+ ```yaml
180
+ doc_to_choice: ['No', 'Yes']
181
+ ```
182
+
183
+ if a dataset feature is already a list, you can set the name of the feature as `doc_to_choice` (See [Hellaswag](https://github.com/EleutherAI/lm-evaluation-harness/blob/e0eda4d3ffa10e5f65e0976161cd134bec61983a/lm_eval/tasks/hellaswag/hellaswag.yaml#L13))
184
+
185
+ ```yaml
186
+ doc_to_choice: choices
187
+ ```
188
+
189
+ ### Writing a prompt with Jinja 2
190
+
191
+ We support the [Jinja 2](https://jinja.palletsprojects.com/en/3.1.x/) templating language for writing prompts. In practice, this means you can take your dataset's columns and do many basic string manipulations to place each document into prompted format.
192
+
193
+ Take for example the dataset `super_glue/boolq`. As input, we'd like to use the features `passage` and `question` and string them together so that for a sample line `doc`, the model sees something in the format of:
194
+
195
+ ```text
196
+ doc["passage"]
197
+ Question: doc["question"]?
198
+ Answer:
199
+ ```
200
+
201
+ We do this by [writing](https://github.com/EleutherAI/lm-evaluation-harness/blob/1710b42d52d0f327cb0eb3cb1bfbbeca992836ca/lm_eval/tasks/super_glue/boolq/default.yaml#L9C1-L9C61)
202
+
203
+ ```yaml
204
+ doc_to_text: "{{passage}}\nQuestion: {{question}}?\nAnswer:"
205
+ ```
206
+
207
+ Such that `{{passage}}` will be replaced by `doc["passage"]` and `{{question}}` with `doc["question"]` when rendering the prompt template.
208
+
209
+ Our intended output is for the model to predict a single whitespace, and then the answer to the question. We do this via:
210
+
211
+ ```yaml
212
+ doc_to_target: "{{answer}}"
213
+ ```
214
+
215
+ #### Multiple choice format
216
+
217
+ For tasks which are multiple choice (a fixed, finite set of label words per each document) and evaluated via comparing loglikelihoods of all label words (the `multiple_choice` task output type) we enforce a particular convention on prompt format.
218
+
219
+ > [!WARNING]
220
+ > We add `target_delimiter` between input and target which defaults to " ", such that the full input-output string is `doc_to_text(doc) + target_delimiter + doc_to_target(doc)`. `doc_to_text` and `doc_to_target` should not contain trailing right or left whitespace, respectively. For multiple choice the target will be each choice index concatenated with the delimiter.
221
+
222
+ An annotated example in the case of SciQ is as follows:
223
+
224
+ ```yaml
225
+ doc_to_text: "{{support.lstrip()}}\nQuestion: {{question}}\nAnswer:" # This is the input portion of the prompt for this doc. It will have " {{choice}}" appended to it as target for each choice in answer_choices.
226
+ doc_to_target: 3 # this contains the index into the answer choice list of the correct answer.
227
+ doc_to_choice: "{{[distractor1, distractor2, distractor3, correct_answer]}}"
228
+ ```
229
+
230
+ Task implementers are thus able to decide what the answer choices should be for a document, and what prompt format to use.
231
+
232
+ The label index can also be sourced from a feature directly. For example in `superglue/boolq`, the label index if defined in the feature `label`. We can set `doc_to_target` as simply `label`. The options or verbalizers can be written in the form of a list `["no", "yes"]` that will correspond to the label index.
233
+
234
+ ```yaml
235
+ doc_to_text: "{{passage}}\nQuestion: {{question}}?\nAnswer:"
236
+ doc_to_target: label
237
+ doc_to_choice: ["no", "yes"]
238
+ ```
239
+
240
+ ### Using Python Functions for Prompts
241
+
242
+ There may be cases where the prompt we want to implement is easier expressed in Python instead of Jinja 2. For this, we can use Python helper functions that are defined in the YAML config. It should be noted that the function script must be in the same directory as the yaml.
243
+
244
+ A good example is WikiText that requires a lot of regex rules to clean the samples.
245
+
246
+ ```python
247
+ def wikitext_detokenizer(doc):
248
+ string = doc["page"]
249
+ # contractions
250
+ string = string.replace("s '", "s'")
251
+ string = re.sub(r"/' [0-9]/", r"/'[0-9]/", string)
252
+ ...
253
+ string = string.replace(" 's", "'s")
254
+
255
+ return string
256
+ ```
257
+
258
+ We can load this function in `doc_to_target` by using a `!function` operator after `doc_to_target` and followed by `<file name>.<function name>`. In the file [wikitext.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/wikitext/wikitext.yaml) we write:
259
+
260
+ ```yaml
261
+ doc_to_target: !function preprocess_wikitext.wikitext_detokenizer
262
+ ```
263
+
264
+ ### Importing a Prompt from Promptsource
265
+
266
+ [Promptsource](https://github.com/bigscience-workshop/promptsource/tree/main/promptsource) is a great repository for crowdsourced prompts for many datasets. We can load these prompts easily by using the `use_prompt` argument and filling it with the format `"promptsource:<name of prompt template>"`. To use this, `doc_to_text` and `doc_to_target` should be left undefined. This will fetch the template of the dataset defined in the YAML file.
267
+
268
+ For example, For Super Glue BoolQ, if we want to use the prompt template `GPT-3 Style` we can add this to the YAML file.
269
+
270
+ ```yaml
271
+ use_prompt: "promptsource:GPT-3 Style"
272
+ ```
273
+
274
+ If you would like to run evaluation on all prompt templates, you can simply call it this way.
275
+
276
+ ```yaml
277
+ use_prompt: "promptsource:*"
278
+ ```
279
+
280
+ ### Setting metrics
281
+
282
+ You're almost done! Now we need to choose how to score our task.
283
+
284
+ - *If this is a multiple choice task:* do you just want to check your model's accuracy in choosing the correct answer choice?
285
+ - *If this is a generation task:* do you just want to check how often your model outputs *exactly the ground-truth output string provided*?
286
+
287
+ If the answer to the above is no: you'll need to record what scoring metrics to use! Metrics can be listed in the following format:
288
+
289
+ ```yaml
290
+ metric_list:
291
+ - metric: <name of the metric here>
292
+ aggregation: <name of the aggregation fn here>
293
+ higher_is_better: <true or false>
294
+ - metric: !function script.function
295
+ aggregation: ...
296
+ higher_is_better: ...
297
+ ```
298
+
299
+ `aggregation` and `higher_is_better` can optionally be left out to default to the manually-set defaults if using a natively supported metric, otherwise it must be defined explicitly (for example, when using a custom metric implemented as a function).
300
+
301
+ For a full list of natively supported metrics and aggregation functions see [`docs/task_guide.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/task_guide.md). All metrics supported in [HuggingFace Evaluate](https://github.com/huggingface/evaluate/tree/main/metrics) can also be used, and will be loaded if a given metric name is not one natively supported in `lm-eval` or `hf_evaluate` is set to `true`.
302
+
303
+ ### Optional, More Advanced Setup
304
+
305
+ Some tasks may require more advanced processing logic than is described in this guide.
306
+
307
+ As a heuristic check:
308
+
309
+ - Does your task require generating multiple free-form outputs per input document?
310
+ - Does your task require complex, multi-step post-processing of generated model outputs?
311
+ - Does your task require subsetting documents on the fly based on their content?
312
+ - Do you expect to compute metrics after applying multiple such processing steps on your model outputs?
313
+ - Does your task rely on metrics that need a custom implementation?
314
+
315
+ For more detail on the task system and advanced features, see [`docs/task_guide.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/task_guide.md). If none of the above sounds like they apply to your task, it's time to continue onto checking your task performance!
316
+
317
+ ### Task name + tags (registering a task)
318
+
319
+ To test a task conveniently, it helps to *register* the task--that is, to give it a name and make the `lm-eval` library aware it exists!
320
+
321
+ If you're writing your YAML file inside the `lm_eval/tasks` folder, you just need to give your task a name! You can do this inside your YAML file:
322
+
323
+ ```yaml
324
+ task: <name of the task>
325
+ ```
326
+
327
+ Including a task name is mandatory.
328
+
329
+ It is often also convenient to label your task with several `tag` values, though this field is optional:
330
+
331
+ ```yaml
332
+ tag:
333
+ - tag1
334
+ - tag2
335
+ ```
336
+
337
+ This will add your task to the `tag1` and `tag2` tags, enabling people to know how to categorize your task, and if desired run all tasks in one of these groups at once, your task along with them.
338
+
339
+ If your task is not in the `lm_eval/tasks` folder, you'll need to tell the Eval Harness where to look for YAML files.
340
+
341
+ You can do this via the `--include_path` argument in `__main__.py`. This command will be used to initialize the `TaskManager` object which you can also use for your custom scripts.
342
+
343
+ ```python
344
+ task_manager = TaskManager(args.verbosity, include_path=args.include_path)
345
+ ```
346
+
347
+ Passing `--tasks /path/to/yaml/file` is also accepted.
348
+
349
+ ### Advanced Group Configs
350
+
351
+ While `tag` values are helpful when you want to be able to quickly and conveniently run a set of related tasks via `--tasks my_tag_name`, often, we wish to implement more complex logic. For example, the MMLU benchmark contains 57 *subtasks* that must all be *averaged* together in order to report a final 'MMLU score'.
352
+
353
+ Groupings of tasks might also use particular variants of a task--for example, we might want to default to evaluating a task as 5-shot when called as part of a given grouping, but not have a preference for number of shots when evaluating it as a standalone.
354
+
355
+ We implement this via **groups**, which are distinct from tags. Groups can be implemented via *group config* YAML files, which are laid out similarly but slightly differently to tasks' YAML configs.
356
+
357
+ The most basic form of group can be defined via a YAML config similar to the following:
358
+
359
+ ```yaml
360
+ group: nli_tasks
361
+ task:
362
+ - cb
363
+ - anli_r1
364
+ - rte
365
+ metadata:
366
+ version: 1.0
367
+ ```
368
+
369
+ This will behave almost identically to a `tag` that includes these 3 tasks, but with one key distinction: we'll print the `nli_tasks` group as a row (with no associated metrics) in our table of outputs, and visually show that these 3 tasks appear under its subheader.
370
+
371
+ Now, let's assume we actually want to report an aggregate score for `nli_tasks`. We would instead use a YAML config like the following:
372
+
373
+ ```yaml
374
+ group: nli_tasks
375
+ task:
376
+ - cb
377
+ - anli_r1
378
+ - rte
379
+ aggregate_metric_list:
380
+ - metric: acc
381
+ aggregation: mean
382
+ weight_by_size: true # defaults to `true`. Set this to `false` to do a "macro" average (taking each subtask's average accuracy, and summing those accuracies and dividing by 3)--by default we do a "micro" average (retain all subtasks' per-document accuracies, and take the mean over all documents' accuracies to get our aggregate mean).
383
+ metadata:
384
+ version: 1.0
385
+ ```
386
+
387
+ Similar to our `metric_list` for listing out the metrics we want to calculate for a given task, we use an `aggregate_metric_list` field to specify which metric name to aggregate across subtasks, what aggregation function to use, and whether we should micro- or macro- average these metrics. See [./task_guide.md](./task_guide.md) for a full list of related sub-keys.
388
+
389
+ **[!Tip]: currently, we predominantly only support the aggregation of group metrics that use `mean` (either micro- or macro- averaged) over their subtasks. If you require even more complex aggregation rules, you may want to perform aggregation offline.**
390
+
391
+ Group configs can be fairly complex! We can do various operations, such as defining new subtask(s) inline in our group YAML, overriding an existing task's specific config value, or nesting existing groups within our
392
+
393
+ For example, let's build a config for evaluating MMLU and a few natural language inference tasks. For MMLU, we can write the name for the benchmark as a subtask written under `task`. You can configure the parameters such as `num_fewshot`. If the task being configured is a group such as `mmlu` or `super_glue`, the parameter set will be applied to all of the subtasks.
394
+
395
+ ```yaml
396
+ group: nli_and_mmlu
397
+ task:
398
+ - group: nli_tasks
399
+ task:
400
+ - cb
401
+ - anli_r1
402
+ - rte
403
+ aggregate_metric_list:
404
+ - metric: acc
405
+ aggregation: mean
406
+ higher_is_better: true
407
+ - task: mmlu
408
+ num_fewshot: 2
409
+ ```
410
+
411
+ ### Configuring python classes
412
+
413
+ There can be occasions when yaml-based tasks cannot accommodate how a task is handled. LM-Eval supports the manually implementing tasks as was previously done before `0.4.x`. To register the task, you can simply make a yaml with the name of the task in `task` and the class object in `class` using the `!function` prefix.
414
+
415
+ ```yaml
416
+ task: squadv2
417
+ class: !function task.SQuAD2
418
+ ```
419
+
420
+ This also applies to building group configurations with subtasks that are python classes.
421
+
422
+ ```yaml
423
+ group: scrolls
424
+ task:
425
+ - task: scrolls_qasper
426
+ class: !function task.Qasper
427
+ - task: scrolls_quality
428
+ class: !function task.QuALITY
429
+ - task: scrolls_narrativeqa
430
+ class: !function task.NarrativeQA
431
+ ...
432
+ ```
433
+
434
+ You can also pass a custom argument to your class by accepting `config` in the custom class constructor.
435
+ Here's how to do it:
436
+
437
+ ```yaml
438
+ task: 20_newsgroups
439
+ class: !function task.Unitxt
440
+ recipe: card=cards.20_newsgroups,template=templates.classification.multi_class.title
441
+ ```
442
+
443
+ In this example, `recipe` is the custom argument for the `Unitxt` class.
444
+
445
+ ## Beautifying Table Display
446
+
447
+ To avoid conflict, each task needs to be registered with a unique name. Because of this, slight variations of task are still counted as unique tasks and need to be named uniquely. This could be done by appending an additional naming that may refer to the variation such as in MMLU where the template used to evaluated for flan are differentiated from the default by the prefix `mmlu_flan_*`. Printing the full task names can easily clutter the results table at the end of the evaluation especially when you have a long list of tasks or are using a benchmark that comprises of many tasks. To make it more legible, you can use `task_alias` and `group_alias` to provide an alternative task name and group name that will be printed. For example in `mmlu_abstract_algebra.yaml` we set `task_alias` to `abstract_algebra`. In group configs, a `group_alias` for a group can also be set.
448
+
449
+ ```yaml
450
+ "dataset_name": "abstract_algebra"
451
+ "description": "The following are multiple choice questions (with answers) about abstract\
452
+ \ algebra.\n\n"
453
+ "include": "_default_template_yaml"
454
+ "task": "mmlu_abstract_algebra"
455
+ "task_alias": "abstract_algebra"
456
+ ```
457
+
458
+ ## Checking validity
459
+
460
+ After registering your task, you can now check on your data downloading and verify that the few-shot samples look as intended. Run the following command with your desired args:
461
+
462
+ ```bash
463
+ python -m scripts.write_out \
464
+ --output_base_path <path> \
465
+ --tasks <your-task-name> \
466
+ --sets <train | val | test> \
467
+ --num_fewshot K \
468
+ --num_examples N \
469
+ ```
470
+
471
+ Open the file specified at the `--output_base_path <path>` and ensure it passes
472
+ a simple eye test.
473
+
474
+ ## Versioning
475
+
476
+ One key feature in LM Evaluation Harness is the ability to version tasks and groups--that is, mark them with a specific version number that can be bumped whenever a breaking change is made.
477
+
478
+ This version info can be provided by adding the following to your new task or group config file:
479
+
480
+ ```yaml
481
+ metadata:
482
+ version: 0
483
+ ```
484
+
485
+ Now, whenever a change needs to be made to your task in the future, please increase the version number by 1 so that users can differentiate the different task iterations and versions.
486
+
487
+ If you are incrementing a task's version, please also consider adding a changelog to the task's README.md noting the date, PR number, what version you have updated to, and a one-liner describing the change.
488
+
489
+ for example,
490
+
491
+ - \[Dec 25, 2023\] (PR #999) Version 0.0 -> 1.0: Fixed a bug with answer extraction that led to underestimated performance.
492
+
493
+ ## Checking performance + equivalence
494
+
495
+ It's now time to check models' performance on your task! In the evaluation harness, we intend to support a wide range of evaluation tasks and setups, but prioritize the inclusion of already-proven benchmarks following the precise evaluation setups in the literature where possible.
496
+
497
+ To enable this, we provide a checklist that should be completed when contributing a new task, to enable accurate book-keeping and to ensure that tasks added to the library are well-tested and, where applicable, precedented.
498
+
499
+ ### Task Validity Checklist
500
+
501
+ The checklist is the following:
502
+
503
+ For adding novel benchmarks/datasets to the library:
504
+
505
+ - [ ] Is the task an existing benchmark in the literature?
506
+ - [ ] Have you referenced the original paper that introduced the task?
507
+ - [ ] If yes, does the original paper provide a reference implementation? If so, have you checked against the reference implementation and documented how to run such a test?
508
+
509
+ If other tasks on this dataset are already supported:
510
+
511
+ - [ ] Is the "Main" variant of this task clearly denoted?
512
+ - [ ] Have you provided a short sentence in a README on what each new variant adds / evaluates?
513
+ - [ ] Have you noted which, if any, published evaluation setups are matched by this variant?
514
+
515
+ It is recommended to include a filled-out copy of this checklist in the README.md for the subfolder you are creating, if you have created a new subfolder in `lm_eval/tasks`.
516
+
517
+ **Finally, please add a short description of your task(s), along with a link to its subfolder in lm_eval/tasks, to [`lm_eval/tasks/README.md`](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/README.md) so that users can discover your task in the library, and follow the link to your README for more information about the variants supported, their task names, and the original source of the dataset and/or evaluation setup.**
518
+
519
+ ## Submitting your task
520
+
521
+ You're all set! Now push your work and make a pull request to the `main` branch! Thanks for the contribution :). If there are any questions, please leave a message in the `#lm-thunderdome` channel on the EAI discord!
lm-evaluation-harness/docs/task_guide.md ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Task Configuration
2
+
3
+ The `lm-evaluation-harness` is meant to be an extensible and flexible framework within which many different evaluation tasks can be defined. All tasks in the new version of the harness are built around a YAML configuration file format.
4
+
5
+ These YAML configuration files, along with the current codebase commit hash, are intended to be shareable such that providing the YAML config enables another researcher to precisely replicate the evaluation setup used by another, in the case that the prompt or setup differs from standard `lm-eval` task implementations.
6
+
7
+ While adding a standard evaluation task on a new dataset can be occasionally as simple as swapping out a Hugging Face dataset path in an existing file, more specialized evaluation setups also exist. Here we'll provide a crash course on the more advanced logic implementable in YAML form available to users.
8
+
9
+ If your intended task relies on features beyond what is described in this guide, we'd love to hear about it! Feel free to open an issue describing the scenario on Github, create a PR to the project with a proposed implementation, or ask in the `#lm-thunderdome` channel on the EleutherAI discord.
10
+
11
+ ## Configurations
12
+
13
+ Tasks are configured via the `TaskConfig` object. Below, we describe all fields usable within the object, and their role in defining a task.
14
+
15
+ ### Parameters
16
+
17
+ Task naming + registration:
18
+
19
+ - **task** (`str`, defaults to None) — name of the task.
20
+ - **task_alias** (`str`, defaults to None) - Alias of the task name that will be printed in the final table results.
21
+ - **tag** (`str`, *optional*) — name of the task tags(s) a task belongs to. Enables one to run all tasks with a specified tag name at once.
22
+
23
+ Dataset configuration options:
24
+
25
+ - **dataset_path** (`str`) — The name of the dataset as listed by HF in the datasets Hub.
26
+ - **dataset_name** (`str`, *optional*, defaults to None) — The name of what HF calls a “data instance” or sub-task of the benchmark. If your task does not contain any data instances, just leave this to default to None. (If you're familiar with the HF `datasets.load_dataset` function, these are just the first 2 arguments to it.)
27
+ - **dataset_kwargs** (`dict`, *optional*) — Auxiliary arguments that `datasets.load_dataset` accepts. This can be used to specify arguments such as `data_files` or `data_dir` if you want to use local datafiles such as json or csv.
28
+ - **custom_dataset** (`Callable`, *optional) - A function that returns a `dict[str, datasets.Dataset]` (<split_name>, dataset) object. This can be used to load a dataset from a custom source or to preprocess the dataset in a way that is not supported by the `datasets` library. Will have access to `metadata` field if defined (from config and passed to TaskManager), and `model_args` from runtime (if using `evaluate`).
29
+ - **training_split** (`str`, *optional*) — Split in the dataset to use as the training split.
30
+ - **validation_split** (`str`, *optional*) — Split in the dataset to use as the validation split.
31
+ - **test_split** (`str`, *optional*) — Split in the dataset to use as the test split.
32
+ - **fewshot_split** (`str`, *optional*) — Split in the dataset to draw few-shot exemplars from. assert that this not None if num_fewshot > 0.
33
+ - **process_docs** (`Callable`, *optional*) — Optionally define a function to apply to each HF dataset split, to preprocess all documents before being fed into prompt template rendering or other evaluation steps. Can be used to rename dataset columns, or to process documents into a format closer to the expected format expected by a prompt template.
34
+
35
+ Prompting / in-context formatting options:
36
+
37
+ - **use_prompt** (`str`, *optional*) — Name of prompt in promptsource to use. if defined, will overwrite doc_to_text, doc_to_target, and doc_to_choice.
38
+ - **description** (`str`, *optional*) — An optional prepended Jinja2 template or string which will be prepended to the few-shot examples passed into the model, often describing the task or providing instructions to a model, such as `"The following are questions (with answers) about {{subject}}.\n\n"`. No delimiters or spacing are inserted between the description and the first few-shot example.
39
+ - **doc_to_text** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into the appropriate input for the model.
40
+ - **doc_to_target** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into the appropriate target output for the model. For multiple choice tasks, this should return an index into the answer choice list of the correct answer.
41
+ - **doc_to_choice** (`Union[Callable, str]`, *optional*) — Jinja2 template, string, or function to process a sample into a list of possible string choices for `multiple_choice` tasks. Left undefined for `generate_until` tasks.
42
+ - **fewshot_delimiter** (`str`, *optional*, defaults to "\n\n") — String to insert between few-shot examples.
43
+ - **target_delimiter** (`str`, *optional*, defaults to `" "`) — String to insert between input and target output for the datapoint being tested.
44
+ - **gen_prefix** (`str`, *optional*) — String to append after the <|assistant|> token. For example, if the task is to generate a question, the gen_prefix could be "The answer is: " to prompt the model to generate an answer to the question. If not using a chat template then this string will be appended to the end of the prompt.
45
+
46
+ Runtime configuration options:
47
+
48
+ - **num_fewshot** (`int`, *optional*, defaults to 0) — Number of few-shot examples before the input.
49
+ - **batch_size** (`int`, *optional*, defaults to 1) — Batch size.
50
+
51
+ Scoring details:
52
+
53
+ - **metric_list** (`str`, *optional*, defaults to None) — A list of metrics to use for evaluation. See docs for expected format.
54
+ - **output_type** (`str`, *optional*, defaults to "generate_until") — Selects the type of model output for the given task. Options are `generate_until`, `loglikelihood`, `loglikelihood_rolling`, and `multiple_choice`.
55
+ - **generation_kwargs** (`dict`, *optional*) — Auxiliary arguments for the `generate` function from HF transformers library. Advanced keyword arguments may not be supported for non-HF LM classes.
56
+ - **repeats** (`int`, *optional*, defaults to 1) — Number of repeated runs through model for each sample. Can be used for cases such as self-consistency.
57
+ - **filter_list** (`Union[str, list]`, *optional*) — List of filters to postprocess model outputs. See below for further detail on the filter API.
58
+ - **should_decontaminate** (`bool`, *optional*, defaults to False) - Whether to decontaminate or not.
59
+ - **doc_to_decontamination_query** (`str`, *optional*) — Query for decontamination if `should_decontaminate` is True. If `should_decontaminate` is True but `doc_to_decontamination_query` is `None`, `doc_to_decontamination_query` will follow `doc_to_text`.
60
+
61
+ Other:
62
+
63
+ - **metadata** (`dict`, *optional*) — An optional field where arbitrary metadata can be passed. Most tasks should include a `version` key in this field that is used to denote the version of the yaml config. Other special metadata keys are: `num_fewshot`, to override the printed `n-shot` table column for a task. Will also be passed to the `custom_dataset` function if defined.
64
+
65
+ ## Filters
66
+
67
+ A key component of the `lm-evaluation-harness` library is the `Filter` object. In a typical evaluation run of the harness, we take the formatted inputs and run them through our LM, with the appropriate output type (greedy or free-form generation, or loglikelihood-based comparative scoring).
68
+
69
+ After getting scores or output text from our LM on each `Instance` or document in the dataset, we then need to feed these responses into a metric or scoring function to return scores to a user.
70
+
71
+ However, certain tasks may require more complex behavior than directly turning over model outputs to a metric function. For example, we may want to post-process our output text by truncating it or extracting a model's answer, we may want to ensemble over multiple "takes" on a different document, et cetera.
72
+
73
+ **Detailed Aside**:
74
+ We do such post-processing by operating on *responses*, which are stored after running an LM on an `Instance` from the task in `Instance.resps`.
75
+
76
+ `resps` is a `List[str]` for each instance, and we pass a `List[List[<expected return type from model>]]` to our filters that is a list of `[instance.resps for instance in instances]`.
77
+
78
+ Our filters, after completing a pipeline, must return a `List[<expected return type from model>]` which we then unpack and store each element of in `Instance.filtered_resps` for the corresponding instance. Thus, we take as input a list of returns from our model for each doc, and must return a return from our model *without it being wrapped in a list* for each doc.
79
+ **End Aside**
80
+
81
+ A full list of supported filter operations can be found in `lm_eval/filters/__init__.py`. Contributions of new filter types are welcome!
82
+
83
+ ### Multiple Filter Pipelines
84
+
85
+ Tasks need not be limited to a single filter pipeline. We enable users to run multiple, distinct, filter pipelines on *the same model outputs* generated in one run on a task.
86
+
87
+ As a case study, let's look at an implementation of solving the Gsm8k math word problem benchmark in `lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml`. Here, we are emulating the setup used by [Self-Consistency Improves Chain of Thought Prompting](https://arxiv.org/abs/2203.11171), in which evaluation is performed by generating N chain-of-thought outputs from a model via temperature-based sampling, then selecting the answers output by the model at the end of the chains of thought, then majority voting across all those numeric answers.
88
+
89
+ Within our YAML file:
90
+
91
+ ```yaml
92
+ ...
93
+ repeats: 64
94
+ filter_list:
95
+ - name: "score-first"
96
+ filter:
97
+ - function: "regex"
98
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
99
+ - function: "take_first"
100
+ - name: "maj@64"
101
+ filter:
102
+ - function: "regex"
103
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
104
+ - function: "majority_vote"
105
+ - function: "take_first"
106
+ - name: "maj@8"
107
+ filter:
108
+ - function: "take_first_k"
109
+ k: 8
110
+ - function: "regex"
111
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
112
+ - function: "majority_vote"
113
+ - function: "take_first"
114
+ ```
115
+
116
+ We are able to provide multiple different filter pipelines, each with their own name and list of filters to apply in sequence.
117
+
118
+ Our first filter pipeline implements
119
+
120
+ - applying a regex to the model generations (extracting the number within the phrase "The answer is (number)")
121
+ - selecting only the first out of the 64 model answers
122
+
123
+ Then scoring this single answer.
124
+
125
+ ```yaml
126
+ - name: "score-first"
127
+ filter:
128
+ - function: "regex"
129
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
130
+ - function: "take_first"
131
+ ```
132
+
133
+ Our second filter pipeline, "maj@64", does majority voting across all 64 answers via:
134
+
135
+ - applying the same regex to all responses, to get the numerical answer from the model for each of the 64 responses per problem
136
+ - applying majority voting to all responses, which then returns a length-1 `[<majority answer>]` list for each
137
+ - taking the first element of this length-1 list, to then score the sole response `<majority answer>` for each document.
138
+
139
+ ```yaml
140
+ - name: "maj@64"
141
+ filter:
142
+ - function: "regex"
143
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
144
+ - function: "majority_vote"
145
+ - function: "take_first"
146
+ ```
147
+
148
+ Our final filter pipeline, "maj@8", does majority voting across the first 8 of the model's responses per document via:
149
+
150
+ - subsetting the len-64 list of responses `[answer1, answer2, ..., answer64]` to `[answer1, answer2, ..., answer8]` for each document
151
+ - performing the same sequence of filters on these new sets of 8 responses, for each document.
152
+
153
+ ```yaml
154
+ - name: "maj@8"
155
+ filter:
156
+ - function: "take_first_k"
157
+ k: 8
158
+ - function: "regex"
159
+ regex_pattern: "The answer is (\\-?[0-9\\.\\,]*[0-9]+)"
160
+ - function: "majority_vote"
161
+ - function: "take_first"
162
+ ```
163
+
164
+ Thus, given the 64 responses from our LM on each document, we can report metrics on these responses in these 3 different ways, as defined by our filter pipelines.
165
+
166
+ ### Adding a custom filter
167
+
168
+ Just like adding a custom model with `register_model` decorator one is able to do the same with filters, for example
169
+
170
+ ```python
171
+ from lm_eval.api.filter import Filter
172
+ from lm_eval.api.registry import register_filter
173
+
174
+ @register_filter("new_filter")
175
+ class NewFilter(Filter)
176
+ ...
177
+ ```
178
+
179
+ ## Embedded Python Code
180
+
181
+ Use can use python functions for certain arguments by using the `!function` operator after the argument name followed by `<filename>.<pythonfunctionname>`. This feature can be used for the following arguments:
182
+
183
+ 1. `doc_to_text`
184
+ 2. `doc_to_target`
185
+ 3. `doc_to_choice`
186
+ 4. `aggregation` for a `metric` in `metric_list`
187
+
188
+ ## (No Longer Recommended) Direct `Task` Subclassing
189
+
190
+ The prior implementation method of new tasks was to subclass `Task`. While we intend to migrate all tasks to the new YAML implementation option going forward, it remains possible to subclass the Task class and implement custom logic. For more information, see `docs/task_guide.md` in v0.3.0 of the `lm-evaluation-harness`.
191
+
192
+ ## Including a Base YAML
193
+
194
+ You can base a YAML on another YAML file as a template. This can be handy when you need to just change the prompt for `doc_to_text` but keep the rest the same or change `filters` to compare which is better. Simply use `include` in the YAML file and write the name of the template you want to base from. This assumes that the base template is in the same directory. Otherwise, You will need to define the full path.
195
+
196
+ ```yaml
197
+ include: <YAML filename or with full path>
198
+ ...
199
+ ```
200
+
201
+ You can find an example of how to use this feature at [gsm8k-cot-self-consistency.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml) where it is based off [gsm8k-cot.yaml](https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/gsm8k/gsm8k-cot.yaml)
202
+
203
+ ## Passing Arguments to Metrics
204
+
205
+ Metrics can be defined in the `metric_list` argument when building the YAML config. Multiple metrics can be listed along with any auxiliary arguments. For example, setting the [`exact_match` metric](https://github.com/huggingface/evaluate/tree/main/metrics/exact_match), auxiliary arguments such as `ignore_case`, `ignore_punctuation`, `regexes_to_ignore` can be listed as well. They will be added to the metric function as `kwargs`. Some metrics have predefined values for `aggregation` and `higher_is_better` so listing the metric name only can be sufficient.
206
+
207
+ ```yaml
208
+ metric_list:
209
+ - metric: acc
210
+ - metric: exact_match
211
+ aggregation: mean
212
+ higher_is_better: true
213
+ ignore_case: true
214
+ ignore_punctuation: false
215
+ regexes_to_ignore:
216
+ - ","
217
+ - "\\$"
218
+ ```
219
+
220
+ ### Natively Supported Metrics
221
+
222
+ Here we list all metrics currently supported natively in `lm-eval`:
223
+
224
+ Metrics:
225
+
226
+ - `acc` (accuracy)
227
+ - `acc_norm` (length-normalized accuracy)
228
+ - `acc_mutual_info` (baseline loglikelihood - normalized accuracy)
229
+ - `perplexity`
230
+ - `word_perplexity` (perplexity per word)
231
+ - `byte_perplexity` (perplexity per byte)
232
+ - `bits_per_byte`
233
+ - `matthews_corrcoef` (Matthews correlation coefficient)
234
+ - `f1` (F1 score)
235
+ - `bleu`
236
+ - `chrf`
237
+ - `ter`
238
+
239
+ Aggregation functions:
240
+
241
+ - `mean`
242
+ - `median`
243
+ - `perplexity`
244
+ - `weighted_perplexity`
245
+ - `bits_per_byte`
246
+
247
+ ### Adding a Multiple Choice Metric
248
+
249
+ Adding a multiple choice metric has a few steps. To get it working you need to:
250
+
251
+ 1. register a metric function
252
+ 2. register an aggregation function
253
+ 3. update the `Task` definition to make sure the correct arguments are passed
254
+
255
+ The default metric and aggregation functions are in `lm_eval/api/metrics.py`, and you can add a function there if it's for general use. The metrics are towards the bottom of the file and look like this:
256
+
257
+ ```python
258
+ @register_metric(
259
+ metric="mcc",
260
+ higher_is_better=True,
261
+ output_type="multiple_choice",
262
+ aggregation="matthews_corrcoef",
263
+ )
264
+ def mcc_fn(items): # This is a passthrough function
265
+ return items
266
+ ```
267
+
268
+ Note that many of these are passthrough functions, and for multiple choice (at least) this function is never actually called.
269
+
270
+ Aggregation functions are defined towards the top of the file, here's an example:
271
+
272
+ ```python
273
+ @register_aggregation("matthews_corrcoef")
274
+ def matthews_corrcoef(items):
275
+ unzipped_list = list(zip(*items))
276
+ golds = unzipped_list[0]
277
+ preds = unzipped_list[1]
278
+ return sklearn.metrics.matthews_corrcoef(golds, preds)
279
+ ```
280
+
281
+ This function returns a single numeric value. The input is defined in `Task.process_results` in `lm_eval/api/task.py`. There's a section that looks like this:
282
+
283
+ ```python
284
+ result_dict = {
285
+ **({"acc": acc} if "acc" in use_metric else {}),
286
+ **({"f1": (gold, pred)} if "f1" in use_metric else {}),
287
+ **({"mcc": (gold, pred)} if "mcc" in use_metric else {}),
288
+ **({"acc_norm": acc_norm} if "acc_norm" in use_metric else {}),
289
+ **({"exact_match": exact_match} if "exact_match" in use_metric else {}),
290
+ }
291
+ ```
292
+
293
+ The value here determines the input to the aggregation function, though the name used matches the metric function. These metrics all have simple needs and just need the accuracy or gold and predicted values, but immediately below this there are examples of metrics with more complicated needs you can use as reference.
294
+
295
+ ## Good Reference Tasks
296
+
297
+ Contributing a new task can be daunting! Luckily, much of the work has often been done for you in a different, similarly evaluated task. Good examples of task implementations to study include:
298
+
299
+ Multiple choice tasks:
300
+
301
+ - SciQ (`lm_eval/tasks/sciq/sciq.yaml`)
302
+
303
+ Corpus perplexity evaluations:
304
+
305
+ - Wikitext (`lm_eval/tasks/wikitext/wikitext.yaml`)
306
+
307
+ Generative tasks:
308
+
309
+ - GSM8k (`lm_eval/tasks/gsm8k/gsm8k.yaml`)
310
+
311
+ Tasks using complex filtering:
312
+
313
+ - GSM8k with CoT (+ with Self-Consistency): (`lm_eval/tasks/gsm8k/gsm8k-cot.yaml` ; `lm_eval/tasks/gsm8k/gsm8k-cot-self-consistency.yaml`)
314
+
315
+ # Group Configuration
316
+
317
+ When evaluating a language model, it is not unusual to test across a number of tasks that may not be related to one another in order to assess a variety of capabilities. To this end, it may be cumbersome to have to list the set of tasks or add a new group name to each yaml of each individual task.
318
+
319
+ To solve this, we can create a **group** yaml config. This is a config that contains the names of the tasks that should be included in a particular group. The config consists of two main keys: a `group` key which denotes the name of the group (as it would be called from the command line, e.g. `mmlu`) and a `task` key which is where we can list the tasks. The tasks listed in `task` are the task names that have been registered. A good example of a group yaml config can be found at [../lm_eval/tasks/mmlu/default/_mmlu.yaml]. See also the [New Task Guide](./new_task_guide.md) for a more in-depth and tutorial-esque explanation of how to write complex GroupConfigs.
320
+
321
+ ## Configurations
322
+
323
+ Groups are configured via the `GroupConfig` object. Below, we describe all fields usable within the object, and their role in defining a task.
324
+
325
+ ### Parameters
326
+
327
+ - **group** (`str`, defaults to `None`) — name of the group. Used to invoke it from the command line.
328
+ - **group_alias** (`str`, defaults to `None`) - Alternative name for the group that will be printed in the table output.
329
+ - **task** (`Union[str, list]`, defaults to `None`) - List of tasks that constitute the group.
330
+ - **aggregate_metric_list** (`list`, defaults to `None`) - similar to `metric_list` in TaskConfigs, provide a list of configurations for metrics that should be aggregated across subtasks. Leaving empty will result in no aggregation being performed for this group. Keys for each list entry are:
331
+ - `metric: str` - the name of the metric to aggregate over (all subtasks must report a metric holding this name.)
332
+ - `aggregation: str` - what aggregation function to apply to aggregate these per-subtask metrics. **currently, only `mean` is supported.**
333
+ - `weight_by_size: bool = True` whether to perform micro- averaging (`True`) or macro- (`False`) averaging of subtasks' accuracy scores when reporting the group's metric. MMLU, for example, averages over per-document accuracies (the *micro average*), resulting in the same accuracy as if one simply concatenated all 57 subjects into a single dataset and evaluated accuracy on that dataset.
334
+ - `filter_list: Union[str, List[str]] = "none"` - what filter keys one should match on to aggregate results. For example, if trying to aggregate over the `exact_match` metric using `strict-match` filter for `bbh_cot_zeroshot`, then set this to be `filter_list: "strict-match"`.
335
+ - **metadata** (`dict`, *optional*) - As with TaskConfigs, a field where extra config metadata can be passed. set the `num_fewshot` key within this to override the printed n_shot value in a results table for your group, for example.
lm-evaluation-harness/eval.log ADDED
The diff for this file is too large to render. See raw diff
 
lm-evaluation-harness/examples/lm-eval-overview.ipynb ADDED
@@ -0,0 +1,1240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "Qw83KAePAhaS"
7
+ },
8
+ "source": [
9
+ "# Releasing LM-Evaluation-Harness v0.4.0"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {
15
+ "id": "Z7k2vq1iAdqr"
16
+ },
17
+ "source": [
18
+ "With the vast amount of work done in the field today, it helps to have a tool that people can use easily to share their results and use to check others to ensure reported numbers are valid. The LM Evaluation Harness is one such tool the community has used extensively. We want to continue to support the community and with that in mind, we’re excited to announce a major update on the LM Evaluation Harness to further our goal for open and accessible AI research."
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "metadata": {
24
+ "id": "0gDoM0AJAvEc"
25
+ },
26
+ "source": [
27
+ "Our refactor stems from our desires to make the following believed best practices easier to carry out. \n",
28
+ "\n",
29
+ "1. Never copy results from other papers\n",
30
+ "2. Always share your exact prompts\n",
31
+ "3. Always provide model outputs\n",
32
+ "4. Qualitatively review a small batch of outputs before running evaluation jobs at scale\n",
33
+ "\n",
34
+ "We also wanted to make the library a better experience to use and to contribute or design evaluations within. New features in the new release that serve this purpose include:\n",
35
+ "\n",
36
+ "1. Faster Evaluation Runtimes (accelerated data-parallel inference with HF Transformers + Accelerate, and commonly used or faster inference libraries such as vLLM and Llama-CPP)\n",
37
+ "2. Easier addition and sharing of new tasks (YAML-based task config formats, allowing single-file sharing of custom tasks)\n",
38
+ "3. More configurability, for more advanced workflows and easier operation with modifying prompts\n",
39
+ "4. Better logging of data at runtime and post-hoc"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "markdown",
44
+ "metadata": {
45
+ "id": "nnwsOpjda_YW"
46
+ },
47
+ "source": [
48
+ "In this notebook we will be going through a short tutorial on how things work."
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "markdown",
53
+ "metadata": {
54
+ "id": "zAov81vTbL2K"
55
+ },
56
+ "source": [
57
+ "## Install LM-Eval"
58
+ ]
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "execution_count": 1,
63
+ "metadata": {
64
+ "colab": {
65
+ "base_uri": "https://localhost:8080/"
66
+ },
67
+ "id": "8hiosGzq_qZg",
68
+ "outputId": "6ab73e5e-1f54-417e-a388-07e0d870b132"
69
+ },
70
+ "outputs": [
71
+ {
72
+ "name": "stdout",
73
+ "output_type": "stream",
74
+ "text": [
75
+ "Collecting git+https://github.com/EleutherAI/lm-evaluation-harness.git@big-refactor\n",
76
+ " Cloning https://github.com/EleutherAI/lm-evaluation-harness.git (to revision big-refactor) to /tmp/pip-req-build-tnssql5s\n",
77
+ " Running command git clone --filter=blob:none --quiet https://github.com/EleutherAI/lm-evaluation-harness.git /tmp/pip-req-build-tnssql5s\n",
78
+ " Running command git checkout -b big-refactor --track origin/big-refactor\n",
79
+ " Switched to a new branch 'big-refactor'\n",
80
+ " Branch 'big-refactor' set up to track remote branch 'big-refactor' from 'origin'.\n",
81
+ " Resolved https://github.com/EleutherAI/lm-evaluation-harness.git to commit 42f486ee49b65926a444cb0620870a39a5b4b0a8\n",
82
+ " Installing build dependencies ... \u001b[?25l\u001b[?25hdone\n",
83
+ " Getting requirements to build wheel ... \u001b[?25l\u001b[?25hdone\n",
84
+ " Preparing metadata (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
85
+ "Collecting accelerate>=0.21.0 (from lm-eval==1.0.0)\n",
86
+ " Downloading accelerate-0.24.1-py3-none-any.whl (261 kB)\n",
87
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m261.4/261.4 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
88
+ "\u001b[?25hCollecting evaluate (from lm-eval==1.0.0)\n",
89
+ " Downloading evaluate-0.4.1-py3-none-any.whl (84 kB)\n",
90
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m84.1/84.1 kB\u001b[0m \u001b[31m5.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
91
+ "\u001b[?25hCollecting datasets>=2.0.0 (from lm-eval==1.0.0)\n",
92
+ " Downloading datasets-2.15.0-py3-none-any.whl (521 kB)\n",
93
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m521.2/521.2 kB\u001b[0m \u001b[31m9.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
94
+ "\u001b[?25hCollecting jsonlines (from lm-eval==1.0.0)\n",
95
+ " Downloading jsonlines-4.0.0-py3-none-any.whl (8.7 kB)\n",
96
+ "Requirement already satisfied: numexpr in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (2.8.7)\n",
97
+ "Collecting peft>=0.2.0 (from lm-eval==1.0.0)\n",
98
+ " Downloading peft-0.6.2-py3-none-any.whl (174 kB)\n",
99
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m174.7/174.7 kB\u001b[0m \u001b[31m7.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
100
+ "\u001b[?25hCollecting pybind11>=2.6.2 (from lm-eval==1.0.0)\n",
101
+ " Downloading pybind11-2.11.1-py3-none-any.whl (227 kB)\n",
102
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m227.7/227.7 kB\u001b[0m \u001b[31m12.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
103
+ "\u001b[?25hCollecting pytablewriter (from lm-eval==1.0.0)\n",
104
+ " Downloading pytablewriter-1.2.0-py3-none-any.whl (111 kB)\n",
105
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m111.1/111.1 kB\u001b[0m \u001b[31m8.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
106
+ "\u001b[?25hCollecting rouge-score>=0.0.4 (from lm-eval==1.0.0)\n",
107
+ " Downloading rouge_score-0.1.2.tar.gz (17 kB)\n",
108
+ " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
109
+ "Collecting sacrebleu>=1.5.0 (from lm-eval==1.0.0)\n",
110
+ " Downloading sacrebleu-2.3.2-py3-none-any.whl (119 kB)\n",
111
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m119.7/119.7 kB\u001b[0m \u001b[31m8.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
112
+ "\u001b[?25hRequirement already satisfied: scikit-learn>=0.24.1 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (1.2.2)\n",
113
+ "Collecting sqlitedict (from lm-eval==1.0.0)\n",
114
+ " Downloading sqlitedict-2.1.0.tar.gz (21 kB)\n",
115
+ " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
116
+ "Requirement already satisfied: torch>=1.8 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (2.1.0+cu118)\n",
117
+ "Collecting tqdm-multiprocess (from lm-eval==1.0.0)\n",
118
+ " Downloading tqdm_multiprocess-0.0.11-py3-none-any.whl (9.8 kB)\n",
119
+ "Requirement already satisfied: transformers>=4.1 in /usr/local/lib/python3.10/dist-packages (from lm-eval==1.0.0) (4.35.2)\n",
120
+ "Collecting zstandard (from lm-eval==1.0.0)\n",
121
+ " Downloading zstandard-0.22.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (5.4 MB)\n",
122
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m5.4/5.4 MB\u001b[0m \u001b[31m29.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
123
+ "\u001b[?25hRequirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (1.23.5)\n",
124
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (23.2)\n",
125
+ "Requirement already satisfied: psutil in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (5.9.5)\n",
126
+ "Requirement already satisfied: pyyaml in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (6.0.1)\n",
127
+ "Requirement already satisfied: huggingface-hub in /usr/local/lib/python3.10/dist-packages (from accelerate>=0.21.0->lm-eval==1.0.0) (0.19.4)\n",
128
+ "Requirement already satisfied: pyarrow>=8.0.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (9.0.0)\n",
129
+ "Collecting pyarrow-hotfix (from datasets>=2.0.0->lm-eval==1.0.0)\n",
130
+ " Downloading pyarrow_hotfix-0.6-py3-none-any.whl (7.9 kB)\n",
131
+ "Collecting dill<0.3.8,>=0.3.0 (from datasets>=2.0.0->lm-eval==1.0.0)\n",
132
+ " Downloading dill-0.3.7-py3-none-any.whl (115 kB)\n",
133
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m115.3/115.3 kB\u001b[0m \u001b[31m14.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
134
+ "\u001b[?25hRequirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (1.5.3)\n",
135
+ "Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (2.31.0)\n",
136
+ "Requirement already satisfied: tqdm>=4.62.1 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (4.66.1)\n",
137
+ "Requirement already satisfied: xxhash in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (3.4.1)\n",
138
+ "Collecting multiprocess (from datasets>=2.0.0->lm-eval==1.0.0)\n",
139
+ " Downloading multiprocess-0.70.15-py310-none-any.whl (134 kB)\n",
140
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m134.8/134.8 kB\u001b[0m \u001b[31m19.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
141
+ "\u001b[?25hRequirement already satisfied: fsspec[http]<=2023.10.0,>=2023.1.0 in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (2023.6.0)\n",
142
+ "Requirement already satisfied: aiohttp in /usr/local/lib/python3.10/dist-packages (from datasets>=2.0.0->lm-eval==1.0.0) (3.8.6)\n",
143
+ "Collecting responses<0.19 (from evaluate->lm-eval==1.0.0)\n",
144
+ " Downloading responses-0.18.0-py3-none-any.whl (38 kB)\n",
145
+ "Requirement already satisfied: safetensors in /usr/local/lib/python3.10/dist-packages (from peft>=0.2.0->lm-eval==1.0.0) (0.4.0)\n",
146
+ "Requirement already satisfied: absl-py in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (1.4.0)\n",
147
+ "Requirement already satisfied: nltk in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (3.8.1)\n",
148
+ "Requirement already satisfied: six>=1.14.0 in /usr/local/lib/python3.10/dist-packages (from rouge-score>=0.0.4->lm-eval==1.0.0) (1.16.0)\n",
149
+ "Collecting portalocker (from sacrebleu>=1.5.0->lm-eval==1.0.0)\n",
150
+ " Downloading portalocker-2.8.2-py3-none-any.whl (17 kB)\n",
151
+ "Requirement already satisfied: regex in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (2023.6.3)\n",
152
+ "Requirement already satisfied: tabulate>=0.8.9 in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (0.9.0)\n",
153
+ "Collecting colorama (from sacrebleu>=1.5.0->lm-eval==1.0.0)\n",
154
+ " Downloading colorama-0.4.6-py2.py3-none-any.whl (25 kB)\n",
155
+ "Requirement already satisfied: lxml in /usr/local/lib/python3.10/dist-packages (from sacrebleu>=1.5.0->lm-eval==1.0.0) (4.9.3)\n",
156
+ "Requirement already satisfied: scipy>=1.3.2 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (1.11.3)\n",
157
+ "Requirement already satisfied: joblib>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (1.3.2)\n",
158
+ "Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from scikit-learn>=0.24.1->lm-eval==1.0.0) (3.2.0)\n",
159
+ "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.13.1)\n",
160
+ "Requirement already satisfied: typing-extensions in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (4.5.0)\n",
161
+ "Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (1.12)\n",
162
+ "Requirement already satisfied: networkx in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.2.1)\n",
163
+ "Requirement already satisfied: jinja2 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (3.1.2)\n",
164
+ "Requirement already satisfied: triton==2.1.0 in /usr/local/lib/python3.10/dist-packages (from torch>=1.8->lm-eval==1.0.0) (2.1.0)\n",
165
+ "Requirement already satisfied: tokenizers<0.19,>=0.14 in /usr/local/lib/python3.10/dist-packages (from transformers>=4.1->lm-eval==1.0.0) (0.15.0)\n",
166
+ "Requirement already satisfied: attrs>=19.2.0 in /usr/local/lib/python3.10/dist-packages (from jsonlines->lm-eval==1.0.0) (23.1.0)\n",
167
+ "Requirement already satisfied: setuptools>=38.3.0 in /usr/local/lib/python3.10/dist-packages (from pytablewriter->lm-eval==1.0.0) (67.7.2)\n",
168
+ "Collecting DataProperty<2,>=1.0.1 (from pytablewriter->lm-eval==1.0.0)\n",
169
+ " Downloading DataProperty-1.0.1-py3-none-any.whl (27 kB)\n",
170
+ "Collecting mbstrdecoder<2,>=1.0.0 (from pytablewriter->lm-eval==1.0.0)\n",
171
+ " Downloading mbstrdecoder-1.1.3-py3-none-any.whl (7.8 kB)\n",
172
+ "Collecting pathvalidate<4,>=2.3.0 (from pytablewriter->lm-eval==1.0.0)\n",
173
+ " Downloading pathvalidate-3.2.0-py3-none-any.whl (23 kB)\n",
174
+ "Collecting tabledata<2,>=1.3.1 (from pytablewriter->lm-eval==1.0.0)\n",
175
+ " Downloading tabledata-1.3.3-py3-none-any.whl (11 kB)\n",
176
+ "Collecting tcolorpy<1,>=0.0.5 (from pytablewriter->lm-eval==1.0.0)\n",
177
+ " Downloading tcolorpy-0.1.4-py3-none-any.whl (7.9 kB)\n",
178
+ "Collecting typepy[datetime]<2,>=1.3.2 (from pytablewriter->lm-eval==1.0.0)\n",
179
+ " Downloading typepy-1.3.2-py3-none-any.whl (31 kB)\n",
180
+ "Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (3.3.2)\n",
181
+ "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (6.0.4)\n",
182
+ "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (4.0.3)\n",
183
+ "Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.9.2)\n",
184
+ "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.4.0)\n",
185
+ "Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.10/dist-packages (from aiohttp->datasets>=2.0.0->lm-eval==1.0.0) (1.3.1)\n",
186
+ "Requirement already satisfied: chardet<6,>=3.0.4 in /usr/local/lib/python3.10/dist-packages (from mbstrdecoder<2,>=1.0.0->pytablewriter->lm-eval==1.0.0) (5.2.0)\n",
187
+ "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (3.4)\n",
188
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (2.0.7)\n",
189
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests>=2.19.0->datasets>=2.0.0->lm-eval==1.0.0) (2023.7.22)\n",
190
+ "Requirement already satisfied: python-dateutil<3.0.0,>=2.8.0 in /usr/local/lib/python3.10/dist-packages (from typepy[datetime]<2,>=1.3.2->pytablewriter->lm-eval==1.0.0) (2.8.2)\n",
191
+ "Requirement already satisfied: pytz>=2018.9 in /usr/local/lib/python3.10/dist-packages (from typepy[datetime]<2,>=1.3.2->pytablewriter->lm-eval==1.0.0) (2023.3.post1)\n",
192
+ "Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.10/dist-packages (from jinja2->torch>=1.8->lm-eval==1.0.0) (2.1.3)\n",
193
+ "Requirement already satisfied: click in /usr/local/lib/python3.10/dist-packages (from nltk->rouge-score>=0.0.4->lm-eval==1.0.0) (8.1.7)\n",
194
+ "Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.10/dist-packages (from sympy->torch>=1.8->lm-eval==1.0.0) (1.3.0)\n",
195
+ "Building wheels for collected packages: lm-eval, rouge-score, sqlitedict\n",
196
+ " Building wheel for lm-eval (pyproject.toml) ... \u001b[?25l\u001b[?25hdone\n",
197
+ " Created wheel for lm-eval: filename=lm_eval-1.0.0-py3-none-any.whl size=994254 sha256=88356155b19f2891981ecef948326ad6ce8ca40a6009378410ec20d0e225995a\n",
198
+ " Stored in directory: /tmp/pip-ephem-wheel-cache-9v6ye7h3/wheels/17/01/26/599c0779e9858a70a73fa8a306699b5b9a868f820c225457b0\n",
199
+ " Building wheel for rouge-score (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
200
+ " Created wheel for rouge-score: filename=rouge_score-0.1.2-py3-none-any.whl size=24933 sha256=6bb0d44e4881972c43ce194e7cb65233d309758cb15f0dec54590d3d2efcfc36\n",
201
+ " Stored in directory: /root/.cache/pip/wheels/5f/dd/89/461065a73be61a532ff8599a28e9beef17985c9e9c31e541b4\n",
202
+ " Building wheel for sqlitedict (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
203
+ " Created wheel for sqlitedict: filename=sqlitedict-2.1.0-py3-none-any.whl size=16863 sha256=5747f7dd73ddf3d8fbcebf51b5e4f718fabe1e94bccdf16d2f22a2e65ee7fdf4\n",
204
+ " Stored in directory: /root/.cache/pip/wheels/79/d6/e7/304e0e6cb2221022c26d8161f7c23cd4f259a9e41e8bbcfabd\n",
205
+ "Successfully built lm-eval rouge-score sqlitedict\n",
206
+ "Installing collected packages: sqlitedict, zstandard, tcolorpy, pybind11, pyarrow-hotfix, portalocker, pathvalidate, mbstrdecoder, jsonlines, dill, colorama, typepy, tqdm-multiprocess, sacrebleu, rouge-score, responses, multiprocess, accelerate, datasets, DataProperty, tabledata, peft, evaluate, pytablewriter, lm-eval\n",
207
+ "Successfully installed DataProperty-1.0.1 accelerate-0.24.1 colorama-0.4.6 datasets-2.15.0 dill-0.3.7 evaluate-0.4.1 jsonlines-4.0.0 lm-eval-1.0.0 mbstrdecoder-1.1.3 multiprocess-0.70.15 pathvalidate-3.2.0 peft-0.6.2 portalocker-2.8.2 pyarrow-hotfix-0.6 pybind11-2.11.1 pytablewriter-1.2.0 responses-0.18.0 rouge-score-0.1.2 sacrebleu-2.3.2 sqlitedict-2.1.0 tabledata-1.3.3 tcolorpy-0.1.4 tqdm-multiprocess-0.0.11 typepy-1.3.2 zstandard-0.22.0\n"
208
+ ]
209
+ }
210
+ ],
211
+ "source": [
212
+ "# Install LM-Eval\n",
213
+ "!pip install git+https://github.com/EleutherAI/lm-evaluation-harness.git"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": 2,
219
+ "metadata": {
220
+ "colab": {
221
+ "base_uri": "https://localhost:8080/",
222
+ "height": 0,
223
+ "referenced_widgets": [
224
+ "a1d3a8aa016544a78e8821c8f6199e06",
225
+ "f61ed33fad754146bdd2ac9db1ba1c48",
226
+ "bfa0af6aeff344c6845e1080a878e92e",
227
+ "fd1ad9e0367d4004aae853b91c3a7617",
228
+ "6b2d90209ec14230b3d58a74ac9b83bf",
229
+ "a73f357065d34d7baf0453ae4a8d75e2",
230
+ "46f521b73fd943c081c648fd873ebc0a",
231
+ "7c5689bc13684db8a22681f41863dddd",
232
+ "48763b6233374554ae76035c0483066f",
233
+ "4986a21eb560448fa79f4b25cde48951",
234
+ "aed3acd2f2d74003b44079c333a0698e"
235
+ ]
236
+ },
237
+ "id": "uyO5MaKkZyah",
238
+ "outputId": "d46e8096-5086-4e49-967e-ea33d4a2a335"
239
+ },
240
+ "outputs": [
241
+ {
242
+ "data": {
243
+ "application/vnd.jupyter.widget-view+json": {
244
+ "model_id": "a1d3a8aa016544a78e8821c8f6199e06",
245
+ "version_major": 2,
246
+ "version_minor": 0
247
+ },
248
+ "text/plain": [
249
+ "Downloading builder script: 0%| | 0.00/5.67k [00:00<?, ?B/s]"
250
+ ]
251
+ },
252
+ "metadata": {},
253
+ "output_type": "display_data"
254
+ }
255
+ ],
256
+ "source": []
257
+ },
258
+ {
259
+ "cell_type": "markdown",
260
+ "metadata": {
261
+ "id": "8rfUeX6n_wkK"
262
+ },
263
+ "source": [
264
+ "## Create new evaluation tasks with config-based tasks\n",
265
+ "\n",
266
+ "Even within the same task, many works have reported numbers based on different choices of evaluation. Some report on the test sets, validation sets, or even subset of the training sets. Others have specialized prompts and verbalizers. We introduce YAMLs to allow users to easily make different variations. By leveraging the YAML configs to configure evaluations, the refactored LM-Eval takes the methods of the `Task` object and makes them configurable by setting the appropriate attributes in the config file. There, users can set the tasks they want by setting the name of the HF dataset (local tasks are also possible), the dataset splits used, and much more. Key configurations relating to prompting, such as `doc_to_text`, previously implemented as a method of the same name, are now configurable with jinja2 to allow high-level scripting to transform a HF dataset to text string as input to the model.\n",
267
+ "\n"
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "markdown",
272
+ "metadata": {
273
+ "id": "HYFUhhfOSJKe"
274
+ },
275
+ "source": [
276
+ "A core-feature to LM-Eval is to configure tasks with YAML configs. With configs, you can fill preset fields to easily set up a task.\n",
277
+ "\n",
278
+ "Here, we write a demo YAML config for a multiple-choice evaluation of BoolQ:"
279
+ ]
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "execution_count": 3,
284
+ "metadata": {
285
+ "id": "bg3dGROW-V39"
286
+ },
287
+ "outputs": [],
288
+ "source": [
289
+ "YAML_boolq_string = \"\"\"\n",
290
+ "task: demo_boolq\n",
291
+ "dataset_path: super_glue\n",
292
+ "dataset_name: boolq\n",
293
+ "output_type: multiple_choice\n",
294
+ "training_split: train\n",
295
+ "validation_split: validation\n",
296
+ "doc_to_text: \"{{passage}}\\nQuestion: {{question}}?\\nAnswer:\"\n",
297
+ "doc_to_target: label\n",
298
+ "doc_to_choice: [\"no\", \"yes\"]\n",
299
+ "should_decontaminate: true\n",
300
+ "doc_to_decontamination_query: passage\n",
301
+ "metric_list:\n",
302
+ " - metric: acc\n",
303
+ "\"\"\"\n",
304
+ "with open(\"boolq.yaml\", \"w\") as f:\n",
305
+ " f.write(YAML_boolq_string)"
306
+ ]
307
+ },
308
+ {
309
+ "cell_type": "markdown",
310
+ "metadata": {},
311
+ "source": [
312
+ "And we can now run evaluation on this task, by pointing to the config file we've just created:"
313
+ ]
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "execution_count": 4,
318
+ "metadata": {
319
+ "id": "LOUHK7PtQfq4"
320
+ },
321
+ "outputs": [
322
+ {
323
+ "name": "stdout",
324
+ "output_type": "stream",
325
+ "text": [
326
+ "2023-11-29:11:54:55,156 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
327
+ "2023-11-29 11:54:55.942051: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
328
+ "2023-11-29 11:54:55.942108: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
329
+ "2023-11-29 11:54:55.942142: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
330
+ "2023-11-29 11:54:57.066802: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
331
+ "2023-11-29:11:55:00,954 INFO [__main__.py:132] Verbosity set to INFO\n",
332
+ "2023-11-29:11:55:11,038 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
333
+ "2023-11-29:11:55:11,038 INFO [__main__.py:143] Including path: ./\n",
334
+ "2023-11-29:11:55:11,046 INFO [__main__.py:205] Selected Tasks: ['demo_boolq']\n",
335
+ "2023-11-29:11:55:11,047 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
336
+ "2023-11-29:11:55:11,110 INFO [huggingface.py:120] Using device 'cuda'\n",
337
+ "config.json: 100% 571/571 [00:00<00:00, 2.87MB/s]\n",
338
+ "model.safetensors: 100% 5.68G/5.68G [00:32<00:00, 173MB/s]\n",
339
+ "tokenizer_config.json: 100% 396/396 [00:00<00:00, 2.06MB/s]\n",
340
+ "tokenizer.json: 100% 2.11M/2.11M [00:00<00:00, 11.6MB/s]\n",
341
+ "special_tokens_map.json: 100% 99.0/99.0 [00:00<00:00, 555kB/s]\n",
342
+ "2023-11-29:11:56:18,658 WARNING [task.py:614] [Task: demo_boolq] metric acc is defined, but aggregation is not. using default aggregation=mean\n",
343
+ "2023-11-29:11:56:18,658 WARNING [task.py:626] [Task: demo_boolq] metric acc is defined, but higher_is_better is not. using default higher_is_better=True\n",
344
+ "Downloading builder script: 100% 30.7k/30.7k [00:00<00:00, 59.0MB/s]\n",
345
+ "Downloading metadata: 100% 38.7k/38.7k [00:00<00:00, 651kB/s]\n",
346
+ "Downloading readme: 100% 14.8k/14.8k [00:00<00:00, 37.3MB/s]\n",
347
+ "Downloading data: 100% 4.12M/4.12M [00:00<00:00, 55.1MB/s]\n",
348
+ "Generating train split: 100% 9427/9427 [00:00<00:00, 15630.89 examples/s]\n",
349
+ "Generating validation split: 100% 3270/3270 [00:00<00:00, 20002.56 examples/s]\n",
350
+ "Generating test split: 100% 3245/3245 [00:00<00:00, 20866.19 examples/s]\n",
351
+ "2023-11-29:11:56:22,315 INFO [task.py:355] Building contexts for task on rank 0...\n",
352
+ "2023-11-29:11:56:22,322 INFO [evaluator.py:319] Running loglikelihood requests\n",
353
+ "100% 20/20 [00:04<00:00, 4.37it/s]\n",
354
+ "fatal: not a git repository (or any of the parent directories): .git\n",
355
+ "hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
356
+ "| Tasks |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
357
+ "|----------|-------|------|-----:|------|----:|---|-----:|\n",
358
+ "|demo_boolq|Yaml |none | 0|acc | 1|± | 0|\n",
359
+ "\n"
360
+ ]
361
+ }
362
+ ],
363
+ "source": [
364
+ "%env LOGLEVEL=DEBUG\n",
365
+ "!lm_eval \\\n",
366
+ " --model hf \\\n",
367
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
368
+ " --include_path ./ \\\n",
369
+ " --tasks demo_boolq \\\n",
370
+ " --limit 10"
371
+ ]
372
+ },
373
+ {
374
+ "cell_type": "markdown",
375
+ "metadata": {
376
+ "id": "LOUHK7PtQfq4"
377
+ },
378
+ "source": [
379
+ "Often, tasks are part of a larger group used to measure different capabilities. The dynamism of the field today means new dimensions of evaluation can come about which would mix and match new and older tasks alike. In LM-Eval, We can also group tasks and call that the group name to evaluate on a set of tasks easily. In this instance, let's evaluate the tag `yes_or_no_tasks` which comprise of the tasks `demo_boolq` and `demo_cola`; tasks which are multiple choice tasks with options `yes` and `no` as the name suggests.\n",
380
+ "\n",
381
+ "<!-- making new groups is easier than ever, allowing user to work bottom-up by makiing individual tasks and linking them to a group or Top-Down, making a new group by listing existing tasks.\n",
382
+ "\n",
383
+ "We also show the aggregate across samples besides only showing the aggregation between subtasks. This may come in handy when certain groups want to be aggregated as a single task. -->\n",
384
+ "\n",
385
+ "\n"
386
+ ]
387
+ },
388
+ {
389
+ "cell_type": "code",
390
+ "execution_count": 5,
391
+ "metadata": {
392
+ "id": "fthNg3ywO-kA"
393
+ },
394
+ "outputs": [],
395
+ "source": [
396
+ "YAML_cola_string = \"\"\"\n",
397
+ "tag: yes_or_no_tasks\n",
398
+ "task: demo_cola\n",
399
+ "dataset_path: glue\n",
400
+ "dataset_name: cola\n",
401
+ "output_type: multiple_choice\n",
402
+ "training_split: train\n",
403
+ "validation_split: validation\n",
404
+ "doc_to_text: \"{{sentence}}\\nQuestion: Does this sentence make sense?\\nAnswer:\"\n",
405
+ "doc_to_target: label\n",
406
+ "doc_to_choice: [\"no\", \"yes\"]\n",
407
+ "should_decontaminate: true\n",
408
+ "doc_to_decontamination_query: sentence\n",
409
+ "metric_list:\n",
410
+ " - metric: acc\n",
411
+ "\"\"\"\n",
412
+ "with open(\"cola.yaml\", \"w\") as f:\n",
413
+ " f.write(YAML_cola_string)"
414
+ ]
415
+ },
416
+ {
417
+ "cell_type": "code",
418
+ "execution_count": 6,
419
+ "metadata": {
420
+ "id": "XceRKCuuDtbn"
421
+ },
422
+ "outputs": [
423
+ {
424
+ "name": "stdout",
425
+ "output_type": "stream",
426
+ "text": [
427
+ "2023-11-29:11:56:33,016 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
428
+ "2023-11-29 11:56:33.852995: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
429
+ "2023-11-29 11:56:33.853050: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
430
+ "2023-11-29 11:56:33.853087: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
431
+ "2023-11-29 11:56:35.129047: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
432
+ "2023-11-29:11:56:38,546 INFO [__main__.py:132] Verbosity set to INFO\n",
433
+ "2023-11-29:11:56:47,509 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
434
+ "2023-11-29:11:56:47,509 INFO [__main__.py:143] Including path: ./\n",
435
+ "2023-11-29:11:56:47,517 INFO [__main__.py:205] Selected Tasks: ['yes_or_no_tasks']\n",
436
+ "2023-11-29:11:56:47,520 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
437
+ "2023-11-29:11:56:47,550 INFO [huggingface.py:120] Using device 'cuda'\n",
438
+ "2023-11-29:11:57:08,743 WARNING [task.py:614] [Task: demo_cola] metric acc is defined, but aggregation is not. using default aggregation=mean\n",
439
+ "2023-11-29:11:57:08,743 WARNING [task.py:626] [Task: demo_cola] metric acc is defined, but higher_is_better is not. using default higher_is_better=True\n",
440
+ "Downloading builder script: 100% 28.8k/28.8k [00:00<00:00, 52.7MB/s]\n",
441
+ "Downloading metadata: 100% 28.7k/28.7k [00:00<00:00, 51.9MB/s]\n",
442
+ "Downloading readme: 100% 27.9k/27.9k [00:00<00:00, 48.0MB/s]\n",
443
+ "Downloading data: 100% 377k/377k [00:00<00:00, 12.0MB/s]\n",
444
+ "Generating train split: 100% 8551/8551 [00:00<00:00, 19744.58 examples/s]\n",
445
+ "Generating validation split: 100% 1043/1043 [00:00<00:00, 27057.01 examples/s]\n",
446
+ "Generating test split: 100% 1063/1063 [00:00<00:00, 22705.17 examples/s]\n",
447
+ "2023-11-29:11:57:11,698 INFO [task.py:355] Building contexts for task on rank 0...\n",
448
+ "2023-11-29:11:57:11,704 INFO [evaluator.py:319] Running loglikelihood requests\n",
449
+ "100% 20/20 [00:03<00:00, 5.15it/s]\n",
450
+ "fatal: not a git repository (or any of the parent directories): .git\n",
451
+ "hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
452
+ "| Tasks |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
453
+ "|---------------|-------|------|-----:|------|----:|---|-----:|\n",
454
+ "|yes_or_no_tasks|N/A |none | 0|acc | 0.7|± |0.1528|\n",
455
+ "| - demo_cola |Yaml |none | 0|acc | 0.7|± |0.1528|\n",
456
+ "\n",
457
+ "| Groups |Version|Filter|n-shot|Metric|Value| |Stderr|\n",
458
+ "|---------------|-------|------|-----:|------|----:|---|-----:|\n",
459
+ "|yes_or_no_tasks|N/A |none | 0|acc | 0.7|± |0.1528|\n",
460
+ "\n"
461
+ ]
462
+ }
463
+ ],
464
+ "source": [
465
+ "# !accelerate launch --no_python\n",
466
+ "%env LOGLEVEL=DEBUG\n",
467
+ "!lm_eval \\\n",
468
+ " --model hf \\\n",
469
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
470
+ " --include_path ./ \\\n",
471
+ " --tasks yes_or_no_tasks \\\n",
472
+ " --limit 10 \\\n",
473
+ " --output output/yes_or_no_tasks/ \\\n",
474
+ " --log_samples"
475
+ ]
476
+ },
477
+ {
478
+ "cell_type": "markdown",
479
+ "metadata": {
480
+ "id": "XceRKCuuDtbn"
481
+ },
482
+ "source": [
483
+ "## Edit Prompt Templates Quickly\n",
484
+ "\n",
485
+ "The following is a yaml made to evaluate the specific subtask of `high_school_geography` from MMLU. It uses the standard prompt where the we choose the letters from the options with most likelihood as the model's prediction."
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "code",
490
+ "execution_count": 7,
491
+ "metadata": {
492
+ "id": "GTFvdt9kSlBG"
493
+ },
494
+ "outputs": [],
495
+ "source": [
496
+ "YAML_mmlu_geo_string = \"\"\"\n",
497
+ "task: demo_mmlu_high_school_geography\n",
498
+ "dataset_path: cais/mmlu\n",
499
+ "dataset_name: high_school_geography\n",
500
+ "description: \"The following are multiple choice questions (with answers) about high school geography.\\n\\n\"\n",
501
+ "test_split: test\n",
502
+ "fewshot_split: dev\n",
503
+ "fewshot_config:\n",
504
+ " sampler: first_n\n",
505
+ "output_type: multiple_choice\n",
506
+ "doc_to_text: \"{{question.strip()}}\\nA. {{choices[0]}}\\nB. {{choices[1]}}\\nC. {{choices[2]}}\\nD. {{choices[3]}}\\nAnswer:\"\n",
507
+ "doc_to_choice: [\"A\", \"B\", \"C\", \"D\"]\n",
508
+ "doc_to_target: answer\n",
509
+ "metric_list:\n",
510
+ " - metric: acc\n",
511
+ " aggregation: mean\n",
512
+ " higher_is_better: true\n",
513
+ " - metric: acc_norm\n",
514
+ " aggregation: mean\n",
515
+ " higher_is_better: true\n",
516
+ "\"\"\"\n",
517
+ "with open(\"mmlu_high_school_geography.yaml\", \"w\") as f:\n",
518
+ " f.write(YAML_mmlu_geo_string)"
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "code",
523
+ "execution_count": 8,
524
+ "metadata": {
525
+ "id": "jyKOfCsKb-xy"
526
+ },
527
+ "outputs": [
528
+ {
529
+ "name": "stdout",
530
+ "output_type": "stream",
531
+ "text": [
532
+ "2023-11-29:11:57:23,598 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
533
+ "2023-11-29 11:57:24.719750: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
534
+ "2023-11-29 11:57:24.719806: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
535
+ "2023-11-29 11:57:24.719847: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
536
+ "2023-11-29 11:57:26.656125: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
537
+ "2023-11-29:11:57:31,563 INFO [__main__.py:132] Verbosity set to INFO\n",
538
+ "2023-11-29:11:57:40,541 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
539
+ "2023-11-29:11:57:40,541 INFO [__main__.py:143] Including path: ./\n",
540
+ "2023-11-29:11:57:40,558 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography']\n",
541
+ "2023-11-29:11:57:40,559 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
542
+ "2023-11-29:11:57:40,589 INFO [huggingface.py:120] Using device 'cuda'\n",
543
+ "Downloading builder script: 100% 5.84k/5.84k [00:00<00:00, 17.7MB/s]\n",
544
+ "Downloading metadata: 100% 106k/106k [00:00<00:00, 892kB/s] \n",
545
+ "Downloading readme: 100% 39.7k/39.7k [00:00<00:00, 631kB/s]\n",
546
+ "Downloading data: 100% 166M/166M [00:01<00:00, 89.0MB/s]\n",
547
+ "Generating auxiliary_train split: 100% 99842/99842 [00:07<00:00, 12536.83 examples/s]\n",
548
+ "Generating test split: 100% 198/198 [00:00<00:00, 1439.20 examples/s]\n",
549
+ "Generating validation split: 100% 22/22 [00:00<00:00, 4181.76 examples/s]\n",
550
+ "Generating dev split: 100% 5/5 [00:00<00:00, 36.25 examples/s]\n",
551
+ "2023-11-29:11:58:09,798 INFO [task.py:355] Building contexts for task on rank 0...\n",
552
+ "2023-11-29:11:58:09,822 INFO [evaluator.py:319] Running loglikelihood requests\n",
553
+ "100% 40/40 [00:05<00:00, 7.86it/s]\n",
554
+ "fatal: not a git repository (or any of the parent directories): .git\n",
555
+ "hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
556
+ "| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
557
+ "|-------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
558
+ "|demo_mmlu_high_school_geography|Yaml |none | 0|acc | 0.3|± |0.1528|\n",
559
+ "| | |none | 0|acc_norm| 0.3|± |0.1528|\n",
560
+ "\n"
561
+ ]
562
+ }
563
+ ],
564
+ "source": [
565
+ "# !accelerate launch --no_python\n",
566
+ "%env LOGLEVEL=DEBUG\n",
567
+ "!lm_eval \\\n",
568
+ " --model hf \\\n",
569
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
570
+ " --include_path ./ \\\n",
571
+ " --tasks demo_mmlu_high_school_geography \\\n",
572
+ " --limit 10 \\\n",
573
+ " --output output/mmlu_high_school_geography/ \\\n",
574
+ " --log_samples"
575
+ ]
576
+ },
577
+ {
578
+ "cell_type": "markdown",
579
+ "metadata": {
580
+ "id": "jyKOfCsKb-xy"
581
+ },
582
+ "source": [
583
+ "We could also evaluate this task in a different way. For example, instead of observing the loglikelihood of the letters, we can instead evaluate on the choices themselves as the continuation. This is done by simply changing `doc_to_choice` from a list of letters to the corresponding `choices` field from the HF dataset. We write `\"{{choices}}\"` so that the string field is interpreted as jinja string that acquires the list from the HF dataset directly.\n",
584
+ "\n",
585
+ "Another convenient feature here is since we're only modifying the `doc_to_choice` and the rest of config is the same as the task above, we can use the above configuration as a template by using `include: mmlu_high_school_geography.yaml` to load the config from that file. We'll need to add a unique task name as to not colide with the existing yaml config we're including. For this case we'll simply name this one `mmlu_high_school_geography_continuation`. `doc_to_text` is added here just for sake of clarity."
586
+ ]
587
+ },
588
+ {
589
+ "cell_type": "code",
590
+ "execution_count": 9,
591
+ "metadata": {
592
+ "id": "lqElwU54TaK-"
593
+ },
594
+ "outputs": [],
595
+ "source": [
596
+ "YAML_mmlu_geo_string = \"\"\"\n",
597
+ "include: mmlu_high_school_geography.yaml\n",
598
+ "task: demo_mmlu_high_school_geography_continuation\n",
599
+ "doc_to_text: \"{{question.strip()}}\\nA. {{choices[0]}}\\nB. {{choices[1]}}\\nC. {{choices[2]}}\\nD. {{choices[3]}}\\nAnswer:\"\n",
600
+ "doc_to_choice: \"{{choices}}\"\n",
601
+ "\"\"\"\n",
602
+ "with open(\"mmlu_high_school_geography_continuation.yaml\", \"w\") as f:\n",
603
+ " f.write(YAML_mmlu_geo_string)"
604
+ ]
605
+ },
606
+ {
607
+ "cell_type": "code",
608
+ "execution_count": 10,
609
+ "metadata": {
610
+ "id": "-_CVnDirdy7j"
611
+ },
612
+ "outputs": [
613
+ {
614
+ "name": "stdout",
615
+ "output_type": "stream",
616
+ "text": [
617
+ "2023-11-29:11:58:21,284 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
618
+ "2023-11-29 11:58:22.850159: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
619
+ "2023-11-29 11:58:22.850219: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
620
+ "2023-11-29 11:58:22.850254: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
621
+ "2023-11-29 11:58:24.948103: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
622
+ "2023-11-29:11:58:28,460 INFO [__main__.py:132] Verbosity set to INFO\n",
623
+ "2023-11-29:11:58:37,935 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
624
+ "2023-11-29:11:58:37,935 INFO [__main__.py:143] Including path: ./\n",
625
+ "2023-11-29:11:58:37,969 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography_continuation']\n",
626
+ "2023-11-29:11:58:37,972 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
627
+ "2023-11-29:11:58:38,008 INFO [huggingface.py:120] Using device 'cuda'\n",
628
+ "2023-11-29:11:58:59,758 INFO [task.py:355] Building contexts for task on rank 0...\n",
629
+ "2023-11-29:11:58:59,777 INFO [evaluator.py:319] Running loglikelihood requests\n",
630
+ "100% 40/40 [00:02<00:00, 16.23it/s]\n",
631
+ "fatal: not a git repository (or any of the parent directories): .git\n",
632
+ "hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
633
+ "| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
634
+ "|--------------------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
635
+ "|demo_mmlu_high_school_geography_continuation|Yaml |none | 0|acc | 0.1|± |0.1000|\n",
636
+ "| | |none | 0|acc_norm| 0.2|± |0.1333|\n",
637
+ "\n"
638
+ ]
639
+ }
640
+ ],
641
+ "source": [
642
+ "# !accelerate launch --no_python\n",
643
+ "%env LOGLEVEL=DEBUG\n",
644
+ "!lm_eval \\\n",
645
+ " --model hf \\\n",
646
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
647
+ " --include_path ./ \\\n",
648
+ " --tasks demo_mmlu_high_school_geography_continuation \\\n",
649
+ " --limit 10 \\\n",
650
+ " --output output/mmlu_high_school_geography_continuation/ \\\n",
651
+ " --log_samples"
652
+ ]
653
+ },
654
+ {
655
+ "cell_type": "markdown",
656
+ "metadata": {
657
+ "id": "-_CVnDirdy7j"
658
+ },
659
+ "source": [
660
+ "If we take a look at the samples, we can see that it is in fact evaluating the continuation based on the choices rather than the letters."
661
+ ]
662
+ },
663
+ {
664
+ "cell_type": "code",
665
+ "execution_count": 11,
666
+ "metadata": {
667
+ "id": "duBDqC6PAdjL"
668
+ },
669
+ "outputs": [
670
+ {
671
+ "data": {
672
+ "application/javascript": "\n ((filepath) => {{\n if (!google.colab.kernel.accessAllowed) {{\n return;\n }}\n google.colab.files.view(filepath);\n }})(\"/content/output/mmlu_high_school_geography_continuation/pretrained__EleutherAI__pythia-2.8b_demo_mmlu_high_school_geography_continuation.jsonl\")",
673
+ "text/plain": [
674
+ "<IPython.core.display.Javascript object>"
675
+ ]
676
+ },
677
+ "metadata": {},
678
+ "output_type": "display_data"
679
+ }
680
+ ],
681
+ "source": [
682
+ "from google.colab import files\n",
683
+ "\n",
684
+ "\n",
685
+ "files.view(\n",
686
+ " \"output/mmlu_high_school_geography_continuation/pretrained__EleutherAI__pythia-2.8b_demo_mmlu_high_school_geography_continuation.jsonl\"\n",
687
+ ")"
688
+ ]
689
+ },
690
+ {
691
+ "cell_type": "markdown",
692
+ "metadata": {
693
+ "id": "6p0-KPwAgK5j"
694
+ },
695
+ "source": [
696
+ "## Closer Look at YAML Fields\n",
697
+ "\n",
698
+ "To prepare a task we can simply fill in a YAML config with the relevant information.\n",
699
+ "\n",
700
+ "`output_type`\n",
701
+ "The current provided evaluation types comprise of the following:\n",
702
+ "1. `loglikelihood`: Evaluates the loglikelihood of a continuation, conditioned on some input string.\n",
703
+ "2. `loglikelihood_rolling`: evaluate the loglikelihood of producing a string, conditioned on the empty string. (Used for perplexity evaluations)\n",
704
+ "3. `multiple_choice`: Evaluates loglikelihood among the a number of choices predicted by the model.\n",
705
+ "4. `greedy_until`: Model outputs greedy generation (can be configured to to use beam search and other generation-related parameters)\n",
706
+ "\n",
707
+ "The core prompt revolves around 3 fields.\n",
708
+ "1. `doc_to_text`: Denotes the prompt template that will be used as input to the model.\n",
709
+ "2. `doc_to_choice`: Available choices that will be used as continuation for the model. This is used when the `output_type` is `multiple_choice`, and otherwise can be left as `None`.\n",
710
+ "3. `doc_to_target`: When `output_type` is `multiple_choice`, this can be an index that corresponds to the correct answer, or the answer string itself (must be a subset of `doc_to_choice`). For other tasks, this is expected to be a string. You can fill this field with a feature name from the HF dataset so long as the resulting feature follows the conditioned described.\n",
711
+ "\n",
712
+ "These three fields can be expressed as strings, column names from the source dataset, or as Jinja2 templates that can use fields from the source dataset as variables.\n"
713
+ ]
714
+ },
715
+ {
716
+ "cell_type": "markdown",
717
+ "metadata": {
718
+ "id": "6p0-KPwAgK5j"
719
+ },
720
+ "source": [
721
+ "## What if Jinja is not Sufficient?\n",
722
+ "\n",
723
+ "There can be times where the Jinja2 templating language is not enough to make the prompt we had in mind. There are a few ways to circumvent this limitation:\n",
724
+ "\n",
725
+ "1. Use `!function` operator for the prompt-related fields to pass a python function that takes as input the dataset row, and will output the prompt template component.\n",
726
+ "2. Perform a transformation on the dataset beforehand."
727
+ ]
728
+ },
729
+ {
730
+ "cell_type": "markdown",
731
+ "metadata": {},
732
+ "source": [
733
+ "Below, we show an example of using `!function` to create `doc_to_text` from a python function:"
734
+ ]
735
+ },
736
+ {
737
+ "cell_type": "code",
738
+ "execution_count": 12,
739
+ "metadata": {
740
+ "colab": {
741
+ "base_uri": "https://localhost:8080/"
742
+ },
743
+ "id": "DYZ5c0JhR1lJ",
744
+ "outputId": "ca945235-fb9e-4f17-8bfa-78e7d6ec1490"
745
+ },
746
+ "outputs": [
747
+ {
748
+ "name": "stdout",
749
+ "output_type": "stream",
750
+ "text": [
751
+ "2023-11-29:11:59:08,312 INFO [utils.py:160] NumExpr defaulting to 2 threads.\n",
752
+ "2023-11-29 11:59:09.348327: E tensorflow/compiler/xla/stream_executor/cuda/cuda_dnn.cc:9342] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered\n",
753
+ "2023-11-29 11:59:09.348387: E tensorflow/compiler/xla/stream_executor/cuda/cuda_fft.cc:609] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered\n",
754
+ "2023-11-29 11:59:09.348421: E tensorflow/compiler/xla/stream_executor/cuda/cuda_blas.cc:1518] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered\n",
755
+ "2023-11-29 11:59:10.573752: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
756
+ "2023-11-29:11:59:14,044 INFO [__main__.py:132] Verbosity set to INFO\n",
757
+ "2023-11-29:11:59:23,654 WARNING [__main__.py:138] --limit SHOULD ONLY BE USED FOR TESTING.REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.\n",
758
+ "2023-11-29:11:59:23,654 INFO [__main__.py:143] Including path: ./\n",
759
+ "2023-11-29:11:59:23,678 INFO [__main__.py:205] Selected Tasks: ['demo_mmlu_high_school_geography_function_prompt']\n",
760
+ "2023-11-29:11:59:23,679 WARNING [evaluator.py:93] generation_kwargs specified through cli, these settings will be used over set parameters in yaml tasks.\n",
761
+ "2023-11-29:11:59:23,708 INFO [huggingface.py:120] Using device 'cuda'\n",
762
+ "2023-11-29:11:59:44,516 INFO [task.py:355] Building contexts for task on rank 0...\n",
763
+ "2023-11-29:11:59:44,524 INFO [evaluator.py:319] Running loglikelihood requests\n",
764
+ "100% 40/40 [00:02<00:00, 15.41it/s]\n",
765
+ "fatal: not a git repository (or any of the parent directories): .git\n",
766
+ "hf (pretrained=EleutherAI/pythia-2.8b), gen_kwargs: (), limit: 10.0, num_fewshot: None, batch_size: 1\n",
767
+ "| Tasks |Version|Filter|n-shot| Metric |Value| |Stderr|\n",
768
+ "|-----------------------------------------------|-------|------|-----:|--------|----:|---|-----:|\n",
769
+ "|demo_mmlu_high_school_geography_function_prompt|Yaml |none | 0|acc | 0.1|± |0.1000|\n",
770
+ "| | |none | 0|acc_norm| 0.2|± |0.1333|\n",
771
+ "\n"
772
+ ]
773
+ }
774
+ ],
775
+ "source": [
776
+ "YAML_mmlu_geo_string = \"\"\"\n",
777
+ "include: mmlu_high_school_geography.yaml\n",
778
+ "task: demo_mmlu_high_school_geography_function_prompt\n",
779
+ "doc_to_text: !function utils.doc_to_text\n",
780
+ "doc_to_choice: \"{{choices}}\"\n",
781
+ "\"\"\"\n",
782
+ "with open(\"demo_mmlu_high_school_geography_function_prompt.yaml\", \"w\") as f:\n",
783
+ " f.write(YAML_mmlu_geo_string)\n",
784
+ "\n",
785
+ "DOC_TO_TEXT = \"\"\"\n",
786
+ "def doc_to_text(x):\n",
787
+ " question = x[\"question\"].strip()\n",
788
+ " choices = x[\"choices\"]\n",
789
+ " option_a = choices[0]\n",
790
+ " option_b = choices[1]\n",
791
+ " option_c = choices[2]\n",
792
+ " option_d = choices[3]\n",
793
+ " return f\"{question}\\\\nA. {option_a}\\\\nB. {option_b}\\\\nC. {option_c}\\\\nD. {option_d}\\\\nAnswer:\"\n",
794
+ "\"\"\"\n",
795
+ "with open(\"utils.py\", \"w\") as f:\n",
796
+ " f.write(DOC_TO_TEXT)\n",
797
+ "\n",
798
+ "!lm_eval \\\n",
799
+ " --model hf \\\n",
800
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
801
+ " --include_path ./ \\\n",
802
+ " --tasks demo_mmlu_high_school_geography_function_prompt \\\n",
803
+ " --limit 10 \\\n",
804
+ " --output output/demo_mmlu_high_school_geography_function_prompt/ \\\n",
805
+ " --log_samples"
806
+ ]
807
+ },
808
+ {
809
+ "cell_type": "markdown",
810
+ "metadata": {},
811
+ "source": [
812
+ "Next, we'll also show how to do this via preprocessing the dataset as necessary using the `process_docs` config field:\n",
813
+ "\n",
814
+ "We will write a function that will modify each document in our evaluation dataset's split to add a field that is suitable for us to use in `doc_to_text`."
815
+ ]
816
+ },
817
+ {
818
+ "cell_type": "code",
819
+ "execution_count": null,
820
+ "metadata": {},
821
+ "outputs": [],
822
+ "source": [
823
+ "YAML_mmlu_geo_string = \"\"\"\n",
824
+ "include: mmlu_high_school_geography.yaml\n",
825
+ "task: demo_mmlu_high_school_geography_function_prompt_2\n",
826
+ "process_docs: !function utils_process_docs.process_docs\n",
827
+ "doc_to_text: \"{{input}}\"\n",
828
+ "doc_to_choice: \"{{choices}}\"\n",
829
+ "\"\"\"\n",
830
+ "with open(\"demo_mmlu_high_school_geography_process_docs.yaml\", \"w\") as f:\n",
831
+ " f.write(YAML_mmlu_geo_string)\n",
832
+ "\n",
833
+ "DOC_TO_TEXT = \"\"\"\n",
834
+ "def process_docs(dataset):\n",
835
+ " def _process_doc(x):\n",
836
+ " question = x[\"question\"].strip()\n",
837
+ " choices = x[\"choices\"]\n",
838
+ " option_a = choices[0]\n",
839
+ " option_b = choices[1]\n",
840
+ " option_c = choices[2]\n",
841
+ " option_d = choices[3]\n",
842
+ " doc[\"input\"] = f\"{question}\\\\nA. {option_a}\\\\nB. {option_b}\\\\nC. {option_c}\\\\nD. {option_d}\\\\nAnswer:\"\n",
843
+ " return out_doc\n",
844
+ "\n",
845
+ " return dataset.map(_process_doc)\n",
846
+ "\"\"\"\n",
847
+ "\n",
848
+ "with open(\"utils_process_docs.py\", \"w\") as f:\n",
849
+ " f.write(DOC_TO_TEXT)\n",
850
+ "\n",
851
+ "!lm_eval \\\n",
852
+ " --model hf \\\n",
853
+ " --model_args pretrained=EleutherAI/pythia-2.8b \\\n",
854
+ " --include_path ./ \\\n",
855
+ " --tasks demo_mmlu_high_school_geography_function_prompt_2 \\\n",
856
+ " --limit 10 \\\n",
857
+ " --output output/demo_mmlu_high_school_geography_function_prompt_2/ \\\n",
858
+ " --log_samples"
859
+ ]
860
+ },
861
+ {
862
+ "cell_type": "markdown",
863
+ "metadata": {},
864
+ "source": [
865
+ "We hope that this explainer gives you a sense of what can be done with and how to work with LM-Evaluation-Harnes v0.4.0 ! \n",
866
+ "\n",
867
+ "For more information, check out our documentation pages in the `docs/` folder, and if you have questions, please raise them in GitHub issues, or in #lm-thunderdome or #release-discussion on the EleutherAI discord server."
868
+ ]
869
+ }
870
+ ],
871
+ "metadata": {
872
+ "accelerator": "GPU",
873
+ "colab": {
874
+ "collapsed_sections": [
875
+ "zAov81vTbL2K"
876
+ ],
877
+ "gpuType": "T4",
878
+ "provenance": []
879
+ },
880
+ "kernelspec": {
881
+ "display_name": "Python 3",
882
+ "name": "python3"
883
+ },
884
+ "language_info": {
885
+ "name": "python"
886
+ },
887
+ "widgets": {
888
+ "application/vnd.jupyter.widget-state+json": {
889
+ "state": {
890
+ "46f521b73fd943c081c648fd873ebc0a": {
891
+ "model_module": "@jupyter-widgets/controls",
892
+ "model_module_version": "1.5.0",
893
+ "model_name": "DescriptionStyleModel",
894
+ "state": {
895
+ "_model_module": "@jupyter-widgets/controls",
896
+ "_model_module_version": "1.5.0",
897
+ "_model_name": "DescriptionStyleModel",
898
+ "_view_count": null,
899
+ "_view_module": "@jupyter-widgets/base",
900
+ "_view_module_version": "1.2.0",
901
+ "_view_name": "StyleView",
902
+ "description_width": ""
903
+ }
904
+ },
905
+ "48763b6233374554ae76035c0483066f": {
906
+ "model_module": "@jupyter-widgets/controls",
907
+ "model_module_version": "1.5.0",
908
+ "model_name": "ProgressStyleModel",
909
+ "state": {
910
+ "_model_module": "@jupyter-widgets/controls",
911
+ "_model_module_version": "1.5.0",
912
+ "_model_name": "ProgressStyleModel",
913
+ "_view_count": null,
914
+ "_view_module": "@jupyter-widgets/base",
915
+ "_view_module_version": "1.2.0",
916
+ "_view_name": "StyleView",
917
+ "bar_color": null,
918
+ "description_width": ""
919
+ }
920
+ },
921
+ "4986a21eb560448fa79f4b25cde48951": {
922
+ "model_module": "@jupyter-widgets/base",
923
+ "model_module_version": "1.2.0",
924
+ "model_name": "LayoutModel",
925
+ "state": {
926
+ "_model_module": "@jupyter-widgets/base",
927
+ "_model_module_version": "1.2.0",
928
+ "_model_name": "LayoutModel",
929
+ "_view_count": null,
930
+ "_view_module": "@jupyter-widgets/base",
931
+ "_view_module_version": "1.2.0",
932
+ "_view_name": "LayoutView",
933
+ "align_content": null,
934
+ "align_items": null,
935
+ "align_self": null,
936
+ "border": null,
937
+ "bottom": null,
938
+ "display": null,
939
+ "flex": null,
940
+ "flex_flow": null,
941
+ "grid_area": null,
942
+ "grid_auto_columns": null,
943
+ "grid_auto_flow": null,
944
+ "grid_auto_rows": null,
945
+ "grid_column": null,
946
+ "grid_gap": null,
947
+ "grid_row": null,
948
+ "grid_template_areas": null,
949
+ "grid_template_columns": null,
950
+ "grid_template_rows": null,
951
+ "height": null,
952
+ "justify_content": null,
953
+ "justify_items": null,
954
+ "left": null,
955
+ "margin": null,
956
+ "max_height": null,
957
+ "max_width": null,
958
+ "min_height": null,
959
+ "min_width": null,
960
+ "object_fit": null,
961
+ "object_position": null,
962
+ "order": null,
963
+ "overflow": null,
964
+ "overflow_x": null,
965
+ "overflow_y": null,
966
+ "padding": null,
967
+ "right": null,
968
+ "top": null,
969
+ "visibility": null,
970
+ "width": null
971
+ }
972
+ },
973
+ "6b2d90209ec14230b3d58a74ac9b83bf": {
974
+ "model_module": "@jupyter-widgets/base",
975
+ "model_module_version": "1.2.0",
976
+ "model_name": "LayoutModel",
977
+ "state": {
978
+ "_model_module": "@jupyter-widgets/base",
979
+ "_model_module_version": "1.2.0",
980
+ "_model_name": "LayoutModel",
981
+ "_view_count": null,
982
+ "_view_module": "@jupyter-widgets/base",
983
+ "_view_module_version": "1.2.0",
984
+ "_view_name": "LayoutView",
985
+ "align_content": null,
986
+ "align_items": null,
987
+ "align_self": null,
988
+ "border": null,
989
+ "bottom": null,
990
+ "display": null,
991
+ "flex": null,
992
+ "flex_flow": null,
993
+ "grid_area": null,
994
+ "grid_auto_columns": null,
995
+ "grid_auto_flow": null,
996
+ "grid_auto_rows": null,
997
+ "grid_column": null,
998
+ "grid_gap": null,
999
+ "grid_row": null,
1000
+ "grid_template_areas": null,
1001
+ "grid_template_columns": null,
1002
+ "grid_template_rows": null,
1003
+ "height": null,
1004
+ "justify_content": null,
1005
+ "justify_items": null,
1006
+ "left": null,
1007
+ "margin": null,
1008
+ "max_height": null,
1009
+ "max_width": null,
1010
+ "min_height": null,
1011
+ "min_width": null,
1012
+ "object_fit": null,
1013
+ "object_position": null,
1014
+ "order": null,
1015
+ "overflow": null,
1016
+ "overflow_x": null,
1017
+ "overflow_y": null,
1018
+ "padding": null,
1019
+ "right": null,
1020
+ "top": null,
1021
+ "visibility": null,
1022
+ "width": null
1023
+ }
1024
+ },
1025
+ "7c5689bc13684db8a22681f41863dddd": {
1026
+ "model_module": "@jupyter-widgets/base",
1027
+ "model_module_version": "1.2.0",
1028
+ "model_name": "LayoutModel",
1029
+ "state": {
1030
+ "_model_module": "@jupyter-widgets/base",
1031
+ "_model_module_version": "1.2.0",
1032
+ "_model_name": "LayoutModel",
1033
+ "_view_count": null,
1034
+ "_view_module": "@jupyter-widgets/base",
1035
+ "_view_module_version": "1.2.0",
1036
+ "_view_name": "LayoutView",
1037
+ "align_content": null,
1038
+ "align_items": null,
1039
+ "align_self": null,
1040
+ "border": null,
1041
+ "bottom": null,
1042
+ "display": null,
1043
+ "flex": null,
1044
+ "flex_flow": null,
1045
+ "grid_area": null,
1046
+ "grid_auto_columns": null,
1047
+ "grid_auto_flow": null,
1048
+ "grid_auto_rows": null,
1049
+ "grid_column": null,
1050
+ "grid_gap": null,
1051
+ "grid_row": null,
1052
+ "grid_template_areas": null,
1053
+ "grid_template_columns": null,
1054
+ "grid_template_rows": null,
1055
+ "height": null,
1056
+ "justify_content": null,
1057
+ "justify_items": null,
1058
+ "left": null,
1059
+ "margin": null,
1060
+ "max_height": null,
1061
+ "max_width": null,
1062
+ "min_height": null,
1063
+ "min_width": null,
1064
+ "object_fit": null,
1065
+ "object_position": null,
1066
+ "order": null,
1067
+ "overflow": null,
1068
+ "overflow_x": null,
1069
+ "overflow_y": null,
1070
+ "padding": null,
1071
+ "right": null,
1072
+ "top": null,
1073
+ "visibility": null,
1074
+ "width": null
1075
+ }
1076
+ },
1077
+ "a1d3a8aa016544a78e8821c8f6199e06": {
1078
+ "model_module": "@jupyter-widgets/controls",
1079
+ "model_module_version": "1.5.0",
1080
+ "model_name": "HBoxModel",
1081
+ "state": {
1082
+ "_dom_classes": [],
1083
+ "_model_module": "@jupyter-widgets/controls",
1084
+ "_model_module_version": "1.5.0",
1085
+ "_model_name": "HBoxModel",
1086
+ "_view_count": null,
1087
+ "_view_module": "@jupyter-widgets/controls",
1088
+ "_view_module_version": "1.5.0",
1089
+ "_view_name": "HBoxView",
1090
+ "box_style": "",
1091
+ "children": [
1092
+ "IPY_MODEL_f61ed33fad754146bdd2ac9db1ba1c48",
1093
+ "IPY_MODEL_bfa0af6aeff344c6845e1080a878e92e",
1094
+ "IPY_MODEL_fd1ad9e0367d4004aae853b91c3a7617"
1095
+ ],
1096
+ "layout": "IPY_MODEL_6b2d90209ec14230b3d58a74ac9b83bf"
1097
+ }
1098
+ },
1099
+ "a73f357065d34d7baf0453ae4a8d75e2": {
1100
+ "model_module": "@jupyter-widgets/base",
1101
+ "model_module_version": "1.2.0",
1102
+ "model_name": "LayoutModel",
1103
+ "state": {
1104
+ "_model_module": "@jupyter-widgets/base",
1105
+ "_model_module_version": "1.2.0",
1106
+ "_model_name": "LayoutModel",
1107
+ "_view_count": null,
1108
+ "_view_module": "@jupyter-widgets/base",
1109
+ "_view_module_version": "1.2.0",
1110
+ "_view_name": "LayoutView",
1111
+ "align_content": null,
1112
+ "align_items": null,
1113
+ "align_self": null,
1114
+ "border": null,
1115
+ "bottom": null,
1116
+ "display": null,
1117
+ "flex": null,
1118
+ "flex_flow": null,
1119
+ "grid_area": null,
1120
+ "grid_auto_columns": null,
1121
+ "grid_auto_flow": null,
1122
+ "grid_auto_rows": null,
1123
+ "grid_column": null,
1124
+ "grid_gap": null,
1125
+ "grid_row": null,
1126
+ "grid_template_areas": null,
1127
+ "grid_template_columns": null,
1128
+ "grid_template_rows": null,
1129
+ "height": null,
1130
+ "justify_content": null,
1131
+ "justify_items": null,
1132
+ "left": null,
1133
+ "margin": null,
1134
+ "max_height": null,
1135
+ "max_width": null,
1136
+ "min_height": null,
1137
+ "min_width": null,
1138
+ "object_fit": null,
1139
+ "object_position": null,
1140
+ "order": null,
1141
+ "overflow": null,
1142
+ "overflow_x": null,
1143
+ "overflow_y": null,
1144
+ "padding": null,
1145
+ "right": null,
1146
+ "top": null,
1147
+ "visibility": null,
1148
+ "width": null
1149
+ }
1150
+ },
1151
+ "aed3acd2f2d74003b44079c333a0698e": {
1152
+ "model_module": "@jupyter-widgets/controls",
1153
+ "model_module_version": "1.5.0",
1154
+ "model_name": "DescriptionStyleModel",
1155
+ "state": {
1156
+ "_model_module": "@jupyter-widgets/controls",
1157
+ "_model_module_version": "1.5.0",
1158
+ "_model_name": "DescriptionStyleModel",
1159
+ "_view_count": null,
1160
+ "_view_module": "@jupyter-widgets/base",
1161
+ "_view_module_version": "1.2.0",
1162
+ "_view_name": "StyleView",
1163
+ "description_width": ""
1164
+ }
1165
+ },
1166
+ "bfa0af6aeff344c6845e1080a878e92e": {
1167
+ "model_module": "@jupyter-widgets/controls",
1168
+ "model_module_version": "1.5.0",
1169
+ "model_name": "FloatProgressModel",
1170
+ "state": {
1171
+ "_dom_classes": [],
1172
+ "_model_module": "@jupyter-widgets/controls",
1173
+ "_model_module_version": "1.5.0",
1174
+ "_model_name": "FloatProgressModel",
1175
+ "_view_count": null,
1176
+ "_view_module": "@jupyter-widgets/controls",
1177
+ "_view_module_version": "1.5.0",
1178
+ "_view_name": "ProgressView",
1179
+ "bar_style": "success",
1180
+ "description": "",
1181
+ "description_tooltip": null,
1182
+ "layout": "IPY_MODEL_7c5689bc13684db8a22681f41863dddd",
1183
+ "max": 5669,
1184
+ "min": 0,
1185
+ "orientation": "horizontal",
1186
+ "style": "IPY_MODEL_48763b6233374554ae76035c0483066f",
1187
+ "value": 5669
1188
+ }
1189
+ },
1190
+ "f61ed33fad754146bdd2ac9db1ba1c48": {
1191
+ "model_module": "@jupyter-widgets/controls",
1192
+ "model_module_version": "1.5.0",
1193
+ "model_name": "HTMLModel",
1194
+ "state": {
1195
+ "_dom_classes": [],
1196
+ "_model_module": "@jupyter-widgets/controls",
1197
+ "_model_module_version": "1.5.0",
1198
+ "_model_name": "HTMLModel",
1199
+ "_view_count": null,
1200
+ "_view_module": "@jupyter-widgets/controls",
1201
+ "_view_module_version": "1.5.0",
1202
+ "_view_name": "HTMLView",
1203
+ "description": "",
1204
+ "description_tooltip": null,
1205
+ "layout": "IPY_MODEL_a73f357065d34d7baf0453ae4a8d75e2",
1206
+ "placeholder": "​",
1207
+ "style": "IPY_MODEL_46f521b73fd943c081c648fd873ebc0a",
1208
+ "value": "Downloading builder script: 100%"
1209
+ }
1210
+ },
1211
+ "fd1ad9e0367d4004aae853b91c3a7617": {
1212
+ "model_module": "@jupyter-widgets/controls",
1213
+ "model_module_version": "1.5.0",
1214
+ "model_name": "HTMLModel",
1215
+ "state": {
1216
+ "_dom_classes": [],
1217
+ "_model_module": "@jupyter-widgets/controls",
1218
+ "_model_module_version": "1.5.0",
1219
+ "_model_name": "HTMLModel",
1220
+ "_view_count": null,
1221
+ "_view_module": "@jupyter-widgets/controls",
1222
+ "_view_module_version": "1.5.0",
1223
+ "_view_name": "HTMLView",
1224
+ "description": "",
1225
+ "description_tooltip": null,
1226
+ "layout": "IPY_MODEL_4986a21eb560448fa79f4b25cde48951",
1227
+ "placeholder": "​",
1228
+ "style": "IPY_MODEL_aed3acd2f2d74003b44079c333a0698e",
1229
+ "value": " 5.67k/5.67k [00:00&lt;00:00, 205kB/s]"
1230
+ }
1231
+ }
1232
+ },
1233
+ "version_major": 2,
1234
+ "version_minor": 0
1235
+ }
1236
+ }
1237
+ },
1238
+ "nbformat": 4,
1239
+ "nbformat_minor": 0
1240
+ }
lm-evaluation-harness/examples/transformer-lens.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformer_lens import HookedTransformer
6
+ from transformers import AutoConfig
7
+
8
+ from lm_eval import evaluator
9
+ from lm_eval.models.huggingface import HFLM
10
+
11
+
12
+ def evaluate_lm_eval(lens_model: HookedTransformer, tasks: list[str], **kwargs):
13
+ class HFLikeModelAdapter(nn.Module):
14
+ """Adapts HookedTransformer to match the HuggingFace interface expected by lm-eval"""
15
+
16
+ def __init__(self, model: HookedTransformer):
17
+ super().__init__()
18
+ self.model = model
19
+ self.tokenizer = model.tokenizer
20
+ self.config = AutoConfig.from_pretrained(model.cfg.tokenizer_name)
21
+ self.device = model.cfg.device
22
+ self.tie_weights = lambda: self
23
+
24
+ def forward(self, input_ids=None, attention_mask=None, **kwargs):
25
+ output = self.model(input_ids, attention_mask=attention_mask, **kwargs)
26
+ # Make sure output has the expected .logits attribute
27
+ if not hasattr(output, "logits"):
28
+ if isinstance(output, torch.Tensor):
29
+ output.logits = output
30
+ return output
31
+
32
+ # Only delegate specific attributes we know we need
33
+ def to(self, *args, **kwargs):
34
+ return self.model.to(*args, **kwargs)
35
+
36
+ def eval(self):
37
+ self.model.eval()
38
+ return self
39
+
40
+ def train(self, mode=True):
41
+ self.model.train(mode)
42
+ return self
43
+
44
+ model = HFLikeModelAdapter(lens_model)
45
+ warnings.filterwarnings("ignore", message="Failed to get model SHA for")
46
+ results = evaluator.simple_evaluate(
47
+ model=HFLM(pretrained=model, tokenizer=model.tokenizer),
48
+ tasks=tasks,
49
+ verbosity="WARNING",
50
+ **kwargs,
51
+ )
52
+ return results
53
+
54
+
55
+ if __name__ == "__main__":
56
+ # Load base model
57
+ model = HookedTransformer.from_pretrained("pythia-70m")
58
+ res = evaluate_lm_eval(model, tasks=["arc_easy"])
59
+ print(res["results"])
lm-evaluation-harness/examples/visualize-wandb.ipynb ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "fc477b96-adee-4829-a9d7-a5eb990df358",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Visualizing Results in Weights and Biases\n",
9
+ "\n",
10
+ "With the Weights and Biases integration, you can now spend more time extracting deeper insights into your evaluation results. The integration is designed to streamline the process of logging and visualizing experiment results using the Weights & Biases (W&B) platform.\n",
11
+ "\n",
12
+ "The integration provide functionalities\n",
13
+ "\n",
14
+ "- to automatically log the evaluation results,\n",
15
+ "- log the samples as W&B Tables for easy visualization,\n",
16
+ "- log the `results.json` file as an artifact for version control,\n",
17
+ "- log the `<task_name>_eval_samples.json` file if the samples are logged,\n",
18
+ "- generate a comprehensive report for analysis and visualization with all the important metric,\n",
19
+ "- log task and cli configs,\n",
20
+ "- and more out of the box like the command used to run the evaluation, GPU/CPU counts, timestamp, etc.\n",
21
+ "\n",
22
+ "The integration is super easy to use with the eval harness. Let's see how!"
23
+ ]
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "execution_count": null,
28
+ "id": "3851439a-bff4-41f2-bf21-1b3d8704913b",
29
+ "metadata": {
30
+ "scrolled": true
31
+ },
32
+ "outputs": [],
33
+ "source": [
34
+ "# Install this project if you did not already have it.\n",
35
+ "# This is all that is needed to be installed to start using Weights and Biases\n",
36
+ "\n",
37
+ "!pip -qq install -e ..[wandb]"
38
+ ]
39
+ },
40
+ {
41
+ "cell_type": "markdown",
42
+ "id": "8507fd7e-3b99-4a92-89fa-9eaada74ba91",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Run the Eval Harness\n",
46
+ "\n",
47
+ "Run the eval harness as usual with a `wandb_args` flag. This flag is used to provide arguments for initializing a wandb run ([wandb.init](https://docs.wandb.ai/ref/python/init)) as comma separated string arguments.\n",
48
+ "\n",
49
+ "If `wandb_args` flag is used, the metrics and all other goodness will be automatically logged to Weights and Biases. In the stdout, you will find the link to the W&B run page as well as link to the generated report."
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "markdown",
54
+ "id": "eec5866e-f01e-42f8-8803-9d77472ef991",
55
+ "metadata": {},
56
+ "source": [
57
+ "## Set your API Key\n",
58
+ "\n",
59
+ "Before you can use W&B, you need to authenticate your machine with an authentication key. Visit https://wandb.ai/authorize to get one."
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "id": "d824d163-71a9-4313-935d-f1d56397841c",
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "import wandb\n",
70
+ "\n",
71
+ "\n",
72
+ "wandb.login()"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "markdown",
77
+ "id": "124e4a34-1547-4bed-bc09-db012bacbda6",
78
+ "metadata": {},
79
+ "source": [
80
+ "> Note that if you are using command line you can simply authenticate your machine by doing `wandb login` in your terminal. For more info check out the [documentation](https://docs.wandb.ai/quickstart#2-log-in-to-wb)."
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "id": "abc6f6b6-179a-4aff-ada9-f380fb74df6e",
86
+ "metadata": {},
87
+ "source": [
88
+ "## Run and log to W&B"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": null,
94
+ "id": "bd0a8130-a97b-451a-acd2-3f9885b88643",
95
+ "metadata": {},
96
+ "outputs": [],
97
+ "source": [
98
+ "!lm_eval \\\n",
99
+ " --model hf \\\n",
100
+ " --model_args pretrained=microsoft/phi-2,trust_remote_code=True \\\n",
101
+ " --tasks hellaswag,mmlu_abstract_algebra \\\n",
102
+ " --device cuda:0 \\\n",
103
+ " --batch_size 8 \\\n",
104
+ " --output_path output/phi-2 \\\n",
105
+ " --limit 10 \\\n",
106
+ " --wandb_args project=lm-eval-harness-integration \\\n",
107
+ " --log_samples"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "markdown",
112
+ "id": "e974cabdbe70b667",
113
+ "metadata": {},
114
+ "source": []
115
+ },
116
+ {
117
+ "cell_type": "markdown",
118
+ "id": "5178ca9445b844e4",
119
+ "metadata": {},
120
+ "source": [
121
+ "W&B can also be initialized programmatically for use outside the CLI to parse and log the results."
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": null,
127
+ "id": "c6a421b2cf3ddac5",
128
+ "metadata": {},
129
+ "outputs": [],
130
+ "source": [
131
+ "import lm_eval\n",
132
+ "from lm_eval.loggers import WandbLogger\n",
133
+ "\n",
134
+ "\n",
135
+ "results = lm_eval.simple_evaluate(\n",
136
+ " model=\"hf\",\n",
137
+ " model_args=\"pretrained=microsoft/phi-2,trust_remote_code=True\",\n",
138
+ " tasks=\"hellaswag,mmlu_abstract_algebra\",\n",
139
+ " log_samples=True,\n",
140
+ ")\n",
141
+ "\n",
142
+ "wandb_logger = WandbLogger(\n",
143
+ " project=\"lm-eval-harness-integration\", job_type=\"eval\"\n",
144
+ ") # or empty if wandb.init(...) already called before\n",
145
+ "wandb_logger.post_init(results)\n",
146
+ "wandb_logger.log_eval_result()\n",
147
+ "wandb_logger.log_eval_samples(results[\"samples\"]) # if log_samples"
148
+ ]
149
+ }
150
+ ],
151
+ "metadata": {
152
+ "kernelspec": {
153
+ "display_name": "Python 3 (ipykernel)",
154
+ "language": "python",
155
+ "name": "python3"
156
+ },
157
+ "language_info": {
158
+ "codemirror_mode": {
159
+ "name": "ipython",
160
+ "version": 3
161
+ },
162
+ "file_extension": ".py",
163
+ "mimetype": "text/x-python",
164
+ "name": "python",
165
+ "nbconvert_exporter": "python",
166
+ "pygments_lexer": "ipython3",
167
+ "version": "3.10.12"
168
+ }
169
+ },
170
+ "nbformat": 4,
171
+ "nbformat_minor": 5
172
+ }
lm-evaluation-harness/examples/visualize-zeno.ipynb ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Visualizing Results in Zeno\n",
8
+ "\n",
9
+ "Benchmarking your models is the first step towards making sure your model performs well.\n",
10
+ "However, looking at the data behind the benchmark, slicing the data into subsets, and comparing models on individual instances can help you even more in evaluating and quantifying the behavior of your AI system.\n",
11
+ "\n",
12
+ "All of this can be done in [Zeno](https://zenoml.com)!\n",
13
+ "Zeno is super easy to use with the eval harness, let's explore how you can easily upload and visualize your eval results.\n"
14
+ ]
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "execution_count": null,
19
+ "metadata": {},
20
+ "outputs": [],
21
+ "source": [
22
+ "# Install this project if you did not already do that. This is all that needs to be installed for you to be able to visualize your data in Zeno!\n",
23
+ "!pip install -e ..\n",
24
+ "!pip install -e ..[zeno]"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "metadata": {},
30
+ "source": [
31
+ "# Run the Eval Harness\n",
32
+ "\n",
33
+ "To visualize the results, run the eval harness with the `log_samples` and `output_path` flags. We expect `output_path` to contain multiple folders that represent individual model names. You can thus run your evaluation on any number of tasks and models and upload all of the results as projects on Zeno.\n"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": null,
39
+ "metadata": {},
40
+ "outputs": [],
41
+ "source": [
42
+ "!lm_eval \\\n",
43
+ " --model hf \\\n",
44
+ " --model_args pretrained=EleutherAI/gpt-neo-2.7B \\\n",
45
+ " --tasks hellaswag,wikitext \\\n",
46
+ " --batch_size 8 \\\n",
47
+ " --device mps \\\n",
48
+ " --log_samples \\\n",
49
+ " --output_path output/gpt-neo-2.7B \\\n",
50
+ " --limit 10"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "markdown",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Set your API Key\n",
58
+ "\n",
59
+ "This is so you can be authenticated with Zeno.\n",
60
+ "If you don't already have a Zeno account, first create an account on [Zeno Hub](https://hub.zenoml.com).\n",
61
+ "After logging in to Zeno Hub, generate your API key by clicking on your profile at the bottom left to navigate to your account page.\n"
62
+ ]
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "execution_count": null,
67
+ "metadata": {},
68
+ "outputs": [],
69
+ "source": [
70
+ "%env ZENO_API_KEY=YOUR_API_KEY"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "markdown",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Visualize Eval Results\n",
78
+ "\n",
79
+ "You can now use the `zeno_visualize` script to upload the results to Zeno.\n",
80
+ "\n",
81
+ "This will use all subfolders in `data_path` as different models and upload all tasks within these model folders to Zeno. If you run the eval harness on multiple tasks, the `project_name` will be used as a prefix and one project will be created per task.\n"
82
+ ]
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "execution_count": null,
87
+ "metadata": {},
88
+ "outputs": [],
89
+ "source": [
90
+ "!python ../scripts/zeno_visualize.py --data_path output --project_name \"Zeno Upload Test\""
91
+ ]
92
+ }
93
+ ],
94
+ "metadata": {
95
+ "kernelspec": {
96
+ "display_name": "zeno_projects",
97
+ "language": "python",
98
+ "name": "python3"
99
+ },
100
+ "language_info": {
101
+ "codemirror_mode": {
102
+ "name": "ipython",
103
+ "version": 3
104
+ },
105
+ "file_extension": ".py",
106
+ "mimetype": "text/x-python",
107
+ "name": "python",
108
+ "nbconvert_exporter": "python",
109
+ "pygments_lexer": "ipython3",
110
+ "version": "3.10.11"
111
+ }
112
+ },
113
+ "nbformat": 4,
114
+ "nbformat_minor": 2
115
+ }
lm-evaluation-harness/ignore.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ROUGE
2
+ rouge
3
+ nin
4
+ maka
5
+ mor
6
+ te
7
+ ond
8
+ extraversion
lm-evaluation-harness/llama3-8b_eval.log ADDED
The diff for this file is too large to render. See raw diff
 
lm-evaluation-harness/lm_eval/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+
4
+ from .evaluator import evaluate, simple_evaluate
5
+
6
+
7
+ __version__ = "0.4.8"
lm-evaluation-harness/lm_eval/__main__.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import os
5
+ import sys
6
+ from functools import partial
7
+ from pathlib import Path
8
+ from typing import Union
9
+
10
+ from lm_eval import evaluator, utils
11
+ from lm_eval.evaluator import request_caching_arg_to_dict
12
+ from lm_eval.loggers import EvaluationTracker, WandbLogger
13
+ from lm_eval.tasks import TaskManager
14
+ from lm_eval.utils import (
15
+ handle_non_serializable,
16
+ make_table,
17
+ simple_parse_args_string,
18
+ )
19
+
20
+
21
+ def try_parse_json(value: str) -> Union[str, dict, None]:
22
+ if value is None:
23
+ return None
24
+ try:
25
+ return json.loads(value)
26
+ except json.JSONDecodeError:
27
+ if "{" in value:
28
+ raise argparse.ArgumentTypeError(
29
+ f"Invalid JSON: {value}. Hint: Use double quotes for JSON strings."
30
+ )
31
+ return value
32
+
33
+
34
+ def _int_or_none_list_arg_type(
35
+ min_len: int, max_len: int, defaults: str, value: str, split_char: str = ","
36
+ ):
37
+ def parse_value(item):
38
+ item = item.strip().lower()
39
+ if item == "none":
40
+ return None
41
+ try:
42
+ return int(item)
43
+ except ValueError:
44
+ raise argparse.ArgumentTypeError(f"{item} is not an integer or None")
45
+
46
+ items = [parse_value(v) for v in value.split(split_char)]
47
+ num_items = len(items)
48
+
49
+ if num_items == 1:
50
+ # Makes downstream handling the same for single and multiple values
51
+ items = items * max_len
52
+ elif num_items < min_len or num_items > max_len:
53
+ raise argparse.ArgumentTypeError(
54
+ f"Argument requires {max_len} integers or None, separated by '{split_char}'"
55
+ )
56
+ elif num_items != max_len:
57
+ logging.warning(
58
+ f"Argument requires {max_len} integers or None, separated by '{split_char}'. "
59
+ "Missing values will be filled with defaults."
60
+ )
61
+ default_items = [parse_value(v) for v in defaults.split(split_char)]
62
+ items.extend(
63
+ default_items[num_items:]
64
+ ) # extend items list with missing defaults
65
+
66
+ return items
67
+
68
+
69
+ def check_argument_types(parser: argparse.ArgumentParser):
70
+ """
71
+ Check to make sure all CLI args are typed, raises error if not
72
+ """
73
+ for action in parser._actions:
74
+ if action.dest != "help" and not action.const:
75
+ if action.type is None:
76
+ raise ValueError(
77
+ f"Argument '{action.dest}' doesn't have a type specified."
78
+ )
79
+ else:
80
+ continue
81
+
82
+
83
+ def setup_parser() -> argparse.ArgumentParser:
84
+ parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
85
+ parser.add_argument(
86
+ "--model", "-m", type=str, default="hf", help="Name of model e.g. `hf`"
87
+ )
88
+ parser.add_argument(
89
+ "--tasks",
90
+ "-t",
91
+ default=None,
92
+ type=str,
93
+ metavar="task1,task2",
94
+ help="Comma-separated list of task names or task groupings to evaluate on.\nTo get full list of tasks, use one of the commands `lm-eval --tasks {{list_groups,list_subtasks,list_tags,list}}` to list out all available names for task groupings; only (sub)tasks; tags; or all of the above",
95
+ )
96
+ parser.add_argument(
97
+ "--model_args",
98
+ "-a",
99
+ default="",
100
+ type=try_parse_json,
101
+ help="""Comma separated string or JSON formatted arguments for model, e.g. `pretrained=EleutherAI/pythia-160m,dtype=float32` or '{"pretrained":"EleutherAI/pythia-160m","dtype":"float32"}'""",
102
+ )
103
+ parser.add_argument(
104
+ "--num_fewshot",
105
+ "-f",
106
+ type=int,
107
+ default=None,
108
+ metavar="N",
109
+ help="Number of examples in few-shot context",
110
+ )
111
+ parser.add_argument(
112
+ "--batch_size",
113
+ "-b",
114
+ type=str,
115
+ default=1,
116
+ metavar="auto|auto:N|N",
117
+ help="Acceptable values are 'auto', 'auto:N' or N, where N is an integer. Default 1.",
118
+ )
119
+ parser.add_argument(
120
+ "--max_batch_size",
121
+ type=int,
122
+ default=None,
123
+ metavar="N",
124
+ help="Maximal batch size to try with --batch_size auto.",
125
+ )
126
+ parser.add_argument(
127
+ "--device",
128
+ type=str,
129
+ default=None,
130
+ help="Device to use (e.g. cuda, cuda:0, cpu).",
131
+ )
132
+ parser.add_argument(
133
+ "--output_path",
134
+ "-o",
135
+ default=None,
136
+ type=str,
137
+ metavar="DIR|DIR/file.json",
138
+ help="Path where result metrics will be saved. Can be either a directory or a .json file. If the path is a directory and log_samples is true, the results will be saved in the directory. Else the parent directory will be used.",
139
+ )
140
+ parser.add_argument(
141
+ "--limit",
142
+ "-L",
143
+ type=float,
144
+ default=None,
145
+ metavar="N|0<N<1",
146
+ help="Limit the number of examples per task. "
147
+ "If <1, limit is a percentage of the total number of examples.",
148
+ )
149
+ parser.add_argument(
150
+ "--samples",
151
+ "-E",
152
+ default=None,
153
+ type=str,
154
+ metavar="/path/to/json",
155
+ help='JSON string or path to JSON file containing doc indices of selected examples to test. Format: {"task_name":[indices],...}',
156
+ )
157
+ parser.add_argument(
158
+ "--use_cache",
159
+ "-c",
160
+ type=str,
161
+ default=None,
162
+ metavar="DIR",
163
+ help="A path to a sqlite db file for caching model responses. `None` if not caching.",
164
+ )
165
+ parser.add_argument(
166
+ "--cache_requests",
167
+ type=str,
168
+ default=None,
169
+ choices=["true", "refresh", "delete"],
170
+ help="Speed up evaluation by caching the building of dataset requests. `None` if not caching.",
171
+ )
172
+ parser.add_argument(
173
+ "--check_integrity",
174
+ action="store_true",
175
+ help="Whether to run the relevant part of the test suite for the tasks.",
176
+ )
177
+ parser.add_argument(
178
+ "--write_out",
179
+ "-w",
180
+ action="store_true",
181
+ default=False,
182
+ help="Prints the prompt for the first few documents.",
183
+ )
184
+ parser.add_argument(
185
+ "--log_samples",
186
+ "-s",
187
+ action="store_true",
188
+ default=False,
189
+ help="If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis. Use with --output_path.",
190
+ )
191
+ parser.add_argument(
192
+ "--system_instruction",
193
+ type=str,
194
+ default=None,
195
+ help="System instruction to be used in the prompt",
196
+ )
197
+ parser.add_argument(
198
+ "--apply_chat_template",
199
+ type=str,
200
+ nargs="?",
201
+ const=True,
202
+ default=False,
203
+ help=(
204
+ "If True, apply chat template to the prompt. "
205
+ "Providing `--apply_chat_template` without an argument will apply the default chat template to the prompt. "
206
+ "To apply a specific template from the available list of templates, provide the template name as an argument. "
207
+ "E.g. `--apply_chat_template template_name`"
208
+ ),
209
+ )
210
+ parser.add_argument(
211
+ "--fewshot_as_multiturn",
212
+ action="store_true",
213
+ default=False,
214
+ help="If True, uses the fewshot as a multi-turn conversation",
215
+ )
216
+ parser.add_argument(
217
+ "--show_config",
218
+ action="store_true",
219
+ default=False,
220
+ help="If True, shows the the full config of all tasks at the end of the evaluation.",
221
+ )
222
+ parser.add_argument(
223
+ "--include_path",
224
+ type=str,
225
+ default=None,
226
+ metavar="DIR",
227
+ help="Additional path to include if there are external tasks to include.",
228
+ )
229
+ parser.add_argument(
230
+ "--gen_kwargs",
231
+ type=try_parse_json,
232
+ default=None,
233
+ help=(
234
+ "Either comma delimited string or JSON formatted arguments for model generation on greedy_until tasks,"
235
+ """ e.g. '{"temperature":0.7,"until":["hello"]}' or temperature=0,top_p=0.1."""
236
+ ),
237
+ )
238
+ parser.add_argument(
239
+ "--verbosity",
240
+ "-v",
241
+ type=str.upper,
242
+ default=None,
243
+ metavar="CRITICAL|ERROR|WARNING|INFO|DEBUG",
244
+ help="(Deprecated) Controls logging verbosity level. Use the `LOGLEVEL` environment variable instead. Set to DEBUG for detailed output when testing or adding new task configurations.",
245
+ )
246
+ parser.add_argument(
247
+ "--wandb_args",
248
+ type=str,
249
+ default="",
250
+ help="Comma separated string arguments passed to wandb.init, e.g. `project=lm-eval,job_type=eval",
251
+ )
252
+ parser.add_argument(
253
+ "--wandb_config_args",
254
+ type=str,
255
+ default="",
256
+ help="Comma separated string arguments passed to wandb.config.update. Use this to trace parameters that aren't already traced by default. eg. `lr=0.01,repeats=3",
257
+ )
258
+ parser.add_argument(
259
+ "--hf_hub_log_args",
260
+ type=str,
261
+ default="",
262
+ help="Comma separated string arguments passed to Hugging Face Hub's log function, e.g. `hub_results_org=EleutherAI,hub_repo_name=lm-eval-results`",
263
+ )
264
+ parser.add_argument(
265
+ "--predict_only",
266
+ "-x",
267
+ action="store_true",
268
+ default=False,
269
+ help="Use with --log_samples. Only model outputs will be saved and metrics will not be evaluated.",
270
+ )
271
+ default_seed_string = "0,1234,1234,1234"
272
+ parser.add_argument(
273
+ "--seed",
274
+ type=partial(_int_or_none_list_arg_type, 3, 4, default_seed_string),
275
+ default=default_seed_string, # for backward compatibility
276
+ help=(
277
+ "Set seed for python's random, numpy, torch, and fewshot sampling.\n"
278
+ "Accepts a comma-separated list of 4 values for python's random, numpy, torch, and fewshot sampling seeds, "
279
+ "respectively, or a single integer to set the same seed for all four.\n"
280
+ f"The values are either an integer or 'None' to not set the seed. Default is `{default_seed_string}` "
281
+ "(for backward compatibility).\n"
282
+ "E.g. `--seed 0,None,8,52` sets `random.seed(0)`, `torch.manual_seed(8)`, and fewshot sampling seed to 52. "
283
+ "Here numpy's seed is not set since the second value is `None`.\n"
284
+ "E.g, `--seed 42` sets all four seeds to 42."
285
+ ),
286
+ )
287
+ parser.add_argument(
288
+ "--trust_remote_code",
289
+ action="store_true",
290
+ help="Sets trust_remote_code to True to execute code to create HF Datasets from the Hub",
291
+ )
292
+ parser.add_argument(
293
+ "--confirm_run_unsafe_code",
294
+ action="store_true",
295
+ help="Confirm that you understand the risks of running unsafe code for tasks that require it",
296
+ )
297
+ parser.add_argument(
298
+ "--metadata",
299
+ type=json.loads,
300
+ default=None,
301
+ help="""JSON string metadata to pass to task configs, for example '{"max_seq_lengths":[4096,8192]}'. Will be merged with model_args. Can also be set in task config.""",
302
+ )
303
+ return parser
304
+
305
+
306
+ def parse_eval_args(parser: argparse.ArgumentParser) -> argparse.Namespace:
307
+ check_argument_types(parser)
308
+ return parser.parse_args()
309
+
310
+
311
+ def cli_evaluate(args: Union[argparse.Namespace, None] = None) -> None:
312
+ if not args:
313
+ # we allow for args to be passed externally, else we parse them ourselves
314
+ parser = setup_parser()
315
+ args = parse_eval_args(parser)
316
+
317
+ if args.wandb_args:
318
+ wandb_args_dict = simple_parse_args_string(args.wandb_args)
319
+ wandb_config_args_dict = simple_parse_args_string(args.wandb_config_args)
320
+ wandb_logger = WandbLogger(wandb_args_dict, wandb_config_args_dict)
321
+
322
+ utils.setup_logging(args.verbosity)
323
+ eval_logger = logging.getLogger(__name__)
324
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
325
+
326
+ # update the evaluation tracker args with the output path and the HF token
327
+ if args.output_path:
328
+ args.hf_hub_log_args += f",output_path={args.output_path}"
329
+ if os.environ.get("HF_TOKEN", None):
330
+ args.hf_hub_log_args += f",token={os.environ.get('HF_TOKEN')}"
331
+ evaluation_tracker_args = simple_parse_args_string(args.hf_hub_log_args)
332
+ evaluation_tracker = EvaluationTracker(**evaluation_tracker_args)
333
+
334
+ if args.predict_only:
335
+ args.log_samples = True
336
+ if (args.log_samples or args.predict_only) and not args.output_path:
337
+ raise ValueError(
338
+ "Specify --output_path if providing --log_samples or --predict_only"
339
+ )
340
+
341
+ if args.fewshot_as_multiturn and args.apply_chat_template is False:
342
+ raise ValueError(
343
+ "When `fewshot_as_multiturn` is selected, `apply_chat_template` must be set (either to `True` or to the chosen template name)."
344
+ )
345
+
346
+ if args.include_path is not None:
347
+ eval_logger.info(f"Including path: {args.include_path}")
348
+ metadata = (
349
+ simple_parse_args_string(args.model_args)
350
+ if isinstance(args.model_args, str)
351
+ else args.model_args
352
+ if isinstance(args.model_args, dict)
353
+ else {}
354
+ ) | (
355
+ args.metadata
356
+ if isinstance(args.metadata, dict)
357
+ else simple_parse_args_string(args.metadata)
358
+ )
359
+
360
+ task_manager = TaskManager(include_path=args.include_path, metadata=metadata)
361
+
362
+ if "push_samples_to_hub" in evaluation_tracker_args and not args.log_samples:
363
+ eval_logger.warning(
364
+ "Pushing samples to the Hub requires --log_samples to be set. Samples will not be pushed to the Hub."
365
+ )
366
+
367
+ if args.limit:
368
+ eval_logger.warning(
369
+ " --limit SHOULD ONLY BE USED FOR TESTING."
370
+ "REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT."
371
+ )
372
+ if args.samples:
373
+ assert args.limit is None, (
374
+ "If --samples is not None, then --limit must be None."
375
+ )
376
+ if (samples := Path(args.samples)).is_file():
377
+ args.samples = json.loads(samples.read_text())
378
+ else:
379
+ args.samples = json.loads(args.samples)
380
+
381
+ if args.tasks is None:
382
+ eval_logger.error("Need to specify task to evaluate.")
383
+ sys.exit()
384
+ elif args.tasks == "list":
385
+ print(task_manager.list_all_tasks())
386
+ sys.exit()
387
+ elif args.tasks == "list_groups":
388
+ print(task_manager.list_all_tasks(list_subtasks=False, list_tags=False))
389
+ sys.exit()
390
+ elif args.tasks == "list_tags":
391
+ print(task_manager.list_all_tasks(list_groups=False, list_subtasks=False))
392
+ sys.exit()
393
+ elif args.tasks == "list_subtasks":
394
+ print(task_manager.list_all_tasks(list_groups=False, list_tags=False))
395
+ sys.exit()
396
+ else:
397
+ if os.path.isdir(args.tasks):
398
+ import glob
399
+
400
+ task_names = []
401
+ yaml_path = os.path.join(args.tasks, "*.yaml")
402
+ for yaml_file in glob.glob(yaml_path):
403
+ config = utils.load_yaml_config(yaml_file)
404
+ task_names.append(config)
405
+ else:
406
+ task_list = args.tasks.split(",")
407
+ task_names = task_manager.match_tasks(task_list)
408
+ for task in [task for task in task_list if task not in task_names]:
409
+ if os.path.isfile(task):
410
+ config = utils.load_yaml_config(task)
411
+ task_names.append(config)
412
+ task_missing = [
413
+ task for task in task_list if task not in task_names and "*" not in task
414
+ ] # we don't want errors if a wildcard ("*") task name was used
415
+
416
+ if task_missing:
417
+ missing = ", ".join(task_missing)
418
+ eval_logger.error(
419
+ f"Tasks were not found: {missing}\n"
420
+ f"{utils.SPACING}Try `lm-eval --tasks list` for list of available tasks",
421
+ )
422
+ raise ValueError(
423
+ f"Tasks not found: {missing}. Try `lm-eval --tasks {{list_groups,list_subtasks,list_tags,list}}` to list out all available names for task groupings; only (sub)tasks; tags; or all of the above, or pass '--verbosity DEBUG' to troubleshoot task registration issues."
424
+ )
425
+
426
+ # Respect user's value passed in via CLI, otherwise default to True and add to comma-separated model args
427
+ if args.trust_remote_code:
428
+ eval_logger.info(
429
+ "Passed `--trust_remote_code`, setting environment variable `HF_DATASETS_TRUST_REMOTE_CODE=true`"
430
+ )
431
+ # HACK: import datasets and override its HF_DATASETS_TRUST_REMOTE_CODE value internally,
432
+ # because it's already been determined based on the prior env var before launching our
433
+ # script--`datasets` gets imported by lm_eval internally before these lines can update the env.
434
+ import datasets
435
+
436
+ datasets.config.HF_DATASETS_TRUST_REMOTE_CODE = True
437
+
438
+ args.model_args = args.model_args + ",trust_remote_code=True"
439
+ (
440
+ eval_logger.info(f"Selected Tasks: {task_names}")
441
+ if eval_logger.getEffectiveLevel() >= logging.INFO
442
+ else print(f"Selected Tasks: {task_names}")
443
+ )
444
+
445
+ request_caching_args = request_caching_arg_to_dict(
446
+ cache_requests=args.cache_requests
447
+ )
448
+
449
+ results = evaluator.simple_evaluate(
450
+ model=args.model,
451
+ model_args=args.model_args,
452
+ tasks=task_names,
453
+ num_fewshot=args.num_fewshot,
454
+ batch_size=args.batch_size,
455
+ max_batch_size=args.max_batch_size,
456
+ device=args.device,
457
+ use_cache=args.use_cache,
458
+ limit=args.limit,
459
+ samples=args.samples,
460
+ check_integrity=args.check_integrity,
461
+ write_out=args.write_out,
462
+ log_samples=args.log_samples,
463
+ evaluation_tracker=evaluation_tracker,
464
+ system_instruction=args.system_instruction,
465
+ apply_chat_template=args.apply_chat_template,
466
+ fewshot_as_multiturn=args.fewshot_as_multiturn,
467
+ gen_kwargs=args.gen_kwargs,
468
+ task_manager=task_manager,
469
+ predict_only=args.predict_only,
470
+ random_seed=args.seed[0],
471
+ numpy_random_seed=args.seed[1],
472
+ torch_random_seed=args.seed[2],
473
+ fewshot_random_seed=args.seed[3],
474
+ confirm_run_unsafe_code=args.confirm_run_unsafe_code,
475
+ metadata=metadata,
476
+ **request_caching_args,
477
+ )
478
+
479
+ if results is not None:
480
+ if args.log_samples:
481
+ samples = results.pop("samples")
482
+ dumped = json.dumps(
483
+ results, indent=2, default=handle_non_serializable, ensure_ascii=False
484
+ )
485
+ if args.show_config:
486
+ print(dumped)
487
+
488
+ batch_sizes = ",".join(map(str, results["config"]["batch_sizes"]))
489
+
490
+ # Add W&B logging
491
+ if args.wandb_args:
492
+ try:
493
+ wandb_logger.post_init(results)
494
+ wandb_logger.log_eval_result()
495
+ if args.log_samples:
496
+ wandb_logger.log_eval_samples(samples)
497
+ except Exception as e:
498
+ eval_logger.info(f"Logging to Weights and Biases failed due to {e}")
499
+
500
+ evaluation_tracker.save_results_aggregated(
501
+ results=results, samples=samples if args.log_samples else None
502
+ )
503
+
504
+ if args.log_samples:
505
+ for task_name, config in results["configs"].items():
506
+ evaluation_tracker.save_results_samples(
507
+ task_name=task_name, samples=samples[task_name]
508
+ )
509
+
510
+ if (
511
+ evaluation_tracker.push_results_to_hub
512
+ or evaluation_tracker.push_samples_to_hub
513
+ ):
514
+ evaluation_tracker.recreate_metadata_card()
515
+
516
+ print(
517
+ f"{args.model} ({args.model_args}), gen_kwargs: ({args.gen_kwargs}), limit: {args.limit}, num_fewshot: {args.num_fewshot}, "
518
+ f"batch_size: {args.batch_size}{f' ({batch_sizes})' if batch_sizes else ''}"
519
+ )
520
+ print(make_table(results))
521
+ if "groups" in results:
522
+ print(make_table(results, "groups"))
523
+
524
+ if args.wandb_args:
525
+ # Tear down wandb run once all the logging is done.
526
+ wandb_logger.run.finish()
527
+
528
+
529
+ if __name__ == "__main__":
530
+ cli_evaluate()
lm-evaluation-harness/lm_eval/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (307 Bytes). View file
 
lm-evaluation-harness/lm_eval/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (360 Bytes). View file
 
lm-evaluation-harness/lm_eval/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/__main__.cpython-311.pyc ADDED
Binary file (24.2 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-310.pyc ADDED
Binary file (19.2 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/evaluator.cpython-311.pyc ADDED
Binary file (32.7 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/evaluator_utils.cpython-311.pyc ADDED
Binary file (24.8 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
lm-evaluation-harness/lm_eval/__pycache__/utils.cpython-311.pyc ADDED
Binary file (28.4 kB). View file