evaluator.py 15.2 KB
Newer Older
lintangsutawika's avatar
lintangsutawika committed
1
import random
Leo Gao's avatar
Leo Gao committed
2
import itertools
FarzanehNakhaee's avatar
FarzanehNakhaee committed
3
import json
lintangsutawika's avatar
lintangsutawika committed
4
import collections
FarzanehNakhaee's avatar
FarzanehNakhaee committed
5
6
import logging
import sys
lintangsutawika's avatar
lintangsutawika committed
7

8
9
import torch

10
import numpy as np
lintangsutawika's avatar
lintangsutawika committed
11
12

import lm_eval.api
13
import lm_eval.tasks
lintangsutawika's avatar
lintangsutawika committed
14
import lm_eval.models
lintangsutawika's avatar
lintangsutawika committed
15
import lm_eval.api.metrics
lintangsutawika's avatar
lintangsutawika committed
16
import lm_eval.api.registry
lintangsutawika's avatar
lintangsutawika committed
17

lintangsutawika's avatar
lintangsutawika committed
18
19
20
21
from lm_eval.utils import (
    positional_deprecated,
    run_task_tests,
    make_table,
22
    create_iterator,
lintangsutawika's avatar
lintangsutawika committed
23
24
    get_git_commit_hash,
)
25

lintangsutawika's avatar
lintangsutawika committed
26
27
from lm_eval.logger import eval_logger

FarzanehNakhaee's avatar
FarzanehNakhaee committed
28
29
30
31
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler(sys.stdout))

Fabrizio Milo's avatar
Fabrizio Milo committed
32

33
@positional_deprecated
Fabrizio Milo's avatar
Fabrizio Milo committed
34
35
36
37
38
39
def simple_evaluate(
    model,
    model_args=None,
    tasks=[],
    num_fewshot=0,
    batch_size=None,
40
    max_batch_size=None,
Fabrizio Milo's avatar
Fabrizio Milo committed
41
    device=None,
haileyschoelkopf's avatar
haileyschoelkopf committed
42
    use_cache=None,
Fabrizio Milo's avatar
Fabrizio Milo committed
43
44
45
46
    limit=None,
    bootstrap_iters=100000,
    check_integrity=False,
    decontamination_ngrams_path=None,
47
    write_out=False,
48
    log_samples=True,
Fabrizio Milo's avatar
Fabrizio Milo committed
49
):
50
    """Instantiate and evaluate a model on a list of tasks.
51

52
53
54
    :param model: Union[str, LM]
        Name of model or LM object, see lm_eval.models.get_model
    :param model_args: Optional[str]
Fabrizio Milo's avatar
Fabrizio Milo committed
55
        String arguments for each model class, see LM.create_from_arg_string.
56
57
        Ignored if `model` argument is a LM object.
    :param tasks: list[Union[str, Task]]
Leo Gao's avatar
Leo Gao committed
58
        List of task names or Task objects. Task objects will be taken to have name task.EVAL_HARNESS_NAME if defined and type(task).__name__ otherwise.
59
60
    :param num_fewshot: int
        Number of examples in few-shot context
61
    :param batch_size: int or str, optional
62
        Batch size for model
63
64
    :param max_batch_size: int, optional
        Maximal batch size to try with automatic batch size detection
65
    :param device: str, optional
66
        PyTorch device (e.g. "cpu" or "cuda:0") for running models
haileyschoelkopf's avatar
haileyschoelkopf committed
67
68
    :param use_cache: str, optional
        A path to a sqlite db file for caching model responses. `None` if not caching.
69
70
    :param limit: int or float, optional
        Limit the number of examples per task (only use this for testing), If <1, limit is a percentage of the total number of examples.
71
72
    :param bootstrap_iters:
        Number of iterations for bootstrap statistics
Stephen Hogg's avatar
Stephen Hogg committed
73
74
    :param check_integrity: bool
        Whether to run the relevant part of the test suite for the tasks
75
    :param write_out: bool
76
77
78
        If True, write out an example document and model input for checking task integrity
    :param log_samples: bool
        If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
79
    :return
80
        Dictionary of results
81
    """
82
    random.seed(0)
83
    np.random.seed(1234)
84
85
86
    torch.manual_seed(
        1234
    )  # TODO: this may affect training runs that are run with evaluation mid-run.
87

88
89
90
    assert tasks != [], "No tasks specified"

    if isinstance(model, str):
Fabrizio Milo's avatar
Fabrizio Milo committed
91
92
        if model_args is None:
            model_args = ""
lintangsutawika's avatar
lintangsutawika committed
93
        lm = lm_eval.api.registry.get_model(model).create_from_arg_string(
lintangsutawika's avatar
lintangsutawika committed
94
95
96
97
98
99
            model_args,
            {
                "batch_size": batch_size,
                "max_batch_size": max_batch_size,
                "device": device,
            },
Fabrizio Milo's avatar
Fabrizio Milo committed
100
        )
101
    else:
102
        assert isinstance(model, lm_eval.api.model.LM)
103
        lm = model
104

haileyschoelkopf's avatar
haileyschoelkopf committed
105
106
107
108
109
110
111
112
113
114
    if use_cache is not None:
        print(f"Using cache at {use_cache + '_rank' + str(lm.rank) + '.db'}")
        lm = lm_eval.api.model.CachingLM(
            lm,
            use_cache
            # each rank receives a different cache db.
            # necessary to avoid multiple writes to cache at once
            + "_rank" + str(lm.rank) + ".db",
        )

lintangsutawika's avatar
update  
lintangsutawika committed
115
    task_dict = lm_eval.tasks.get_task_dict(tasks, num_fewshot=num_fewshot)
Jonathan Tow's avatar
Merge  
Jonathan Tow committed
116

Stephen Hogg's avatar
Stephen Hogg committed
117
    if check_integrity:
118
        run_task_tests(task_list=tasks)
Stephen Hogg's avatar
Stephen Hogg committed
119

120
121
122
123
    results = evaluate(
        lm=lm,
        task_dict=task_dict,
        limit=limit,
Niklas Muennighoff's avatar
Niklas Muennighoff committed
124
        bootstrap_iters=bootstrap_iters,
Fabrizio Milo's avatar
Fabrizio Milo committed
125
        decontamination_ngrams_path=decontamination_ngrams_path,
126
        write_out=write_out,
127
        log_samples=log_samples,
128
    )
129

130
131
132
    if lm.rank == 0:
        # add info about the model and few shot config
        results["config"] = {
lintangsutawika's avatar
lintangsutawika committed
133
134
135
            "model": model
            if isinstance(model, str)
            else model.model.config._name_or_path,
136
137
138
            "model_args": model_args,
            "num_fewshot": num_fewshot,
            "batch_size": batch_size,
lintangsutawika's avatar
lintangsutawika committed
139
140
141
            "batch_sizes": list(lm.batch_sizes.values())
            if hasattr(lm, "batch_sizes")
            else [],
142
            "device": device,
haileyschoelkopf's avatar
haileyschoelkopf committed
143
            "use_cache": use_cache,
144
145
146
            "limit": limit,
            "bootstrap_iters": bootstrap_iters,
        }
147
        results["git_hash"] = get_git_commit_hash()
148
149
150
        return results
    else:
        return None
151

Leo Gao's avatar
Leo Gao committed
152

153
decontaminate_suffix = "_decontaminate"
Leo Gao's avatar
Leo Gao committed
154

Fabrizio Milo's avatar
Fabrizio Milo committed
155

156
@positional_deprecated
Fabrizio Milo's avatar
Fabrizio Milo committed
157
158
159
160
161
162
def evaluate(
    lm,
    task_dict,
    limit=None,
    bootstrap_iters=100000,
    decontamination_ngrams_path=None,
163
    write_out=False,
164
    log_samples=True,
Fabrizio Milo's avatar
Fabrizio Milo committed
165
):
166
167
168
169
170
    """Instantiate and evaluate a model on a list of tasks.

    :param lm: obj
        Language Model
    :param task_dict: dict[str, Task]
Leo Gao's avatar
Leo Gao committed
171
        Dictionary of tasks. Tasks will be taken to have name task.EVAL_HARNESS_NAME if defined and type(task).__name__ otherwise.
172
173
174
175
176
177
    :param num_fewshot: int
        Number of examples in few-shot context
    :param limit: int, optional
        Limit the number of examples per task (only use this for testing)
    :param bootstrap_iters:
        Number of iterations for bootstrap statistics
178
    :param write_out: bool
179
180
181
        If True, write out an example document and model input for checking task integrity
    :param log_samples: bool
        If True, write out all model outputs and documents for per-sample measurement and post-hoc analysis
182
183
184
    :return
        Dictionary of results
    """
185

lintangsutawika's avatar
lintangsutawika committed
186
    # decontaminate = decontamination_ngrams_path is not None
187

Leo Gao's avatar
Leo Gao committed
188
    results = collections.defaultdict(dict)
Leo Gao's avatar
Leo Gao committed
189
    versions = collections.defaultdict(dict)
190
    configs = collections.defaultdict(dict)
lintangsutawika's avatar
lintangsutawika committed
191
    samples = collections.defaultdict(list)
Leo Gao's avatar
Leo Gao committed
192
    requests = collections.defaultdict(list)
lintangsutawika's avatar
lintangsutawika committed
193
    aggregate = collections.defaultdict(dict)
194
    task_groups = collections.defaultdict(dict)
195
196
    padding_requests = collections.defaultdict(int)

197
    # get lists of each type of request
198
    for task_name, task in task_dict.items():
199
200
201
202
203
204
205
206
207
208

        if type(task) == tuple:
            group, task = task

        # if group in task_groups:
        #     task_groups[group].append(task_name)
        # else:
        #     task_groups[group] = [task_name]
        task_groups[task_name] = group

Leo Gao's avatar
Leo Gao committed
209
        versions[task_name] = task.VERSION
haileyschoelkopf's avatar
haileyschoelkopf committed
210
211
        configs[task_name] = dict(task.dump_config())

Hailey Schoelkopf's avatar
Hailey Schoelkopf committed
212
        if limit is not None:
213
214
215
216
217
218
            if task.has_test_docs():
                task_docs = task.test_docs()
            elif task.has_validation_docs():
                task_docs = task.validation_docs()
            else:
                raise RuntimeError("Task has neither test_docs nor validation_docs")
219
            limit = int(len(task_docs) * limit) if limit < 1.0 else int(limit)
220

221
222
        task.build_all_requests(limit=limit, rank=lm.rank, world_size=lm.world_size)

haileyschoelkopf's avatar
haileyschoelkopf committed
223
224
225
226
227
228
229
        eval_logger.info(
            f"Task: {task_name}; number of requests on this rank: {len(task.instances)}"
        )

        if write_out:
            for inst in task.instances:
                # print the prompt for the first few documents
Hailey Schoelkopf's avatar
Hailey Schoelkopf committed
230
231
                if inst.doc_id < 1:
                    eval_logger.info(
haileyschoelkopf's avatar
haileyschoelkopf committed
232
233
                        f"Task: {task_name}; document {inst.doc_id}; context prompt (starting on next line):\n{inst.args[0]}\n(end of prompt on previous line)"
                    )
Hailey Schoelkopf's avatar
Hailey Schoelkopf committed
234
                    eval_logger.info("Request:", inst)
haileyschoelkopf's avatar
haileyschoelkopf committed
235

236
        # aggregate Instances by LM method requested to get output.
lintangsutawika's avatar
lintangsutawika committed
237
238
        reqtype = (
            "loglikelihood"
haileyschoelkopf's avatar
haileyschoelkopf committed
239
240
241
242
            if (
                task.OUTPUT_TYPE == "multiple_choice"
                or task.OUTPUT_TYPE == "winograd_schema"
            )
lintangsutawika's avatar
lintangsutawika committed
243
244
245
            else task.OUTPUT_TYPE
        )  # TODO: this is hacky, fix in task.py
        requests[reqtype].extend(task.instances)
246
247

        if lm.world_size > 1:
248
249
250
251
            instances_rnk = torch.tensor(len(task._instances), device=lm.device)
            gathered_item = (
                lm.accelerator.gather(instances_rnk).cpu().detach().numpy().tolist()
            )
252

253
            # compute number of pseudobatches to pad with (FSDP/DDP require even batches among ranks)
254
            numpad = max(gathered_item) - gathered_item[lm.rank]
255
            padding_requests[task.OUTPUT_TYPE] += numpad
256

257
    ### Run LM on inputs, get all outputs ###
Leo Gao's avatar
Leo Gao committed
258
259
    # execute each type of request
    for reqtype, reqs in requests.items():
lintangsutawika's avatar
lintangsutawika committed
260
        eval_logger.info("Running {} requests".format(reqtype))
261
262
263
264
        # create `K` copies of each request `req` based off `K = req.repeats`
        cloned_reqs = []
        for req in reqs:
            cloned_reqs.extend([req] * req.repeats)
lintangsutawika's avatar
lintangsutawika committed
265

266
267
        if (lm.world_size > 1) and (padding_requests[reqtype] > 0):
            for _ in range(padding_requests[reqtype]):
268
269
                cloned_reqs.extend([req] * req.repeats)

270
271
272
273
274
275
276
        # run requests through model
        resps = getattr(lm, reqtype)(cloned_reqs)

        # put responses from model into a list of length K for each request.
        for x, req in zip(resps, cloned_reqs):
            req.resps.append(x)

277
278
        if lm.world_size > 1:
            lm.accelerator.wait_for_everyone()
279

280
281
282
    ### Postprocess outputs ###
    # TODO: del model here, maybe (idea: allow user to specify device of e.g. reward model separately)
    for task_name, task in task_dict.items():
283
284
        if type(task) == tuple:
            group, task = task
285
286
287
        task.apply_filters()

    ### Collect values of metrics on all datapoints ###
Leo Gao's avatar
Leo Gao committed
288
289
290
    vals = collections.defaultdict(list)

    # unpack results and sort back in order and return control to Task
291
    for task_name, task in task_dict.items():
292
293
        if type(task) == tuple:
            group, task = task
haileyschoelkopf's avatar
haileyschoelkopf committed
294
295
        # TODO: make it possible to use a different metric per filter
        # iterate over different filters used
296
        for key in task.instances[0].filtered_resps.keys():
297
298
299
300
            doc_iterator = (
                itertools.islice(
                    enumerate(task.test_docs()), lm.rank, limit, lm.world_size
                )
lintangsutawika's avatar
lintangsutawika committed
301
                if task.has_test_docs()
302
303
304
305
                else itertools.islice(
                    enumerate(task.validation_docs()), lm.rank, limit, lm.world_size
                )
            )
306
            for doc_id, doc in doc_iterator:
307
308
                # subset instances to only this document id ; sort by idx
                requests = list(filter(lambda x: x.doc_id == doc_id, task.instances))
309
                requests.sort(key=lambda x: x.idx)
lintangsutawika's avatar
lintangsutawika committed
310
311
312
                metrics = task.process_results(
                    doc, [req.filtered_resps[key] for req in requests]
                )
313
314
315
316
317
318
319
320
321
322
323
324
                if log_samples:
                    target = task.doc_to_target(doc)
                    example = {
                        "doc_id": doc_id,
                        "doc": doc,
                        "target": target,
                        "arguments": [req.args for req in requests],
                        "resps": [req.resps for req in requests],
                        "filtered_resps": [req.filtered_resps[key] for req in requests],
                    }
                    example.update(metrics)
                    samples[task_name].append(example)
325
326
327
                for metric, value in metrics.items():
                    vals[(task_name, key, metric)].append(value)

328
    if lm.world_size > 1:
329
        # if multigpu, then gather data across all ranks
330
331
332
333
334
335
336
337
338
        # first gather logged samples across all ranks
        for task_name, task_samples in list(samples.items()):

            full_samples = [None] * lm.world_size
            torch.distributed.all_gather_object(full_samples, task_samples)

            samples[task_name] = list(itertools.chain.from_iterable(full_samples))

        # then collect metrics across all ranks
339
340
        vals_torch = collections.defaultdict(list)
        for (task_name, key, metric), items in vals.items():
341
342

            numitem = 0
343
            if type(items[0]) == tuple:
344
345
                numitem = len(items[0])

346
347
            # distributed gather requires all ranks to have same dimensions
            # so we pad out with float32 min value
348
            pad_value = torch.finfo(torch.float32).min
349
350
351
352
353
354
            metrics_tensor = torch.tensor(items, device=lm.device)

            original_dtype = metrics_tensor.dtype  # store original dtype
            torch_device_tensor = lm.accelerator.pad_across_processes(
                metrics_tensor.to(torch.float32), pad_index=pad_value
            )
355
            gathered_item = lm.accelerator.gather(torch_device_tensor)
356

357
            if numitem > 0:
358
                gathered_filtered = gathered_item[gathered_item[:, 0] != pad_value]
359
360
            else:
                gathered_filtered = gathered_item[gathered_item != pad_value]
361
362
363
364

            gathered_item = (
                gathered_filtered.to(original_dtype).cpu().detach().numpy().tolist()
            )
365
366
367
            # reconvert if we were passed a tuple of values
            if numitem > 0:
                gathered_item = [tuple(g) for g in gathered_item]
368

369
370
            if lm.rank == 0:
                vals_torch[(task_name, key, metric)] = gathered_item
371

372
        vals = vals_torch
373

374
375
376
377
378
    if lm.rank == 0:
        ### Aggregate results over all datapoints ###
        # aggregate results ; run bootstrap CIs
        for (task_name, key, metric), items in vals.items():
            task = task_dict[task_name]
379
380
            if type(task) == tuple:
                group, task = task
lintangsutawika's avatar
lintangsutawika committed
381
382
383
            task_score = task.aggregation()[metric](items)
            results[task_name][metric + "," + key] = task_score

384
385
386
387
388
389
390
391
392
            # if task_name not in benchmark_agg:
            #     benchmark[] = [task_score]

            # Need to put back in results
            # pythia | acc
            #        | perplexity
            #        | word_perplexity
            #        | byte_perplexity
            #        | bits_per_byte
393
394
395
            group_name = task_groups[task_name]
            if metric not in aggregate[group_name]:
                aggregate[group_name][metric] = [task_score]
lintangsutawika's avatar
lintangsutawika committed
396
            else:
397
                aggregate[group_name][metric].append(task_score)
Leo Gao's avatar
Leo Gao committed
398

399
400
            # hotfix: bleu, chrf, ter seem to be really expensive to bootstrap
            # so we run them less iterations. still looking for a cleaner way to do this
haileyschoelkopf's avatar
haileyschoelkopf committed
401
402
403
404
405
406
407
            if bootstrap_iters > 0:
                stderr = lm_eval.api.metrics.stderr_for_metric(
                    metric=task.aggregation()[metric],
                    bootstrap_iters=min(bootstrap_iters, 1000)
                    if metric in ["bleu", "chrf", "ter"]
                    else bootstrap_iters,
                )
408

haileyschoelkopf's avatar
haileyschoelkopf committed
409
410
                if stderr is not None:
                    results[task_name][metric + "_stderr" + "," + key] = stderr(items)
Fabrizio Milo's avatar
Fabrizio Milo committed
411

412
413
414
415
        for group in aggregate.keys():
            for metric in aggregate[group].keys():
                aggregate[group][metric] = np.average(aggregate[group][metric])
                versions[group] = "N/A"
lintangsutawika's avatar
lintangsutawika committed
416

417
        results_dict = {
418
            "results": dict(results),
lintangsutawika's avatar
lintangsutawika committed
419
            "aggregate": dict(aggregate),
420
421
422
            "configs": dict(configs),
            "versions": dict(versions),
        }
423
424
425
426
        if log_samples:
            results_dict["samples"] = dict(samples)

        return results_dict
Fabrizio Milo's avatar
Fabrizio Milo committed
427

428
429
    else:
        return None