| 1 | #!/usr/bin/env python3 |
| 2 | """Checked shared-language benchmarks; builds, verification and timing are separate.""" |
| 3 | from pathlib import Path |
| 4 | import argparse |
| 5 | import hashlib |
| 6 | import json |
| 7 | import math |
| 8 | import os |
| 9 | import re |
| 10 | import shutil |
| 11 | import statistics |
| 12 | import subprocess |
| 13 | import sys |
| 14 | import time |
| 15 | |
| 16 | ROOT = Path(__file__).resolve().parents[2] |
| 17 | VARIANTS = ['interpreter-arena', 'interpreter-gc', 'native-arena', 'native-gc', 'guile-3'] |
| 18 | parser = argparse.ArgumentParser(description=__doc__) |
| 19 | parser.add_argument('phase', choices=['build', 'verify', 'scaling', 'measure', 'report']) |
| 20 | parser.add_argument('--suite', choices=['native', 'wm'], default='native') |
| 21 | parser.add_argument('--output') |
| 22 | parser.add_argument('--samples', type=int, default=31) |
| 23 | parser.add_argument('--native-cache', choices=['off', 'reuse'], default='off', |
| 24 | help='off records first-use compilation; reuse shares an isolated cache across phases') |
| 25 | args = parser.parse_args() |
| 26 | DRIVERS = ROOT / 'bench' / args.suite |
| 27 | sys.path.insert(0, str(DRIVERS)) |
| 28 | from catalog import guile_wrapper, vile_source, validate_catalog, SCALING_CASES |
| 29 | args.output = args.output or ('native-results-v3' if args.suite == 'native' else 'wm-results-v1') |
| 30 | if sys.platform != 'darwin': |
| 31 | sys.exit('Run on the Mac validation host under the shared validation lock.') |
| 32 | if not 3 <= args.samples <= 101: |
| 33 | sys.exit('Use 3..101 measured samples.') |
| 34 | out = (ROOT / args.output).resolve() |
| 35 | if out == ROOT / 'bench' or ROOT / 'bench' in out.parents: |
| 36 | sys.exit('Keep output outside bench so artifacts are separate from source inputs.') |
| 37 | env = dict(os.environ, VJOBS='1', VFLAGS='-no-parallel', MAKEFLAGS='-j1', GUILE_AUTO_COMPILE='0') |
| 38 | env['VILE_NATIVE_CACHE'] = 'off' if args.native_cache == 'off' else str(out / 'native-cache') |
| 39 | native_environment = {k:env.get(k) for k in ['VILE_NATIVE_CACHE', 'CPATH', 'C_INCLUDE_PATH', |
| 40 | 'CPLUS_INCLUDE_PATH', 'OBJC_INCLUDE_PATH', 'SDKROOT', 'MACOSX_DEPLOYMENT_TARGET', 'DEVELOPER_DIR']} |
| 41 | if any(env.get(k) is not None for k in ['GUILE_JIT_THRESHOLD', 'GUILE_JIT_STOP_AFTER', 'GUILE_JIT_LOG']): |
| 42 | sys.exit('Use Guile default JIT settings for this comparison.') |
| 43 | record = json.loads((DRIVERS / 'cases.json').read_text()) |
| 44 | cases = record['cases'] |
| 45 | assert len({c['name'] for c in cases}) == len(cases) |
| 46 | assert all(re.fullmatch('[a-z0-9-]+', c['name']) for c in cases) |
| 47 | |
| 48 | |
| 49 | def sha(path): |
| 50 | h = hashlib.sha256() |
| 51 | with Path(path).open('rb') as stream: |
| 52 | while chunk := stream.read(256 * 1024): |
| 53 | h.update(chunk) |
| 54 | return h.hexdigest() |
| 55 | |
| 56 | |
| 57 | def atomic(name, value, compact=False): |
| 58 | target = out / name |
| 59 | temporary = target.with_suffix('.tmp') |
| 60 | temporary.write_text(json.dumps(value, indent=None if compact else 2) + '\n') |
| 61 | temporary.replace(target) |
| 62 | |
| 63 | |
| 64 | def source_hashes(): |
| 65 | paths = {ROOT / 'v.mod', ROOT / 'main.v', Path(__file__).resolve(), ROOT / record['original_cases_path']} |
| 66 | for folder in ['scheme', 'lexer', 'reader', 'unicode17', 'bench/native', 'bench/' + args.suite]: |
| 67 | paths.update(p for p in (ROOT / folder).rglob('*') if p.is_file() and p.suffix in {'.v', '.h', '.scm', '.sld', '.vile', '.tsv', '.json', '.py'}) |
| 68 | return {str(p.relative_to(ROOT)): sha(p) for p in sorted(paths)} |
| 69 | |
| 70 | |
| 71 | def source_guard(): |
| 72 | validate_catalog(record, ROOT) |
| 73 | if (ROOT / 'SHA256SUMS').is_file(): |
| 74 | subprocess.run(['shasum', '-a', '256', '--quiet', '-c', 'SHA256SUMS'], cwd=ROOT, check=True) |
| 75 | assert sha(ROOT / record['original_cases_path']) == record['original_cases_sha256'] |
| 76 | for case in cases: |
| 77 | assert sha(ROOT / case['source']) == case['source_sha256'], case['name'] |
| 78 | |
| 79 | |
| 80 | def idle(): |
| 81 | names = {'v', 'vtest', 'clang', 'clang-17', 'clang-18', 'ld', 'make', 'ninja', 'port', 'guile-3.0', 'guile-2.2'} |
| 82 | busy = [] |
| 83 | for line in subprocess.check_output(['ps', '-axo', 'pid=,comm='], text=True).splitlines(): |
| 84 | parts = line.split(maxsplit=1) |
| 85 | if len(parts) == 2: |
| 86 | name = Path(parts[1]).name |
| 87 | if name in names or name.startswith('shared-bench-') or name.startswith('native-bench-'): |
| 88 | busy.append(line) |
| 89 | if busy: |
| 90 | raise RuntimeError('Mac is busy: ' + repr(busy)) |
| 91 | |
| 92 | |
| 93 | def idle_record(name): |
| 94 | idle() |
| 95 | cpu = subprocess.check_output(['top', '-l', '2', '-s', '1', '-n', '0'], text=True) |
| 96 | (out / name).write_text(cpu) |
| 97 | assert float(re.findall(r'([0-9.]+)% idle', cpu)[-1]) >= 90, cpu |
| 98 | |
| 99 | |
| 100 | def logged(command, label): |
| 101 | with (out / (label + '.log')).open('wb') as output: |
| 102 | result = subprocess.run(command, cwd=ROOT, env=env, stdout=output, stderr=subprocess.STDOUT, timeout=300) |
| 103 | if result.returncode: |
| 104 | raise RuntimeError((out / (label + '.log')).read_text()[-5000:]) |
| 105 | |
| 106 | |
| 107 | def executable(key, names): |
| 108 | path = os.environ.get(key) or next((found for name in names if (found := shutil.which(name))), None) |
| 109 | if path is None: |
| 110 | sys.exit('Set ' + key + ' to the executable; it is outside PATH.') |
| 111 | return str(Path(path).resolve()) |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | source_guard() |
| 117 | if args.phase == 'build': |
| 118 | out.mkdir(exist_ok=True) |
| 119 | compiler = executable('VEXE', ['v']) |
| 120 | guile = executable('GUILE', ['guile-3.0', 'guile']) |
| 121 | guild = executable('GUILD', ['guild-3.0', 'guild']) |
| 122 | version = subprocess.check_output([guile, '--version'], env=env, text=True) |
| 123 | assert re.search(r'\b3\.0\.', version), version |
| 124 | native_compilers = sorted({shutil.which('clang'), subprocess.check_output(['xcrun', '--find', 'clang'], text=True).strip()}) |
| 125 | dependencies = [compiler, guile, guild, *native_compilers] |
| 126 | libraries = subprocess.check_output(['otool', '-L', guile], text=True) |
| 127 | dependencies.extend(line.strip().split(' ', 1)[0] for line in libraries.splitlines()[1:] if line.strip().startswith('/opt/local/')) |
| 128 | inputs = source_hashes() |
| 129 | tools = {p: sha(p) for p in dependencies} |
| 130 | state_path = out / 'build-state.json' |
| 131 | state = json.loads(state_path.read_text()) if state_path.exists() else dict(sources=inputs, tools=tools, jobs={}) |
| 132 | assert state['sources'] == inputs and state['tools'] == tools, 'Build inputs changed; use fresh output.' |
| 133 | flags = [compiler, '-no-parallel', '-new-compiler', '-no-retry-compilation', '-cc', 'clang', '-prod', '-path', str(ROOT) + '|@vlib'] |
| 134 | jobs = [] |
| 135 | for variant in VARIANTS[:-1]: |
| 136 | gc_flags = ['-gc', 'none'] if variant.endswith('arena') else ['-gc', 'boehm', '-d', 'use_bundled_libgc'] |
| 137 | native_flags = ['-d', 'vile_native'] if variant.startswith('native-') else [] |
| 138 | target = out / ('shared-bench-' + variant) |
| 139 | jobs.append((target, [*flags, *gc_flags, *native_flags, '-o', str(target), str(ROOT / 'bench/native/main.v')])) |
| 140 | for case in cases: |
| 141 | source = out / ('guile-' + case['name'] + '.scm') |
| 142 | source.write_text(guile_wrapper(case, ROOT)) |
| 143 | (out / ('vile-' + case['name'] + '.scm')).write_text(vile_source(case, ROOT)) |
| 144 | target = out / ('guile-' + case['name'] + '.go') |
| 145 | jobs.append((target, [guild, 'compile', '-O2', '-o', str(target), str(source)])) |
| 146 | atomic('build-state.json', state) |
| 147 | for target, command in jobs: |
| 148 | if target.name in state['jobs']: |
| 149 | assert sha(target) == state['jobs'][target.name] |
| 150 | continue |
| 151 | idle() |
| 152 | logged(command, target.name + '-build') |
| 153 | source_guard() |
| 154 | assert source_hashes() == inputs and all(sha(p) == h for p, h in tools.items()) |
| 155 | state['jobs'][target.name] = sha(target) |
| 156 | atomic('build-state.json', state) |
| 157 | print('Built', target.name, flush=True) |
| 158 | artifacts = [target for target, _ in jobs] + list(out.glob('*.scm')) |
| 159 | atomic('hashes.json', {str(p): sha(p) for p in [*dependencies, *artifacts]}) |
| 160 | atomic('config.json', dict(schema_version=3, suite=args.suite, seed_values=record['seed_values'], sources=inputs, compiler=compiler, guile=guile, guild=guild, |
| 161 | guile_version=version, native_compiler_version=subprocess.check_output(['clang', '--version'], text=True), |
| 162 | v_common_flags=flags[1:], guile_compile_flags=['-O2'], variants=VARIANTS, cases=cases, samples=args.samples, |
| 163 | excluded_warmup_process_samples=1, cpu=subprocess.check_output(['sysctl', '-n', 'machdep.cpu.brand_string'], text=True).strip(), |
| 164 | memory_bytes=int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'], text=True)), |
| 165 | os_version=subprocess.check_output(['sw_vers'], text=True), dependency_libraries=libraries, |
| 166 | guile_environment={k:env.get(k) for k in ['GUILE_AUTO_COMPILE','GUILE_JIT_THRESHOLD','GUILE_JIT_STOP_AFTER','GUILE_JIT_LOG']}, |
| 167 | native_cache=args.native_cache, native_environment=native_environment, |
| 168 | scaling_protocol=dict(calls=[4, 400], repetitions=3, minimum_total_time_ratio=20), |
| 169 | timing='prepared varying-input shared batch; setup and first-use compilation excluded; first-call and whole-process durations separate', |
| 170 | compatibility='Per-engine imports occur before timing; timed benchmark definitions and batch loop are identical.')) |
| 171 | idle() |
| 172 | sys.exit() |
| 173 | |
| 174 | config = json.loads((out / 'config.json').read_text()) |
| 175 | hashes = json.loads((out / 'hashes.json').read_text()) |
| 176 | assert args.samples == config['samples'], 'Use the sample count recorded at build.' |
| 177 | assert args.native_cache == config['native_cache'] and native_environment == config['native_environment'], 'Native cache policy or compiler environment changed; use fresh output.' |
| 178 | |
| 179 | |
| 180 | def guard(): |
| 181 | source_guard() |
| 182 | assert source_hashes() == config['sources'] |
| 183 | for p, digest in hashes.items(): |
| 184 | assert sha(p) == digest, p |
| 185 | |
| 186 | |
| 187 | def checked(case, variant, calls=None): |
| 188 | calls = case['batch_calls'] if calls is None else calls |
| 189 | if variant == 'guile-3': |
| 190 | assert calls == case['batch_calls'], 'Guile batch size is compiled into its wrapper.' |
| 191 | command = [config['guile'], '--no-auto-compile', '-q', '-c', '(load-compiled ' + json.dumps(str(out / ('guile-' + case['name'] + '.go'))) + ')'] |
| 192 | else: |
| 193 | command = [str(out / ('shared-bench-' + variant)), case['name'], str(out / ('vile-' + case['name'] + '.scm')), str(case['expected']), str(calls), str(case['warmup_calls'])] |
| 194 | idle() |
| 195 | start = time.monotonic_ns() |
| 196 | result = subprocess.run(command, env=env, text=True, capture_output=True, timeout=90) |
| 197 | duration = time.monotonic_ns() - start |
| 198 | if result.returncode: |
| 199 | raise RuntimeError(repr(command) + '\n' + result.stdout + '\n' + result.stderr) |
| 200 | row = json.loads(result.stdout) |
| 201 | assert row['name'] == case['name'] and row['result'] == case['expected'] |
| 202 | assert row['calls'] == calls and row['warmup_calls'] == case['warmup_calls'] |
| 203 | assert row['elapsed_ns'] > 0 and row['first_call_ns'] > 0 |
| 204 | for field in ['native_hits', 'native_deopts', 'warmup_native_hits', 'warmup_native_deopts']: |
| 205 | assert isinstance(row[field], int) and row[field] >= 0 |
| 206 | if not variant.startswith('native-'): |
| 207 | assert row[field] == 0 |
| 208 | for field in ['cache_hits', 'compilations', 'warmup_cache_hits', 'warmup_compilations']: |
| 209 | if variant == 'guile-3': |
| 210 | row[field] = 0 |
| 211 | assert isinstance(row[field], int) and row[field] >= 0 |
| 212 | if not variant.startswith('native-'): |
| 213 | assert row[field] == 0 |
| 214 | return dict(row, variant=variant, process_ns=duration) |
| 215 | |
| 216 | |
| 217 | guard() |
| 218 | if args.phase == 'verify': |
| 219 | path = out / 'verification.json' |
| 220 | verified = json.loads(path.read_text()) if path.exists() else [] |
| 221 | done = {(r['name'], r['variant']) for r in verified} |
| 222 | for case in cases: |
| 223 | for variant in VARIANTS: |
| 224 | if (case['name'], variant) in done: |
| 225 | continue |
| 226 | verified.append(checked(case, variant)) |
| 227 | atomic('verification.json', verified) |
| 228 | print('Verified', case['name'], flush=True) |
| 229 | assert len(verified) == len(cases) * len(VARIANTS) |
| 230 | guard() |
| 231 | sys.exit() |
| 232 | |
| 233 | if args.phase == 'scaling': |
| 234 | verified = json.loads((out / 'verification.json').read_text()) |
| 235 | assert len(verified) == len(cases) * len(VARIANTS), 'Finish verification first.' |
| 236 | path = out / 'scaling.json' |
| 237 | groups = json.loads(path.read_text()) if path.exists() else {} |
| 238 | for case in cases: |
| 239 | if case['name'] not in SCALING_CASES: |
| 240 | continue |
| 241 | for variant in ['native-arena', 'native-gc']: |
| 242 | key = case['name'] + '/' + variant |
| 243 | if key in groups and groups[key]['passed']: |
| 244 | continue |
| 245 | idle_record('scaling-idle-' + key.replace('/', '-') + '.txt') |
| 246 | samples = [] |
| 247 | for repeat in range(3): |
| 248 | for count in ([4, 400] if repeat % 2 == 0 else [400, 4]): |
| 249 | samples.append(dict(checked(case, variant, count), repeat=repeat)) |
| 250 | ratio = statistics.median(r['elapsed_ns'] for r in samples if r['calls'] == 400) / statistics.median(r['elapsed_ns'] for r in samples if r['calls'] == 4) |
| 251 | groups[key] = dict(samples=samples, total_time_ratio=ratio, passed=ratio >= 20) |
| 252 | atomic('scaling.json', groups) |
| 253 | assert groups[key]['passed'], 'Repeated work may have been optimized away: ' + key + ' ratio=' + str(ratio) |
| 254 | print('Scaling', key, ratio, flush=True) |
| 255 | guard() |
| 256 | sys.exit() |
| 257 | |
| 258 | if args.phase == 'measure': |
| 259 | scaling = json.loads((out / 'scaling.json').read_text()) |
| 260 | assert len(scaling) == len(SCALING_CASES) * 2 and all(g['passed'] for g in scaling.values()), 'Finish scaling checks first.' |
| 261 | verified = json.loads((out / 'verification.json').read_text()) |
| 262 | assert len(verified) == len(cases) * len(VARIANTS), 'Finish verification first.' |
| 263 | rows = json.loads((out / 'samples.json').read_text()) if (out / 'samples.json').exists() else [] |
| 264 | done = {(r['sample'], r['name'], r['variant']) for r in rows} |
| 265 | for ci, case in enumerate(cases): |
| 266 | if all((s, case['name'], v) in done for s in range(args.samples + 1) for v in VARIANTS): |
| 267 | continue |
| 268 | idle_record('idle-' + case['name'] + '.txt') |
| 269 | for sample in range(args.samples + 1): |
| 270 | offset = (sample + ci) % len(VARIANTS) |
| 271 | variants = VARIANTS[offset:] + VARIANTS[:offset] |
| 272 | if sample % 2: |
| 273 | variants.reverse() |
| 274 | for variant in variants: |
| 275 | if (sample, case['name'], variant) in done: |
| 276 | continue |
| 277 | rows.append(dict(checked(case, variant), sample=sample)) |
| 278 | atomic('samples.json', rows, compact=True) |
| 279 | print('Measured', case['name'], flush=True) |
| 280 | guard() |
| 281 | else: |
| 282 | rows = json.loads((out / 'samples.json').read_text()) |
| 283 | |
| 284 | measured = [r for r in rows if r['sample'] > 0] |
| 285 | assert len(rows) == (args.samples + 1) * len(cases) * len(VARIANTS) |
| 286 | assert len(measured) == args.samples * len(cases) * len(VARIANTS) |
| 287 | medians = {} |
| 288 | for case in cases: |
| 289 | name = case['name'] |
| 290 | medians[name] = dict(category=case['category'], batch_calls=case['batch_calls'], variants={}) |
| 291 | for variant in VARIANTS: |
| 292 | subset = [r for r in measured if r['name'] == name and r['variant'] == variant] |
| 293 | assert len(subset) == args.samples |
| 294 | values = [r['elapsed_ns'] / r['calls'] for r in subset] |
| 295 | q1, _, q3 = statistics.quantiles(values, n=4, method='inclusive') |
| 296 | medians[name]['variants'][variant] = dict(per_call_ns=statistics.median(values), q1_ns=q1, q3_ns=q3, |
| 297 | min_ns=min(values), max_ns=max(values), first_call_ns=statistics.median(r['first_call_ns'] for r in subset), |
| 298 | whole_process_ns=statistics.median(r['process_ns'] for r in subset), |
| 299 | median_native_hits=statistics.median(r['native_hits'] for r in subset), |
| 300 | median_native_deopts=statistics.median(r['native_deopts'] for r in subset), |
| 301 | median_warmup_native_hits=statistics.median(r['warmup_native_hits'] for r in subset), |
| 302 | median_warmup_native_deopts=statistics.median(r['warmup_native_deopts'] for r in subset), |
| 303 | **{'median_' + field:statistics.median(r[field] for r in subset) |
| 304 | for field in ['cache_hits','compilations','warmup_cache_hits','warmup_compilations']}) |
| 305 | summary = {} |
| 306 | for category in ['all', *sorted({c['category'] for c in cases})]: |
| 307 | names = [c['name'] for c in cases if category == 'all' or c['category'] == category] |
| 308 | summary[category] = {} |
| 309 | for variant in VARIANTS[:-1]: |
| 310 | ratios = [medians[n]['variants']['guile-3']['per_call_ns'] / medians[n]['variants'][variant]['per_call_ns'] for n in names] |
| 311 | summary[category][variant] = dict(cases=len(names), geometric_mean_speedup=math.exp(statistics.mean(math.log(r) for r in ratios)), faster_cases=sum(r>1 for r in ratios), slower_cases=sum(r<1 for r in ratios)) |
| 312 | atomic('results.json', dict(config=config, medians=medians, summary=summary, measured_rows=len(measured), warmup_rows=len(rows)-len(measured))) |
| 313 | print(json.dumps(summary, indent=2), flush=True) |
| 314 | |