-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_utils.py
More file actions
280 lines (238 loc) · 10.4 KB
/
Copy pathdata_utils.py
File metadata and controls
280 lines (238 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import logging
import random
import torch
import numpy as np
import datasets
from copy import deepcopy
from typing import List, Optional, Union
from datasets import concatenate_datasets, disable_caching
from zarth_utils.nn_utils import random_split, set_random_seed
from lm_eval.evaluator_utils import run_task_tests
from lm_eval.tasks import TaskManager, get_task_dict
from lm_eval.utils import simple_parse_args_string
eval_logger = logging.getLogger(__name__)
disable_caching()
datasets.config.HF_DATASETS_TRUST_REMOTE_CODE = True
def get_tasks(
tasks: Optional[List[Union[str, dict, object]]] = None,
num_fewshot: Optional[int] = None,
check_integrity: bool = False,
gen_kwargs: Optional[str] = None,
task_manager: Optional[TaskManager] = None,
verbosity: str = "INFO",
predict_only: bool = False,
random_seed: int = 0,
numpy_random_seed: int = 1234,
torch_random_seed: int = 1234,
fewshot_random_seed: int = 1234,
):
eval_logger.setLevel(getattr(logging, f"{verbosity}"))
seed_message = []
if random_seed is not None:
# See https://github.com/EleutherAI/lm-evaluation-harness/pull/1412
seed_message.append(f"Setting random seed to {random_seed}")
random.seed(random_seed)
if numpy_random_seed is not None:
seed_message.append(f"Setting numpy seed to {numpy_random_seed}")
np.random.seed(numpy_random_seed)
if torch_random_seed is not None:
seed_message.append(f"Setting torch manual seed to {torch_random_seed}")
torch.manual_seed(torch_random_seed)
if seed_message:
eval_logger.info(" | ".join(seed_message))
if tasks is None:
tasks = []
if len(tasks) == 0:
raise ValueError(
"No tasks specified, or no tasks found. Please verify the task names."
)
if gen_kwargs is not None:
gen_kwargs = simple_parse_args_string(gen_kwargs)
eval_logger.warning(
"generation_kwargs specified through cli, these settings will update set parameters in yaml tasks. "
"Ensure 'do_sample=True' for non-greedy decoding!"
)
if gen_kwargs == "":
gen_kwargs = None
if task_manager is None:
task_manager = TaskManager(verbosity)
task_dict = get_task_dict(tasks, task_manager)
# helper function to recursively apply config overrides to leaf subtasks, skipping their constituent groups.
# (setting of num_fewshot ; bypassing metric calculation ; setting fewshot seed)
def _adjust_config(task_dict):
adjusted_task_dict = {}
for task_name, task_obj in task_dict.items():
if isinstance(task_obj, dict):
adjusted_task_dict = {
**adjusted_task_dict,
**{task_name: _adjust_config(task_obj)},
}
else:
if task_obj.get_config("output_type") == "generate_until":
if gen_kwargs is not None:
task_obj.set_config(
key="generation_kwargs", value=gen_kwargs, update=True
)
if predict_only:
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")
# override tasks' fewshot values to the provided num_fewshot arg value
# except if tasks have it set to 0 manually in their configs--then we should never overwrite that
if num_fewshot is not None:
if (default_num_fewshot := task_obj.get_config("num_fewshot")) == 0:
eval_logger.info(
f"num_fewshot has been set to 0 for {task_name} in its config. Manual configuration will be ignored."
)
else:
eval_logger.warning(
f"Overwriting default num_fewshot of {task_name} from {default_num_fewshot} to {num_fewshot}"
)
task_obj.set_config(key="num_fewshot", value=num_fewshot)
else:
# if num_fewshot not provided, and the task does not define a default one, default to 0
if (
default_num_fewshot := task_obj.get_config("num_fewshot")
) is None:
task_obj.set_config(key="num_fewshot", value=0)
# fewshot_random_seed set for tasks, even with a default num_fewshot (e.g. in the YAML file)
task_obj.set_fewshot_seed(seed=fewshot_random_seed)
eval_logger.info(
f"Setting fewshot random generator seed to {fewshot_random_seed}"
)
adjusted_task_dict[task_name] = task_obj
return adjusted_task_dict
task_dict = _adjust_config(task_dict)
if check_integrity:
run_task_tests(task_list=tasks)
return task_dict, task_manager
def get_dataset(
task_names,
random_seed=0,
max_num_train=-1,
max_num_valid=-1,
max_num_test=-1,
apply_chat_template=False,
use_system_role=True,
):
task_dict, task_manager = get_tasks(tasks=task_names)
validation_task_dict = deepcopy(task_dict)
set_random_seed(random_seed)
all_train, all_valid, all_test = {}, {}, {}
for task_name in task_names:
task = task_dict[task_name]
assert task.has_training_docs()
# split the dataset into train/valid/test
if task.has_validation_docs() and task.has_test_docs():
train_dataset = task.training_docs()
valid_dataset = task.validation_docs()
test_dataset = task.test_docs()
else:
train_dataset = task.training_docs()
train_indices, valid_indices = random_split(
len(train_dataset), (0.8, 0.2), random_seed
)
valid_dataset = train_dataset.select(valid_indices)
train_dataset = train_dataset.select(train_indices)
test_dataset = task.eval_docs
class _OverrideTask(type(task_dict[task_name])):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._eval_docs = None
@property
def eval_docs(self):
return self._eval_docs
# handle the training set
if max_num_train != -1 and len(train_dataset) > max_num_train:
np.random.seed(random_seed)
train_dataset = train_dataset.select(
np.random.permutation(len(train_dataset))[:max_num_train]
)
# handle the validation set
if max_num_valid != -1 and len(valid_dataset) > max_num_valid:
np.random.seed(random_seed)
valid_dataset = valid_dataset.select(
np.random.permutation(len(valid_dataset))[:max_num_valid]
)
validation_task_dict[task_name].__class__ = _OverrideTask
validation_task_dict[task_name]._eval_docs = valid_dataset
# handle the test set
if max_num_test != -1 and len(test_dataset) > max_num_test:
np.random.seed(random_seed)
test_dataset = test_dataset.select(
np.random.permutation(len(test_dataset))[:max_num_test]
)
task_dict[task_name].__class__ = _OverrideTask
task_dict[task_name]._eval_docs = test_dataset
all_train[task_name] = train_dataset
all_valid[task_name] = valid_dataset
all_test[task_name] = test_dataset
ret_train, ret_valid, ret_test = [], [], []
for task_name in task_names:
task = task_dict[task_name]
def formatting_func(x):
question = task.doc_to_text(x)
target = task.doc_to_target(x)
if task_name == "winogrande":
choices = task.doc_to_choice(x)
x["text"] = choices[int(question)] + " " + target
assert not apply_chat_template
return x
if not apply_chat_template:
if task.config.doc_to_choice is not None:
choices = task.doc_to_choice(x)
if type(target) is int:
target = choices[target]
x["text"] = question + " " + target
else:
if type(target) is list:
target = " ".join(target)
x["text"] = question + " " + target
else:
if task.config.doc_to_choice is not None:
choices = task.doc_to_choice(x)
if type(target) is int:
target = choices[target]
x["messages"] = [
{"role": "system", "content": "You are helpful"},
{"role": "user", "content": question},
{"role": "assistant", "content": target},
]
else:
if type(target) is list:
target = " ".join(target)
x["messages"] = [
{"role": "system", "content": "You are helpful"},
{"role": "user", "content": question},
{"role": "assistant", "content": target},
]
if not use_system_role:
x["messages"] = x["messages"][1:]
return x
train_dataset = train_dataset.map(
formatting_func,
batched=False,
load_from_cache_file=False,
remove_columns=[
c
for c in train_dataset.column_names
if c not in ["text", "messages"]
],
)
valid_dataset = valid_dataset.map(
formatting_func,
batched=False,
load_from_cache_file=False,
remove_columns=[
c
for c in valid_dataset.column_names
if c not in ["text", "messages"]
],
)
ret_train.append(train_dataset)
ret_valid.append(valid_dataset)
ret_train = concatenate_datasets(ret_train)
ret_valid = concatenate_datasets(ret_valid)
return ret_train, ret_valid, task_dict, validation_task_dict, task_manager