Skip to content

Commit cdffbcf

Browse files
committed
docs,bench: update numerical accuracy benchmarks and documentation
1 parent d460f02 commit cdffbcf

4 files changed

Lines changed: 76 additions & 25 deletions

File tree

‎benchmarks/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ Reproducible performance benchmarks comparing Oxideon (`--release`) against PyTo
77
| Script | Scope |
88
|---|---|
99
| [`bench_vs_pytorch.py`](bench_vs_pytorch.py) | Core ops, norms, `Conv2d`, and `MLP` forward+backward vs PyTorch |
10-
| [`core_ops_bench_compare.py`](core_ops_bench_compare.py) | Core Rust vs PyTorch operation comparison runner |
10+
| [`core_ops_bench_compare.py`](core_ops_bench_compare.py) | Core Rust vs PyTorch operation comparison runner: time and numerical error (worst / mean, vs a float64 reference) side by side |
11+
| [`accuracy_vs_pytorch.py`](accuracy_vs_pytorch.py) | Numerical error of 40 operations vs a float64 reference, oxideon next to PyTorch (needs `cargo build --release --example accuracy_dump`) |
1112
| [`core_ops_bench_torch.py`](core_ops_bench_torch.py) | PyTorch reference timings for core operations |
1213
| [`ops_bench.py`](ops_bench.py) | Tensor op microbenchmarks |
1314
| [`gpu_bench.py`](gpu_bench.py) | GPU (`wgpu` / CUDA) throughput benchmarks |

‎benchmarks/accuracy_vs_pytorch.py‎

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,21 @@ def gn64(i):
184184
lambda i: (lambda d: ((d ** 2).mean(), (d ** 2).mean()))(i["a"].astype(np.float64) - i["b"].astype(np.float64)))
185185

186186

187-
def main():
188-
only = set(sys.argv[1:])
187+
def better(t, o):
188+
"""How many times smaller oxideon's error is than torch's (> 1 = oxideon more accurate)."""
189+
if t < 1e-3 and o < 1e-3:
190+
return float("nan") # both exact to the last bit: nothing to compare
191+
return t / o if o > 0 else float("inf")
192+
193+
194+
def verdict_of(bw, bm):
195+
both = [x for x in (bw, bm) if x == x]
196+
lo = min(both) if both else float("nan")
197+
return "exact" if not both else ">=2x" if lo >= 2 else ">=1.5x" if lo >= 1.5 else "better" if lo > 1.05 else "tie" if lo >= 0.95 else "WORSE"
198+
199+
200+
def measure(only=()):
201+
"""Runs the cases (all, or the names in `only`); returns {name: (worst_ox, worst_torch, x_better, mean_ox, mean_torch, x_better, verdict)}."""
189202
work = Path(tempfile.mkdtemp(prefix="oxideon_accuracy_"))
190203
manifest = []
191204
selected = {k: v for k, v in cases.items() if not only or k in only}
@@ -196,18 +209,7 @@ def main():
196209
manifest.append(f"{name} {iname} {','.join(map(str, arr.shape))} {fn}")
197210
(work / "manifest.txt").write_text("\n".join(manifest))
198211
subprocess.run([str(EXE), str(work)], check=True, stdout=subprocess.DEVNULL)
199-
200-
def better(t, o):
201-
"""How many times smaller oxideon's error is than torch's (> 1 = oxideon more accurate)."""
202-
if t < 1e-3 and o < 1e-3:
203-
return float("nan") # both exact to the last bit: nothing to compare
204-
return t / o if o > 0 else float("inf")
205-
206-
def fmt(x):
207-
return " tie" if x != x else " inf" if x == float("inf") else f"{x:5.2f}"
208-
209-
print(f"{'case':20} | {'worst: oxideon':>14} {'torch':>10} {'x better':>9} | {'mean: oxideon':>13} {'torch':>10} {'x better':>9} | verdict")
210-
rows = []
212+
rows = {}
211213
for name, (inputs, torch_fn, ref_fn) in selected.items():
212214
ref, scale = ref_fn(inputs)
213215
ref = np.asarray(ref, dtype=np.float64)
@@ -218,14 +220,22 @@ def fmt(x):
218220
e_ox, e_th = np.abs(ox - ref) / scale / EPS, np.abs(th - ref) / scale / EPS
219221
wo, wt, mo, mt = e_ox.max(), e_th.max(), e_ox.mean(), e_th.mean()
220222
bw, bm = better(wt, wo), better(mt, mo)
221-
both = [x for x in (bw, bm) if x == x]
222-
lo = min(both) if both else float("nan")
223-
verdict = "exact" if not both else ">=2x" if lo >= 2 else ">=1.5x" if lo >= 1.5 else "better" if lo > 1.05 else "tie" if lo >= 0.95 else "WORSE"
224-
rows.append((name, verdict))
223+
rows[name] = (wo, wt, bw, mo, mt, bm, verdict_of(bw, bm))
224+
return rows
225+
226+
227+
def fmt(x):
228+
return " tie" if x != x else " inf" if x == float("inf") else f"{x:5.2f}"
229+
230+
231+
def main():
232+
rows = measure(set(sys.argv[1:]))
233+
print(f"{'case':20} | {'worst: oxideon':>14} {'torch':>10} {'x better':>9} | {'mean: oxideon':>13} {'torch':>10} {'x better':>9} | verdict")
234+
for name, (wo, wt, bw, mo, mt, bm, verdict) in rows.items():
225235
print(f"{name:20} | {wo:14.4f} {wt:10.4f} {fmt(bw):>9} | {mo:13.5f} {mt:10.5f} {fmt(bm):>9} | {verdict}")
226236
print()
227237
for v in ("exact", ">=2x", ">=1.5x", "better", "tie", "WORSE"):
228-
names = [n for n, x in rows if x == v]
238+
names = [n for n, r in rows.items() if r[6] == v]
229239
if names:
230240
print(f"{v:>7} ({len(names)}): {', '.join(names)}")
231241
print("\nverdict =the smaller of the two 'x better' figures (worst and mean); tie = within 5%; exact = both below 0.001 half-ulps.")
Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
"""Runs every benchmark of examples/core_ops_bench.rs and benchmarks/core_ops_bench_torch.py in its own process (with a pause
2-
in between, so power throttling of long-running processes does not distort later rows) and prints both side by side.
2+
in between, so power throttling of long-running processes does not distort later rows) and prints both side by side, together with
3+
the numerical error of the same operation against a float64 reference (from `accuracy_vs_pytorch.py`; "x better" = PyTorch's error
4+
divided by oxideon's, so above 1 oxideon is more accurate).
35
4-
cargo build --release --example core_ops_bench
5-
python benchmarks/core_ops_bench_compare.py
6+
cargo build --release --example core_ops_bench --example accuracy_dump
7+
python benchmarks/core_ops_bench_compare.py [--no-accuracy]
8+
9+
The accuracy case is the one named in the last column; its shape is not always the benchmark's. Operations whose result is one
10+
correctly rounded IEEE operation (add, mul, relu, copies ...) are `exact` in both libraries.
611
"""
712
import re
813
import subprocess
@@ -11,11 +16,22 @@
1116
from pathlib import Path
1217

1318
ROOT = Path(__file__).resolve().parent.parent
19+
sys.path.insert(0, str(Path(__file__).resolve().parent))
1420
EXE = ROOT / "target/release/examples/core_ops_bench.exe"
1521
if not EXE.exists():
1622
EXE = ROOT / "target/release/examples/core_ops_bench"
1723
NAMES = re.findall(r'bench\("([^"]+)"', (ROOT / "examples/core_ops_bench.rs").read_text(encoding="utf-8"))
1824

25+
# benchmark -> case of accuracy_vs_pytorch.py measuring the same operation; "exact" = a single correctly rounded operation
26+
ACCURACY = {
27+
"add 1M": "exact", "mul 1M": "exact", "add broadcast row 1M": "exact", "mul_scalar 1M": "exact", "relu 1M": "exact",
28+
"max axis1 1M": "exact", "transpose+contiguous 1M": "exact", "add transposed 1M": "exact", "index_select 4096 rows": "exact",
29+
"cat 2x1M": "exact", "max_pool2d": "exact",
30+
"exp 1M": "exp", "tanh 1M": "tanh", "gelu 1M": "gelu", "sum 1M": "sum_1M", "sum axis0 1M": "sum_axis0", "sum axis1 1M": "sum_axis1",
31+
"softmax 1M": "softmax", "matmul 512": "matmul_512", "matmul 256x4096x256": "matmul_k8192",
32+
"conv2d 8x16x64x64 k3": "conv2d_16ch", "conv2d 4x64x56x56 k3": "conv2d_64ch", "layer_norm 32x128x256": "layer_norm_offset",
33+
}
34+
1935

2036
def one(cmd, name):
2137
out = subprocess.run(cmd + [name], capture_output=True, text=True).stdout
@@ -24,8 +40,31 @@ def one(cmd, name):
2440
return float(m.group(1)) if m else float("nan")
2541

2642

27-
print(f"{'op':<28}{'oxideon us':>12}{'torch us':>12}{'ratio':>8}")
43+
acc = {}
44+
if "--no-accuracy" not in sys.argv:
45+
import accuracy_vs_pytorch
46+
47+
acc = accuracy_vs_pytorch.measure({c for c in ACCURACY.values() if c != "exact"})
48+
49+
50+
def fx(v):
51+
return "tie" if v != v else "inf" if v == float("inf") else f"{v:.2f}x"
52+
53+
54+
def error_columns(name):
55+
case = ACCURACY.get(name)
56+
if case is None:
57+
return f"{'-':>9}{'-':>9} -"
58+
if case == "exact":
59+
return f"{'exact':>9}{'exact':>9} both libraries exact"
60+
if case not in acc:
61+
return f"{'?':>9}{'?':>9} {case}"
62+
_, _, bw, _, _, bm, _ = acc[case]
63+
return f"{fx(bw):>9}{fx(bm):>9} {case}"
64+
65+
66+
print(f"{'op':<28}{'oxideon us':>12}{'torch us':>12}{'ratio':>8}" + (f"{'err worst':>11}{'err mean':>9} accuracy case" if acc else ""))
2867
for n in NAMES:
2968
o = one([str(EXE)], n)
3069
t = one([sys.executable, str(ROOT / "benchmarks/core_ops_bench_torch.py")], n)
31-
print(f"{n:<28}{o:>12.1f}{t:>12.1f}{o / t:>8.2f}", flush=True)
70+
print(f"{n:<28}{o:>12.1f}{t:>12.1f}{o / t:>8.2f}{error_columns(n) if acc else ''}", flush=True)

‎docs/NUMERICAL_ACCURACY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ cargo build --release --example accuracy_dump
248248
python benchmarks/accuracy_vs_pytorch.py # all 40 cases, worst + mean, x better, verdict
249249
python benchmarks/accuracy_vs_pytorch.py matmul_512 tanh # selected cases
250250
OXIDEON_PRECISION=highest python benchmarks/accuracy_vs_pytorch.py matmul_512 matmul_k8192 # default is balanced
251+
cargo build --release --example core_ops_bench && python benchmarks/core_ops_bench_compare.py # time and error per operation, side by side
251252
```
252253

253254
Needs `numpy` and `torch`. Inputs are seeded, so the numbers reproduce on the same machine; the `exp`/`sigmoid`/`tanh` vector paths

0 commit comments

Comments
 (0)