Skip to content

Commit d460f02

Browse files
committed
feat(core,cuda,io,deploy): SIMD/NEON, conv2d training, channels_last, int8 kernels, mmap, zero-copy views, grad checkpoint, graph tracing/fusion, PNG/JPEG, .pt writer, einops, deploy exporters, C API, WASM & no_std
1 parent 9b5f5b3 commit d460f02

110 files changed

Lines changed: 17775 additions & 893 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,46 @@
22

33
## Unreleased
44

5+
### Speed (accuracy unchanged unless noted)
6+
- Balanced `gelu` 150 -> 135 us per 1M elements (PyTorch 111 us): the tail exponent `poly - z^2` is never positive, so it uses an `exp` without the
7+
upper clamp and the NaN restore (a NaN input still gives NaN through `x * cdf`), the 0.5 of the cdf folds into the quotient factor, and
8+
two vectors run per iteration. Fastest `gelu` 113 -> 101 us. The measured errors are identical.
9+
- Balanced conv2d: the TwoSum error of each channel chain starts the next chain instead of living in a register set of its own (that
10+
spilled 24 vectors at every chain boundary), and from 32 input channels the chains are 8 deep. 4x64x56x56 conv2d 1690 -> 1340-1470 us
11+
(PyTorch 1529 us); 8x16x64x64 665 -> 640-660 us (PyTorch 512 us). Accuracy vs PyTorch (worst / mean): 16 channels 3.05x / 1.55x -> 2.69x /
12+
1.54x, 64 channels 4.64x / 2.99x -> 4.58x / 2.67x.
13+
14+
### Fixes
15+
- CUDA: `where_cond` with a broadcast mask (kernel declined) returned a host-backed tensor labelled `cuda:0`, so the next matmul failed with
16+
`device mismatch (cuda:0 vs cuda:0)` (attention with a causal mask on the composed path); it now returns CUDA storage.
17+
- NVRTC is loaded with the wide-character Windows loader, so it is found under a user directory with non-ASCII characters
18+
(`C:\Users\Jürgen\...`); before, the CUDA tests quietly skipped and every `.cu` kernel fell back to the host.
19+
- `ox.compile` sets `_compiled` once a call has been traced into a graph.
20+
- Examples: `gguf_generate` and `gguf_info`/`accuracy_dump` report a bad path, an unsupported tokenizer or a missing argument instead of
21+
panicking; `browser_demo` says that it is a simulation; the duplicate `tools/core_ops_bench_*.py` scripts are gone (use `benchmarks/`).
22+
23+
### Numerical accuracy (see `docs/NUMERICAL_ACCURACY.md`)
24+
- `PrecisionMode { Fastest, Balanced, Highest }`: one application-wide switch for `f32` matrix products (default `Balanced`; `Highest` does f64
25+
accumulation at ~1.9x the time of `Fastest`). Set with `oxideon_core::set_precision_mode`, the `OXIDEON_PRECISION` environment
26+
variable, or `oxideon.set_precision_mode("balanced")` in Python.
27+
- Float32 results measured against a float64 reference next to PyTorch (`benchmarks/accuracy_vs_pytorch.py`, 40 cases, worst and
28+
mean error together). Large wins on long sums/means/dot/norm (f64 accumulators), matmul, softmax/log_softmax, layer/batch/group
29+
norm and variance of offset data (accurate centring, `Tensor::centered_by_mean`), `cosine_similarity`, `softplus`, `elu`.
30+
- Default `Balanced` matmul: 48-deep f32 chains (matmul 2.35x / 1.66x better than PyTorch on worst / mean error); sigmoid, silu and tanh
31+
use a hi/lo `exp` (accurate to ~0.03 ulp; tanh now ties PyTorch on worst and mean, sigmoid/silu worst 2.5-2.8x better); Winograd convolution sums channels in TwoSum-combined chains (conv2d 3.0x / 1.5x and 4.6x / 3.0x); `normalize`
32+
(L2) and `var_axis` run in f64 on the host fast path.
33+
- `Fastest` matmul runs through the same block grid in 256-deep `f32` slices (was one `gemm` call: a 1x4096x4096 product took 2.5 ms, now 1.2 ms; matmul 512 / 1024 / k=4096 now 352 / 2823 / 707 us, all at or under PyTorch), and its k=512 error falls from about 6 to about 2.6 half-ulps. Balanced products inside a rayon worker run their chains serially instead of opening a parallel region per chain.
34+
- `Fastest` keeps plain `f32` accumulation for any `k` (the `f64` group combine of the long-`k` chain loop is `Balanced` only), the wide chain loop reuses per-thread work buffers, and the GELU mode is read once per tensor.
35+
- The buffer pool reads its limit and updates its byte accounting under one lock (a racing `give` could overshoot a freshly lowered limit, which made `typed_buffers_stay_inside_the_global_byte_limit` flaky).
36+
- `Fastest` mode evaluates GELU with a cheaper five-term erfc (150 -> 113 us per 1M elements, level with PyTorch; abs. CDF error ~1.5e-7).
37+
- Faster `Balanced` matmul (bit-identical results): the accumulation chains of one product run inside a single parallel region over output
38+
blocks instead of one region per chain (matmul 512: 568 -> 391 us, 1024: 4.5 -> 3.3 ms, k=4096: 2.05 -> 0.96 ms, MLP step 1.35 -> 1.0 ms;
39+
PyTorch 392 / 3045 / 804 / 832 us; with a 2-D block grid: 371 / 2813 / 866 / 860 us). The erfc polynomial of `gelu` and the plain `exp` polynomial use Estrin evaluation (gelu 184 -> 150 us, same error). Fused `layer_norm` variance is vectorized (83 -> 52 us, now faster than PyTorch and more accurate).
40+
- Faster: Winograd 3x3 convolution pipeline, fused unary backward, adaptive column blocks for leading-axis reductions.
41+
- Image codecs: PNG Adam7 interlacing and progressive JPEG decoding.
42+
- Fixed: `f32_row_broadcast` used x86 stubs on aarch64 (wrong layer-norm output on ARM); `c_char` portability on aarch64;
43+
stale `Linear` graph test.
44+
545
### Added
646
- Training and serving infrastructure (oxideon-core), each with tests:
747
- `loader`: `PrefetchLoader` (worker threads, output order independent of the worker count, per-epoch order fixed by

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ rayon = ["oxideon-core/rayon"]
4141
fast-gemm = ["oxideon-core/fast-gemm"]
4242
avx512 = ["oxideon-core/avx512"]
4343
wgpu = ["oxideon-core/wgpu"]
44+
wasm = ["oxideon-core/wasm"]
4445
python = ["dep:pyo3"]
4546
python-ext = ["python", "pyo3/extension-module"]
4647

‎README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,17 @@ cargo clippy --workspace --all-targets -- -D warnings
211211
pytest tests/ -q
212212
```
213213

214+
Environment notes (mostly Windows):
215+
216+
- **Embedded Python.** With `--features python`, the tests that start an interpreter (`complete_dl`, `complete_millennium`) need to
217+
find the standard library; set `PYTHONHOME` to your Python installation, or they abort with `No module named 'encodings'`.
218+
- **UTF-8 output.** The Python examples print characters such as `✓`. When their output is redirected on a console whose code page
219+
cannot show them, run Python with `-X utf8` (or set `PYTHONUTF8=1`).
220+
- **CUDA kernels.** The `.cu` kernels need NVRTC. Without it the CUDA tests print `skipped: no CUDA device / NVRTC` and pass, and the
221+
operations fall back to the host. Install it with `pip install --target <dir> nvidia-cuda-nvrtc-cu12` and set
222+
`OXIDEON_NVRTC_SITE=<dir>` (see `backend/nvrtc.rs` for the search order); `cuda_bench` then reports its launched kernels.
223+
- **Interop example.** `examples/python_interop_showcase.py` also needs `pillow`, `pandas`, `polars`, `networkx` and `sympy`.
224+
214225
---
215226

216227
## Note on Cryptography Modules

‎benchmarks/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,7 @@ python benchmarks/bench_vs_pytorch.py
5454

5555
- `CUDA matmul 1024x1024` (32x32 2x2 register-blocked PTX): **1.404 ms** (**1529.9 GFLOP/s**)
5656
- `CUDA matmul 2048x2048` (32x32 2x2 register-blocked PTX): **10.148 ms** (**1692.9 GFLOP/s**)
57+
58+
## Numerical accuracy
59+
60+
`accuracy_vs_pytorch.py` scores oxideon and PyTorch float32 results against a float64 reference (worst and mean error side by side); see [`docs/NUMERICAL_ACCURACY.md`](../docs/NUMERICAL_ACCURACY.md).

‎benchmarks/accuracy_vs_pytorch.py‎

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
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

Comments
 (0)