-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrunbench.py
More file actions
1549 lines (1391 loc) · 56.6 KB
/
Copy pathrunbench.py
File metadata and controls
1549 lines (1391 loc) · 56.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
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
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import html
import json
import math
import os
import re
import shutil
import statistics
import subprocess
import sys
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Iterable, NamedTuple
def variant_key(*, engine: str, runtime: str, mode: str, label: str = "") -> str:
if label:
return f"{engine}#{label}:{runtime}:{mode}"
return f"{engine}:{runtime}:{mode}"
@dataclass(frozen=True)
class EngineVariant:
engine: str
runtime: str
mode: str
bin: str
label: str = ""
cli: str = ""
@property
def key(self) -> str:
return variant_key(engine=self.engine, runtime=self.runtime, mode=self.mode, label=self.label)
@dataclass
class RunResult:
engine: str
runtime: str
mode: str
label: str
wasm: str
bench_kind: str
bench_tags: list[str]
ok: bool
rc: int
wall_ms: float
internal_ms: float | None
metric: str
metric_kind: str
metric_ms: float | None
stdout_tail: str
stderr_tail: str
TIME_PATTERNS: list[re.Pattern[str]] = [
re.compile(r"^Elapsed time:\s*(?P<ms>\d+(?:\.\d+)?)\s*ms\b", re.MULTILINE | re.IGNORECASE),
re.compile(r"^Elapsed:\s*(?P<ms>\d+(?:\.\d+)?)\s*ms\b", re.MULTILINE | re.IGNORECASE),
re.compile(r"^Time:\s*(?P<ms>\d+(?:\.\d+)?)\s*ms\b", re.MULTILINE),
re.compile(r"^time:\s*(?P<ms>\d+(?:\.\d+)?)\s*ms\b", re.MULTILINE | re.IGNORECASE),
]
def extract_internal_ms(out: str) -> float | None:
last: float | None = None
for pat in TIME_PATTERNS:
for m in pat.finditer(out):
try:
last = float(m.group("ms"))
except Exception:
continue
if last is not None:
return last
return None
def tail(s: str, max_chars: int = 800) -> str:
s = s.strip("\n")
if len(s) <= max_chars:
return s
return s[-max_chars:]
def decode(b: bytes | str | None) -> str:
if b is None:
return ""
if isinstance(b, str):
return b
return b.decode("utf-8", errors="replace")
class CmdOut(NamedTuple):
rc: int
wall_ms: float
out: str
err: str
def run_one(cmd: list[str], cwd: Path, timeout_s: float) -> CmdOut:
t0 = time.perf_counter()
try:
cp = subprocess.run(
cmd,
cwd=str(cwd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False,
timeout=timeout_s,
check=False,
)
wall_ms = (time.perf_counter() - t0) * 1000.0
return CmdOut(cp.returncode, wall_ms, decode(cp.stdout), decode(cp.stderr))
except subprocess.TimeoutExpired as e:
wall_ms = (time.perf_counter() - t0) * 1000.0
return CmdOut(124, wall_ms, decode(e.stdout), decode(e.stderr))
def geomean(values: Iterable[float]) -> float:
vals = [v for v in values if v > 0.0 and math.isfinite(v)]
if not vals:
return float("nan")
return math.exp(sum(math.log(v) for v in vals) / len(vals))
def which_or(path: str | None, default: str) -> str | None:
if path:
return path
return shutil.which(default)
def parse_labeled_bin(spec: str) -> tuple[str, str]:
spec = spec.strip()
if not spec:
raise SystemExit("empty --*-bin spec")
if "=" not in spec:
return ("", spec)
label, path = spec.split("=", 1)
label = label.strip()
path = path.strip()
if not label or not path:
raise SystemExit(f"invalid --*-bin spec (expected label=path): {spec!r}")
if ":" in label or "#" in label:
raise SystemExit(f"invalid label in --*-bin spec (must not contain ':' or '#'): {label!r}")
return (label, path)
def resolve_executable(path: str, *, engine: str) -> str:
p = os.path.expanduser(path.strip())
if not p:
raise SystemExit(f"{engine} binary path is empty")
# Treat anything that looks like a path as a path.
if os.path.sep in p or p.startswith("."):
if Path(p).exists():
return p
raise SystemExit(f"{engine} binary not found: {p}")
found = shutil.which(p)
if found:
return found
if Path(p).exists():
return p
raise SystemExit(f"{engine} binary not found in PATH: {p}")
def uniquify_bin_entries(engine: str, entries: list[tuple[str, str]]) -> list[tuple[str, str]]:
if not entries:
return entries
seen: set[str] = set()
for label, _ in entries:
if not label:
continue
if label in seen:
raise SystemExit(f"duplicate label for {engine}: {label!r}")
seen.add(label)
if len(entries) == 1:
return entries
out: list[tuple[str, str]] = []
empty_used = False
for idx, (label, path) in enumerate(entries):
if label:
out.append((label, path))
continue
if not empty_used:
empty_used = True
out.append(("", path))
continue
auto = str(idx + 1)
if auto in seen:
auto = f"auto{idx + 1}"
base = auto
n = 2
while auto in seen or not auto:
auto = f"{base}_{n}"
n += 1
seen.add(auto)
out.append((auto, path))
return out
def resolve_bin_entries(
*,
engine: str,
specs: list[str],
default_cmd: str | None = None,
default_path: str | None = None,
) -> list[tuple[str, str]]:
entries: list[tuple[str, str]] = []
if specs:
for spec in specs:
label, path = parse_labeled_bin(spec)
entries.append((label, resolve_executable(path, engine=engine)))
return uniquify_bin_entries(engine, entries)
if default_path:
p = os.path.expanduser(default_path)
if Path(p).exists():
return [("", p)]
if default_cmd:
found = shutil.which(default_cmd)
if found:
return [("", found)]
return []
def detect_wamr_cli_kind(bin_path: str, *, cwd: Path, timeout_s: float = 2.0) -> str:
"""
Detect whether an iwasm binary is the full CLI (supports --dir/args) or a minimal CLI.
Returns: "full" or "minimal"
"""
cp = run_one([bin_path, "-h"], cwd, timeout_s)
text = (cp.out + "\n" + cp.err).strip()
if "Usage: iwasm" in text:
return "full"
if "Required arguments:" in text:
return "minimal"
if "--dir=<dir>" in text or "--dir=" in text or "\n --dir" in text:
return "full"
# Conservative fallback: treat unknown output as minimal.
return "minimal"
def find_wasms(root: Path) -> list[Path]:
skip_parts = {".git", "__pycache__", ".venv", "logs", "cache"}
wasms: list[Path] = []
for p in root.rglob("*.wasm"):
if set(p.parts) & skip_parts:
continue
wasms.append(p)
return sorted(wasms)
def classify_bench(wasm_rel: str) -> tuple[str, list[str]]:
"""
Classify a benchmark into a primary "kind" plus optional tags.
Kinds are intended to match high-level performance characteristics:
- compute_dense
- memory_dense
- io_dense
- syscall_dense
- local_dense
- operand_stack_dense
- call_dense
- control_flow_dense
- unknown
"""
rel = wasm_rel.replace("\\", "/").lower()
name = Path(rel).name
tags: set[str] = set()
def ret(primary: str) -> tuple[str, list[str]]:
tags.add(primary)
return (primary, sorted(tags))
# Numeric flavor tags (orthogonal to primary kind).
if any(k in name for k in ("f32", "f64")):
tags.add("float_dense")
if any(k in name for k in ("i8", "u8", "i16", "u16", "i32", "i64", "u32", "u64")):
tags.add("int_dense")
# Generated WASI corpus under wasm/corpus/.
if rel.startswith("wasi/"):
tags.add("wasi")
tags.add("syscall_dense")
if "file_rw" in name or "small_io" in name:
tags.add("io_dense")
return ret("io_dense")
if "readv" in name or "writev" in name:
tags.add("io_dense")
return ret("io_dense")
if "pread" in name or "pwrite" in name:
tags.add("io_dense")
return ret("io_dense")
if "seek_read" in name:
tags.add("io_dense")
return ret("io_dense")
return ret("syscall_dense")
if rel.startswith("micro/"):
tags.add("micro")
if "global_dense" in name:
tags.add("compute_dense")
tags.add("global_dense")
return ret("compute_dense")
if "select_dense" in name:
tags.add("compute_dense")
tags.add("operand_stack_dense")
return ret("compute_dense")
if "local_dense" in name:
tags.add("compute_dense")
return ret("local_dense")
if "operand_stack_dense" in name:
tags.add("compute_dense")
return ret("operand_stack_dense")
if "call_direct" in name:
tags.add("compute_dense")
return ret("call_dense")
if "call_dense" in name:
tags.add("compute_dense")
return ret("call_dense")
if "call_indirect" in name or "indirect_call" in name:
tags.add("compute_dense")
return ret("call_dense")
if "br_table" in name:
tags.add("compute_dense")
return ret("control_flow_dense")
if "br_if" in name:
tags.add("compute_dense")
return ret("control_flow_dense")
if "control_flow_dense" in name:
tags.add("compute_dense")
return ret("control_flow_dense")
if "switch" in name:
tags.add("compute_dense")
return ret("control_flow_dense")
if "mem_sum" in name or "mem_fill" in name or "mem_copy" in name:
return ret("memory_dense")
if name.startswith("mem_") or "mem_" in name:
return ret("memory_dense")
if "pointer_chase" in name:
return ret("memory_dense")
if "random_access" in name:
return ret("memory_dense")
if "memory_grow" in name:
return ret("memory_dense")
if "malloc" in name or "alloc" in name:
return ret("memory_dense")
if "rle_" in name or name.startswith("rle"):
tags.add("control_flow_dense")
return ret("memory_dense")
if "utf8" in name:
tags.add("control_flow_dense")
return ret("control_flow_dense")
if "json" in name:
tags.add("control_flow_dense")
tags.add("memory_dense")
return ret("control_flow_dense")
if "quicksort" in name or "qsort" in name:
tags.add("control_flow_dense")
tags.add("memory_dense")
return ret("control_flow_dense")
if "varint" in name:
tags.add("control_flow_dense")
tags.add("memory_dense")
return ret("control_flow_dense")
tags.add("compute_dense")
return ret("compute_dense")
if rel.startswith("crypto/"):
tags.add("crypto")
tags.add("int_dense")
return ret("compute_dense")
if rel.startswith("science/"):
tags.add("science")
tags.add("compute_dense")
if "pagerank" in name:
tags.add("graph")
tags.add("iterative_solver")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("memory_dense", sorted(tags))
if "graph_sssp" in name:
tags.add("graph")
tags.add("control_flow_dense")
tags.add("memory_dense")
return ("control_flow_dense", sorted(tags))
if "spmv" in name:
tags.add("sparse_linear_algebra")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "value_iteration" in name:
tags.add("dynamic_programming")
tags.add("iterative_solver")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("memory_dense", sorted(tags))
if "kalman" in name:
tags.add("estimation")
tags.add("iterative_solver")
return ("compute_dense", sorted(tags))
if "ising" in name:
tags.add("physics")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "boids" in name:
tags.add("simulation")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "power_flow" in name:
tags.add("power_system")
tags.add("iterative_solver")
tags.add("circuit")
return ("compute_dense", sorted(tags))
if "lqr_control" in name or "control_" in name:
tags.add("control_system")
tags.add("iterative_solver")
return ("compute_dense", sorted(tags))
if "ik_jacobian" in name:
tags.add("robotics")
tags.add("control_system")
return ("compute_dense", sorted(tags))
if "pose_graph" in name:
tags.add("graph")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "multigrid" in name:
tags.add("iterative_solver")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "circuit" in name:
tags.add("circuit")
tags.add("iterative_solver")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "truss" in name:
tags.add("physics")
tags.add("iterative_solver")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "poisson" in name or "jacobi" in name or "heat3d" in name:
tags.add("iterative_solver")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "reaction_diffusion" in name:
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "lbm" in name:
tags.add("fluid")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "fdtd" in name:
tags.add("electromagnetics")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "shallow_water" in name:
tags.add("fluid")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "particle_filter" in name:
tags.add("estimation")
tags.add("stochastic")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "mpc_boxqp" in name:
tags.add("control_system")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "dc_opf" in name:
tags.add("power_system")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "trajectory_sqp" in name:
tags.add("control_system")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "bundle_adjustment" in name:
tags.add("computer_vision")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "factor_graph" in name:
tags.add("graph")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "advection" in name:
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "finite_volume" in name or "burgers" in name:
tags.add("fluid")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "euler1d" in name or "riemann" in name:
tags.add("fluid")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "contact_dynamics" in name:
tags.add("physics")
tags.add("simulation")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "red_black_sor" in name:
tags.add("iterative_solver")
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "wave_" in name:
tags.add("pde")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "fir" in name:
tags.add("dsp")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "convolution" in name:
tags.add("dsp")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "biquad" in name or "iir" in name:
tags.add("dsp")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "viterbi" in name:
tags.add("dynamic_programming")
tags.add("control_flow_dense")
tags.add("memory_dense")
return ("control_flow_dense", sorted(tags))
if "smith_waterman" in name:
tags.add("dynamic_programming")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "floyd_warshall" in name:
tags.add("graph")
tags.add("dynamic_programming")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "bitonic_sort" in name:
tags.add("sorting")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "hopfield" in name:
tags.add("simulation")
tags.add("control_flow_dense")
tags.add("memory_dense")
return ("control_flow_dense", sorted(tags))
if "kaczmarz" in name:
tags.add("linear_algebra")
tags.add("iterative_solver")
return ("compute_dense", sorted(tags))
if "bicgstab" in name:
tags.add("linear_algebra")
tags.add("iterative_solver")
return ("compute_dense", sorted(tags))
if "gmres" in name:
tags.add("linear_algebra")
tags.add("iterative_solver")
return ("compute_dense", sorted(tags))
if "qubo_anneal" in name:
tags.add("combinatorial_optimization")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "maxcut_local_search" in name:
tags.add("graph")
tags.add("combinatorial_optimization")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "auction_assignment" in name:
tags.add("combinatorial_optimization")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "push_relabel" in name:
tags.add("graph")
tags.add("combinatorial_optimization")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "alpha_expansion" in name:
tags.add("graph")
tags.add("combinatorial_optimization")
tags.add("image_processing")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "bfs_frontier" in name:
tags.add("graph")
tags.add("graph_search")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "belief_propagation" in name:
tags.add("graph")
tags.add("probabilistic_inference")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "hmm_forward_backward" in name:
tags.add("probabilistic_inference")
tags.add("dynamic_programming")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "levenshtein" in name:
tags.add("dynamic_programming")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "knapsack" in name:
tags.add("dynamic_programming")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "binomial_option" in name:
tags.add("finance")
tags.add("dynamic_programming")
return ("compute_dense", sorted(tags))
if "game_of_life" in name:
tags.add("cellular_automata")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "lorenz" in name:
tags.add("ode")
return ("compute_dense", sorted(tags))
if "lotka_volterra" in name or "rk4_" in name:
tags.add("ode")
return ("compute_dense", sorted(tags))
if "newton_raphson" in name:
tags.add("optimization")
tags.add("root_finding")
return ("compute_dense", sorted(tags))
if "halley_root" in name:
tags.add("optimization")
tags.add("root_finding")
return ("compute_dense", sorted(tags))
if "monte_carlo" in name:
tags.add("stochastic")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "projected_gradient_qp" in name:
tags.add("optimization")
tags.add("linear_algebra")
return ("compute_dense", sorted(tags))
if "coordinate_descent_l1" in name:
tags.add("optimization")
tags.add("linear_algebra")
return ("compute_dense", sorted(tags))
if "admm_lasso" in name:
tags.add("optimization")
tags.add("linear_algebra")
return ("compute_dense", sorted(tags))
if "sinkhorn" in name:
tags.add("optimization")
tags.add("linear_algebra")
return ("compute_dense", sorted(tags))
if "primal_dual_tv" in name:
tags.add("optimization")
tags.add("image_processing")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "soft_kmeans" in name:
tags.add("machine_learning")
tags.add("optimization")
return ("compute_dense", sorted(tags))
if "mass_spring" in name:
tags.add("physics")
tags.add("simulation")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "thomas_solver" in name:
tags.add("linear_algebra")
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if "stochastic_vol" in name:
tags.add("finance")
tags.add("stochastic")
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
if "daxpy" in name:
tags.add("memory_dense")
return ("memory_dense", sorted(tags))
if any(k in name for k in ("mandelbrot", "sieve", "gcd")):
tags.add("control_flow_dense")
return ("control_flow_dense", sorted(tags))
return ("compute_dense", sorted(tags))
if rel.startswith("db/"):
tags.add("db")
tags.add("int_dense")
tags.add("memory_dense")
tags.add("control_flow_dense")
return ("memory_dense", sorted(tags))
if rel.startswith("vm/"):
tags.add("vm")
tags.add("int_dense")
tags.add("control_flow_dense")
tags.add("call_dense")
return ("control_flow_dense", sorted(tags))
# Legacy flat corpus (extreme few-variable microbenches).
if name.startswith(("call", "inline")) or "call_" in name or name.startswith("bench_call"):
return ret("call_dense")
if (
name.startswith(("branch", "br_table", "br_"))
or "branch" in name
or name.startswith("bench_branchy")
or "_br_" in name
or "br_ret" in name
):
return ret("control_flow_dense")
if name.startswith("mem_") or "mem_" in name or name.startswith("stack_spill"):
return ret("memory_dense")
if name.startswith(("blake", "sha", "siphash", "chacha")) or name in {"blake2s.wasm", "chacha20.wasm", "sha512.wasm", "sha512_constant.wasm", "siphash.wasm"}:
tags.add("crypto")
return ret("compute_dense")
if name.startswith(
(
"arith_",
"bench_compute_",
"bitops_",
"divrem_",
"deepstack",
"inloop_deepstack",
"stack_reduce",
"keepstack",
"local_",
"global_",
"inline_step",
"inline_empty",
"aabb",
)
):
if name.startswith("local_") or "local_" in name:
tags.add("compute_dense")
return ret("local_dense")
if name.startswith(("deepstack", "inloop_deepstack", "stack_reduce", "keepstack")):
tags.add("compute_dense")
return ret("operand_stack_dense")
return ret("compute_dense")
if name in {"coremark.wasm", "python.wasm"}:
tags.add("control_flow_dense")
tags.add("vm")
return ("control_flow_dense", sorted(tags))
return ret("unknown")
def wasm3_cmd(bin_path: str, wasm_rel: str, mode: str) -> list[str]:
cmd = [bin_path]
if mode == "full":
cmd.append("--compile")
cmd.append(wasm_rel)
return cmd
def uwvm2_cmd(bin_path: str, wasm_rel: str, runtime: str, mode: str) -> list[str]:
return [
bin_path,
"-Rcc",
runtime,
"-Rcm",
mode,
"-I1dir",
".",
".",
"--",
wasm_rel,
]
def wamr_cmd(bin_path: str, wasm_rel: str) -> list[str]:
raise AssertionError("call wamr_cmd_with_cli() instead")
def wamr_cmd_with_cli(bin_path: str, wasm_rel: str, cli: str) -> list[str]:
if cli == "minimal":
# Minimal WAMR iwasm CLI (product-mini variants) uses: -f <wasm> -d <dir>
return [bin_path, "-f", wasm_rel, "-d", "."]
# Full WAMR iwasm CLI (recommended): runtime options are not forwarded into guest argv.
return [bin_path, "--dir=.", wasm_rel]
def wasmtime_cmd(bin_path: str, wasm_rel: str) -> list[str]:
return [bin_path, "run", "--dir", ".", wasm_rel]
def wasmer_cmd(bin_path: str, wasm_rel: str) -> list[str]:
return [bin_path, "run", "--dir", ".", wasm_rel]
def wasmedge_cmd(bin_path: str, wasm_rel: str, runtime: str) -> list[str]:
# WasmEdge uses guest:host mapping; ".:." is safe (same either way).
cmd = [bin_path, "--dir", ".:.", wasm_rel]
if runtime == "jit":
return [bin_path, "--enable-jit", "--dir", ".:.", wasm_rel]
if runtime == "int":
return [bin_path, "--force-interpreter", "--dir", ".:.", wasm_rel]
raise ValueError(f"unsupported wasmedge runtime: {runtime}")
def wavm_cmd(bin_path: str, wasm_rel: str) -> list[str]:
# WAVM's WASI flags differ across builds; this is a best-effort default.
return [bin_path, "run", "--mount-root", ".", wasm_rel]
def supported_variants(
*,
engine: str,
bin_path: str,
label: str = "",
cli: str = "",
runtimes: list[str],
modes: list[str],
) -> list[EngineVariant]:
variants: list[EngineVariant] = []
# NOTE: be conservative. If we can't *control* a dimension, mark it unsupported.
if engine == "wasm3":
supp_r = {"int"}
supp_m = {"full", "lazy"}
elif engine == "uwvm2":
# The uwvm2 binary used in this repo only supports: -Rcc int -Rcm full.
# Be conservative and skip unsupported combinations.
supp_r = {"int"}
supp_m = {"full"}
elif engine == "wamr":
supp_r = {"int"}
supp_m = {"full"}
elif engine == "wasmtime":
supp_r = {"jit"}
# Mode semantics:
# - lazy: run the wasm directly (compilation happens on first run)
# - full: precompile (wasmtime compile) then run with --allow-precompiled
supp_m = {"full", "lazy"}
elif engine == "wasmer":
supp_r = {"jit"}
supp_m = {"full"}
elif engine == "wasmedge":
supp_r = {"int", "jit"}
supp_m = {"full"}
elif engine == "wavm":
supp_r = {"jit"}
supp_m = {"full"}
else:
raise ValueError(f"unknown engine: {engine}")
for r in runtimes:
if r not in supp_r:
continue
for m in modes:
if m not in supp_m:
continue
variants.append(EngineVariant(engine=engine, runtime=r, mode=m, bin=bin_path, label=label, cli=cli))
return variants
def build_cmd(variant: EngineVariant, wasm_rel: str) -> list[str]:
eng = variant.engine
if eng == "wasm3":
return wasm3_cmd(variant.bin, wasm_rel, variant.mode)
if eng == "uwvm2":
return uwvm2_cmd(variant.bin, wasm_rel, variant.runtime, variant.mode)
if eng == "wamr":
return wamr_cmd_with_cli(variant.bin, wasm_rel, variant.cli)
if eng == "wasmtime":
# "full" is handled specially (precompile+run) in the main loop.
# For "lazy", run the wasm directly.
if variant.mode == "lazy":
return wasmtime_cmd(variant.bin, wasm_rel)
return [variant.bin, "run", "--dir", ".", wasm_rel]
if eng == "wasmer":
return wasmer_cmd(variant.bin, wasm_rel)
if eng == "wasmedge":
return wasmedge_cmd(variant.bin, wasm_rel, variant.runtime)
if eng == "wavm":
return wavm_cmd(variant.bin, wasm_rel)
raise ValueError(f"unknown engine: {eng}")
def _metric_value(r: RunResult, metric: str) -> float | None:
if metric == "wall":
return r.wall_ms
if metric == "internal":
return r.internal_ms
if metric == "auto":
return r.internal_ms if r.internal_ms is not None else r.wall_ms
raise ValueError(f"unknown metric: {metric}")
def metric_kind_and_value(*, wall_ms: float, internal_ms: float | None, metric: str) -> tuple[str, float | None]:
if metric == "wall":
return ("wall", wall_ms)
if metric == "internal":
return ("internal", internal_ms)
if metric == "auto":
if internal_ms is not None:
return ("internal", internal_ms)
return ("wall", wall_ms)
raise ValueError(f"unknown metric: {metric}")
def summarize(results: list[RunResult], baseline_key: str, *, metric: str) -> dict[str, object]:
by_key: dict[str, list[RunResult]] = {}
for r in results:
key = variant_key(engine=r.engine, runtime=r.runtime, mode=r.mode, label=r.label)
by_key.setdefault(key, []).append(r)
# Compute per-config stats
stats: dict[str, dict[str, object]] = {}
for key, rs in sorted(by_key.items()):
vals: list[float] = []
ok_rc = 0
ok_metric = 0
for r in rs:
if not r.ok:
continue
ok_rc += 1
v = _metric_value(r, metric)
if v is None:
continue
if v > 0.0 and math.isfinite(v):
ok_metric += 1
vals.append(v)
stats[key] = {
"ok_rc": ok_rc,
"ok_metric": ok_metric,
"total": len(rs),
"ms_geomean": geomean(vals),
"ms_median": statistics.median(vals) if vals else float("nan"),
}
# Ratios vs baseline (pairwise intersection for fairness)
base_rs = [r for r in by_key.get(baseline_key, []) if r.ok]
base_vals: dict[str, float] = {}
for r in base_rs:
v = _metric_value(r, metric)
if v is None or not (v > 0.0 and math.isfinite(v)):
continue
base_vals[r.wasm] = v
ratios: dict[str, dict[str, object]] = {}
for key, rs in sorted(by_key.items()):
if key == baseline_key:
continue
cur_vals: dict[str, float] = {}
for r in rs:
if not r.ok:
continue
v = _metric_value(r, metric)
if v is None or not (v > 0.0 and math.isfinite(v)):
continue
cur_vals[r.wasm] = v
common = [w for w in base_vals.keys() if w in cur_vals]
pair: list[float] = []
for w in common:
a = cur_vals[w]
b = base_vals[w]
if a > 0.0 and b > 0.0 and math.isfinite(a) and math.isfinite(b):
pair.append(a / b)
ratios[key] = {
"common_ok": len(common),
"ratio_geomean": geomean(pair),
"ratio_median": statistics.median(pair) if pair else float("nan"),
}
return {"metric": metric, "stats": stats, "ratios_vs_baseline": ratios}
def wasmtime_precompile_path(root: Path, wasm_rel: str, *, bin_path: str) -> Path:
wasm_path = (root / wasm_rel).resolve()
wasm_st = wasm_path.stat()
bin_real = Path(bin_path).resolve()
bin_st = bin_real.stat()
# Include the wasmtime binary identity so multi-binary comparisons don't share precompiled artifacts.
key = f"{bin_real}|{bin_st.st_size}|{bin_st.st_mtime_ns}|{wasm_rel}|{wasm_st.st_size}|{wasm_st.st_mtime_ns}".encode(
"utf-8", errors="strict"