evaluator.py 21.7 KB
Newer Older
lintangsutawika's avatar
lintangsutawika committed
1
import collections
Baber Abbasi's avatar
Baber Abbasi committed
2
import itertools
3
import logging
Baber Abbasi's avatar
Baber Abbasi committed
4
import random
5
from typing import TYPE_CHECKING, Optional, Union
Baber Abbasi's avatar
Baber Abbasi committed
6

7
import numpy as np
Baber Abbasi's avatar
Baber Abbasi committed
8
import torch
lintangsutawika's avatar
lintangsutawika committed
9

lintangsutawika's avatar
lintangsutawika committed
10
import lm_eval.api.metrics
lintangsutawika's avatar
lintangsutawika committed
11
import lm_eval.api.registry
Baber Abbasi's avatar
Baber Abbasi committed
12
import lm_eval.models
13
14
15
16
17
18
19
20
from lm_eval.evaluator_utils import (
    consolidate_results,
    get_sample_size,
    get_task_list,
    prepare_print_tasks,
    print_writeout,
    run_task_tests,
)
21
from lm_eval.logging_utils import add_env_info, get_git_commit_hash
Baber Abbasi's avatar
Baber Abbasi committed
22
from lm_eval.tasks import TaskManager, get_task_dict
lintangsutawika's avatar
lintangsutawika committed
23
from lm_eval.utils import (
Baber Abbasi's avatar
Baber Abbasi committed
24
    eval_logger,
lintangsutawika's avatar
lintangsutawika committed
25
    positional_deprecated,
lintangsutawika's avatar
lintangsutawika committed
26
    simple_parse_args_string,
lintangsutawika's avatar
lintangsutawika committed
27
)
28

Fabrizio Milo's avatar
Fabrizio Milo committed
29

30
31
32
33
34
35
36
if TYPE_CHECKING:
    from lm_eval.api.model import LM
    from lm_eval.tasks import Task

from lm_eval.caching.cache import delete_cache


37
@positional_deprecated
Fabrizio Milo's avatar
Fabrizio Milo committed
38
39
def simple_evaluate(
    model,
40
    model_args: Optional[Union[str, dict, None]] = None,
41
    tasks=None,
Baber Abbasi's avatar
Baber Abbasi committed
42
43
44
45
46
    num_fewshot: Optional[int] = None,
    batch_size: Optional[int] = None,
    max_batch_size: Optional[int] = None,
    device: Optional[str] = None,
    use_cache: Optional[str] = None,
47
48
49
    cache_requests: bool = False,
    rewrite_requests_cache: bool = False,
    delete_requests_cache: bool = False,
Baber Abbasi's avatar
Baber Abbasi committed
50
    limit: Optional[Union[int, float]] = None,
Ethan Smith's avatar
Ethan Smith committed
51
52
    bootstrap_iters: int = 100000,
    check_integrity: bool = False,
Fabrizio Milo's avatar
Fabrizio Milo committed
53
    decontamination_ngrams_path=None,
Ethan Smith's avatar
Ethan Smith committed
54
55
    write_out: bool = False,
    log_samples: bool = True,
lintangsutawika's avatar
lintangsutawika committed
56
    gen_kwargs: str = None,
57
58
    task_manager: TaskManager = None,
    verbosity: str = "INFO",
Baber Abbasi's avatar
Baber Abbasi committed
59
    predict_only: bool = False,
60
61
62
    random_seed: int = 0,
    numpy_random_seed: int = 1234,
    torch_random_seed: int = 1234,
Fabrizio Milo's avatar
Fabrizio Milo committed
63
):
64
    """Instantiate and evaluate a model on a list of tasks.
65

66
67
    :param model: Union[str, LM]
        Name of model or LM object, see lm_eval.models.get_model
68
69
    :param model_args: Optional[str, dict]
        String or dict arguments for each model class, see LM.create_from_arg_string and LM.create_from_arg_object.
70
        Ignored if `model` argument is a LM object.
71
    :param tasks: list[Union[str, dict, Task]]
Leo Gao's avatar
Leo Gao committed
72
        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.
73
74
    :param num_fewshot: int
        Number of examples in few-shot context
75
    :param batch_size: int or str, optional
76
        Batch size for model
77
78
    :param max_batch_size: int, optional
        Maximal batch size to try with automatic batch size detection
79
    :param device: str, optional
80
        PyTorch device (e.g. "cpu" or "cuda:0") for running models
haileyschoelkopf's avatar
haileyschoelkopf committed
81
82
    :param use_cache: str, optional
        A path to a sqlite db file for caching model responses. `None` if not caching.
83
84
85
86
87
88
    :param cache_requests: bool, optional
        Speed up evaluation by caching the building of dataset requests. `None` if not caching.
    :param rewrite_requests_cache: bool, optional
        Rewrites all of the request cache if set to `True`. `None` if not desired.
    :param delete_requests_cache: bool, optional
        Deletes all of the request cache if set to `True`. `None` if not desired.
89
90
    :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.
91
92
    :param bootstrap_iters:
        Number of iterations for bootstrap statistics
Stephen Hogg's avatar
Stephen Hogg committed
93
94
    :param check_integrity: bool
        Whether to run the relevant part of the test suite for the tasks
95
    :param write_out: bool
96
97
98
        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
99
100
101
    :param gen_kwargs: str
        String arguments for model generation
        Ignored for all tasks with loglikelihood output_type
Baber Abbasi's avatar
Baber Abbasi committed
102
103
    :param predict_only: bool
        If true only model outputs will be generated and returned. Metrics will not be evaluated
104
105
106
107
108
109
    :param random_seed: int
        Random seed for python's random module. If set to None, the seed will not be set.
    :param numpy_random_seed: int
        Random seed for numpy. If set to None, the seed will not be set.
    :param torch_random_seed: int
        Random seed for torch. If set to None, the seed will not be set.
Baber Abbasi's avatar
Baber Abbasi committed
110

111
    :return
112
        Dictionary of results
113
    """
114
115
    eval_logger.setLevel(getattr(logging, f"{verbosity}"))

116
117
118
119
    if delete_requests_cache:
        eval_logger.info("Deleting requests cache...")
        delete_cache()

120
    seed_message = []
121
122
    if random_seed is not None:
        # See https://github.com/EleutherAI/lm-evaluation-harness/pull/1412
123
        seed_message.append(f"Setting random seed to {random_seed}")
124
125
126
        random.seed(random_seed)

    if numpy_random_seed is not None:
127
        seed_message.append(f"Setting numpy seed to {numpy_random_seed}")
128
129
130
        np.random.seed(numpy_random_seed)

    if torch_random_seed is not None:
131
        seed_message.append(f"Setting torch manual seed to {torch_random_seed}")
132
133
        torch.manual_seed(torch_random_seed)

134
135
136
    if seed_message:
        eval_logger.info(" | ".join(seed_message))

137
138
    if tasks is None:
        tasks = []
139
140
141
    assert (
        tasks != []
    ), "No tasks specified, or no tasks found. Please verify the task names."
142

lintangsutawika's avatar
lintangsutawika committed
143
144
    if gen_kwargs is not None:
        gen_kwargs = simple_parse_args_string(gen_kwargs)
lintangsutawika's avatar
udate  
lintangsutawika committed
145
        eval_logger.warning(
Baber Abbasi's avatar
Baber Abbasi committed
146
            "generation_kwargs specified through cli, these settings will update set parameters in yaml tasks. Ensure 'do_sample=True' for non-greedy decoding!"
lintangsutawika's avatar
udate  
lintangsutawika committed
147
        )
lintangsutawika's avatar
lintangsutawika committed
148
149
150
        if gen_kwargs == "":
            gen_kwargs = None

151
    if isinstance(model, str):
Fabrizio Milo's avatar
Fabrizio Milo committed
152
153
        if model_args is None:
            model_args = ""
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

        elif isinstance(model_args, dict):
            lm = lm_eval.api.registry.get_model(model).create_from_arg_obj(
                model_args,
                {
                    "batch_size": batch_size,
                    "max_batch_size": max_batch_size,
                    "device": device,
                },
            )

        else:
            lm = lm_eval.api.registry.get_model(model).create_from_arg_string(
                model_args,
                {
                    "batch_size": batch_size,
                    "max_batch_size": max_batch_size,
                    "device": device,
                },
            )
174
    else:
175
        assert isinstance(model, lm_eval.api.model.LM)
176
        lm = model
177

haileyschoelkopf's avatar
haileyschoelkopf committed
178
    if use_cache is not None:
179
        eval_logger.info(f"Using cache at {use_cache + '_rank' + str(lm.rank) + '.db'}")
haileyschoelkopf's avatar
haileyschoelkopf committed
180
181
182
183
184
        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
185
186
187
            + "_rank"
            + str(lm.rank)
            + ".db",
haileyschoelkopf's avatar
haileyschoelkopf committed
188
189
        )

190
191
192
193
194
    if task_manager is None:
        task_manager = TaskManager(verbosity)

    eval_logger.info(
        "get_task_dict has been updated to accept an optional argument, `task_manager`"
Baber Abbasi's avatar
Baber Abbasi committed
195
196
        "Read more here:https://github.com/EleutherAI/lm-evaluation-harness/blob/main/docs/interface.md#external-library-usage"
    )
197
    task_dict = get_task_dict(tasks, task_manager)
198
    for task_name in task_dict.keys():
lintangsutawika's avatar
lintangsutawika committed
199
        task_obj = task_dict[task_name]
200
        if isinstance(task_obj, tuple):
201
            _, task_obj = task_obj
202
203
            if task_obj is None:
                continue
lintangsutawika's avatar
lintangsutawika committed
204

Baber Abbasi's avatar
Baber Abbasi committed
205
206
        if task_obj.get_config("output_type") == "generate_until":
            if gen_kwargs is not None:
Baber Abbasi's avatar
Baber Abbasi committed
207
                task_obj.set_config(
Baber Abbasi's avatar
Baber Abbasi committed
208
209
210
                    key="generation_kwargs", value=gen_kwargs, update=True
                )

211
212
213
214
215
216
217
        if predict_only:
            log_samples = True
            eval_logger.info(
                f"Processing {task_name} in output-only mode. Metrics will not be calculated!"
            )
            # we have to change the class properties post-hoc. This is pretty hacky.
            task_obj.override_metric(metric_name="bypass")
218

219
        if num_fewshot is not None:
Baber Abbasi's avatar
Baber Abbasi committed
220
            if (default_num_fewshot := task_obj.get_config("num_fewshot")) == 0:
221
222
223
                eval_logger.info(
                    f"num_fewshot has been set to 0 for {task_name} in its config. Manual configuration will be ignored."
                )
224
            else:
Baber Abbasi's avatar
Baber Abbasi committed
225
226
227
                eval_logger.warning(
                    f"Overwriting default num_fewshot of {task_name} from {default_num_fewshot} to {num_fewshot}"
                )
Baber Abbasi's avatar
Baber Abbasi committed
228
                task_obj.set_config(key="num_fewshot", value=num_fewshot)
Jonathan Tow's avatar
Merge  
Jonathan Tow committed
229

Stephen Hogg's avatar
Stephen Hogg committed
230
    if check_integrity:
231
        run_task_tests(task_list=tasks)
Stephen Hogg's avatar
Stephen Hogg committed
232

233
234
235
236
    results = evaluate(
        lm=lm,
        task_dict=task_dict,
        limit=limit,
237
238
        cache_requests=cache_requests,
        rewrite_requests_cache=rewrite_requests_cache,
Niklas Muennighoff's avatar
Niklas Muennighoff committed
239
        bootstrap_iters=bootstrap_iters,
Fabrizio Milo's avatar
Fabrizio Milo committed
240
        decontamination_ngrams_path=decontamination_ngrams_path,
241
        write_out=write_out,
242
        log_samples=log_samples,
243
        verbosity=verbosity,
244
    )
245

246
    if lm.rank == 0:
247
248
249
250
251
252
253
        if isinstance(model, str):
            model_name = model
        elif hasattr(model, "config") and hasattr(model.config, "_name_or_path"):
            model_name = model.config._name_or_path
        else:
            model_name = type(model).__name__

254
255
        # add info about the model and few shot config
        results["config"] = {
256
            "model": model_name,
257
258
            "model_args": model_args,
            "batch_size": batch_size,
259
260
261
            "batch_sizes": (
                list(lm.batch_sizes.values()) if hasattr(lm, "batch_sizes") else []
            ),
262
            "device": device,
haileyschoelkopf's avatar
haileyschoelkopf committed
263
            "use_cache": use_cache,
264
265
            "limit": limit,
            "bootstrap_iters": bootstrap_iters,
lintangsutawika's avatar
lintangsutawika committed
266
            "gen_kwargs": gen_kwargs,
267
        }
268
        results["git_hash"] = get_git_commit_hash()
269
        add_env_info(results)  # additional environment info to results
270
271
272
        return results
    else:
        return None
273

Leo Gao's avatar
Leo Gao committed
274

275
decontaminate_suffix = "_decontaminate"
Leo Gao's avatar
Leo Gao committed
276

Fabrizio Milo's avatar
Fabrizio Milo committed
277

278
@positional_deprecated
Fabrizio Milo's avatar
Fabrizio Milo committed
279
def evaluate(
280
    lm: "LM",
Fabrizio Milo's avatar
Fabrizio Milo committed
281
    task_dict,
Baber Abbasi's avatar
Baber Abbasi committed
282
    limit: Optional[int] = None,
283
284
    cache_requests=False,
    rewrite_requests_cache=False,
Baber Abbasi's avatar
Baber Abbasi committed
285
    bootstrap_iters: Optional[int] = 100000,
Fabrizio Milo's avatar
Fabrizio Milo committed
286
    decontamination_ngrams_path=None,
Ethan Smith's avatar
Ethan Smith committed
287
288
    write_out: bool = False,
    log_samples: bool = True,
289
    verbosity: str = "INFO",
Fabrizio Milo's avatar
Fabrizio Milo committed
290
):
291
292
293
294
295
    """Instantiate and evaluate a model on a list of tasks.

    :param lm: obj
        Language Model
    :param task_dict: dict[str, Task]
haileyschoelkopf's avatar
haileyschoelkopf committed
296
        Dictionary of tasks. Tasks will be taken to have name type(task).config.task .
297
298
299
300
    :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
301
    :param write_out: bool
302
303
304
        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
305
306
307
    :return
        Dictionary of results
    """
308

309
    eval_logger.setLevel(getattr(logging, f"{verbosity}"))
lintangsutawika's avatar
lintangsutawika committed
310
    # decontaminate = decontamination_ngrams_path is not None
311

312
    # tracks all Instances/requests a model must generate output on.
Leo Gao's avatar
Leo Gao committed
313
    requests = collections.defaultdict(list)
314
315
    # stores the amount to pad out reqs per req. type so that
    # number of fwd passes per distributed rank is equal
316
    padding_requests = collections.defaultdict(int)
317

318
319
320
321
322
323
324
325
326
327
    # get lists of group hierarchy and each type of request
    task_hierarchy, eval_tasks = get_task_list(task_dict)
    if not log_samples:
        assert all(
            "bypass" not in getattr(task_output.task, "_metric_fn_list", {}).keys()
            for task_output in eval_tasks
        ), "log_samples must be True for 'bypass' only tasks"
    for task_output in eval_tasks:
        task: Task = task_output.task
        limit = get_sample_size(task, limit)
328
329
330
331
332
333
334
        task.build_all_requests(
            limit=limit,
            rank=lm.rank,
            world_size=lm.world_size,
            cache_requests=cache_requests,
            rewrite_requests_cache=rewrite_requests_cache,
        )
335
        eval_logger.debug(
336
            f"Task: {task_output.task_name}; number of requests on this rank: {len(task.instances)}"
haileyschoelkopf's avatar
haileyschoelkopf committed
337
338
339
        )

        if write_out:
340
            print_writeout(task)
341
        # aggregate Instances by LM method requested to get output.
lintangsutawika's avatar
lintangsutawika committed
342
343
344
        for instance in task.instances:
            reqtype = instance.request_type
            requests[reqtype].append(instance)
345
346

        if lm.world_size > 1:
347
348
349
350
            instances_rnk = torch.tensor(len(task._instances), device=lm.device)
            gathered_item = (
                lm.accelerator.gather(instances_rnk).cpu().detach().numpy().tolist()
            )
351

352
            # compute number of pseudo-batches to pad with (FSDP/DDP require even batches among ranks)
353
            numpad = max(gathered_item) - gathered_item[lm.rank]
354
            padding_requests[task.OUTPUT_TYPE] += numpad
355

356
    ### Run LM on inputs, get all outputs ###
Leo Gao's avatar
Leo Gao committed
357
358
    # execute each type of request
    for reqtype, reqs in requests.items():
359
        eval_logger.info(f"Running {reqtype} requests")
360
361
362
363
        # 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
364

365
366
        if (lm.world_size > 1) and (padding_requests[reqtype] > 0):
            for _ in range(padding_requests[reqtype]):
367
368
                cloned_reqs.extend([req] * req.repeats)

369
370
371
372
373
374
375
        # 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)

376
377
        if lm.world_size > 1:
            lm.accelerator.wait_for_everyone()
378

379
380
    RANK = lm.rank
    WORLD_SIZE = lm.world_size
381
382
    ### Postprocess outputs ###
    # TODO: del model here, maybe (idea: allow user to specify device of e.g. reward model separately)
383
384
    for task_output in eval_tasks:
        task = task_output.task
385
386
        task.apply_filters()

387
388
        ### Collect values of metrics on all datapoints ###
        # # unpack results and sort back in order and return control to Task
haileyschoelkopf's avatar
haileyschoelkopf committed
389
        # TODO: make it possible to use a different metric per filter
390
391
392
393
394
395
396
        # Pre-process task.instances to group by doc_id
        instances_by_doc_id = collections.defaultdict(list)
        for instance in task.instances:
            instances_by_doc_id[instance.doc_id].append(instance)
        # Sort instances within each group
        for instances in instances_by_doc_id.values():
            instances.sort(key=lambda x: x.idx)
haileyschoelkopf's avatar
haileyschoelkopf committed
397
        # iterate over different filters used
398
399
400
        for filter_key in task.instances[0].filtered_resps.keys():
            doc_iterator = task.doc_iterator(
                rank=RANK, limit=limit, world_size=WORLD_SIZE
401
            )
402
            for doc_id, doc in doc_iterator:
403
                requests = instances_by_doc_id[doc_id]
lintangsutawika's avatar
lintangsutawika committed
404
                metrics = task.process_results(
405
                    doc, [req.filtered_resps[filter_key] for req in requests]
lintangsutawika's avatar
lintangsutawika committed
406
                )
407
408
409
410
411
412
413
414
                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],
415
416
417
                        "filtered_resps": [
                            req.filtered_resps[filter_key] for req in requests
                        ],
418
419
                    }
                    example.update(metrics)
420
                    task_output.logged_samples.append(example)
421
                for metric, value in metrics.items():
422
                    task_output.sample_metrics[(metric, filter_key)].append(value)
423

424
425
    if WORLD_SIZE > 1:
        # if multigpu, then gather data across all ranks to rank 0
426
        # first gather logged samples across all ranks
427
428
429
430
431
432
433
434
        for task_output in eval_tasks:
            if log_samples:
                # for task_name, task_samples in list(samples.items()):
                full_samples = [None] * WORLD_SIZE if RANK == 0 else None
                torch.distributed.gather_object(
                    obj=task_output.logged_samples,
                    object_gather_list=full_samples,
                    dst=0,
435
                )
436

437
438
439
440
                if RANK == 0:
                    task_output.logged_samples = list(
                        itertools.chain.from_iterable(full_samples)
                    )
441

442
443
444
445
446
447
448
            # then collect metrics across all ranks
            for metrics in task_output.sample_metrics:
                metric_list = [None] * WORLD_SIZE if RANK == 0 else None
                torch.distributed.gather_object(
                    obj=task_output.sample_metrics[metrics],
                    object_gather_list=metric_list,
                    dst=0,
449
                )
450
451
452
453
                if RANK == 0:
                    task_output.sample_metrics[metrics] = list(
                        itertools.chain.from_iterable(metric_list)
                    )
454

455
    if RANK == 0:
456
457
        ### Aggregate results over all datapoints ###
        # aggregate results ; run bootstrap CIs
458
459
460
461
462
        for task_output in eval_tasks:
            task_output.calculate_aggregate_metric(bootstrap_iters=bootstrap_iters)
        results, samples, configs, versions, num_fewshot = consolidate_results(
            eval_tasks
        )
Fabrizio Milo's avatar
Fabrizio Milo committed
463

464
        ### Calculate group metrics ###
lintangsutawika's avatar
lintangsutawika committed
465
        if bool(results):
466
            for group, task_list in reversed(task_hierarchy.items()):
467
468
469
470
471
472
                if len(task_list) == 0:
                    # task_hierarchy entries are either
                    # `group_name: [subtask1, subtask2, ...]`
                    # or `task_name: []`.
                    # we only want to operate on groups here.
                    continue
473
474
475
476
477
478
479
480
481
                metric_list = list(
                    {
                        key
                        for task in task_list
                        for key in results[task].keys()
                        if "_stderr" not in key and key not in ["alias", "samples"]
                    }
                )
                for metric in metric_list:
482
483
484
                    stderr = "_stderr,".join(metric.split(","))

                    # gather metrics, sizes, and stderrs from subtasks
Baber Abbasi's avatar
Baber Abbasi committed
485
                    metrics = [
486
487
488
                        results[task][metric]
                        for task in task_list
                        if metric in results[task]
Baber Abbasi's avatar
Baber Abbasi committed
489
                    ]  # TODO: copy?
490
491
492
493
494
495
496
497
498
499
                    stderrs = [
                        results[task][stderr]
                        for task in task_list
                        if stderr in results[task]
                    ]
                    sizes = [
                        results[task]["samples"]
                        for task in task_list
                        if metric in results[task]
                    ]
500
501

                    # compute group's pooled metric and stderr
Baber Abbasi's avatar
Baber Abbasi committed
502
503
504
                    results[group][
                        metric
                    ] = lm_eval.api.metrics.aggregate_subtask_metrics(metrics, sizes)
505
506
507
508
                    # TODO: calculate grouped metric using aggregation fn
                    if "N/A" in stderrs:
                        results[group][stderr] = "N/A"
                    else:
Baber Abbasi's avatar
Baber Abbasi committed
509
510
511
                        results[group][
                            stderr
                        ] = lm_eval.api.metrics.pooled_sample_stderr(stderrs, sizes)
512
513
514
515
516
                        # TODO: allow GroupConfigs to choose which variance formula is used, for back-compatibility
                        # To use the old (likely incorrect) variance formula, comment out the above and uncomment this line:
                        # results[group][stderr] = lm_eval.api.metrics.combined_sample_stderr(stderrs, sizes, metrics=metrics)

                    results[group]["samples"] = sum(sizes)
lintangsutawika's avatar
lintangsutawika committed
517

Lintang Sutawika's avatar
Lintang Sutawika committed
518
519
520
521
522
523
524
525
526
527
528
529
530
        results_agg = collections.defaultdict(dict)
        groups_agg = collections.defaultdict(dict)
        all_tasks_list = list(task_hierarchy.keys())
        left_tasks_list = []
        while True:
            add_tasks_list = list(k for k in results_agg.keys())
            left_tasks_list = sorted(list(set(all_tasks_list) - set(add_tasks_list)))
            if len(left_tasks_list) == 0:
                break

            _task_hierarchy = {
                k: v for k, v in task_hierarchy.items() if k in left_tasks_list
            }
531
            _results_agg, _groups_agg = prepare_print_tasks(_task_hierarchy, results)
Lintang Sutawika's avatar
Lintang Sutawika committed
532
533
534

            results_agg = {**results_agg, **_results_agg}
            groups_agg = {**groups_agg, **_groups_agg}
lintangsutawika's avatar
lintangsutawika committed
535

536
        for group_name, task_list in task_hierarchy.items():
Baber Abbasi's avatar
Baber Abbasi committed
537
538
539
540
            if task_list:
                num_fewshot[group_name] = num_fewshot[
                    task_list[0]
                ]  # TODO: validate this
541

542
        results_dict = {
543
            "results": dict(results_agg.items()),
lintangsutawika's avatar
lintangsutawika committed
544
            **({"groups": dict(groups_agg.items())} if bool(groups_agg) else {}),
545
            "group_subtasks": {k: v for k, v in reversed(task_hierarchy.items())},
546
547
            "configs": dict(sorted(configs.items())),
            "versions": dict(sorted(versions.items())),
548
            "n-shot": dict(sorted(num_fewshot.items())),
549
        }
550
551
552
553
        if log_samples:
            results_dict["samples"] = dict(samples)

        return results_dict
Fabrizio Milo's avatar
Fabrizio Milo committed
554

555
556
    else:
        return None
557
558
559
560
561
562
563
564
565
566
567
568


def request_caching_arg_to_dict(cache_requests: str) -> dict:
    request_caching_args = {
        "cache_requests": (
            True if cache_requests == "true" or cache_requests == "refresh" else False
        ),
        "rewrite_requests_cache": True if cache_requests == "refresh" else False,
        "delete_requests_cache": True if cache_requests == "delete" else False,
    }

    return request_caching_args