Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-dnn/blob/main/python/omega_dnn/__init__.py # omega-dnn aien-dev/omega-dnn Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-dnn / python / omega_dnn / __init__.py` 269 lines ยท 8824 bytes Raw Blame History 1 """omega-dnn: deep-learning primitives compiled from om/dnn.om (seeded Omega, OM-2). 2 3 This module is the Python wrapper over the omega-bridge ABI v2 binding (build/omega_native.py, 4 generated, not edited). It owns no arithmetic: every value is computed by the Omega unit. The 5 wrapper lays tensors out in one float32 arena, writes the node descriptor (docs/DESCRIPTOR.md) 6 and calls ``dnn_run``. Tensors enter through DLPack (``torch.from_dlpack``) and leave as torch 7 tensors that view the arena (zero copy) or as copies. 8 """ 9 import ctypes 10 import importlib.util 11 import os 12 import struct 13 14 import torch 15 16 MAGIC = 0x4F444E 17 NONE = 0xFFFFFFFFFFFFFFFF 18 MAX_NODES = 31 19 KEEP = 2 20 21 RMS, LN, SOFTMAX, ROPE = 1, 2, 3, 4 22 SILU, GELU, SWIGLU, ADD, MUL, BIAS, RELU = 5, 6, 7, 8, 9, 10, 11 23 MATMUL, ATTN, PAGED_DECODE, CONV, MAXPOOL, AVGPOOL, GAP = 12, 13, 14, 15, 16, 17, 18 24 ELEMENTWISE = (SILU, GELU, SWIGLU, ADD, MUL, BIAS, RELU) 25 26 27 def _load_binding(): 28 d = os.environ.get("OMEGA_DNN_BUILD") or os.path.join( 29 os.path.dirname(os.path.abspath(__file__)), "..", "..", "build") 30 path = os.path.join(d, "omega_native.py") 31 spec = importlib.util.spec_from_file_location("omega_dnn_native", path) 32 mod = importlib.util.module_from_spec(spec) 33 spec.loader.exec_module(mod) 34 return mod 35 36 37 _nat = _load_binding() 38 39 40 class OmegaError(RuntimeError): 41 pass 42 43 44 def f64bits(x): 45 return struct.unpack(" 0xFFFFFFFF): 84 raise ValueError("uint32 side input out of range") 85 return self._place(t.numel(), ("i", t)) 86 87 def empty(self, n): 88 return self._place(n, None) 89 90 def node(self, op, args, keep=False): 91 if len(self._nodes) >= MAX_NODES: 92 raise ValueError("at most %d nodes" % MAX_NODES) 93 a = [0] * 16 94 a[0] = op 95 for k, v in args.items(): 96 if not 1 <= k <= 14: 97 raise ValueError("argument index %d" % k) 98 a[k] = int(v) 99 a[15] = KEEP if keep else 0 100 self._nodes.append(a) 101 return a[3] 102 103 def _desc(self, fuse): 104 words = [0] * 512 105 words[0] = MAGIC 106 words[1] = len(self._nodes) 107 words[2] = 1 if fuse else 0 108 for i, a in enumerate(self._nodes): 109 words[4 + 16 * i: 20 + 16 * i] = a 110 return (ctypes.c_ubyte * 4096).from_buffer_copy(struct.pack("<512Q", *words)) 111 112 def materialize(self): 113 self.arena = torch.zeros(self._size, dtype=torch.float32) 114 iv = self.arena.view(torch.int32) 115 for off, init in self._chunks: 116 if init is None: 117 continue 118 kind, t = init 119 if kind == "f": 120 self.arena[off: off + t.numel()] = t 121 else: 122 iv[off: off + t.numel()] = t.to(torch.uint32).view(torch.int32) if hasattr(torch, "uint32") else t.to(torch.int32) 123 return self.arena 124 125 def run(self, fuse=True): 126 if self.arena is None: 127 self.materialize() 128 desc = self._desc(fuse) 129 res = ctypes.c_uint64() 130 ws = ctypes.cast(self.arena.data_ptr(), ctypes.POINTER(ctypes.c_uint32)) 131 st = _nat.omega2_dnn_run(ctypes.byref(res), ws, self.arena.numel(), 132 ctypes.cast(desc, ctypes.c_char_p)) 133 if st: 134 raise OmegaError("dnn_run status %d" % st) 135 return res.value 136 137 def out(self, off, shape): 138 n = 1 139 for s in shape: 140 n *= int(s) 141 return self.arena[off: off + n].view(*shape) 142 143 144 def _one(op, ins, args, out_n, out_shape, ints=None, extra=None): 145 g = Graph() 146 offs = {k: g.input(v) for k, v in ins.items()} 147 for k, v in (ints or {}).items(): 148 offs[k] = g.ints(v) 149 for k, n in (extra or {}).items(): 150 offs[k] = g.empty(n) 151 offs[3] = g.empty(out_n) 152 a = dict(args) 153 a.update(offs) 154 g.node(op, a, keep=True) 155 g.run() 156 return g.out(offs[3], out_shape).clone() 157 158 159 def rms_norm(x, scale, eps=1e-6): 160 c = x.shape[-1] 161 return _one(RMS, {1: x, 2: scale}, {4: x.numel() // c, 5: c, 6: f64bits(eps)}, x.numel(), x.shape) 162 163 164 def layer_norm(x, scale, bias=None, eps=1e-5): 165 c = x.shape[-1] 166 ins = {1: x, 2: scale} 167 args = {4: x.numel() // c, 5: c, 6: f64bits(eps)} 168 if bias is None: 169 args[7] = NONE 170 else: 171 ins[7] = bias 172 return _one(LN, ins, args, x.numel(), x.shape) 173 174 175 def softmax(x): 176 c = x.shape[-1] 177 return _one(SOFTMAX, {1: x}, {4: x.numel() // c, 5: c}, x.numel(), x.shape) 178 179 180 def rope(x, cos, sin, pos, rot=0, interleaved=False): 181 b, h, s, d = x.shape 182 return _one(ROPE, {1: x, 2: cos, 4: sin}, 183 {6: b, 7: h, 8: s, 9: d, 10: rot, 11: 1 if interleaved else 0}, 184 x.numel(), x.shape, ints={5: pos}) 185 186 187 def elementwise(op, a, b=None, gelu_tanh=False, cols=0): 188 ins = {1: a} 189 if b is not None: 190 ins[2] = b 191 args = {4: a.numel()} 192 if op == GELU: 193 args[6] = 1 if gelu_tanh else 0 194 if op == BIAS: 195 args[5] = cols or b.numel() 196 return _one(op, ins, args, a.numel(), a.shape) 197 198 199 def matmul(a, b, bias=None, trans_b=False): 200 m, k = a.shape 201 n = b.shape[0] if trans_b else b.shape[1] 202 ins = {1: a, 2: b} 203 args = {4: m, 5: n, 6: k, 8: 1 if trans_b else 0} 204 if bias is None: 205 args[7] = NONE 206 else: 207 ins[7] = bias 208 return _one(MATMUL, ins, args, m * n, (m, n)) 209 210 211 def attention(q, k, v, causal=False, scale=None, block=64): 212 b, hq, sq, d = q.shape 213 hkv, skv = k.shape[1], k.shape[2] 214 sc = scale if scale is not None else d ** -0.5 215 return _one(ATTN, {1: q, 2: k, 4: v}, 216 {5: b, 6: hq, 7: hkv, 8: sq, 9: skv, 10: d, 11: 1 if causal else 0, 217 12: f64bits(sc), 13: block}, q.numel(), q.shape) 218 219 220 def paged_decode(q, k_cache, v_cache, block_table, seqlens, scale=None): 221 b, hq, d = q.shape 222 _, bs, hkv, _ = k_cache.shape 223 sc = scale if scale is not None else d ** -0.5 224 return _one(PAGED_DECODE, {1: q, 2: k_cache, 4: v_cache}, 225 {7: b, 8: hq, 9: hkv, 10: d, 11: bs, 12: block_table.shape[1], 13: f64bits(sc)}, 226 q.numel(), q.shape, ints={5: block_table, 6: seqlens}) 227 228 229 def _odim(h, k, s, p, dl): 230 return (h + 2 * p - dl * (k - 1) - 1) // s + 1 231 232 233 def _pack(vals): 234 w = 0 235 for i, v in enumerate(vals): 236 if not 0 <= v <= 255: 237 raise ValueError("packed conv/pool parameter out of 0..255") 238 w |= int(v) << (8 * i) 239 return w 240 241 242 def conv2d(x, w, bias=None, stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, algo=0): 243 n, c, h, wd = x.shape 244 o, cg, kh, kw = w.shape 245 oh = _odim(h, kh, stride[0], padding[0], dilation[0]) 246 ow = _odim(wd, kw, stride[1], padding[1], dilation[1]) 247 ins = {1: x, 2: w} 248 args = {6: n, 7: c, 8: h, 9: wd, 10: o, 12: groups, 13: algo, 249 11: _pack([kh, kw, stride[0], stride[1], padding[0], padding[1], dilation[0], dilation[1]])} 250 if bias is None: 251 args[4] = NONE 252 else: 253 ins[4] = bias 254 extra = {5: cg * kh * kw * oh * ow if algo == 1 else 1} 255 return _one(CONV, ins, args, n * o * oh * ow, (n, o, oh, ow), extra=extra) 256 257 258 def pool2d(x, kernel, stride, padding=(0, 0), avg=False, count_include_pad=False): 259 n, c, h, w = x.shape 260 oh = _odim(h, kernel[0], stride[0], padding[0], 1) 261 ow = _odim(w, kernel[1], stride[1], padding[1], 1) 262 args = {4: n * c, 5: h, 6: w, 8: 1 if count_include_pad else 0, 263 7: _pack([kernel[0], kernel[1], stride[0], stride[1], padding[0], padding[1]])} 264 return _one(AVGPOOL if avg else MAXPOOL, {1: x}, args, n * c * oh * ow, (n, c, oh, ow)) 265 266 267 def global_avg_pool(x): 268 n, c, h, w = x.shape 269 return _one(GAP, {1: x}, {4: n * c, 5: h * w}, n * c, (n, c, 1, 1))