-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark.py
553 lines (494 loc) · 19.6 KB
/
benchmark.py
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import json
from functools import lru_cache
import os
import random
import re
from typing import Union
from textwrap import dedent, indent
import requests
from loguru import logger
from datasets import load_dataset, get_dataset_config_names
from pygments import highlight, lexers, formatters, styles
from yaml import load_all, dump, CLoader as Loader
from fsspec.implementations.github import GithubFileSystem
from fsspec.implementations.local import LocalFileSystem
from template import README_TEMPLATE
def get_all_pygments():
all_lexers = lexers.get_all_lexers()
all_formatters = formatters.get_all_formatters()
all_styles = styles.get_all_styles()
return {
"lexers": list(all_lexers),
"formatters": list(all_formatters),
"styles": list(all_styles),
}
def show(obj, lexer: str = None, formatter: str = None, style: str = None):
"""indent 넣어서 이쁘게 프린트해주기"""
if not lexer:
lexer = "json"
if lexer == "json":
obj = json.dumps(obj, indent=4, ensure_ascii=False)
lexer = lexers.find_lexer_class_by_name(lexer)
if not formatter:
formatter = "terminal256"
formatter = formatters.find_formatter_class(formatter)
if not style:
style = "one-dark"
encoded = highlight(
obj,
lexer=lexer(),
formatter=formatter(style=style),
)
print(encoded)
class Config:
def __init__(self, path: str = None):
if not path:
path = os.path.dirname(__file__)
path = os.path.join(path, "config.yaml")
with open(path, "r") as f:
file = f.read()
conf = list(load_all(file, Loader=Loader))[0]
self.raw_config = conf
self.config = {k: v for k, v in conf.items() if not k.startswith("default")}
for k, v in self.config.items():
setattr(self, k, v)
@property
def all_names(self):
return self.get_all_names()
def get_all_names(self):
"""yaml내 벤치마크들의 전체 이름 출력"""
return list(self.config.keys())
def get_all_values(self, key: str):
"""벤치마크들의 key로 전달된 값의 value들만 출력"""
return {
k: v_v
for k, v in self.config.items()
for v_k, v_v in v.items()
if v_k == key
}
def get_benchmark(self, name: str):
"""벤치마크의 전체 정보 출력"""
return self.config[name]
def make_folder_tree(self, key: Union[list, str] = None, overwrite: bool = False):
# if key is none, make all benchmark folder tree
if not key:
key = self.get_all_names()
if isinstance(key, str):
key = [key]
# Guide Markdown within the folder
for k in key:
# Make Folder Tree and README.md
os.makedirs(f"tasks/{k}", exist_ok=True)
guide_doc = f"tasks/{k}/README.md"
if not overwrite and os.path.exists(f"tasks/{k}/README.md"):
continue
# Make default Markdown
on_the_fly = {}
for key, value in self.config[k].items():
if isinstance(value, list):
# toggle should be written in html tag like below:
# <details>
# <summary> click </summary>
# <div>- <code>value</code></div>
# </details>
lines = []
for idx, ele in enumerate(value):
if idx == 0:
indent_num = 8 # 첫번째 라인은 prefix = " "*4를 적용받으므로 8칸만 indent
else:
indent_num = 12 # 두번째 라인부터는 prefix를 적용받지 않으므로 12칸 indent
lines.append(
indent(
f"<div> - <code>{ele}</code></div>",
prefix=" " * indent_num,
)
)
on_the_fly.update(
{
key: indent(
dedent(
"""
<details>
<summary>Click</summary>
{}
</details>
"""
),
prefix=" " * 4,
).format("\n".join(lines))
}
)
# path, name은 backtick 처리
elif isinstance(value, str) and key in ("path", "name"):
on_the_fly.update({key: f"`{value}`"})
else:
on_the_fly.update({key: value})
# README_TEMPLATE:
# {benchmark_name}
# + ** source **: {source}
# + ** hf_path **: {hf_path}
# + ** hf_name **: {hf_name}
# + ** url **: [{url}]({url})
# + ** paper **: [{paper}]({paper})
# + ** annotation **: [{annotation}]({annotation})
guide_doc_md = README_TEMPLATE.format(benchmark_name=k, **on_the_fly)
# None이 있으면 해당 줄 삭제처리
guide_doc_md_processed = []
for line in guide_doc_md.split("\n"):
if "None" in line:
continue
else:
guide_doc_md_processed.append(line)
guide_doc_md = "\n".join(guide_doc_md_processed)
# 저장
with open(f"tasks/{k}/README.md", "w") as f:
f.write(guide_doc_md)
logger.info(f"{guide_doc}을 초기화합니다")
def get_config(self, key: str, print_yaml=False, update=True):
hf_name = get_dataset_config_names(self.config[key]["hf_path"])
if print_yaml:
print(f" hf_name:\n{indent(dump(hf_name), ' ')}")
return hf_name
def __len__(self):
return len(self.get_all_names())
def __getitem__(self, key):
return self.config[key]
def __repr__(self):
return "Benchmark List:\n{}\n\n---------- More details in self.config".format(
"\n".join([f" - {name}" for name in self.get_all_names()])
)
class HFReader:
def __init__(
self,
benchmark_name: str,
hf_path: str = None,
hf_name: str = None,
num_proc: int = 6,
dataset=None,
dataset_options: dict = None,
):
"""
Benchmark를 EDA하는 클래스
Args:
path: dataset의 path(hf)
name: config로 전달되는 path값, ARC-Challenge, ARC-easy, logiqa-en ... 등
num_proc: 작업 프로세스 수
"""
hf_conf = Config()
self.benchmark_name = benchmark_name
self.path = hf_path
self.hf_name = hf_name
self.dataset_option = dataset_options or {}
if not hf_path:
self.path = hf_conf.config[benchmark_name]["hf_path"]
if not hf_name:
self.hf_name = hf_conf.config[benchmark_name]["hf_name"]
if not isinstance(self.hf_name, str):
if isinstance(self.hf_name, list):
self.hf_name_list = hf_conf.config[benchmark_name]["hf_name"]
self.hf_name = hf_conf.config[benchmark_name]["hf_name"][
random.randint(0, len(self.hf_name) - 1)
]
logger.info(
f"name is type of list. randomly picked '{self.hf_name}'\nall names are saved within 'self.hf_name_list':\n{hf_conf.config[benchmark_name]['hf_name']}"
)
if not isinstance(self.path, str):
raise ValueError("path must be strings")
if not self.hf_name:
self.datasetdict = load_dataset(
self.path, num_proc=num_proc, **self.dataset_option
)
else:
self.datasetdict = load_dataset(
self.path, self.hf_name, num_proc=num_proc, **self.dataset_option
)
if not dataset:
self.split = list(self.datasetdict.keys())
self.prior_split = "train" if "train" in self.split else self.split[0]
self.prior_split = (
"default" if "default" in self.split else self.split[0]
) # bigbench case
self.dataset = self.datasetdict[self.prior_split]
else:
self.dataset = dataset
repr = f"path: {self.path}\n"
repr += f"name: {self.hf_name}\n"
repr += f"total_split: {self.split}\n"
repr += f"prior_split: {self.prior_split}\n"
for s in self.split:
repr += f"{s}: {len(self.datasetdict[s])}\n"
self.repr = repr
logger.info(self.repr)
def show(
self,
split: str = None,
sample: dict = None,
category: str = None,
idx: int = None,
):
"""
Sample 1개를 JSON indent = 4로 보여줌
Args:
split: 'train', 'test', 'validation'...
sample: 보려는 샘플
category: task를 나누는 카테고리, pass되면 카테고리마다 샘플링하는 list samples에서 sample로 뽑음
idx: 보려는 samples의 index
"""
if not split:
dataset = self.dataset
else:
dataset = self.datasetdict[split]
if not sample:
samples = self.sampling(dataset=dataset, category=category)
if not idx:
idx = random.randint(0, len(samples) - 1)
show(samples[idx])
def save(
self,
split: str = None,
samples: list = None,
path: str = None,
category: str = None,
):
"""
samples를 저장함
Args:
split: 'train', 'test', 'validation'...
samples: 저장하려는 samples
path: 저장 path
"""
if not split:
dataset = self.dataset
else:
dataset = self.datasetdict[split]
if not samples:
samples = self.sampling(dataset=dataset, category=category)
if not path:
file_name = f"{self.path.split('/')[-1] + '-' + self.hf_name if self.hf_name else self.path.split('/')[-1]}"
path = f"./tasks/{self.benchmark_name}/{file_name}.json"
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
logger.info(f"{path}에 저장합니다.")
logger.info(f"{len(samples)}의 샘플이 저장됩니다.")
json.dump(samples, f, ensure_ascii=False, indent=4)
def save_all(
self,
split: str = None,
samples: list = None,
path: str = None,
category: str = None,
):
if self.hf_name_list:
for hf_name in self.hf_name_list:
instance = HFReader(benchmark_name=self.benchmark_name, hf_name=hf_name)
instance.save(
split=split, samples=samples, path=path, category=category
)
else:
self.save(split=split, samples=samples, path=path, category=category)
def show_all(
self,
split: str = None,
sample: dict = None,
category: str = None,
idx: int = None,
):
if self.hf_name_list:
for hf_name in self.hf_name_list:
instance = HFReader(benchmark_name=self.benchmark_name, hf_name=hf_name)
instance.show(split=split, sample=sample, category=category, idx=idx)
def __repr__(self):
return f"{self.repr}"
@lru_cache
def sampling(self, split: str = None, dataset=None, category: str = None):
"""
dataset에서 sampling하기, 카테고리가 있으면 카테고리마다 1개씩 샘플링함
Args:
dataset: 샘플링할 데이터셋
category: 구분하려는 카테고리
"""
if not split:
dataset = self.dataset
else:
dataset = self.datasetdict[split]
if category is not None:
logger.info("카테고리가 있어서 카테고리마다 3개씩 샘플링합니다")
samples = []
for task in dataset.unique(category):
sample = dataset.filter(
lambda x: x[category] == task, writer_batch_size=1000
)
iteration = 3
for idx in range(iteration):
dic = {}
for k in sample.features.keys():
dic.update({k: sample[random.randint(0, len(sample) - 1)][k]})
samples.append(dic)
if category is None:
logger.info("카테고리가 없어서 전체에서 20개를 샘플링합니다")
samples = []
iteration = 20
for idx in range(iteration):
dic = {}
rand_idx = random.randint(0, len(dataset) - 1)
for k in dataset.features.keys():
dic.update({k: dataset[rand_idx][k]})
samples.append(dic)
logger.info(f"총 {len(samples)}개의 샘플이 있습니다.")
self.samples = samples
return self.samples
class GithubReader:
def __init__(
self, benchmark_name: str, user: str = None, repo: str = None, fpath: str = None
):
"""
Github 파일을 읽어옴
Args:
user: github user명, ex) 'aiqwe'
repo: repo 이름 ex) 'papers', 'benchmark'
fpath: 파일의 위치. ex) 'tasks/arc/ai2-arc-ARC-Challenge.json'
"""
conf = Config()
pattern = r"https://github.com/(.*)/(.*)"
benchmark_url = conf.config[benchmark_name]["url"]
matched = re.match(pattern, benchmark_url)
if not user:
user = matched.group(1)
if not repo:
repo = matched.group(2)
self.benchmark_name = benchmark_name
self.download_url = f"https://raw.githubusercontent.com/{user}/{repo}/master"
self.user = user.lower()
self.repo = repo.lower()
self.fpath = fpath
self.fs = GithubFileSystem(org=self.user, repo=self.repo)
def get_files(self, folder: str, pattern=None):
if not pattern:
logger.info("searching for '*.json' and '*.jsonl' patterns")
result = self.fs.glob(self.fs.sep.join([folder, "*.json"])) + self.fs.glob(
self.fs.sep.join([folder, "*.jsonl"])
)
else:
result = self.fs.glob(self.fs.sep.join([folder, pattern]))
result = [f.split("/")[-1].split(".")[0] for f in result]
return result
@lru_cache
def get_jsonl(self, fpath: None):
if not self.fpath:
if not fpath:
raise ValueError(
"if self.fpath is None, argument 'fpath' from 'get' should be passed"
)
else:
if fpath:
logger.info(f"{self.fpath} will be overwritten by {fpath}")
self.fpath = fpath
url = self.download_url + f"/{self.fpath}"
response = requests.get(url)
if self.fpath.endswith("jsonl"):
self.data = [json.loads(obj) for obj in response.text.splitlines()]
if self.fpath.endswith("json"):
self.data = json.loads(response.text)
return self.data
def sampling(self, data: list = None, fpath=None, n: int = 1000):
self.get_jsonl(fpath)
if isinstance(self.data, list):
return self.data[:n]
else:
logger.info(
"samples are not list. please check self.data and pass sample manually through self.show"
)
def show(self, data: list = None, fpath=None, idx=None, colored=True):
if not data:
samples = self.sampling(fpath)
else:
samples = data
if not idx:
idx = random.randint(0, len(samples) - 1)
show(samples[idx], colored=colored)
def save(self, data: list = None, fpath: str = None, path: str = None, n: int = 20):
if not data:
total = self.get_jsonl(fpath)
else:
total = data
samples = random.sample(total, k=n)
if not path:
file_name = self.repo + "-" + os.path.basename(self.fpath).split(".")[0]
path = f"./tasks/{self.benchmark_name}/{file_name}.json"
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
logger.info(f"{path}에 저장합니다.")
logger.info(f"{len(samples)}의 샘플이 저장됩니다.")
json.dump(samples, f, ensure_ascii=False, indent=4)
class LocalReader:
def __init__(self, benchmark_name: str, fpath: str = None):
"""
Github 파일을 읽어옴
Args:
user: github user명, ex) 'aiqwe'
repo: repo 이름 ex) 'papers', 'benchmark'
fpath: 파일의 위치. ex) 'tasks/arc/ai2-arc-ARC-Challenge.json'
"""
self.benchmark_name = benchmark_name
self.fpath = fpath
self.fs = LocalFileSystem()
def get_files(self, folder: str, pattern=None):
if not pattern:
logger.info("searching for '*.json' and '*.jsonl' patterns")
result = self.fs.glob(self.fs.sep.join([folder, "*.json"])) + self.fs.glob(
self.fs.sep.join([folder, "*.jsonl"])
)
else:
result = self.fs.glob(self.fs.sep.join([folder, pattern]))
result = [f.split("/")[-1].split(".")[0] for f in result]
return result
@lru_cache
def get_jsonl(self, fpath: None):
if not self.fpath:
if not fpath:
raise ValueError(
"if self.fpath is None, argument 'fpath' in 'get_jsonl' should be passed"
)
else:
if fpath:
logger.info(f"{self.fpath} will be overwritten by {fpath}")
self.fpath = fpath
text = self.fs.read_text(self.fpath)
if self.fpath.endswith("jsonl"):
self.data = [json.loads(obj) for obj in text.splitlines()]
if self.fpath.endswith("json"):
self.data = json.loads(text)
return self.data
def sampling(self, data: list = None, fpath=None, n: int = 1000):
if fpath:
self.get_jsonl(fpath=fpath)
if data:
return data[:n]
if isinstance(self.data, list):
return self.data[:n]
else:
logger.info(
"samples are not list. please check self.data and pass sample manually through self.show"
)
def show(self, exist: str = True, data: list = None, fpath=None, idx=None, colored=True):
if not idx:
idx = random.randint(0, len() - 1)
if not data:
samples = self.sampling(fpath)
else:
samples = data
show(samples[idx], colored=colored)
def save(self, data: list = None, fpath: str = None, path: str = None, n: int = 20):
if not data:
total = self.get_jsonl(fpath)
else:
total = data
samples = random.sample(total, k=n)
if not path:
file_name = self.repo + "-" + os.path.basename(self.fpath).split(".")[0]
path = f"./tasks/{self.benchmark_name}/{file_name}.json"
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
logger.info(f"{path}에 저장합니다.")
logger.info(f"{len(samples)}의 샘플이 저장됩니다.")
json.dump(samples, f, ensure_ascii=False, indent=4)