Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
601 lines (501 loc) · 17.6 KB
/
Copy pathbenchmark.py
File metadata and controls
601 lines (501 loc) · 17.6 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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import inspect
import json
import logging
import os
import re
import sys
import xml.etree.ElementTree as ET
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Generic, TypeVar
from binsparse import BinsparseTensor as BinsparseTensor
from saps.framework import load_framework
from saps.freshness import repo_root, source_freshness
from saps.storage import build_storage_backend
from saps_framework.framework import Framework
def _apply_memory_limit() -> None:
"""Cap this process's address space to SAPS_MEMORY_LIMIT_BYTES if set, so a
runaway benchmark raises MemoryError instead of OOM-killing the machine.
Only enforced on Linux: macOS accepts setrlimit(RLIMIT_AS) but silently does
not enforce it, and Windows has no resource module at all. On those platforms
we warn rather than give a false sense of protection.
"""
limit = os.environ.get("SAPS_MEMORY_LIMIT_BYTES")
if not limit:
return
if sys.platform != "linux":
logging.warning(
"Memory limit requested (SAPS_MEMORY_LIMIT_BYTES=%s) but it is only "
"enforced on Linux; benchmark memory is uncapped on %s.",
limit,
sys.platform,
)
return
try:
import resource
except ImportError: # non-Unix platforms
return
nbytes = int(limit)
_soft, hard = resource.getrlimit(resource.RLIMIT_AS)
new_soft = nbytes if hard == resource.RLIM_INFINITY else min(nbytes, hard)
resource.setrlimit(resource.RLIMIT_AS, (new_soft, hard))
@dataclass
class Author:
name: str
email: str | None = None
def __str__(self):
if self.email is None:
return self.name
return f"{self.name} <{self.email}>"
@dataclass
class Contributor:
name: str
email: str
def __str__(self):
return f"{self.name} <{self.email}>"
@dataclass
class Ref:
title: str
authors: list[Author]
journal: str | None = None
conference: str | None = None
booktitle: str | None = None
publisher: str | None = None
institution: str | None = None
volume: str | int | None = None
number: str | int | None = None
pages: str | None = None
city: str | None = None
year: int | None = None
url: str | None = None
doi: str | None = None
def __str__(self):
author_str = ", ".join(author.name for author in self.authors)
journal_str = f", {self.journal}" if self.journal else ""
conference_str = f", {self.conference}" if self.conference else ""
booktitle_str = f", In {self.booktitle}" if self.booktitle else ""
publisher_str = f", {self.publisher}" if self.publisher else ""
institution_str = f", {self.institution}" if self.institution else ""
volume_str = f", Vol. {self.volume}" if self.volume else ""
number_str = f", No. {self.number}" if self.number else ""
pages_str = f", pp. {self.pages}" if self.pages else ""
city_str = f", {self.city}" if self.city else ""
year_str = f", {self.year}" if self.year else ""
url_str = f", URL: {self.url}" if self.url else ""
doi_str = f", DOI: {self.doi}" if self.doi else ""
return (
f'{author_str}. "{self.title}"'
f"{journal_str}{conference_str}{booktitle_str}{publisher_str}{institution_str}"
f"{volume_str}{number_str}{pages_str}{city_str}{year_str}{url_str}{doi_str}."
)
def _tag_slug(value: str) -> str:
tag = re.sub(r"[^0-9A-Za-z]+", "-", value.lower())
return re.sub(r"-+", "-", tag).strip("-")
def ccs_xml_to_tags(xml_text: str | None) -> list[str]:
"""Convert pasted ACM CCS XML into SAPS tag slugs."""
if not xml_text:
return []
try:
root = ET.fromstring(xml_text)
except ET.ParseError:
return []
tags: set[str] = set()
for node in root.iter():
if node.tag.rsplit("}", 1)[-1] != "concept_desc" or not node.text:
continue
for part in re.split(r"\s*(?:~|::)\s*", node.text.strip()):
tag = _tag_slug(part)
if tag:
tags.add(f"concept-{tag}")
return sorted(tags)
def _get_or_add_record(records: list[dict], key: str, value: str, defaults: dict):
for record in records:
if record.get(key) == value:
return record
record = {key: value, **defaults}
records.append(record)
return record
def _write_statistics_tags(
statistics_path: Path,
benchmark_name: str,
generator_name: str,
dataset_name: str,
dataset_file: str,
dataset_freshness: str,
tags: list[str],
):
statistics_path.parent.mkdir(parents=True, exist_ok=True)
if statistics_path.exists():
document = json.loads(statistics_path.read_text(encoding="utf-8"))
else:
document = {"benchmarks": []}
benchmark = _get_or_add_record(
document.setdefault("benchmarks", []),
"name",
benchmark_name,
{"statistics": [], "generators": []},
)
benchmark.setdefault("statistics", [])
generator = _get_or_add_record(
benchmark.setdefault("generators", []),
"name",
generator_name,
{"statistics": [], "datasets": []},
)
generator.setdefault("statistics", [])
dataset = _get_or_add_record(
generator.setdefault("datasets", []),
"name",
dataset_name,
{
"file": dataset_file,
"freshness": dataset_freshness,
"statistics": [],
},
)
dataset["file"] = dataset_file
dataset["freshness"] = dataset_freshness
dataset["statistics"] = sorted({*dataset.get("statistics", []), *tags})
document["benchmarks"] = sorted(
document.get("benchmarks", []),
key=lambda record: record["name"],
)
for record in document["benchmarks"]:
record["generators"] = sorted(
record.get("generators", []),
key=lambda generator: generator["name"],
)
for generator in record["generators"]:
generator["datasets"] = sorted(
generator.get("datasets", []),
key=lambda dataset: dataset["name"],
)
statistics_path.write_text(
json.dumps(document, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
logging.getLogger("saps.work").info(
"traced %s.%s.%s: %s",
benchmark_name,
generator_name,
dataset_name,
", ".join(tags),
)
class Metadata(ABC):
@property
@abstractmethod
def metadata(self) -> dict[str, Any]: ...
class Tagged(Metadata):
@property
@abstractmethod
def name(self) -> str: ...
@property
@abstractmethod
def pretty_name(self) -> str: ...
@property
@abstractmethod
def description(self) -> str: ...
@property
@abstractmethod
def suites(self) -> list[str]: ...
@property
@abstractmethod
def concepts(self) -> str: ...
@property
def topics(self) -> list[str]:
return ccs_xml_to_tags(self.concepts)
@property
def file(self) -> str:
source_path = Path(inspect.getfile(self.__class__)).resolve()
try:
package_path = source_path.relative_to(Path(__file__).resolve().parent)
except ValueError:
return source_path.relative_to(repo_root()).as_posix()
return (Path("src/saps") / package_path).as_posix()
@property
def freshness(self) -> str:
source_path = Path(inspect.getfile(self.__class__)).resolve()
return source_freshness(self.__class__.__module__, source_path)
class Attributed(ABC):
@property
@abstractmethod
def authors(self) -> list[Contributor]: ...
@property
@abstractmethod
def references(self) -> list[Ref]: ...
@property
@abstractmethod
def ai_disclosure(self) -> str: ...
class Motivated(ABC):
@property
@abstractmethod
def motivation(self) -> str: ...
class Dataset(Tagged):
@property
def metadata(self) -> dict[str, Any]:
return {
"file": self.file,
"freshness": self.freshness,
"name": self.name,
"pretty_name": self.pretty_name,
"description": self.description,
"suites": self.suites,
"concepts": self.concepts,
"topics": self.topics,
}
@dataclass
class DataInstance:
inputs: list[Any]
meta: dict[str, Any]
ref_outputs: list[Any] | None = None
ref_meta: dict[str, Any] | None = None
TDataset = TypeVar("TDataset", bound=Dataset)
class Generator(Tagged, Attributed, Motivated, Generic[TDataset]):
@property
@abstractmethod
def datasets(self) -> list[TDataset]: ...
@property
def cacheable(self) -> bool:
return True
@property
def dataset_names(self) -> list[str]:
return [dataset.name for dataset in self.datasets]
@property
def backend(self):
if getattr(self, "_backend", None) is None:
backend_type = os.environ.get("REMOTE_STORAGE_BACKEND")
backend_bucket = os.environ.get("REMOTE_STORAGE_BUCKET")
self._backend = build_storage_backend(backend_type, backend_bucket)
return self._backend
def cached_generate(self, dataset: TDataset) -> DataInstance:
cacheable = self.cacheable
if not cacheable:
return self.generate(dataset)
return self.backend.retrieve_dataset(self, dataset)
@abstractmethod
def generate(self, dataset: TDataset) -> DataInstance: ...
@property
def metadata(self) -> dict[str, Any]:
return {
"file": self.file,
"freshness": self.freshness,
"name": self.name,
"pretty_name": self.pretty_name,
"description": self.description,
"suites": self.suites,
"concepts": self.concepts,
"topics": self.topics,
"authors": [str(a) for a in self.authors],
"references": [str(r) for r in self.references],
"ai_disclosure": self.ai_disclosure,
"motivation": self.motivation,
"datasets": [dataset.metadata for dataset in self.datasets],
}
@dataclass
class Param(Generic[TDataset]):
generator: Generator[TDataset]
dataset: TDataset
def __repr__(self):
return f"{self.generator.name}.{self.dataset.name}"
class Benchmark(Tagged, Attributed, Motivated):
@property
@abstractmethod
def generators(self) -> list[Generator[Any]]: ...
@abstractmethod
def benchmark(self, xp: Framework, data: list[Any], meta: Any) -> Any: ...
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if inspect.isabstract(cls):
return
try:
instance = cls()
except (TypeError, ValueError):
return
benchmark_source = inspect.getsource(cls.benchmark)
def _peakmem_run(self, param):
self.run(param)
setattr(cls, f"peakmem_{instance.name}", _peakmem_run)
getattr(cls, f"peakmem_{instance.name}").pretty_source = benchmark_source
def _time_run(self, param):
self.run(param)
setattr(cls, f"time_{instance.name}", _time_run)
getattr(cls, f"time_{instance.name}").pretty_source = benchmark_source
cls.setup.pretty_source = "\n".join(
inspect.getsource(generator.generate) for generator in instance.generators
)
@property
def params(self):
return [
Param(generator, dataset)
for generator in self.generators
for dataset in generator.datasets
]
param_names = ["dataset"]
def setup(self, param, *, use_cache: bool = True, xp: Framework | None = None):
if not logging.getLogger().handlers:
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s %(name)s: %(message)s",
)
log_path = os.environ.get("SAPS_LOG_PATH")
work_log = logging.getLogger("saps.work")
if log_path and not work_log.handlers:
Path(log_path).parent.mkdir(parents=True, exist_ok=True)
work_log.setLevel(logging.INFO)
work_log.propagate = False
work_log.addHandler(logging.FileHandler(log_path))
_apply_memory_limit()
if os.environ.get("SAPS_CACHE_DATASETS"):
if param.generator.cacheable and not param.generator.backend.upload_dataset(
param.generator, param.dataset
):
raise RuntimeError(
"Failed to cache dataset "
f"{param.generator.name}.{param.dataset.name}"
)
raise NotImplementedError("dataset cached")
problem = (
param.generator.cached_generate(param.dataset)
if use_cache
else param.generator.generate(param.dataset)
)
self._input = problem.inputs
self._meta = problem.meta
self._ref_outputs = problem.ref_outputs
self._ref_meta = problem.ref_meta
if xp is None:
try:
xp = load_framework()
except RuntimeError:
xp = None
if xp is not None:
self._xp = xp
def benchmark(data, meta):
return self.benchmark(xp, data, meta)
self._compiled_benchmark = xp.compile(benchmark)
def run(self, param):
if not hasattr(self, "_xp") or not hasattr(self, "_compiled_benchmark"):
raise RuntimeError(
"Benchmark.setup must bind a framework before run. Pass xp to "
"setup or set SAPS_FRAMEWORK."
)
xp = self._xp
if hasattr(xp, "reset_stats"):
xp.reset_stats()
input = [xp.from_binsparse(d) for d in self._input]
output = self._compiled_benchmark(input, self._meta)
output = [xp.to_binsparse(o) for o in output]
self._output = output
self._write_tagger_stats(param, xp)
def _write_tagger_stats(self, param, xp: Framework):
stats_dir = os.environ.get("SAPS_TAGGER_STATS_DIR")
statistics_path = os.environ.get("SAPS_STATISTICS_PATH")
if not hasattr(xp, "tags"):
return
tags = sorted(getattr(xp, "tags", []))
data = {
"benchmark_name": self.name,
"generator_name": param.generator.name,
"dataset_name": param.dataset.name,
"tags": tags,
}
if stats_dir:
path = Path(stats_dir)
path.mkdir(parents=True, exist_ok=True)
record_id = f"{self.name}.{param.generator.name}.{param.dataset.name}"
safe_id = "".join(
char if char.isalnum() or char in "._-" else "_" for char in record_id
)
output_path = path / f"{safe_id}.json"
output_path.write_text(
json.dumps(data, indent=2, default=str) + "\n",
encoding="utf-8",
)
if statistics_path:
_write_statistics_tags(
Path(statistics_path),
self.name,
param.generator.name,
param.dataset.name,
param.dataset.file,
param.dataset.freshness,
tags,
)
def teardown(self, param):
if hasattr(self, "_output"):
if (
os.environ.get("SAPS_CHECK_SUITE") == "1"
and "test" in param.dataset.suites
):
self.check(param)
del self._output
if hasattr(self, "_meta"):
del self._meta
if hasattr(self, "_ref_outputs"):
del self._ref_outputs
if hasattr(self, "_ref_meta"):
del self._ref_meta
if hasattr(self, "_input"):
del self._input
if hasattr(self, "_xp"):
del self._xp
if hasattr(self, "_compiled_benchmark"):
del self._compiled_benchmark
@abstractmethod
def check(self, param): ...
@property
def metadata(self) -> dict[str, Any]:
return {
"file": self.file,
"freshness": self.freshness,
"name": self.name,
"pretty_name": self.pretty_name,
"description": self.description,
"suites": self.suites,
"concepts": self.concepts,
"topics": self.topics,
"authors": [str(a) for a in self.authors],
"references": [str(r) for r in self.references],
"ai_disclosure": self.ai_disclosure,
"motivation": self.motivation,
"generators": [generator.metadata for generator in self.generators],
}
class ShellBenchmark(Benchmark, ABC):
@property
@abstractmethod
def generator(self) -> Generator[Any]: ...
@property
def name(self) -> str:
return f"{self.generator.name}_shell"
@property
def pretty_name(self) -> str:
return self.generator.pretty_name
@property
def description(self) -> str:
return ""
@property
def suites(self) -> list[str]:
return []
@property
def concepts(self) -> str:
return "<ccs2012></ccs2012>"
@property
def authors(self) -> list[Contributor]:
return []
@property
def references(self) -> list[Ref]:
return []
@property
def ai_disclosure(self) -> str:
return ""
@property
def motivation(self) -> str:
return ""
@property
def generators(self) -> list[Generator[Any]]:
return [self.generator]
def benchmark(self, xp: Framework, data: list[Any], meta: Any) -> Any:
return []
def check(self, param):
pass