omega-blas
aien-dev/omega-blas
Brought by drakestapleton
omega-blas / tests / smoke.py
| 1 | """Smoke check: cblas_sgemm / cblas_sgemv against a float64 numpy reference (omb_gemm_ex is not exercised here).""" |
| 2 | import ctypes as C |
| 3 | import os |
| 4 | import sys |
| 5 | |
| 6 | import numpy as np |
| 7 | |
| 8 | lib = C.CDLL(os.environ.get("OMEGABLAS_LIB", os.path.join(os.path.dirname(__file__), "..", "build", "libomegablas.so"))) |
| 9 | fp = C.POINTER(C.c_float) |
| 10 | lib.cblas_sgemm.argtypes = [C.c_int] * 6 + [C.c_float, fp, C.c_int, fp, C.c_int, C.c_float, fp, C.c_int] |
| 11 | lib.cblas_sgemv.argtypes = [C.c_int] * 4 + [C.c_float, fp, C.c_int, fp, C.c_int, C.c_float, fp, C.c_int] |
| 12 | P = lambda a: a.ctypes.data_as(fp) |
| 13 | rng = np.random.default_rng(1) |
| 14 | bad = 0 |
| 15 | for (m, n, k) in [(1, 1, 1), (2, 3, 4), (5, 7, 3), (17, 9, 300), (300, 260, 513)]: |
| 16 | for ta in (0, 1): |
| 17 | for tb in (0, 1): |
| 18 | a = rng.standard_normal((k, m) if ta else (m, k)).astype(np.float32) |
| 19 | b = rng.standard_normal((n, k) if tb else (k, n)).astype(np.float32) |
| 20 | c = rng.standard_normal((m, n)).astype(np.float32) |
| 21 | al, be = 1.5, -0.5 |
| 22 | ref = al * ((a.T if ta else a).astype(np.float64) @ (b.T if tb else b).astype(np.float64)) + be * c |
| 23 | out = c.copy() |
| 24 | lib.cblas_sgemm(101, 112 if ta else 111, 112 if tb else 111, m, n, k, al, P(a), a.shape[1], P(b), b.shape[1], be, P(out), n) |
| 25 | err = np.abs(out - ref).max() / max(1.0, np.abs(ref).max()) |
| 26 | ok = err < 1e-5 |
| 27 | bad += not ok |
| 28 | print(f"sgemm m={m} n={n} k={k} ta={ta} tb={tb} relerr={err:.2e} {'ok' if ok else 'FAIL'}") |
| 29 | a = rng.standard_normal((37, 23)).astype(np.float32) |
| 30 | for t in (0, 1): |
| 31 | x = rng.standard_normal(37 if t else 23).astype(np.float32) |
| 32 | y = rng.standard_normal(23 if t else 37).astype(np.float32) |
| 33 | ref = 2.0 * ((a.T if t else a).astype(np.float64) @ x) + 0.25 * y |
| 34 | out = y.copy() |
| 35 | lib.cblas_sgemv(101, 112 if t else 111, 37, 23, 2.0, P(a), 23, P(x), 1, 0.25, P(out), 1) |
| 36 | err = np.abs(out - ref).max() |
| 37 | bad += err > 1e-4 |
| 38 | print(f"sgemv t={t} abserr={err:.2e}") |
| 39 | print("FAILURES", bad) |
| 40 | sys.exit(1 if bad else 0) |