Repository navigation
Expand file tree
/
Copy pathrunbms.py
More file actions
578 lines (521 loc) · 19.7 KB
/
Copy pathrunbms.py
File metadata and controls
578 lines (521 loc) · 19.7 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
import logging
import math
import os
import random
import socket
import subprocess
import sys
import tempfile
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
)
import yaml
from running.benchmark import Benchmark, SubprocessrExit
from running.command.fillin import fillin
from running.config import Configuration
from running.runtime import Runtime
from running.suite import BenchmarkSuite, is_dry_run
from running.util import (
config_index_to_chr,
config_str_encode,
detect_rogue_processes,
dont_emit_heapsize_modifier,
get_logged_in_users,
parse_config_str,
system,
)
if TYPE_CHECKING:
from running.plugin.runbms import RunbmsPlugin
from running.__version__ import __VERSION__
configuration: Configuration
minheap_multiplier: float
remote_host: str | None
skip_oom: int | None
skip_timeout: int | None
skip_log_compression: bool = False
skip_env_dump: bool = False
randomize_configs: bool = False
plugins: dict[str, Any]
resume: str | None
exit_on_failure_code: int | None = None
def setup_parser(subparsers):
f = subparsers.add_parser("runbms")
f.set_defaults(which="runbms")
f.add_argument("LOG_DIR", type=Path)
f.add_argument("CONFIG", type=Path)
f.add_argument("N", type=int, nargs="?")
f.add_argument("n", type=int, nargs="*")
f.add_argument("-i", "--invocations", type=int)
f.add_argument("-s", "--slice", type=str)
f.add_argument("-p", "--id-prefix")
f.add_argument("-m", "--minheap-multiplier", type=float)
f.add_argument("--skip-oom", type=int)
f.add_argument("--skip-timeout", type=int)
f.add_argument("--resume", type=str)
f.add_argument("--workdir", type=Path)
f.add_argument(
"--skip-log-compression", action="store_true", help="Skip compressing log files"
)
f.add_argument(
"--skip-env-dump",
action="store_true",
help="Skip dumping all environment variables into the log",
)
f.add_argument(
"--exit-on-failure",
nargs="?",
const=1,
type=int,
metavar="CODE",
help="Exit with specified code (default: 1) if any configuration fails",
)
f.add_argument(
"--randomize-configs",
action="store_true",
help="Randomize the order of configs for each benchmark run",
)
def getid() -> str:
host = socket.gethostname()
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d-%a-%H%M%S")
return f"{host}-{timestamp}"
def spread(spread_factor: int, N: int, n: int) -> float:
"""Spread the numbers
For example, when we have N = 8, n = 0, 1, ..., 7, N,
we can have fractions of form n / N with equal distances between them:
0/8, 1/8, 2/8, ..., 7/8, 8/8
Sometimes it's desirable to transform such sequence with finer steppings
at the start than at the end.
The idea is that when the values are small, even small changes can greatly
affect the behaviour of a system (such as the heap sizes of GC), so we want
to explore smaller values at a finer granularity.
For each n, we define
n' = n + spread_factor / (N - 1) * (1 + 2 + ... + n-2 + n-1)
For a consecutive pair (n-1, n), we can see that they are additionally
(n-1) / (N-1) * spread_factor apart.
For a special case when n = N, we have N' = N + N/2 * spread_factor,
and (N'-1, N') is spread_factor apart.
Let's concretely use spread_factor = 1 as as example.
Let N and n be the same.
So we have spread_factor / (N - 1) = 1/7
n = 0, n' = 0,
n = 1, n' = 1.
n = 2, n' = 2 + 1/7
n = 3, n' = 3 + 1/7 + 2/7 = 3 + 3/7
...
n = 7, n' = 7 + 1/7 + 2/7 + ... + 6/7 = 7 + 21/7 = 10
n = 8, n' = 8 + 1/7 + 2/7 + ... + 7/7 = 8 + 28/7 = 12
Parameters
----------
N : int
Denominator
spread_factor : int
How much coarser is the spacing at the end relative to start
spread_factor = 0 doesn't change the sequence at all
n: int
Nominator
"""
sum_1_n_minus_1 = (n * n - n) / 2
return n + spread_factor / (N - 1) * sum_1_n_minus_1
def hfac_str(hfac: float) -> str:
return str(int(hfac * 1000))
def get_heapsize(hfac: float, minheap: int) -> int:
return round(minheap * hfac * minheap_multiplier)
def get_hfacs(
heap_range: int, spread_factor: int, N: int, ns: list[int]
) -> list[float]:
start = 1.0
end = float(heap_range)
divisor = spread(spread_factor, N, N) / (end - start)
return [spread(spread_factor, N, n) / divisor + start for n in ns]
def run_benchmark_with_config(
c: str, b: Benchmark, runbms_dir: Path, size: int | None, fd: BinaryIO | None
) -> tuple[bytes, SubprocessrExit]:
runtime, mods = parse_config_str(configuration, c)
mod_b = b.attach_modifiers(mods)
mod_b = mod_b.attach_modifiers(b.get_runtime_specific_modifiers(runtime))
if size is not None:
mod_b = mod_b.attach_modifiers(runtime.get_heapsize_modifiers(size))
if fd:
prologue = get_log_prologue(runtime, mod_b)
fd.write(prologue.encode("ascii"))
output, companion_out, exit_status = mod_b.run(runtime, cwd=runbms_dir)
if fd:
fd.write(output)
if companion_out:
fd.write(b"*****\n")
fd.write(companion_out)
if fd:
epilogue = get_log_epilogue(runtime, mod_b)
fd.write(epilogue.encode("ascii"))
return output, exit_status
def get_filename_no_ext(
bm: Benchmark, hfac: float | None, size: int | None, config: str
) -> str:
# If we have / in benchmark names, replace with -.
safe_bm_name = bm.name.replace("/", "-")
return "{}.{}.{}.{}.{}".format(
safe_bm_name,
# plotty uses "^(\w+)\.(\d+)\.(\d+)\.([a-zA-Z0-9_\-\.\:\,]+)\.log\.gz$"
# to match filenames
hfac_str(hfac) if hfac is not None else "0",
size if size is not None else "0",
config_str_encode(config),
bm.suite_name,
)
def get_filename(
bm: Benchmark, hfac: float | None, size: int | None, config: str
) -> str:
return get_filename_no_ext(bm, hfac, size, config) + ".log"
def get_filename_completed(
bm: Benchmark, hfac: float | None, size: int | None, config: str
) -> str:
return f"{get_filename(bm, hfac, size, config)}.gz"
def get_log_epilogue(runtime: Runtime, bm: Benchmark) -> str:
return ""
def hz_to_ghz(hzstr: str) -> str:
return f"{int(hzstr) / 1000 / 1000:.2f} GHz"
def get_log_prologue(runtime: Runtime, bm: Benchmark) -> str:
output = "\n-----\n"
output += "mkdir -p PLOTTY_WORKAROUND; timedrun; "
output += bm.to_string(runtime)
output += "\n"
output += f"running-ng v{__VERSION__}\n"
output += system("date") + "\n"
output += system("w") + "\n"
output += system("vmstat 1 2") + "\n"
output += system("top -bcn 1 -w512 |head -n 12") + "\n"
if not skip_env_dump:
output += "Environment variables: \n"
for k, v in sorted(os.environ.items()):
output += f"\t{k}={v}\n"
output += "OS: "
output += system("uname -a")
output += "CPU: "
output += system("cat /proc/cpuinfo | grep 'model name' | head -1")
output += "number of cores: "
cores = system("cat /proc/cpuinfo | grep MHz | wc -l")
output += cores
has_cpufreq = Path("/sys/devices/system/cpu/cpu0/cpufreq").is_dir()
if has_cpufreq:
for i in range(0, int(cores)):
output += f"Frequency of cpu {i}: "
output += hz_to_ghz(
system(f"cat /sys/devices/system/cpu/cpu{i}/cpufreq/scaling_cur_freq")
)
output += "\n"
output += f"Governor of cpu {i}: "
output += system(
f"cat /sys/devices/system/cpu/cpu{i}/cpufreq/scaling_governor"
)
output += f"Scaling_min_freq of cpu {i}: "
output += hz_to_ghz(
system(f"cat /sys/devices/system/cpu/cpu{i}/cpufreq/scaling_min_freq")
)
output += "\n"
return output
def run_one_benchmark(
invocations: int,
suite: BenchmarkSuite,
bm: Benchmark,
hfac: float | None,
configs: list[str],
runbms_dir: Path,
log_dir: Path,
):
p: RunbmsPlugin
bm_name = bm.name
print(bm_name, end=" ")
size: int | None # heap size measured in MB
if hfac is not None:
print(hfac_str(hfac), end=" ")
size = get_heapsize(hfac, suite.get_minheap(bm))
print(size, end=" ")
else:
size = None
for p in plugins.values():
p.start_benchmark(hfac, size, bm)
oomed_count: defaultdict[str, int]
oomed_count = defaultdict(int)
timeout_count: defaultdict[str, int]
timeout_count = defaultdict(int)
logged_in_users: set[str]
logged_in_users = get_logged_in_users()
if len(logged_in_users) > 1:
logging.warning(
"More than one user logged in: {}".format(" ".join(logged_in_users))
)
# Check for rogue processes with high CPU usage
top_output = system("top -bcn 1 -w512 |head -n 12")
rogue_processes = detect_rogue_processes(top_output)
for pid, user, cpu_percent, command in rogue_processes:
logging.warning(
f"High CPU usage process detected: {command}"
f" (PID: {pid}, User: {user})"
f" using {cpu_percent:.1f}% CPU"
)
ever_ran = [False] * len(configs)
for i in range(0, invocations):
for p in plugins.values():
p.start_invocation(hfac, size, bm, i)
print(i, end="", flush=True)
# Create order for configs - randomized if flag is set, otherwise sequential
config_indices = list(range(len(configs)))
if randomize_configs:
random.shuffle(config_indices)
for j in config_indices:
c = configs[j]
config_passed = False
for p in plugins.values():
p.start_config(hfac, size, bm, i, c, j)
if skip_oom is not None and oomed_count[c] >= skip_oom:
print(".", end="", flush=True)
if exit_on_failure_code is not None:
sys.exit(exit_on_failure_code)
continue
if skip_timeout is not None and timeout_count[c] >= skip_timeout:
print(".", end="", flush=True)
if exit_on_failure_code is not None:
sys.exit(exit_on_failure_code)
continue
if resume:
log_filename_completed = get_filename_completed(bm, hfac, size, c)
if (log_dir / log_filename_completed).exists():
print(config_index_to_chr(j), end="", flush=True)
continue
log_filename = get_filename(bm, hfac, size, c)
logging.debug(f"Running with log filename {log_filename}")
runtime, _ = parse_config_str(configuration, c)
if is_dry_run():
output, exit_status = run_benchmark_with_config(
c, bm, runbms_dir, size, None
)
assert exit_status is SubprocessrExit.Dryrun
else:
fd: BinaryIO
with (log_dir / log_filename).open("ab") as fd:
output, exit_status = run_benchmark_with_config(
c, bm, runbms_dir, size, fd
)
ever_ran[j] = True
if runtime.is_oom(output):
oomed_count[c] += 1
if exit_status is SubprocessrExit.Timeout:
timeout_count[c] += 1
print(".", end="", flush=True)
if exit_on_failure_code is not None:
sys.exit(exit_on_failure_code)
elif exit_status is SubprocessrExit.Error:
print(".", end="", flush=True)
if exit_on_failure_code is not None:
sys.exit(exit_on_failure_code)
elif exit_status is SubprocessrExit.Normal:
if suite.is_passed(output):
config_passed = True
print(config_index_to_chr(j), end="", flush=True)
else:
print(".", end="", flush=True)
if exit_on_failure_code is not None:
sys.exit(exit_on_failure_code)
elif exit_status is SubprocessrExit.Dryrun:
print(".", end="", flush=True)
else:
raise ValueError("Not a valid SubprocessrExit value")
for p in plugins.values():
p.end_config(hfac, size, bm, i, c, j, config_passed)
for p in plugins.values():
p.end_invocation(hfac, size, bm, i)
for p in plugins.values():
p.end_benchmark(hfac, size, bm)
for j, c in enumerate(configs):
log_filename = get_filename(bm, hfac, size, c)
# Check that this is not a dry-run and we have actually executed this
# config for a particular benchmark/hfac (method parameters)
if not is_dry_run() and ever_ran[j]:
if not skip_log_compression:
subprocess.check_call(["gzip", log_dir / log_filename])
print()
def run_one_hfac(
invocations: int,
hfac: float | None,
suites: dict[str, BenchmarkSuite],
benchmarks: dict[str, list[Benchmark]],
configs: list[str],
runbms_dir: Path,
log_dir: Path,
):
p: RunbmsPlugin
for p in plugins.values():
p.start_hfac(hfac)
for suite_name, bms in benchmarks.items():
suite = suites[suite_name]
for bm in bms:
run_one_benchmark(
invocations, suite, bm, hfac, configs, runbms_dir, log_dir
)
rsync(log_dir)
for p in plugins.values():
p.end_hfac(hfac)
def ensure_remote_dir(log_dir):
if not is_dry_run() and remote_host is not None:
log_dir = log_dir.resolve()
system(f"ssh {remote_host} mkdir -p {log_dir}")
def rsync(log_dir):
if not is_dry_run() and remote_host is not None:
log_dir = log_dir.resolve()
system(f"rsync -ae ssh {log_dir}/ {remote_host}:{log_dir}")
def run(args):
if args.get("which") != "runbms":
return False
with tempfile.TemporaryDirectory(prefix="runbms-") as runbms_dir:
logging.info(f"Temporary directory: {runbms_dir}")
if args.get("workdir"):
args.get("workdir").mkdir(parents=True, exist_ok=True)
runbms_dir = str(args.get("workdir").resolve())
# Processing command lines args
global resume
resume = args.get("resume")
if resume:
run_id = resume
else:
prefix = args.get("id_prefix")
run_id = getid()
if prefix:
run_id = f"{prefix}-{run_id}"
print(f"Run id: {run_id}")
log_dir = args.get("LOG_DIR") / run_id
if not is_dry_run():
log_dir.mkdir(parents=True, exist_ok=True)
with (log_dir / "runbms_args.yml").open("w") as fd:
yaml.dump(args, fd)
N = args.get("N")
ns = args.get("n")
slice = args.get("slice")
slice = [float(s) for s in slice.split(",")] if slice else []
global skip_oom
skip_oom = args.get("skip_oom")
global skip_timeout
skip_timeout = args.get("skip_timeout")
global skip_log_compression
skip_log_compression = args.get("skip_log_compression")
global skip_env_dump
skip_env_dump = args.get("skip_env_dump")
global exit_on_failure_code
exit_on_failure_code = args.get("exit_on_failure")
global randomize_configs
randomize_configs = args.get("randomize_configs")
# Load from configuration file
global configuration
configuration = Configuration.from_file(Path(os.getcwd()), args.get("CONFIG"))
# Save metadata
if not is_dry_run():
with (log_dir / "runbms.yml").open("w") as fd:
configuration.save_to_file(fd)
configuration.resolve_class()
# Read from configuration, override with command line arguments if
# needed
invocations = configuration.get("invocations")
if args.get("invocations"):
invocations = args.get("invocations")
global minheap_multiplier
minheap_multiplier = configuration.get("minheap_multiplier")
if args.get("minheap_multiplier"):
minheap_multiplier = args.get("minheap_multiplier")
heap_range = configuration.get("heap_range")
spread_factor = configuration.get("spread_factor")
suites = configuration.get("suites")
benchmarks = configuration.get("benchmarks")
if benchmarks is None:
benchmarks = {}
configs = configuration.get("configs")
global remote_host
remote_host = configuration.get("remote_host")
if not is_dry_run() and remote_host is not None:
ensure_remote_dir(log_dir)
global plugins
plugins = configuration.get("plugins")
if plugins is None:
plugins = {}
else:
from running.plugin.runbms import RunbmsPlugin
if type(plugins) is not dict:
raise TypeError("plugins must be a dictionary")
plugins = {k: RunbmsPlugin.from_config(k, v) for k, v in plugins.items()}
for p in plugins.values():
p.set_run_id(run_id)
p.set_runbms_dir(runbms_dir)
p.set_log_dir(log_dir)
configs_no_heapsize = [
c for c in configs if dont_emit_heapsize_modifier(configuration, c)
]
configs_with_heapsize = [
c for c in configs if not dont_emit_heapsize_modifier(configuration, c)
]
# Simple case
if not slice and N is None:
# run all configs without specifying heap size
run_one_hfac(
invocations,
None, # not specifying heap size
suites,
benchmarks,
configs,
Path(runbms_dir),
log_dir,
)
# early return
return True
# In all other cases, we will first run configs that don't want
# implicit heapsize modifiers
if configs_no_heapsize:
logging.info("Running all configs with NoImplicitHeapSizeModifier set")
run_one_hfac(
invocations,
None, # not specifying heap size
suites,
benchmarks,
configs_no_heapsize,
Path(runbms_dir),
log_dir,
)
# Helper function for running benchmarks using multiple heap factors
def run_hfacs(hfacs):
logging.info(
"hfacs: {}".format(", ".join([hfac_str(hfac) for hfac in hfacs]))
)
for hfac in hfacs:
run_one_hfac(
invocations,
hfac,
suites,
benchmarks,
configs_with_heapsize,
Path(runbms_dir),
log_dir,
)
print()
# Helper function for using the heap factor spreading algorithm
def run_N_ns(N, ns):
hfacs = get_hfacs(heap_range, spread_factor, N, ns)
run_hfacs(hfacs)
if slice: # specified -s, we respect that first
if N is not None:
logging.warning(
"You specified both N={} and -s {}, N is ignored.".format(
N,
",".join([str(s) for s in slice]),
)
)
run_hfacs(slice)
else:
assert N is not None
if len(ns) == 0:
fillin(run_N_ns, round(math.log2(N)))
else:
run_N_ns(N, ns)
return True