forked from modular/modular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkbench_model.py
More file actions
1343 lines (1140 loc) · 44 KB
/
kbench_model.py
File metadata and controls
1343 lines (1140 loc) · 44 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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from __future__ import annotations
import copy
import csv
import functools
import glob
import logging
import math
import os
import shutil
import string
import subprocess
import sys
from dataclasses import dataclass, field
from enum import Enum, auto
from itertools import product
from multiprocessing import Pool
from pathlib import Path
from subprocess import list2cmdline
from time import time
from typing import Any
import numpy as np
import pandas as pd
import utils
import yaml
from rich.progress import (
Progress,
)
@dataclass
class ProcessOutput:
stdout: str | None = None
stderr: str | None = None
return_code: int = -1
path: Path | None = None
def log(self) -> None:
if self.stdout:
logging.debug("output " + self.stdout + utils.LINE)
if self.stderr:
logging.debug("error " + self.stderr + utils.LINE)
# TODO: remove and replace directly with subprocess.run
def _run_cmdline(
cmd: list[str],
dryrun: bool = False,
timeout: int | None = None,
env: dict[str, str] | None = None,
) -> ProcessOutput:
"""Execute a shell command with error handling."""
if env is None:
env = {}
try:
if dryrun:
print(list2cmdline(cmd))
return ProcessOutput(None, None, -1, None)
# Pass the current environment to subprocess, including MODULAR_MOJO_MAX_IMPORT_PATH
_env = os.environ.copy()
_env.update(dict(env))
if timeout is None:
output = subprocess.run(
cmd, check=False, capture_output=True, env=_env
)
else:
try:
output = subprocess.run(
cmd,
check=False,
capture_output=True,
env=_env,
timeout=timeout,
)
except Exception as e:
return ProcessOutput(None, str(e), os.EX_OSERR)
return ProcessOutput(
output.stdout.decode("utf-8"),
output.stderr.decode("utf-8"),
output.returncode,
)
except Exception as exc:
raise SystemExit(f"Unable to run command {list2cmdline(cmd)}") from exc
@dataclass(frozen=True)
class Lang:
name: str
extensions: list[str]
path: str
needs_compilation: bool
# TODO: enabled cached property option
# @functools.cached_property
# @staticmethod
def mojo_binary() -> str:
"""Find mojo binary in PATH."""
# Check for Bazel-provided mojo binary first
if mojo_path := os.environ.get("MODULAR_MOJO_MAX_DRIVER_PATH"):
if os.path.exists(mojo_path):
return mojo_path
else:
raise FileNotFoundError(
f"MODULAR_MOJO_MAX_DRIVER_PATH '{mojo_path}' does not exist."
)
# Fall back to searching in PATH
if mojo := shutil.which("mojo"):
return mojo
raise FileNotFoundError("Could not find the `mojo` binary.")
def python_binary() -> str:
"""Find python binary in PATH."""
return sys.executable
class SupportedLangs:
MOJO = Lang("mojo", [".mojo"], mojo_binary(), needs_compilation=True)
PYTHON = Lang("python", [".py"], python_binary(), needs_compilation=False)
@staticmethod
def which_executor(file: Path) -> Lang:
if file.suffix in SupportedLangs.PYTHON.extensions:
return SupportedLangs.PYTHON
elif file.suffix in SupportedLangs.MOJO.extensions:
return SupportedLangs.MOJO
else:
raise ValueError(f"Extension {file.suffix} is not supported!")
@dataclass
class Param:
name: str
value: Any
def define(self, lang: Lang) -> list[str]:
"""Generate command line arguments for this parameter."""
if lang == SupportedLangs.MOJO:
if self.name.startswith("$"):
var_name = self.name.removeprefix("$")
return [f"--{var_name}={self.value}"]
return ["-D", f"{self.name}={self.value}"]
if lang == SupportedLangs.PYTHON:
var_name = self.name.removeprefix("$")
return [f"--{var_name}={self.value}"]
return [""]
@dataclass
class ParamSpace:
name: str
value: Any
value_set: list[Any] = field(default_factory=list)
length: int = 0
def __post_init__(self) -> None:
"""Initialize value set from flattened values."""
# Try evaluating value as an arithmetic expression:
try:
if not isinstance(self.value, list):
self.value = [self.value]
self.value = [eval(x) for x in self.value]
except:
pass
# Note: as of python3.7+ the built-in dict is guaranteed to maintain insertion order.
self.value_set = list(dict.fromkeys(utils.flatten(self.value)))
self.value = None
self.length = len(self.value_set)
# Singleton build failed state
@dataclass(frozen=True)
class _BuildFailed:
pass
BuildFailed = _BuildFailed()
class KBENCH_MODE(Enum):
RUN = auto()
BUILD = auto()
BUILD_AND_RUN = auto()
class KbenchCache:
"""Cache for compiled binaries."""
def __init__(self, path: Path | str = "kbench_cache.pkl") -> None:
self.path = Path(path)
self.data: dict[str, str | _BuildFailed] = {}
self.is_active = False
def clear(self) -> None:
"""Remove cache file if it exists."""
logging.debug(f"Removing kbench-cache: {self.path}")
if self.path.exists():
subprocess.run(["rm", str(self.path)])
def load(self) -> None:
"""Load cache from file."""
if self.path.exists():
self.data = utils.load_pickle(self.path)
self.is_active = True
def dump(self) -> None:
"""Save cache to file."""
if self.is_active and self.data:
utils.store_pickle(self.path, self.data)
def query(self, key: str) -> str | _BuildFailed | None:
"""Get cached path for given key if it exists."""
if not self.is_active:
return None
obj_path = self.data.get(key)
if isinstance(obj_path, str):
return obj_path if Path(obj_path).exists() else None
return obj_path
def store(self, key: str, obj_path: Path) -> Path | None:
"""Store object in cache and return its new path."""
if not self.is_active:
return None
# TODO: revise the following conflict.
if key in self.data:
logging.debug(f"overwriting {key} already in obj-cache")
self.data[key] = str(obj_path)
return obj_path
def store_failed(self, key: str) -> None:
"""Store build failure result for the specified key."""
if not self.is_active:
return None
# TODO: revise the following conflict.
if key in self.data:
logging.debug(f"overwriting {key} already in obj-cache")
self.data[key] = BuildFailed
@dataclass(frozen=True)
class SpecInstance:
name: str
file: Path
executor: Lang
params: list[Param] = field(default_factory=list)
def __bool__(self) -> bool:
return bool(self.params)
@functools.cached_property
def _get_defines(self) -> list[str]:
defines = []
for param in self.params:
if not param.name.startswith("$"):
defines.append(param.define(self.executor))
return [item for sublist in defines for item in sublist]
@functools.cached_property
def _get_vars(self) -> list[str]:
vars = []
for param in self.params:
if param.name.startswith("$"):
vars.append(param.define(self.executor))
return [item for sublist in vars for item in sublist]
def build(
self,
*,
output_dir: Path,
build_opts: list[str] = [], # noqa: B006
dryrun: bool = False,
idx: int = -1,
enable_logging: bool = True,
) -> ProcessOutput:
"""Build the spec instance. Use set of compile-time
parameters as path of the compiled binary and store
the executable in 'output_dir'.
"""
bin_name = self.hash(with_variables=False)
bin_path = output_dir / Path(bin_name)
if enable_logging:
logging.info(f"building [{idx}][{bin_name}]")
logging.debug(
f"defines: {self._get_defines}"
+ "\n"
+ f"vars : {self._get_vars}"
)
executor = self.executor
if not executor.needs_compilation:
return ProcessOutput(return_code=os.EX_OK, path=self.file)
if executor == SupportedLangs.MOJO:
cmd = [executor.path]
cmd.extend(["build"])
if build_opts:
cmd.extend(build_opts)
cmd.extend(
[
*self._get_defines,
str(self.file),
"-o",
str(bin_path),
]
)
out = _run_cmdline(cmd, dryrun)
if out.return_code == os.EX_OK:
out.path = bin_path
else:
out.path = None
return out
return ProcessOutput()
def execute(
self,
binary_path: Path,
output_file: Path,
dryrun: bool = False,
exec_prefix: list[str] = [], # noqa: B006
exec_suffix: list[str] = [], # noqa: B006
env: dict[str, str] = {}, # noqa: B006
timeout_secs: int | None = None,
) -> ProcessOutput:
if self.executor == SupportedLangs.PYTHON:
exec_prefix = exec_prefix + [self.executor.path]
vars = self._get_defines + self._get_vars
else:
vars = self._get_vars
cmd = []
if exec_prefix:
logging.debug(f"exec-prefix: {exec_prefix}")
cmd.extend(exec_prefix)
cmd.extend([str(binary_path), *vars, "-o", str(output_file)])
if exec_suffix:
cmd.extend(exec_suffix)
logging.debug(f"exec-suffix: {exec_suffix}")
out = _run_cmdline(cmd, dryrun, timeout=timeout_secs, env=env)
return out
def to_obj(self) -> dict[str, Any]:
return {param.name: param.value for param in self.params}
@functools.cached_property
def file_stem(self) -> str:
return Path(self.file).with_suffix("").stem
def __str__(self) -> str:
tokens = [self.file_stem]
for param in self.params:
tokens.append(f"{param.name}={param.value}")
return "/".join(tokens)
def hash(self, with_variables: bool = True) -> str:
MAX_FILENAME_LEN = 224
tokens = [self.file_stem]
for param in self.params:
name = param.name
# just use compile-time parameters and ignore runtime variables.
if name.startswith("$") and not with_variables:
continue
name = name.replace("$", "")
tokens.append(f"{name}-{param.value}")
hash_str = "_".join(tokens)
if len(hash_str) < MAX_FILENAME_LEN:
return hash_str
else:
MAX_HASH_DIGITS = 8
hash_hex = hash(hash_str) % (10**MAX_HASH_DIGITS)
return f"{hash_str[: MAX_FILENAME_LEN - MAX_HASH_DIGITS]}{hash_hex}"
class GridSearchStrategy:
instances: list[SpecInstance] = field(default_factory=list)
def __init__(self, name, file, params) -> None: # noqa: ANN001
self.instances: list[SpecInstance] = []
# Expand the product of all the param:value-set's per each group of parameters
for cfg in params:
name_list = [p.name for p in cfg]
param_list = [p.value_set for p in cfg]
param_mesh = list(product(*param_list))
num_params = len(cfg)
for idx in range(len(param_mesh)):
s = SpecInstance(
name=name,
file=file,
params=[
Param(name=name_list[i], value=param_mesh[idx][i])
for i in range(num_params)
],
executor=SupportedLangs.which_executor(file),
)
self.instances.append(s)
def __iter__(self):
self.offset = 0
return self
def __next__(self):
# Stop condition
if self.offset == len(self.instances):
raise StopIteration
res = self.instances[self.offset]
self.offset += 1
return res
def __getitem__(self, i): # noqa: ANN001
return self.instances[i]
def __len__(self) -> int:
return len(self.instances)
def extend(self, other) -> None: # noqa: ANN001
self.instances.extend(other.instances)
@dataclass(repr=True)
class Spec:
name: str = ""
file: Path = Path("")
params: list[list[ParamSpace]] = field(default_factory=list)
mesh_idx: int = 0
mesh: list[SpecInstance] = field(default_factory=list)
rules: list[str] = field(default_factory=list)
@staticmethod
def load_yaml(file: Path) -> Spec:
"""
Loads the spec from a YAML file
Args:
file (Path): the yaml file Path
Returns:
Spec: the spec
"""
if not file.exists():
raise FileNotFoundError(
f'Unable to find the spec file at "{file}".'
)
try:
logging.info(f"Loading yaml [{file}]" + utils.LINE)
return Spec.loads(file.read_text())
except Exception as e:
raise ValueError(f"Could not load spec from {file}\nException: {e}") # noqa: B904
@staticmethod
def load_yaml_list(yaml_path_list: list[str]) -> Spec:
spec: Spec = None # type: ignore
for i, yaml_path in enumerate(yaml_path_list):
spec_ld = Spec.load_yaml(Path(yaml_path))
if i == 0:
spec = spec_ld
else:
spec.join(spec_ld)
return spec
@staticmethod
def parse_params(param_list: list[str]): # noqa: ANN205
"""
Parse the parameters as (key,value) dictionary.
The parameters can be defined as follows:
- `PARAM_NAME:PARAM_VALUE` (single value)
- `PARAM_NAME:[PARAM_VALUE0, PARAM_VALUE1]` (Pythonic list of values)
Args:
param_list (List): a list of param-value's as strings/
Returns:
Spec: Dictionary of with extra param names as keys and param values.
"""
d: dict[str, list] = {}
IFS = ":"
for p in param_list:
name = ""
val = ""
if IFS in p:
name, val = p.split(IFS)
if name not in d:
d[name] = []
# This supports list of params per one definition
# The following works for parsing a single-value, or a Pythonic list of values.
vals = val.split(",")
vals[0] = vals[0].strip("[")
vals[-1] = vals[-1].strip("]")
for i, v in enumerate(vals):
v = v.strip()
try:
vals[i] = eval(v)
except:
vals[i] = v
d[name].extend(vals)
return d
def extend_params(self, param_list: list[str]) -> None:
# Expand with CLI params
extra_params = self.parse_params(param_list)
# For all params in each config either, update the existing `value_set`
# with the new param value(s).
for cfg in self.params:
for k, v in extra_params.items():
found = False
for ps in cfg:
if ps.name == k:
ps.value_set.append(v)
ps.value_set = list(
dict.fromkeys(utils.flatten(ps.value_set))
)
found = True
break
if not found:
cfg.append(ParamSpace(k, v))
self.setup_mesh()
def extend_shape_params(self, param_set: list[Param]) -> None:
# TODO: check for collisions in param-names
extra_params: list[ParamSpace] = []
for ps in param_set:
extra_params.append(ParamSpace(ps.name, ps.value))
# add extended set of parameter to each bundle of parameters:
for p in self.params:
p.extend(extra_params)
if not self.params:
self.params = [extra_params]
self.setup_mesh()
def dump_yaml(self, out_path: Path) -> None:
assert self.mesh, "There are no instances to write to YAML!"
obj = {
"name": self.name,
"file": self.file,
"params": [s.to_obj() for s in self.mesh],
}
with open(out_path, "w") as f:
yaml.dump(obj, f, sort_keys=False)
logging.debug(f"dumped {len(self.mesh)} instances to [{out_path}]")
@staticmethod
def loads(yaml_str: str) -> Spec:
"""
Deserializes a Spec object from the given yaml string.
Args:
yaml_str (str): the yaml string representation of the model manifest
Returns:
Spec: a Spec loaded from the given yaml string
"""
obj = yaml.safe_load(yaml_str)
if "name" not in obj:
logging.warning("Field [name] is not set in YAML")
if "file" not in obj:
logging.warning("Field [file] is not set in YAML")
params: list[list[ParamSpace]] = []
if "params" in obj:
for cfg in obj["params"]:
e: list[ParamSpace] = []
for k, v in cfg.items():
if k == "metadata":
continue
e.append(ParamSpace(name=k, value=v))
params.append(e)
return Spec(
name=obj.get("name", ""),
file=obj.get("file", ""),
params=params,
rules=obj.get("rules", []),
)
def __len__(self) -> int:
return len(self.mesh)
def __post_init__(self):
# checking if the file source path is valid
file_abs_path = Path(
string.Template(str(self.file)).substitute(os.environ)
).absolute()
assert file_abs_path.exists(), (
f"error: '{file_abs_path}' does not exist."
)
self.file = file_abs_path
# setup mesh
if self.params:
self.setup_mesh()
else:
# default values for empty mesh
self.mesh = [
SpecInstance("", Path("./"), executor=SupportedLangs.MOJO)
]
def setup_mesh(self): # noqa: ANN201
"""
Setup a mesh (cartesian product) of all values for all params. For example,
if we have 2 set of params M=[64,256] and N=[A,B,C], the mesh will include
to the following values:
M=[64,256] x N=[A,B,C]
======================
idx : values
0 : [64,A]
1 : [64,B]
2 : [64,C]
3 : [256,A]
4 : [256,B]
5 : [256,C]
At the end, append the configs with fixed parameters, if any exists in YAML.
Return the total size of mesh.
"""
grid_mesh = list(GridSearchStrategy(self.name, self.file, self.params))
self.mesh = self.apply_rules(grid_mesh, self.rules)
return len(self.mesh)
def join(self, other: Spec) -> None:
assert self.name == other.name
assert self.file == other.file
assert len(other.mesh) > 0
self.mesh_idx = 0
self.params.extend(other.params)
self.mesh.extend(other.mesh)
@staticmethod
def apply_rules(
mesh: list[SpecInstance], rules: list[str]
) -> list[SpecInstance]:
new_mesh: list[SpecInstance] = []
if not rules:
return mesh
def remove_dlr(s: str) -> str:
return s.replace("$", "")
for s in mesh:
valid = True
for r in rules:
# TODO: revise handling of $ in string.
locals = {remove_dlr(p.name): p.value for p in s.params}
r = remove_dlr(r)
try:
e = eval(r, {}, locals)
# the following exception is required in case a parameter
# is present in rule and missing from spec-instance combination.
except NameError:
e = True
valid = valid & e
if not valid:
break
if valid:
new_mesh.append(s)
return new_mesh
def filter(self, filter_list: list[str]) -> None:
filters: dict[str, list] = {}
for f in filter_list:
if "=" in f:
name, val = f.split("=")
elif ":" in f:
name, val = f.split(":")
if name not in filters:
filters[name] = []
filters[name].append(val)
filtered_insts: list[SpecInstance] = []
num_filters = len(filter_list)
# Count the number of valid filters in each instance.
# If the count==num_filters then add the instance to the result.
valid_cnt = np.zeros(len(self.mesh), dtype=np.int32)
for k_filter, v_filter in filters.items():
for i, s in enumerate(self.mesh):
for p in s.params:
if p.name == k_filter and str(p.value) in v_filter:
valid_cnt[i] += 1
for i, idx in enumerate(valid_cnt):
if idx == num_filters:
filtered_insts.append(self.mesh[i])
self.mesh = filtered_insts[:]
self.mesh_idx = 0
def __iter__(self):
self.iter_offset = 0
return self
def __next__(self) -> SpecInstance:
assert self.mesh is not None, (
"Should call self.init_mesh after loading or in postinit."
)
# Stop condition
if self.iter_offset == len(self.mesh):
raise StopIteration
# Retrieve and update self.mesh_idx
idx = self.iter_offset
self.iter_offset += 1
return self.mesh[idx]
def __repr__(self) -> str:
rs = [f"[{i}] {str(s)}" for i, s in enumerate(self.mesh)]
rs += [utils.LINE]
rs += [f"Num Instances: {len(self.mesh)}"]
rs += [utils.LINE]
return "\n".join(rs)
@dataclass
class BuildItem:
"""
To store all necessary details for building a spec item (instance).
Args:
idx: unique index of item in the list of scheduler items
spec_instance: the parameter set used as the basis of build
output_dir: output directory specific for this build item
dryrun: set to True to enable dryrun
output_path: path to output file
bin_path: path to executable binary
build_output: output message for build
build_elapsed_time: elapsed time for build
exec_output: output message for exec
exec_benchmark_time: measured time for executing the entire benchmark
"""
idx: int
spec_instance: SpecInstance
output_dir: Path
build_opts: list
dryrun: bool = False
output_path: Path = Path()
bin_path: Path = Path()
build_output: ProcessOutput = field(default_factory=ProcessOutput)
build_elapsed_time: float = 0
exec_output: ProcessOutput = field(default_factory=ProcessOutput)
exec_benchmark_time: float = 0
def _get_similar_files(path: Path) -> list[Path]:
"""Returns a list of files that belong to the same benchmark but are
created by different processes, e.g. due to using mpirun
"""
dir_name = os.path.dirname(path)
stem = path.stem
suffix = path.suffix
pattern = os.path.join(dir_name, f"{stem}*{suffix}")
return [Path(p) for p in sorted(glob.glob(pattern))]
class Scheduler:
"""
Kbench singleton scheduler class to coordinate building and running all items in spec.
Args:
num_cpu: number of cpu's (cores) used for building items
num_gpu: number of gpu's used for executing items
build_items: list of spec items to build (BuildItem's)
obj_cache: kbench obj-cache
output_dir: parent output directory for all results
num_specs: total number of spec items added to scheduler (to build+run)
"""
num_cpu: int
num_gpu: int
build_items: list[BuildItem]
obj_cache: KbenchCache
run_only: bool
output_suffix: str
output_dir: Path
num_specs: int
num_unique_build_items: int = 0
CHUNK_SIZE: int = 1
EXEC_STRIDE: int = 100
def __init__(
self,
num_cpu: int,
num_gpu: int,
obj_cache: KbenchCache,
run_only: bool,
spec_list: list[SpecInstance],
output_dir: Path,
build_opts: list[str],
dryrun: bool,
output_suffix: str = "output.csv",
progress: Progress = Progress(),
) -> None:
self.num_cpu = num_cpu
self.num_gpu = num_gpu
if not (0 < num_gpu <= num_cpu):
raise ValueError(
"num_gpu must be greater than 0 and less than or equal to num_cpu."
)
self.obj_cache = obj_cache
self.num_specs = len(spec_list)
output_dir_list = [
Path(f"{output_dir}/out_{i}") for i in range(self.num_specs)
]
self.output_suffix = output_suffix
self.output_dir = output_dir
self.run_only = run_only
self.build_items = [
BuildItem(
idx=i,
spec_instance=spec_list[i],
output_dir=output_dir_list[i],
build_opts=build_opts,
dryrun=dryrun,
output_path=output_dir_list[i] / output_suffix,
)
for i in range(self.num_specs)
]
self.setup_build_pool()
self.mk_output_dirs()
self.progress = progress
@staticmethod
def kbench_mkdir(args: tuple[Path, str, bool]) -> Path:
"""Run the following command:
`mkdir -p {output_dir}`
"""
output_dir, output_suffix, run_only = args
path_exists: bool = os.path.exists(output_dir) and os.path.isdir(
output_dir
)
if not run_only:
if path_exists:
logging.warning(
f"Following output dir already exists and will be overwritten!\n[{str(output_dir)}]\n"
)
# Check for existing output files and remove them (if any):
existing_csv = _get_similar_files(output_dir / output_suffix)
for f in existing_csv:
os.remove(f)
os.makedirs(output_dir, exist_ok=True)
else:
if not path_exists:
raise ValueError(
f"--run-only specified but output directory does not exist: {output_dir}"
)
return output_dir
def get_chunksize(self, num_elements: int) -> int:
elements_per_cpu = math.ceil(num_elements / self.num_cpu)
return min(elements_per_cpu, self.CHUNK_SIZE)
def mk_output_dirs(self) -> None:
"""
Make output directories for kbench results (one per spec-instance)
"""
output_dir_list = [
(b.output_dir, self.output_suffix, self.run_only)
for b in self.build_items
]
for r in self.build_pool.imap(
self.kbench_mkdir,
output_dir_list,
chunksize=self.CHUNK_SIZE,
):
logging.debug(f"mkdir [{r}]")
logging.debug(
"Created directories for all instances in spec." + utils.LINE
)
def schedule_unique_build_items(self) -> list[dict]:
# Stores items that need to be build (i.e. not in cache)
unique_build_items: dict[str, int] = {}
# Stores paths to real binaries that have been cached beforehand
unique_build_paths: dict[str, str] = {}
for b in self.build_items:
i = b.idx
s = b.spec_instance
bin_name = s.hash(with_variables=False)
logging.debug(f"schedule [{i}][{bin_name}]")
debug_msg = [
f"defines: {s._get_defines}",
f"vars : {s._get_vars}",
]
# first, check cache for build from previous rounds
bin_path = self.obj_cache.query(bin_name)
debug_msg += [f"In cache: {bool(bin_path)}"]
if isinstance(bin_path, str):
unique_build_paths[bin_name] = bin_path
elif bin_path is BuildFailed:
# This binary failed to build before and would just fail again.
# Skip it.
continue
else:
# Neither found in the cache, nor exists in the unique_build_items
if bin_name not in unique_build_items:
unique_build_items[bin_name] = i
debug_msg += [f"Added to schedule (ref_idx=[{i}])"]
else:
# Already in the unique_build_items list
idx = unique_build_items[bin_name]
debug_msg += [f"Currently in schedule (ref_idx=[{idx}])"]
logging.debug("\n".join(debug_msg) + utils.LINE)
return [unique_build_items, unique_build_paths]
@staticmethod
def _pool_build_wrapper(bi: BuildItem) -> BuildItem:
t_start_item = time()
bi.build_output = bi.spec_instance.build(
output_dir=bi.output_dir,
build_opts=bi.build_opts,
dryrun=bi.dryrun,
idx=bi.idx,
enable_logging=False,
)
build_elapsed_time = int((time() - t_start_item) * 1e3)
bi.build_elapsed_time = build_elapsed_time
return bi
def build_all(self) -> None:
"""
Build all unique items scheduled by the scheduler.
"""
unique_build_items_dict, unique_build_paths = (
self.schedule_unique_build_items()
)
self.num_unique_build_items = len(unique_build_items_dict)
if self.run_only and len(unique_build_items_dict) > 0:
logging.error("Run only but not all binaries are found")
raise ValueError(
f"--run-only specified but {len(unique_build_items_dict)} binaries not found in cache. "
"Please build first or remove --run-only flag."
)
unique_build_items = [
self.build_items[i] for i in list(unique_build_items_dict.values())
]
logging.info(
f"scheduled {len(unique_build_items)} unique build items out of {self.num_specs}"
+ utils.LINE
)
if unique_build_items:
obj_cache = self.obj_cache
build_progress = self.progress.add_task(
"build",