interplane.Get Omega
Read in your language

omega-blas

aien-dev/omega-blas

Brought by drakestapleton

branch main Branches Tags History

omega-blas / python / omegablas / __init__.py

270 lines · 11629 bytes Raw Blame History
1"""omegablas: Python binding of libomegablas (aien-dev/omega-blas) over DLPack.
2
3Operands are any object with ``__dlpack__`` (numpy, torch, jax, cupy-on-host, ...) on the CPU
4device, or a numpy array (which also covers the ml_dtypes bfloat16 / float8 dtypes that numpy
5cannot export through DLPack). Nothing is copied: the library reads the producer's memory through
6the DLPack pointer, shape and strides, and writes C in place.
7
8 import numpy as np, omegablas as ob
9 c = ob.gemm(a, b, alpha=1.0, bias=v, bias_axis="col", act="gelu_tanh")
10
11Element types: float32, float16, bfloat16, float8_e4m3fn, float8_e5m2 for A and B; float32,
12float16, bfloat16 for C. Accumulation is f32 (see docs/TOLERANCE.md).
13"""
14import ctypes as _C
15import os as _os
16
17__all__ = ["gemm", "gemv", "widen", "narrow", "ident", "lib", "Tensor", "tensor"]
18
19F32, F16, BF16, E4M3, E5M2 = 0, 1, 2, 3, 4
20_ROW, _NT, _T = 101, 111, 112
21_ACT = {"none": 0, None: 0, "relu": 1, "gelu_tanh": 2}
22_BIAS = {None: 0, "row": 1, "col": 2}
23_SIZE = {F32: 4, F16: 2, BF16: 2, E4M3: 1, E5M2: 1}
24# DLPack 1.1 DLDataTypeCode: (code, bits) -> omb_type
25_DL = {(2, 32): F32, (2, 16): F16, (4, 16): BF16, (10, 8): E4M3, (12, 8): E5M2}
26_NP = {"float32": F32, "float16": F16, "bfloat16": BF16, "float8_e4m3fn": E4M3, "float8_e5m2": E5M2}
27
28
29def _load():
30 p = _os.environ.get("OMEGABLAS_LIB")
31 if not p:
32 here = _os.path.dirname(_os.path.abspath(__file__))
33 for cand in (_os.path.join(here, "libomegablas.so"),
34 _os.path.join(here, "..", "..", "build", "libomegablas.so")):
35 if _os.path.exists(cand):
36 p = cand
37 break
38 if not p:
39 raise OSError("libomegablas.so not found: build it (make) or set OMEGABLAS_LIB")
40 lib = _C.CDLL(p)
41 i, f, v, i64 = _C.c_int, _C.c_float, _C.c_void_p, _C.c_int64
42 lib.omb_gemm_ex.argtypes = [i, i, i, i, i, i, f, v, i, i, v, i, i, f, v, i, i, v, i, i]
43 lib.omb_gemm_ex.restype = i
44 lib.omb_gemm_strided_batched.argtypes = [i, i, i, i, i, i, f, v, i, i, i64, v, i, i, i64, f,
45 v, i, i, i64, i]
46 lib.omb_gemm_strided_batched.restype = i
47 lib.omb_gemm_batched.argtypes = [i, i, i, i, i, i, f, v, i, i, v, i, i, f, v, i, i, i]
48 lib.omb_gemm_batched.restype = i
49 lib.cblas_sgemv.argtypes = [i, i, i, i, f, v, i, v, i, f, v, i]
50 lib.cblas_sgemv.restype = None
51 lib.cblas_sgemm.argtypes = [i, i, i, i, i, i, f, v, i, v, i, f, v, i]
52 lib.cblas_sgemm.restype = None
53 lib.omb_widen.argtypes = [i, v, v, _C.c_size_t]
54 lib.omb_narrow.argtypes = [i, v, v, _C.c_size_t]
55 lib.omb_ident.restype = _C.c_char_p
56 return lib
57
58
59lib = _load()
60
61
62class _DLDevice(_C.Structure):
63 _fields_ = [("device_type", _C.c_int32), ("device_id", _C.c_int32)]
64
65
66class _DLDataType(_C.Structure):
67 _fields_ = [("code", _C.c_uint8), ("bits", _C.c_uint8), ("lanes", _C.c_uint16)]
68
69
70class _DLTensor(_C.Structure):
71 _fields_ = [("data", _C.c_void_p), ("device", _DLDevice), ("ndim", _C.c_int32),
72 ("dtype", _DLDataType), ("shape", _C.POINTER(_C.c_int64)),
73 ("strides", _C.POINTER(_C.c_int64)), ("byte_offset", _C.c_uint64)]
74
75
76class _DLManagedTensor(_C.Structure):
77 _fields_ = [("dl_tensor", _DLTensor), ("manager_ctx", _C.c_void_p), ("deleter", _C.c_void_p)]
78
79
80_capsule_ptr = _C.pythonapi.PyCapsule_GetPointer
81_capsule_ptr.restype = _C.c_void_p
82_capsule_ptr.argtypes = [_C.py_object, _C.c_char_p]
83
84
85class Tensor:
86 """A borrowed view: address of element 0, omb_type, shape and strides (in elements).
87
88 ``keep`` holds the producer object and its DLPack capsule (unconsumed, so the producer's
89 capsule destructor releases it) for the life of the view."""
90 __slots__ = ("ptr", "dtype", "shape", "strides", "keep")
91
92 def __init__(self, ptr, dtype, shape, strides, keep):
93 self.ptr, self.dtype, self.shape, self.strides, self.keep = ptr, dtype, shape, strides, keep
94
95
96def tensor(x):
97 """Borrow x through DLPack (CPU device), or through the numpy array interface."""
98 if isinstance(x, Tensor):
99 return x
100 try:
101 import numpy as np
102 if isinstance(x, np.ndarray) and x.dtype.name in _NP and x.dtype.name not in ("float32", "float16"):
103 ai = x.__array_interface__
104 st = tuple(s // x.itemsize for s in x.strides)
105 if any(s * x.itemsize != b for s, b in zip(st, x.strides)):
106 raise ValueError("omegablas: strides must be whole elements")
107 return Tensor(ai["data"][0], _NP[x.dtype.name], tuple(x.shape), st, x)
108 except ImportError:
109 pass
110 if not hasattr(x, "__dlpack__"):
111 raise TypeError("omegablas: operand has no __dlpack__ and is not a numpy array")
112 cap = x.__dlpack__()
113 mt = _DLManagedTensor.from_address(_capsule_ptr(cap, b"dltensor"))
114 t = mt.dl_tensor
115 if t.device.device_type != 1:
116 raise ValueError(f"omegablas: device type {t.device.device_type} is not kDLCPU "
117 "(GPU operands go through CUDApp; not wired in this binding)")
118 key = (t.dtype.code, t.dtype.bits)
119 if t.dtype.lanes != 1 or key not in _DL:
120 raise TypeError(f"omegablas: unsupported DLPack dtype code={t.dtype.code} bits={t.dtype.bits}"
121 f" lanes={t.dtype.lanes}")
122 nd = t.ndim
123 shape = tuple(t.shape[i] for i in range(nd))
124 if t.strides:
125 strides = tuple(t.strides[i] for i in range(nd))
126 else:
127 strides, acc = [], 1
128 for d in reversed(shape):
129 strides.append(acc)
130 acc *= max(d, 1)
131 strides = tuple(reversed(strides))
132 return Tensor((t.data or 0) + t.byte_offset, _DL[key], shape, strides, (x, cap))
133
134
135def _mat(t, name):
136 """(trans, ld) of a 2-D view for a row-major call; strides of length-1 axes are free."""
137 r, c = t.shape[-2], t.shape[-1]
138 s0, s1 = t.strides[-2], t.strides[-1]
139 if c == 1 or s1 == 1:
140 if r == 1 or s0 >= max(c, 1):
141 return _NT, max(s0 if r > 1 else c, c, 1)
142 if r == 1 or s0 == 1:
143 if c == 1 or s1 >= max(r, 1):
144 return _T, max(s1 if c > 1 else r, r, 1)
145 raise ValueError(f"omegablas: {name} needs one unit stride and a leading stride >= its extent "
146 f"(shape {t.shape[-2:]}, strides {t.strides[-2:]})")
147
148
149def _out(c, shape, out_dtype):
150 if c is not None:
151 return c, tensor(c)
152 import numpy as np
153 if out_dtype == "bfloat16":
154 import ml_dtypes
155 dt = ml_dtypes.bfloat16
156 else:
157 dt = np.dtype(out_dtype)
158 arr = np.zeros(shape, dtype=dt)
159 return arr, tensor(arr)
160
161
162def gemm(a, b, c=None, *, alpha=1.0, beta=0.0, bias=None, bias_axis=None, act="none",
163 out_dtype="float32"):
164 """C = act(alpha * a @ b + beta * C + bias); a (M,K) or (batch,M,K), b (K,N) or (batch,K,N).
165
166 bias_axis "row" adds bias[i] (length M), "col" adds bias[j] (length N). C is written in place
167 when given (it must have a unit last stride); otherwise a new numpy array is returned."""
168 ta_, tb_ = tensor(a), tensor(b)
169 if len(ta_.shape) != len(tb_.shape) or len(ta_.shape) not in (2, 3):
170 raise ValueError("omegablas.gemm: a and b must both be 2-D or both 3-D")
171 m, k = ta_.shape[-2:]
172 k2, n = tb_.shape[-2:]
173 if k != k2:
174 raise ValueError(f"omegablas.gemm: inner dimensions {k} and {k2} differ")
175 batched = len(ta_.shape) == 3
176 nb = ta_.shape[0] if batched else 1
177 if batched and tb_.shape[0] != nb:
178 raise ValueError("omegablas.gemm: batch sizes differ")
179 res, tc = _out(c, (nb, m, n) if batched else (m, n), out_dtype)
180 if tuple(tc.shape) != ((nb, m, n) if batched else (m, n)):
181 raise ValueError(f"omegablas.gemm: C has shape {tc.shape}")
182 if tc.dtype not in (F32, F16, BF16):
183 raise TypeError("omegablas.gemm: C must be float32, float16 or bfloat16")
184 if n > 1 and tc.strides[-1] != 1:
185 raise ValueError("omegablas.gemm: C needs a unit last stride")
186 ldc = max(tc.strides[-2] if m > 1 else n, n, 1)
187 tra, lda = _mat(ta_, "a")
188 trb, ldb = _mat(tb_, "b")
189 bptr, bmode = None, _BIAS[bias_axis]
190 if bias is not None:
191 tv = tensor(bias)
192 want = m if bias_axis == "row" else n
193 if bias_axis is None or tv.dtype != F32 or tv.shape != (want,) or (want > 1 and tv.strides[0] != 1):
194 raise ValueError(f"omegablas.gemm: bias must be contiguous float32 of length {want} "
195 "with bias_axis 'row' or 'col'")
196 bptr = tv.ptr
197 elif bmode:
198 raise ValueError("omegablas.gemm: bias_axis given without bias")
199 av = _ACT[act]
200 if batched and not bptr and not av:
201 rc = lib.omb_gemm_strided_batched(_ROW, tra, trb, m, n, k, alpha, ta_.ptr, ta_.dtype, lda,
202 ta_.strides[0], tb_.ptr, tb_.dtype, ldb, tb_.strides[0],
203 beta, tc.ptr, tc.dtype, ldc, tc.strides[0], nb)
204 else:
205 rc = 0
206 for i in range(nb):
207 oa = ta_.strides[0] * i * _SIZE[ta_.dtype] if batched else 0
208 ob = tb_.strides[0] * i * _SIZE[tb_.dtype] if batched else 0
209 oc = tc.strides[0] * i * _SIZE[tc.dtype] if batched else 0
210 rc = lib.omb_gemm_ex(_ROW, tra, trb, m, n, k, alpha, (ta_.ptr or 0) + oa, ta_.dtype, lda,
211 (tb_.ptr or 0) + ob, tb_.dtype, ldb, beta, (tc.ptr or 0) + oc, tc.dtype,
212 ldc, bptr, bmode, av)
213 if rc:
214 break
215 if rc:
216 raise ValueError(f"omegablas.gemm: library rejected argument {rc}")
217 return res
218
219
220def gemv(a, x, y=None, *, alpha=1.0, beta=0.0, trans=False):
221 """y = alpha * op(a) @ x + beta * y in float32 (cblas_sgemv); x and y may have any stride."""
222 ta_, tx = tensor(a), tensor(x)
223 if len(ta_.shape) != 2 or len(tx.shape) != 1 or ta_.dtype != F32 or tx.dtype != F32:
224 raise ValueError("omegablas.gemv: a must be 2-D float32 and x 1-D float32")
225 m, n = ta_.shape
226 lx, ly = (m, n) if trans else (n, m)
227 if tx.shape[0] != lx:
228 raise ValueError(f"omegablas.gemv: x has length {tx.shape[0]}, expected {lx}")
229 res, ty = _out(y, (ly,), "float32")
230 if ty.shape != (ly,) or ty.dtype != F32:
231 raise ValueError(f"omegablas.gemv: y must be float32 of length {ly}")
232 tr, lda = _mat(ta_, "a")
233 if tr == _T: # a stored as a^T in row-major: swap the operation instead
234 trans = not trans
235 m, n = n, m
236 ix = tx.strides[0] if lx > 1 else 1
237 iy = ty.strides[0] if ly > 1 else 1
238 if ix == 0 or iy == 0:
239 raise ValueError("omegablas.gemv: zero stride")
240 # BLAS addresses a negative increment from the lowest element
241 px = tx.ptr + (min(ix, 0) * (lx - 1)) * 4
242 py = ty.ptr + (min(iy, 0) * (ly - 1)) * 4
243 lib.cblas_sgemv(_ROW, _T if trans else _NT, m, n, alpha, ta_.ptr, lda, px, ix, beta, py, iy)
244 return res
245
246
247def widen(x):
248 """float32 copy of a contiguous float16/bfloat16/float8 array (exact)."""
249 import numpy as np
250 t = tensor(x)
251 n = 1
252 for d in t.shape:
253 n *= d
254 out = np.empty(t.shape, np.float32)
255 lib.omb_widen(t.dtype, t.ptr, out.ctypes.data, n)
256 return out
257
258
259def narrow(x, dtype):
260 """Round a contiguous float32 array to float16 or bfloat16 (round to nearest even)."""
261 import numpy as np
262 src = np.ascontiguousarray(x, np.float32)
263 res, t = _out(None, src.shape, dtype)
264 lib.omb_narrow(t.dtype, src.ctypes.data, t.ptr, src.size)
265 return res
266
267
268def ident():
269 """Identity of the bound Omega unit (om/blas.om source and compiler sha256)."""
270 return lib.omb_ident().decode()