benchmark_fd.py ダウンロード/コピー

benchmark_fd.py をダウンロード

benchmark_fd.py
benchmark_fd.py
  1"""添付6実装のF_{1/2}(eta)を比較する。元のプログラムは変更しない。"""
  2import argparse
  3import csv
  4import importlib.util
  5import math
  6from pathlib import Path
  7import statistics
  8import sys
  9from time import perf_counter
 10
 11import numpy as np
 12from scipy.integrate import quad
 13from scipy.special import expit
 14
 15
 16SOURCES = [
 17    ('sonnet5.5', 'Ne-T_sonnet5.5.py'),
 18    ('tkfermi', 'tkfermi_integral.py'),
 19    ('copilot', 'Ne-T_copilot.py'),
 20    ('Gemini3.8Flash', 'Ne-T_Gemini3.8Flash.py'),
 21    ('Gemini3Flash', 'Ne-T_Gemini3Flash.py'),
 22    ('sol', 'Ne-T_sol.py'),
 23]
 24NORMALIZATION = math.gamma(1.5)
 25
 26
 27def load_function(label, path):
 28    # ファイル名にハイフンや括弧が含まれるので、パスからimportする。
 29    name = 'fd_bench_' + label.replace('.', '_')
 30    spec = importlib.util.spec_from_file_location(name, path)
 31    module = importlib.util.module_from_spec(spec)
 32    sys.modules[name] = module  # dataclassを使用するモジュールにも必要
 33    spec.loader.exec_module(module)
 34
 35    disabled = []
 36    for name, obj in list(vars(module).items()):
 37        if callable(obj) and hasattr(obj, 'cache_clear') and hasattr(obj, '__wrapped__'):
 38            obj.cache_clear()
 39            # キャッシュのラッパーを外す。毎回cache_clearする時間は計測しない。
 40            while hasattr(obj, '__wrapped__'):
 41                obj = obj.__wrapped__
 42            setattr(module, name, obj)
 43            disabled.append(name)
 44
 45    # 全実装を 1/Gamma(3/2) * integral(x**0.5 * f, x=0..inf) に統一。
 46    if label == 'tkfermi':
 47        fn = module.FermiIntegral_half
 48        function = lambda eta: fn(eta) / NORMALIZATION
 49    elif label == 'sonnet5.5':
 50        function = module.fd_half
 51    elif label == 'Gemini3Flash':
 52        fn = module.Fj
 53        function = lambda eta: fn(eta) / NORMALIZATION
 54    elif label == 'sol':
 55        function = module.Fj
 56    else:
 57        fn = module.Fj
 58        function = lambda eta: fn(0.5, eta)
 59    return function, disabled
 60
 61
 62def reference(eta):
 63    # 精度確認用の独立な数値積分。ベンチマーク時間には含めない。
 64    # 負のetaではexp(eta)を外に出して小さな値の相対精度を保つ。
 65    scale = math.exp(eta) if eta < 0 else 1.0
 66    def integrand(t):
 67        x = t * t
 68        f = math.exp(-x) * expit(x - eta) if eta < 0 else expit(eta - x)
 69        return 2 * t * t * f
 70    cuts = sorted(set([0.0, math.sqrt(max(eta, 0)),
 71                       math.sqrt(max(eta, 0) + 100)]))
 72    value = sum(quad(integrand, a, b, epsabs=1e-12, epsrel=1e-12,
 73                     limit=500)[0] for a, b in zip(cuts[:-1], cuts[1:]))
 74    return scale * value / NORMALIZATION
 75
 76
 77def positive_int(text):
 78    value = int(text)
 79    if value < 1:
 80        raise argparse.ArgumentTypeError('1以上を指定してください')
 81    return value
 82
 83
 84def main():
 85    parser = argparse.ArgumentParser(description=__doc__)
 86    parser.add_argument('-n', '--count', type=positive_int, default=1000,
 87                        help='各実装・各試行の総計算回数 (default: 1000)')
 88    parser.add_argument('--repeat', type=positive_int, default=3,
 89                        help='試行数。代表値は中央値 (default: 3)')
 90    parser.add_argument('--eta', type=float, nargs='+',
 91                        default=[-10, -3, -1, -0.1, 0, 1, 5, 19.9, 20, 50, 100],
 92                        help='順番に循環させるetaのリスト')
 93    parser.add_argument('--source-dir', type=Path, default=Path(__file__).resolve().parent)
 94    parser.add_argument('--output', type=Path, default=Path('benchmark_fd'))
 95    args = parser.parse_args()
 96    if not all(math.isfinite(e) for e in args.eta):
 97        parser.error('etaは有限値を指定してください')
 98    if args.count < len(args.eta):
 99        parser.error('countはetaの個数以上にしてください')
100    # 全実装で同じ入力・順序。入力配列の作成とimportは計測外。
101    inputs = [args.eta[i % len(args.eta)] for i in range(args.count)]
102    functions = []
103    for label, filename in SOURCES:
104        fn, disabled = load_function(label, args.source_dir / filename)
105        functions.append((label, fn))
106        print(f'{label}: cache disabled: {", ".join(disabled) or "none found"}')
107
108    # ウォームアップ兼精度確認。例外や積分警告を隠さない。
109    accuracy = []
110    errors = {}
111    refs = [reference(eta) for eta in args.eta]
112    for label, fn in functions:
113        errors[label] = []
114        for eta, ref in zip(args.eta, refs):
115            value = float(fn(eta))
116            relative = abs(value - ref) / abs(ref) if ref != 0 else float('nan')
117            if not math.isfinite(value):
118                relative = float('inf')
119            errors[label].append(relative)
120            accuracy.append(dict(implementation=label, eta=eta, value=value,
121                                 reference=ref, relative_error=relative))
122
123    times = {label: [] for label, _ in functions}
124    # 試行ごとに実行順を回転して、常に同じ実装が先頭になるのを避ける。
125    for trial in range(args.repeat):
126        offset = trial % len(functions)
127        for label, fn in functions[offset:] + functions[:offset]:
128            start = perf_counter()
129            for eta in inputs:
130                fn(eta)
131            elapsed = perf_counter() - start
132            times[label].append(elapsed)
133            print(f'trial {trial+1}/{args.repeat}: {label:16s} {elapsed:.6f} s', flush=True)
134
135    rows = []
136    for label, _ in functions:
137        seconds = statistics.median(times[label])
138        rows.append(dict(implementation=label, count=args.count, repeat=args.repeat,
139                         median_seconds=seconds, min_seconds=min(times[label]),
140                         us_per_call=seconds / args.count * 1e6,
141                         max_relative_error=max(errors[label])))
142    rows.sort(key=lambda row: row['median_seconds'])
143    print('\nNormalized F_1/2; count = calls per implementation per trial')
144    print(f'{"implementation":16s} {"median(s)":>12s} {"us/call":>12s} {"max rel.err":>14s}')
145    for row in rows:
146        print(f'{row["implementation"]:16s} {row["median_seconds"]:12.6f} '
147              f'{row["us_per_call"]:12.3f} {row["max_relative_error"]:14.3e}')
148    for suffix, data in [('timing', rows), ('values', accuracy),
149                         ('trials', [dict(implementation=k, trial=i+1, seconds=t)
150                                     for k, ts in times.items() for i, t in enumerate(ts)])]:
151        path = args.output.with_name(args.output.name + '_' + suffix + '.csv')
152        path.parent.mkdir(parents=True, exist_ok=True)
153        with path.open('w', newline='', encoding='utf-8-sig') as f:
154            writer = csv.DictWriter(f, fieldnames=list(data[0]))
155            writer.writeheader()
156            writer.writerows(data)
157        print('Saved:', path)
158
159
160if __name__ == '__main__':
161    main()