interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / pytorch / omega_torch / __init__.py

333 lines · 13851 bytes Raw Blame History
1"""torch.compile(model, backend="omega"): core-ATen graphs run on Omega-generated AArch64 kernels.
2
3Interim Python glue (migration step, not the destination). This module only registers the backend,
4walks the FX graph, allocates output tensors and calls compiled Omega units through the omega-bridge
5native call ABI v1 (docs/NATIVE-ABI.md). It never computes a tensor value: every value an output holds
6was written by machine code the seeded Omega compiler produced from pytorch/kernels/*.om.
7
8Successor (named in docs/OMEGA-TORCH.md): the graph walk, shape specialisation and op dispatch move to
9an Omega unit behind the same bridge C ABI, driven from a PrivateUse1 "omega" device, so the Python
10side shrinks to the device registration PyTorch itself requires.
11
12Fail closed: an op outside SUPPORTED raises OmegaRefused at compile time, listing every refused node.
13An eager fallback happens only for ops the caller names in OMEGA_TORCH_FALLBACK (or set_fallback()),
14and every such call is counted in STATS["eager_fallback_calls"].
15"""
16
17import ctypes
18import hashlib
19import os
20import subprocess
21import tempfile
22import threading
23
24import torch
25from torch._dynamo import register_backend
26from torch._functorch.aot_autograd import aot_module_simplified
27from torch._decomp import core_aten_decompositions
28
29aten = torch.ops.aten
30
31# omega-mv main 369dbc96daa1684db2d7c2c7085bbf16b3fd77ee, seed/out/omc as committed (not rebuilt).
32OMC_SHA256 = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f"
33
34HERE = os.path.dirname(os.path.abspath(__file__))
35ROOT = os.path.dirname(os.path.dirname(HERE))
36KERNEL_DIR = os.environ.get("OMEGA_TORCH_KERNELS", os.path.join(ROOT, "pytorch", "kernels"))
37CACHE = os.environ.get("OMEGA_TORCH_CACHE", os.path.join(ROOT, "build", "torch"))
38
39STATS = {"graphs": 0, "omega_calls": 0, "eager_fallback_calls": 0, "units_built": 0, "per_op": {}}
40_FALLBACK = set(filter(None, os.environ.get("OMEGA_TORCH_FALLBACK", "").split(",")))
41_LOCK = threading.Lock()
42_LIBS = {}
43_NATIVE = None
44
45STATUS = {1: "overflow", 2: "divide by zero", 3: "bounds", 4: "loop bound", 5: "conversion",
46 6: "resource", 7: "shift", 32: "foreign argument refused", 33: "reentry",
47 34: "runtime entry not provided", 35: "no stack"}
48
49
50class OmegaRefused(RuntimeError):
51 """The graph holds work the Omega backend does not implement. Nothing ran."""
52
53
54class OmegaCallError(RuntimeError):
55 """A compiled Omega unit returned a nonzero status (trap or refused argument)."""
56
57
58def set_fallback(ops):
59 """Name the ops (e.g. "aten.tanh.default") that may run in eager PyTorch. Each call is counted."""
60 _FALLBACK.clear()
61 _FALLBACK.update(ops)
62
63
64def reset_stats():
65 STATS.update(graphs=0, omega_calls=0, eager_fallback_calls=0, per_op={})
66
67
68def _sha(path):
69 with open(path, "rb") as f:
70 return hashlib.sha256(f.read()).hexdigest()
71
72
73def _omc():
74 path = os.environ.get("OMEGA_OMC")
75 if not path:
76 raise OmegaRefused("set OMEGA_OMC to omega-mv seed/out/omc (sha256 %s)" % OMC_SHA256)
77 got = _sha(path)
78 if got != OMC_SHA256:
79 raise OmegaRefused("omc sha256 %s is not the pinned %s" % (got, OMC_SHA256))
80 return path
81
82
83def _compile_om(src, out):
84 with open(out, "wb") as o, tempfile.TemporaryFile() as err:
85 rc = subprocess.run([_omc()], input=src, stdout=o, stderr=err).returncode
86 err.seek(0)
87 msg = err.read().decode(errors="replace").strip()
88 if rc != 0 or msg:
89 os.unlink(out)
90 raise OmegaRefused("omc refused the unit (rc=%d): %s" % (rc, msg))
91
92
93def _native():
94 global _NATIVE
95 if _NATIVE is None:
96 os.makedirs(CACHE, exist_ok=True)
97 path = os.path.join(CACHE, "native-%s" % OMC_SHA256[:12])
98 with open(os.path.join(ROOT, "src", "native.om"), "rb") as f:
99 _compile_om(f.read(), path)
100 os.chmod(path, 0o700)
101 _NATIVE = path
102 return _NATIVE
103
104
105def unit_source(kernel, consts):
106 """The unit text: one "const NAME ulong V" line per shape constant, then the kernel file."""
107 head = "".join("const %s ulong %d\n" % (k, v) for k, v in consts)
108 with open(os.path.join(KERNEL_DIR, kernel + ".om"), "rb") as f:
109 return head.encode() + f.read()
110
111
112def load_unit(kernel, consts, nargs):
113 """Compile kernel specialised to consts, bind it with src/native.om, build and load the library.
114 Returns the ctypes function omega_<kernel>(uint64_t *result, (ptr, len) * nargs)."""
115 src = unit_source(kernel, consts)
116 with open(os.path.join(ROOT, "src", "native.om"), "rb") as f:
117 key = hashlib.sha256(src + OMC_SHA256.encode() + f.read()).hexdigest()[:24]
118 with _LOCK:
119 if key in _LIBS:
120 return _LIBS[key]
121 d = os.path.join(CACHE, key)
122 os.makedirs(d, exist_ok=True)
123 so = os.path.join(d, "lib%s.so" % kernel)
124 if not os.path.exists(so):
125 binp = os.path.join(d, kernel + ".bin")
126 _compile_om(src, binp)
127 with open(binp, "rb") as f:
128 code = f.read()
129 frame = src + b"\0" + b"%08d" % len(code) + code
130 cfile = os.path.join(d, "binding.c")
131 with open(cfile, "wb") as o:
132 rc = subprocess.run([_native(), "c"], input=frame, stdout=o, stderr=subprocess.DEVNULL).returncode
133 if rc != 0:
134 raise OmegaRefused("src/native.om refused unit %s (exit %d)" % (kernel, rc))
135 tmp = so + ".tmp"
136 subprocess.run(["cc", "-std=gnu11", "-O2", "-Wall", "-Wextra", "-Werror", "-fPIC", "-shared",
137 "-o", tmp, cfile], check=True)
138 os.replace(tmp, so)
139 STATS["units_built"] += 1
140 fn = getattr(ctypes.CDLL(so), "omega_" + kernel)
141 fn.argtypes = [ctypes.POINTER(ctypes.c_uint64)] + [ctypes.c_void_p, ctypes.c_uint64] * nargs
142 fn.restype = ctypes.c_uint32
143 _LIBS[key] = fn
144 return fn
145
146
147def call_unit(fn, name, tensors):
148 """Call a bound unit on f32 CPU tensors (borrowed for the call). Raises on any nonzero status."""
149 args = []
150 for t in tensors:
151 args += [t.data_ptr(), t.numel()]
152 res = ctypes.c_uint64(0)
153 st = fn(ctypes.byref(res), *args)
154 if st != 0:
155 raise OmegaCallError("omega_%s returned status %d (%s)" % (name, st, STATUS.get(st, "trap")))
156 STATS["omega_calls"] += 1
157 STATS["per_op"][name] = STATS["per_op"].get(name, 0) + 1
158
159
160# ---- graph lowering -----------------------------------------------------------------------------
161
162SUPPORTED = ("aten.mm.default", "aten.addmm.default", "aten.permute.default", "aten.add.Tensor",
163 "aten.relu.default", "aten._softmax.default")
164
165# Language limits at the pinned omc (OMEGESE 9.4): an array holds 1 .. 16777216 elements, and a
166# function's local arrays total at most 4 MiB (softmax keeps one f64 row: 8 bytes per column).
167OM_MAX_ARRAY = 16777216
168OM_MAX_LOCAL_BYTES = 4 << 20
169
170
171def _meta(n):
172 v = n.meta.get("val") if hasattr(n, "meta") else None
173 return v
174
175
176def _static_shape(v):
177 out = []
178 for s in v.shape:
179 if not isinstance(s, int):
180 return None
181 out.append(s)
182 return out
183
184
185def _check_tensor(v, why):
186 if not isinstance(v, torch.Tensor):
187 return why + ": not a tensor"
188 if v.dtype != torch.float32:
189 return why + ": dtype %s (only float32)" % v.dtype
190 if v.device.type != "cpu":
191 return why + ": device %s (only cpu)" % v.device
192 if _static_shape(v) is None:
193 return why + ": symbolic shape %s (compile with dynamic=False)" % (tuple(v.shape),)
194 if any(s == 0 for s in v.shape):
195 return why + ": empty tensor"
196 if v.numel() > OM_MAX_ARRAY:
197 return why + ": %d elements, above the Omega array limit %d (OMEGESE 9.4)" % (v.numel(), OM_MAX_ARRAY)
198 return None
199
200
201def _plan_node(n, users):
202 """Return (kernel, consts, input nodes) for n, or a refusal string."""
203 t = str(n.target)
204 ins = [a for a in n.args if isinstance(a, torch.fx.Node)]
205 for a in ins + [n]:
206 bad = _check_tensor(_meta(a), "%s %s" % (t, a.name))
207 if bad:
208 return bad
209 sh = lambda a: _static_shape(_meta(a))
210 if n.kwargs:
211 return "%s: keyword arguments %s not supported" % (t, dict(n.kwargs))
212 if t == "aten.mm.default":
213 a, b = n.args
214 (M, K), (K2, N) = sh(a), sh(b)
215 return ("mm", [("M", M), ("K", K), ("N", N), ("MK", M * K), ("KN", K * N), ("MN", M * N)], [a, b])
216 if t == "aten.addmm.default":
217 if len(n.args) != 3:
218 return "aten.addmm: beta/alpha other than 1 not supported"
219 c, a, b = n.args
220 if len(sh(a)) != 2 or len(sh(b)) != 2:
221 return "aten.addmm: operands must be 2-D"
222 (M, K), (K2, N) = sh(a), sh(b)
223 if sh(c) != [N]:
224 return "aten.addmm: bias shape %s (only a 1-D bias of length N=%d)" % (sh(c), N)
225 cs = [("M", M), ("K", K), ("N", N), ("MK", M * K)]
226 p = b
227 if p.op == "call_function" and str(p.target) == "aten.permute.default" and list(p.args[1]) == [1, 0] \
228 and len(users[p]) == 1:
229 # nn.Linear: read the [N,K] weight in place instead of materialising its transpose.
230 return ("linear", cs + [("NK", N * K), ("MN", M * N)], [c, a, p.args[0]])
231 return ("addmm", cs + [("KN", K * N), ("MN", M * N)], [c, a, b])
232 if t == "aten.permute.default":
233 x, dims = n.args
234 if len(sh(x)) != 2 or list(dims) != [1, 0]:
235 return "aten.permute: only 2-D [1, 0] (got dims %s on shape %s)" % (list(dims), sh(x))
236 R, C = sh(x)
237 return ("tr", [("R", R), ("C", C), ("RC", R * C)], [x])
238 if t == "aten.add.Tensor":
239 if len(n.args) != 2 or len(ins) != 2:
240 return "aten.add.Tensor: only tensor + tensor with alpha 1"
241 a, b = n.args
242 if sh(a) != sh(b):
243 return "aten.add.Tensor: broadcasting %s + %s not supported" % (sh(a), sh(b))
244 return ("eadd", [("L", _meta(a).numel())], [a, b])
245 if t == "aten.relu.default":
246 (x,) = n.args
247 return ("relu", [("L", _meta(x).numel())], [x])
248 if t == "aten._softmax.default":
249 x, dim, half = n.args
250 r = len(sh(x))
251 if half or (dim % r) != r - 1 or r != 2:
252 return "aten._softmax: only 2-D over the last dim, half_to_float False"
253 R, C = sh(x)
254 if 8 * C > OM_MAX_LOCAL_BYTES:
255 return "aten._softmax: row of %d columns exceeds the 4 MiB local-array limit" % C
256 return ("softmax", [("R", R), ("C", C), ("RC", R * C)], [x])
257 return "%s: no Omega kernel" % t
258
259
260def _lower(gm, example_inputs):
261 g = gm.graph
262 users = {n: list(n.users) for n in g.nodes}
263 steps, refused, fused = [], [], set()
264 for n in g.nodes:
265 if n.op in ("placeholder", "output"):
266 continue
267 if n.op != "call_function":
268 refused.append("%s (%s): only call_function nodes" % (n.name, n.op))
269 continue
270 t = str(n.target)
271 p = _plan_node(n, users) if t in SUPPORTED else "%s: no Omega kernel" % t
272 if isinstance(p, tuple):
273 if p[0] == "linear":
274 fused.add(n.args[2])
275 steps.append(("omega", n, p))
276 elif t in _FALLBACK:
277 steps.append(("eager", n, None))
278 else:
279 refused.append("%s: %s" % (n.name, p))
280 steps = [s for s in steps if s[1] not in fused or len(users[s[1]]) != 1]
281 if refused:
282 raise OmegaRefused("Omega backend refuses this graph (nothing ran; no eager fallback):\n "
283 + "\n ".join(refused))
284 compiled = []
285 for kind, n, p in steps:
286 if kind == "omega":
287 kernel, consts, ins = p
288 compiled.append((kind, n, kernel, load_unit(kernel, consts, len(ins) + 1), ins,
289 _static_shape(_meta(n))))
290 else:
291 compiled.append((kind, n, None, None, None, None))
292 placeholders = [n for n in g.nodes if n.op == "placeholder"]
293 (out_node,) = [n for n in g.nodes if n.op == "output"]
294 live_steps = [s for s in compiled if s[1] not in fused]
295 STATS["graphs"] += 1
296
297 def run(*args):
298 env = {}
299 for ph, a in zip(placeholders, args):
300 if isinstance(a, torch.Tensor) and not a.is_contiguous():
301 raise OmegaRefused("input %s is not contiguous; Omega kernels read row-major storage" % ph.name)
302 env[ph] = a
303 for kind, n, kernel, fn, ins, shape in live_steps:
304 if kind == "omega":
305 xs = [env[a] for a in ins]
306 o = torch.empty(shape, dtype=torch.float32)
307 call_unit(fn, kernel, xs + [o])
308 env[n] = o
309 else:
310 STATS["eager_fallback_calls"] += 1
311 a = torch.fx.node.map_arg(n.args, lambda x: env[x])
312 k = torch.fx.node.map_arg(n.kwargs, lambda x: env[x])
313 env[n] = n.target(*a, **k)
314 return tuple(torch.fx.node.map_arg(out_node.args[0], lambda x: env[x]))
315
316 run._omega_steps = [(s[0], s[2] or str(s[1].target)) for s in live_steps]
317 return run
318
319
320@register_backend
321def omega(gm, example_inputs):
322 """torch.compile backend "omega": inference only, float32 CPU, static shapes."""
323 if torch.is_grad_enabled() and any(getattr(x, "requires_grad", False) for x in example_inputs):
324 raise OmegaRefused("autograd is not supported by the Omega backend (milestone 1); "
325 "run the compiled model under torch.no_grad()")
326 if torch.cuda.is_available():
327 raise OmegaRefused("a CUDA device is visible; milestone 1 is CPU-only (set CUDA_VISIBLE_DEVICES=)")
328
329 def fw(g, inputs):
330 return _lower(g, inputs)
331
332 return aot_module_simplified(gm, example_inputs, fw_compiler=fw,
333 decompositions=core_aten_decompositions())