|
| 1 | +"""Numerical accuracy of oxideon against PyTorch, both float32 CPU, measured against a float64 reference on identical inputs. |
| 2 | +
|
| 3 | + cargo build --release --example accuracy_dump |
| 4 | + python benchmarks/accuracy_vs_pytorch.py |
| 5 | +
|
| 6 | +The error of one element is |result - reference| / scale, in units of the float32 machine epsilon (2^-24, half an ulp at 1.0): |
| 7 | + * element-wise functions: scale = |reference|, so the value is the relative error (0.5 = correctly rounded, 1.0 = one ulp); |
| 8 | + * reductions and matrix products: scale = the sum of the absolute terms (sum |x_i|, |A| @ |B|), the condition-aware error |
| 9 | + that is independent of cancellation and is what summation order controls. |
| 10 | +Each case reports the worst and the mean element together, for both libraries, with "x better" = torch error / oxideon error |
| 11 | +(above 1 means oxideon is more accurate); the verdict is the smaller of the two figures. |
| 12 | +Set OXIDEON_PRECISION=fastest|balanced|highest to choose oxideon's matmul mode (default balanced). |
| 13 | +""" |
| 14 | +import math |
| 15 | +import os |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +import tempfile |
| 19 | +from pathlib import Path |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +import torch |
| 23 | + |
| 24 | +ROOT = Path(__file__).resolve().parent.parent |
| 25 | +EXE = ROOT / "target/release/examples/accuracy_dump.exe" |
| 26 | +if not EXE.exists(): |
| 27 | + EXE = ROOT / "target/release/examples/accuracy_dump" |
| 28 | +EPS = 2.0 ** -24 |
| 29 | +rng = np.random.default_rng(2026) |
| 30 | + |
| 31 | + |
| 32 | +def f32(a): |
| 33 | + return np.ascontiguousarray(a, dtype=np.float32) |
| 34 | + |
| 35 | + |
| 36 | +def erf64(x): |
| 37 | + return np.array([math.erf(v) for v in x.ravel()]).reshape(x.shape) |
| 38 | + |
| 39 | + |
| 40 | +# case -> (inputs, torch function, float64 reference function returning (reference, scale)) |
| 41 | +def elementwise(fn64): |
| 42 | + def ref(i): |
| 43 | + r = fn64(i["x"].astype(np.float64)) |
| 44 | + return r, np.abs(r) |
| 45 | + return ref |
| 46 | + |
| 47 | + |
| 48 | +def abs_sum(i): |
| 49 | + return np.abs(i["x"].astype(np.float64)).sum() |
| 50 | + |
| 51 | + |
| 52 | +cases = {} |
| 53 | + |
| 54 | + |
| 55 | +def case(name, inputs, torch_fn, ref_fn): |
| 56 | + cases[name] = (inputs, torch_fn, ref_fn) |
| 57 | + |
| 58 | + |
| 59 | +case("sum_1M", {"x": f32(rng.standard_normal(1_000_000))}, lambda i: i["x"].sum(), |
| 60 | + lambda i: (i["x"].astype(np.float64).sum(), abs_sum(i))) |
| 61 | +case("sum_16M_offset", {"x": f32(rng.standard_normal(16_000_000) + 100)}, lambda i: i["x"].sum(), |
| 62 | + lambda i: (i["x"].astype(np.float64).sum(), abs_sum(i))) |
| 63 | +case("mean_4M_offset", {"x": f32(rng.standard_normal(4_000_000) + 1e4)}, lambda i: i["x"].mean(), |
| 64 | + lambda i: (i["x"].astype(np.float64).mean(), abs_sum(i) / 4_000_000)) |
| 65 | +case("sum_axis0", {"x": f32(rng.standard_normal((1024, 1024)) + 50)}, lambda i: i["x"].sum(0), |
| 66 | + lambda i: (i["x"].astype(np.float64).sum(0), np.abs(i["x"].astype(np.float64)).sum(0))) |
| 67 | +case("sum_axis1", {"x": f32(rng.standard_normal((1024, 1024)) + 50)}, lambda i: i["x"].sum(1), |
| 68 | + lambda i: (i["x"].astype(np.float64).sum(1), np.abs(i["x"].astype(np.float64)).sum(1))) |
| 69 | +a4, b4 = f32(rng.standard_normal(4_000_000)), f32(rng.standard_normal(4_000_000)) |
| 70 | +case("dot_4M", {"a": a4, "b": b4}, lambda i: torch.dot(i["a"], i["b"]), |
| 71 | + lambda i: ((i["a"].astype(np.float64) * i["b"]).sum(), np.abs(i["a"].astype(np.float64) * i["b"]).sum())) |
| 72 | +case("norm_4M", {"x": a4}, lambda i: torch.linalg.vector_norm(i["x"]), |
| 73 | + lambda i: (math.sqrt((i["x"].astype(np.float64) ** 2).sum()), math.sqrt((i["x"].astype(np.float64) ** 2).sum()))) |
| 74 | + |
| 75 | + |
| 76 | +def mm(i): |
| 77 | + a, b = i["a"].astype(np.float64), i["b"].astype(np.float64) |
| 78 | + return a @ b, np.abs(a) @ np.abs(b) |
| 79 | + |
| 80 | + |
| 81 | +case("matmul_512", {"a": f32(rng.standard_normal((512, 512))), "b": f32(rng.standard_normal((512, 512)))}, lambda i: i["a"] @ i["b"], mm) |
| 82 | +case("matmul_k8192", {"a": f32(rng.standard_normal((64, 8192))), "b": f32(rng.standard_normal((8192, 64)))}, lambda i: i["a"] @ i["b"], mm) |
| 83 | + |
| 84 | + |
| 85 | +def softmax64(x): |
| 86 | + e = np.exp(x - x.max(-1, keepdims=True)) |
| 87 | + return e / e.sum(-1, keepdims=True) |
| 88 | + |
| 89 | + |
| 90 | +def log_softmax64(x): |
| 91 | + m = x.max(-1, keepdims=True) |
| 92 | + return x - m - np.log(np.exp(x - m).sum(-1, keepdims=True)) |
| 93 | + |
| 94 | + |
| 95 | +logits = f32(rng.standard_normal((1024, 1000)) * 10) |
| 96 | +case("softmax", {"x": logits}, lambda i: torch.softmax(i["x"], -1), elementwise(softmax64)) |
| 97 | +case("log_softmax", {"x": logits}, lambda i: torch.log_softmax(i["x"], -1), |
| 98 | + lambda i: (log_softmax64(i["x"].astype(np.float64)), np.abs(log_softmax64(i["x"].astype(np.float64))) + 1e-3)) |
| 99 | +case("logsumexp", {"x": logits}, lambda i: torch.logsumexp(i["x"], -1), |
| 100 | + lambda i: (lambda m: (m.squeeze(-1) + np.log(np.exp(i["x"].astype(np.float64) - m).sum(-1)), None))(i["x"].astype(np.float64).max(-1, keepdims=True))) |
| 101 | + |
| 102 | +ln_x = f32(rng.standard_normal((256, 1024)) + 1000) |
| 103 | +ln_w, ln_b = f32(rng.uniform(0.5, 1.5, 1024)), f32(rng.standard_normal(1024)) |
| 104 | + |
| 105 | + |
| 106 | +def ln64(i): |
| 107 | + x = i["x"].astype(np.float64) |
| 108 | + mean = x.mean(-1, keepdims=True) |
| 109 | + var = ((x - mean) ** 2).mean(-1, keepdims=True) |
| 110 | + y = (x - mean) / np.sqrt(var + 1e-5) * i["w"] + i["b"] |
| 111 | + return y, np.abs(y) + 0.5 |
| 112 | + |
| 113 | + |
| 114 | +case("layer_norm_offset", {"x": ln_x, "w": ln_w, "b": ln_b}, lambda i: torch.nn.functional.layer_norm(i["x"], (1024,), i["w"], i["b"], 1e-5), ln64) |
| 115 | + |
| 116 | +xs = f32(rng.uniform(-20, 20, 1_000_000)) |
| 117 | +case("exp", {"x": f32(rng.uniform(-30, 30, 1_000_000))}, lambda i: torch.exp(i["x"]), elementwise(np.exp)) |
| 118 | +case("tanh", {"x": xs}, lambda i: torch.tanh(i["x"]), elementwise(np.tanh)) |
| 119 | +case("sigmoid", {"x": xs}, lambda i: torch.sigmoid(i["x"]), elementwise(lambda x: 1 / (1 + np.exp(-x)))) |
| 120 | +case("gelu", {"x": f32(rng.uniform(-8, 8, 1_000_000))}, lambda i: torch.nn.functional.gelu(i["x"]), |
| 121 | + elementwise(lambda x: 0.5 * x * (1 + erf64(x / math.sqrt(2))))) |
| 122 | +case("erf", {"x": f32(rng.uniform(-4, 4, 1_000_000))}, lambda i: torch.erf(i["x"]), elementwise(erf64)) |
| 123 | +case("ln", {"x": f32(np.exp(rng.uniform(-14, 14, 1_000_000)))}, lambda i: torch.log(i["x"]), elementwise(np.log)) |
| 124 | +case("sqrt", {"x": f32(np.exp(rng.uniform(-14, 14, 1_000_000)))}, lambda i: torch.sqrt(i["x"]), elementwise(np.sqrt)) |
| 125 | + |
| 126 | + |
| 127 | +def conv64(i): |
| 128 | + x, w = torch.from_numpy(i["x"]).double(), torch.from_numpy(i["w"]).double() |
| 129 | + r = torch.nn.functional.conv2d(x, w, padding=1).numpy() |
| 130 | + s = torch.nn.functional.conv2d(x.abs(), w.abs(), padding=1).numpy() |
| 131 | + return r, s |
| 132 | + |
| 133 | + |
| 134 | +case("conv2d_16ch", {"x": f32(rng.standard_normal((8, 16, 64, 64))), "w": f32(rng.standard_normal((16, 16, 3, 3)) * 0.2)}, |
| 135 | + lambda i: torch.nn.functional.conv2d(i["x"], i["w"], padding=1), conv64) |
| 136 | +case("conv2d_64ch", {"x": f32(rng.standard_normal((4, 64, 32, 32))), "w": f32(rng.standard_normal((64, 64, 3, 3)) * 0.1)}, |
| 137 | + lambda i: torch.nn.functional.conv2d(i["x"], i["w"], padding=1), conv64) |
| 138 | +cs = f32(rng.standard_normal(1_000_000) + 0.5) |
| 139 | +case("cumsum_1M", {"x": cs}, lambda i: torch.cumsum(i["x"], 0), |
| 140 | + lambda i: (np.cumsum(i["x"].astype(np.float64)), np.cumsum(np.abs(i["x"].astype(np.float64))))) |
| 141 | + |
| 142 | + |
| 143 | +# ---- second group: more element-wise functions, statistics and normalisations ---- |
| 144 | +F = torch.nn.functional |
| 145 | +case("sin", {"x": f32(rng.uniform(-100, 100, 1_000_000))}, lambda i: torch.sin(i["x"]), elementwise(np.sin)) |
| 146 | +case("cos", {"x": f32(rng.uniform(-100, 100, 1_000_000))}, lambda i: torch.cos(i["x"]), elementwise(np.cos)) |
| 147 | +case("log1p", {"x": f32(np.exp(rng.uniform(-18, 2, 1_000_000)))}, lambda i: torch.log1p(i["x"]), elementwise(np.log1p)) |
| 148 | +case("expm1", {"x": f32(rng.uniform(-5, 5, 1_000_000) * np.exp(rng.uniform(-12, 0, 1_000_000)))}, lambda i: torch.expm1(i["x"]), elementwise(np.expm1)) |
| 149 | +case("softplus", {"x": f32(rng.uniform(-20, 20, 1_000_000))}, lambda i: F.softplus(i["x"]), elementwise(lambda x: np.log1p(np.exp(x)))) |
| 150 | +case("silu", {"x": f32(rng.uniform(-20, 20, 1_000_000))}, lambda i: F.silu(i["x"]), elementwise(lambda x: x / (1 + np.exp(-x)))) |
| 151 | +case("sinh", {"x": f32(rng.uniform(-10, 10, 1_000_000))}, lambda i: torch.sinh(i["x"]), elementwise(np.sinh)) |
| 152 | +case("cosh", {"x": f32(rng.uniform(-10, 10, 1_000_000))}, lambda i: torch.cosh(i["x"]), elementwise(np.cosh)) |
| 153 | +case("atan", {"x": f32(rng.uniform(-50, 50, 1_000_000))}, lambda i: torch.atan(i["x"]), elementwise(np.arctan)) |
| 154 | +case("rsqrt", {"x": f32(np.exp(rng.uniform(-14, 14, 1_000_000)))}, lambda i: torch.rsqrt(i["x"]), elementwise(lambda x: 1 / np.sqrt(x))) |
| 155 | +case("pow_2_5", {"x": f32(np.exp(rng.uniform(-6, 6, 1_000_000)))}, lambda i: torch.pow(i["x"], 2.5), elementwise(lambda x: x ** 2.5)) |
| 156 | + |
| 157 | +off = f32(rng.standard_normal((2048, 512)) + 1000) |
| 158 | +case("var_offset", {"x": off}, lambda i: i["x"].var(1, unbiased=False), |
| 159 | + lambda i: (i["x"].astype(np.float64).var(1), None)) |
| 160 | +bn = f32(rng.standard_normal((16, 8, 64)) + 1000) |
| 161 | +gn = f32(rng.standard_normal((16, 8, 64)) + 1000) |
| 162 | + |
| 163 | + |
| 164 | +def bn64(i): |
| 165 | + x = i["x"].astype(np.float64) |
| 166 | + m, v = x.mean((0, 2), keepdims=True), x.var((0, 2), keepdims=True) |
| 167 | + return (x - m) / np.sqrt(v + 1e-5), np.ones_like(x) |
| 168 | + |
| 169 | + |
| 170 | +def gn64(i): |
| 171 | + x = i["x"].astype(np.float64).reshape(16, 4, -1) |
| 172 | + m, v = x.mean(-1, keepdims=True), x.var(-1, keepdims=True) |
| 173 | + return ((x - m) / np.sqrt(v + 1e-5)).reshape(16, 8, 64), np.ones((16, 8, 64)) |
| 174 | + |
| 175 | + |
| 176 | +case("batch_norm_offset", {"x": bn}, lambda i: F.batch_norm(i["x"], None, None, None, None, True, 0.1, 1e-5), bn64) |
| 177 | +case("group_norm_offset", {"x": gn}, lambda i: F.group_norm(i["x"], 4, None, None, 1e-5), gn64) |
| 178 | +ca, cb = f32(rng.standard_normal((4096, 256))), f32(rng.standard_normal((4096, 256)) + 0.3) |
| 179 | +case("cosine_sim", {"a": ca, "b": cb}, lambda i: F.cosine_similarity(i["a"], i["b"], 1, 1e-8), |
| 180 | + lambda i: (lambda a, b: ((a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)), None))(i["a"].astype(np.float64), i["b"].astype(np.float64))) |
| 181 | +case("normalize_l2", {"x": ca}, lambda i: F.normalize(i["x"], 2.0, 1, 1e-12), |
| 182 | + lambda i: (lambda a: (a / np.linalg.norm(a, axis=1, keepdims=True), None))(i["x"].astype(np.float64))) |
| 183 | +case("mse", {"a": f32(rng.standard_normal(2_000_000) + 100), "b": f32(rng.standard_normal(2_000_000) + 100)}, lambda i: F.mse_loss(i["a"], i["b"]), |
| 184 | + lambda i: (lambda d: ((d ** 2).mean(), (d ** 2).mean()))(i["a"].astype(np.float64) - i["b"].astype(np.float64))) |
| 185 | + |
| 186 | + |
| 187 | +def main(): |
| 188 | + only = set(sys.argv[1:]) |
| 189 | + work = Path(tempfile.mkdtemp(prefix="oxideon_accuracy_")) |
| 190 | + manifest = [] |
| 191 | + selected = {k: v for k, v in cases.items() if not only or k in only} |
| 192 | + for name, (inputs, _, _) in selected.items(): |
| 193 | + for iname, arr in inputs.items(): |
| 194 | + fn = f"{name}.{iname}.in.f32" |
| 195 | + arr.tofile(work / fn) |
| 196 | + manifest.append(f"{name} {iname} {','.join(map(str, arr.shape))} {fn}") |
| 197 | + (work / "manifest.txt").write_text("\n".join(manifest)) |
| 198 | + 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 = [] |
| 211 | + for name, (inputs, torch_fn, ref_fn) in selected.items(): |
| 212 | + ref, scale = ref_fn(inputs) |
| 213 | + ref = np.asarray(ref, dtype=np.float64) |
| 214 | + scale = np.abs(np.asarray(ref if scale is None else scale, dtype=np.float64)) + 1e-300 |
| 215 | + ox = np.fromfile(work / f"{name}.oxideon.f32", dtype=np.float32).astype(np.float64).reshape(ref.shape) |
| 216 | + with torch.no_grad(): |
| 217 | + th = torch_fn({k: torch.from_numpy(v) for k, v in inputs.items()}).numpy().astype(np.float64).reshape(ref.shape) |
| 218 | + e_ox, e_th = np.abs(ox - ref) / scale / EPS, np.abs(th - ref) / scale / EPS |
| 219 | + wo, wt, mo, mt = e_ox.max(), e_th.max(), e_ox.mean(), e_th.mean() |
| 220 | + 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)) |
| 225 | + print(f"{name:20} | {wo:14.4f} {wt:10.4f} {fmt(bw):>9} | {mo:13.5f} {mt:10.5f} {fmt(bm):>9} | {verdict}") |
| 226 | + print() |
| 227 | + for v in ("exact", ">=2x", ">=1.5x", "better", "tie", "WORSE"): |
| 228 | + names = [n for n, x in rows if x == v] |
| 229 | + if names: |
| 230 | + print(f"{v:>7} ({len(names)}): {', '.join(names)}") |
| 231 | + print("\nverdict =the smaller of the two 'x better' figures (worst and mean); tie = within 5%; exact = both below 0.001 half-ulps.") |
| 232 | + |
| 233 | + |
| 234 | +if __name__ == "__main__": |
| 235 | + main() |
0 commit comments