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-bridge/blob/main/pytorch/tests/test_omega_torch.py # omega-bridge Omega-first language interoperability: checked conversion backends and native language bindings 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-bridge / pytorch / tests / test_omega_torch.py` 247 lines ยท 10072 bytes Raw Blame History 1 """Milestone 1 checks for torch.compile(backend="omega"). CPU only; the oracle is eager PyTorch. 2 3 Run: CUDA_VISIBLE_DEVICES= OMEGA_OMC= python3 -m unittest -v pytorch/tests/test_omega_torch.py 4 Tolerance: torch.testing.assert_close float32 defaults (rtol 1.3e-6, atol 1e-5) against eager float32. 5 """ 6 7 import os 8 import re 9 import shutil 10 import subprocess 11 import sys 12 import tempfile 13 import unittest 14 15 import torch 16 import torch.nn as nn 17 18 sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) 19 import omega_torch as ot # noqa: E402 20 21 torch.manual_seed(0) 22 23 24 def compiled(fn): 25 torch._dynamo.reset() 26 return torch.compile(fn, backend="omega", fullgraph=True, dynamic=False) 27 28 29 def run_both(fn, *args): 30 ot.reset_stats() 31 with torch.no_grad(): 32 got = compiled(fn)(*args) 33 want = fn(*args) 34 return got, want 35 36 37 def two_ulp(got, ref64): 38 """|got - ref| <= 2^-22 |ref| elementwise: two float32 ulps from a float64 eager reference.""" 39 return bool(((got.double() - ref64).abs() <= ref64.abs() * 2.0 ** -22).all()) 40 41 42 class MLP(nn.Module): 43 def __init__(self, i=16, h=32, o=8): 44 super().__init__() 45 self.l1 = nn.Linear(i, h) 46 self.l2 = nn.Linear(h, o) 47 self.p = nn.Parameter(torch.randn(o, o)) 48 49 def forward(self, x, y): 50 h = torch.relu(self.l1(x)) + y 51 z = torch.matmul(self.l2(h), self.p) 52 return torch.softmax(z, dim=-1) 53 54 55 class Ops(unittest.TestCase): 56 """One op at a time, each through an Omega kernel, against eager float32.""" 57 58 def check(self, fn, *args, kernels): 59 got, want = run_both(fn, *args) 60 torch.testing.assert_close(got, want) 61 self.assertEqual(ot.STATS["eager_fallback_calls"], 0) 62 for k in kernels: 63 self.assertGreaterEqual(ot.STATS["per_op"].get(k, 0), 1, (k, ot.STATS)) 64 65 def test_mm(self): 66 self.check(torch.mm, torch.randn(5, 7), torch.randn(7, 3), kernels=["mm"]) 67 68 def test_addmm(self): 69 self.check(torch.addmm, torch.randn(3), torch.randn(5, 7), torch.randn(7, 3), kernels=["addmm"]) 70 71 def test_linear(self): 72 lin = nn.Linear(7, 3) 73 self.check(lin, torch.randn(5, 7), kernels=["linear"]) 74 self.assertNotIn("tr", ot.STATS["per_op"]) 75 76 def test_permute(self): 77 self.check(lambda x, y: x.t() + y, torch.randn(4, 6), torch.randn(6, 4), kernels=["tr", "eadd"]) 78 79 def test_add(self): 80 self.check(torch.add, torch.randn(3, 5), torch.randn(3, 5), kernels=["eadd"]) 81 82 def test_relu(self): 83 x = torch.randn(4, 9) 84 x[0, 0] = float("nan") 85 x[0, 1] = float("-inf") 86 x[0, 2] = float("inf") 87 got, want = run_both(torch.relu, x) 88 torch.testing.assert_close(got, want, equal_nan=True) 89 self.assertEqual(ot.STATS["per_op"], {"relu": 1}) 90 91 def test_softmax(self): 92 x = torch.randn(6, 11) * 40.0 93 x[1, 3] = float("-inf") 94 self.check(lambda t: torch.softmax(t, dim=-1), x, kernels=["softmax"]) 95 96 def test_softmax_two_ulp_of_float64(self): 97 # Stricter than the float32 default: within 2^-22 relative (2 float32 ulps) of eager float64. 98 # The default (atol 1e-5) cannot see an exp truncated at degree 4 (measured 4.9e-5 relative). 99 x = torch.randn(6, 11) * 4.0 100 got, _ = run_both(lambda t: torch.softmax(t, dim=-1), x) 101 self.assertTrue(two_ulp(got, torch.softmax(x.double(), dim=-1))) 102 103 def test_softmax_wolfram(self): 104 # WolframLanguageEvaluator: Exp[k]/(Exp[1]+Exp[2]+Exp[3]), k = 1, 2, 3, to 20 digits -> 105 # 0.`090030573170380457998`, 0.`24472847105479765247`, 0.`66524095577482188953`. 106 # Omega must give the float32 nearest to each exact value (one rounding of an f64 result). 107 exact = torch.tensor([[0.`090030573170380457998`, 0.`24472847105479765247`, 108 0.`66524095577482188953`]], dtype=torch.float64).to(torch.float32) 109 got, _ = run_both(lambda t: torch.softmax(t, dim=-1), torch.tensor([[1.0, 2.0, 3.0]])) 110 self.assertTrue(torch.equal(got, exact), (got, exact)) 111 112 def test_mm_exact_integers(self): 113 # Small integers: every product and sum is exact in f32, so Omega and eager must agree bitwise. 114 a = torch.randint(-9, 10, (6, 5)).float() 115 b = torch.randint(-9, 10, (5, 4)).float() 116 got, want = run_both(torch.mm, a, b) 117 self.assertTrue(torch.equal(got, want)) 118 119 120 class Model(unittest.TestCase): 121 def test_mlp_parity_and_all_omega(self): 122 m = MLP().eval() 123 x, y = torch.randn(4, 16), torch.randn(4, 32) 124 got, want = run_both(m, x, y) 125 torch.testing.assert_close(got, want) 126 s = ot.STATS 127 self.assertEqual(s["eager_fallback_calls"], 0) 128 self.assertEqual(s["per_op"], {"linear": 2, "relu": 1, "eadd": 1, "mm": 1, "softmax": 1}) 129 # Independent float64 eager reference: Omega's error is no larger than eager float32's plus 1e-7. 130 with torch.no_grad(): 131 ref = m.double()(x.double(), y.double()) 132 err_o = (got.double() - ref).abs().max().item() 133 err_e = (want.double() - ref).abs().max().item() 134 self.assertLessEqual(err_o, err_e + 1e-7, (err_o, err_e)) 135 136 137 class FailClosed(unittest.TestCase): 138 def test_unsupported_op_raises_and_runs_nothing(self): 139 ot.set_fallback(()) 140 ot.reset_stats() 141 with torch.no_grad(), self.assertRaises(Exception) as cm: 142 compiled(lambda x: torch.tanh(x) + x)(torch.randn(3, 3)) 143 self.assertIn("OmegaRefused", repr(cm.exception) + str(cm.exception)) 144 self.assertIn("aten.tanh.default", str(cm.exception)) 145 self.assertEqual(ot.STATS["omega_calls"], 0) 146 self.assertEqual(ot.STATS["eager_fallback_calls"], 0) 147 148 def test_broadcast_add_refused(self): 149 with torch.no_grad(), self.assertRaises(Exception) as cm: 150 compiled(lambda a, b: a + b)(torch.randn(3, 4), torch.randn(4)) 151 self.assertIn("broadcasting", str(cm.exception)) 152 153 def test_explicit_fallback_is_counted(self): 154 ot.set_fallback({"aten.tanh.default"}) 155 try: 156 got, want = run_both(lambda x: torch.tanh(x) + x, torch.randn(3, 3)) 157 finally: 158 ot.set_fallback(()) 159 torch.testing.assert_close(got, want) 160 self.assertEqual(ot.STATS["eager_fallback_calls"], 1) 161 self.assertEqual(ot.STATS["per_op"], {"eadd": 1}) 162 163 def test_array_limit_refused(self): 164 with torch.no_grad(), self.assertRaises(Exception) as cm: 165 compiled(torch.relu)(torch.zeros(4097, 4096)) 166 self.assertIn("above the Omega array limit `16777216`", str(cm.exception)) 167 168 def test_wrong_length_status_32(self): 169 fn = ot.load_unit("relu", [("L", 4)], 2) 170 with self.assertRaises(ot.OmegaCallError) as cm: 171 ot.call_unit(fn, "relu", [torch.zeros(5), torch.zeros(4)]) 172 self.assertIn("status 32", str(cm.exception)) 173 174 175 class NegativeControl(unittest.TestCase): 176 """Deliberately wrong kernels must make the parity checks fail.""" 177 178 def mutate(self, name, old, new): 179 d = tempfile.mkdtemp(prefix="omega-torch-mut-") 180 for f in os.listdir(ot.KERNEL_DIR): 181 shutil.copy(os.path.join(ot.KERNEL_DIR, f), d) 182 p = os.path.join(d, name + ".om") 183 with open(p) as f: 184 src = f.read() 185 self.assertIn(old, src) 186 with open(p, "w") as f: 187 f.write(src.replace(old, new, 1)) 188 return d 189 190 def with_kernels(self, d, fn, *args): 191 saved = ot.KERNEL_DIR 192 ot.KERNEL_DIR = d 193 try: 194 return run_both(fn, *args) 195 finally: 196 ot.KERNEL_DIR = saved 197 198 def test_mutant_linear_caught(self): 199 d = self.mutate("linear", "s = add s mul", "s = sub s mul") 200 got, want = self.with_kernels(d, MLP().eval(), torch.randn(4, 16), torch.randn(4, 32)) 201 with self.assertRaises(AssertionError): 202 torch.testing.assert_close(got, want) 203 204 def test_mutant_relu_caught(self): 205 d = self.mutate("relu", "if lt v 0.0f32", "if gt v 0.0f32") 206 got, want = self.with_kernels(d, torch.relu, torch.randn(4, 9)) 207 with self.assertRaises(AssertionError): 208 torch.testing.assert_close(got, want) 209 210 def test_mutant_softmax_caught(self): 211 # exp truncated at degree 4 instead of 13: 4.9e-5 relative error, which the float32 default 212 # tolerance (atol 1e-5) misses on probabilities this small; the two-ulp float64 check catches it. 213 d = self.mutate("softmax", "for j ulong 13\nn = f64 sub 13 j", "for j ulong 4\nn = f64 sub 4 j") 214 x = torch.randn(6, 11) * 4.0 215 got, _ = self.with_kernels(d, lambda t: torch.softmax(t, dim=-1), x) 216 self.assertFalse(two_ulp(got, torch.softmax(x.double(), dim=-1))) 217 218 219 class Binding(unittest.TestCase): 220 """src/native.om: f32 arrays and const-named lengths are bound; anything else is refused.""" 221 222 def gen(self, src): 223 with tempfile.NamedTemporaryFile() as t: 224 ot._compile_om(src.encode(), t.name) 225 code = t.read() 226 frame = src.encode() + b"\0" + b"%08d" % len(code) + code 227 p = subprocess.run([ot._native(), "c"], input=frame, capture_output=True) 228 return p.returncode, p.stdout.decode() 229 230 def test_const_f32_bound(self): 231 rc, c = self.gen("const L ulong 6\nfn k a view f32 L o edit f32 L to void\nput o 0 get a 0\nend\n") 232 self.assertEqual(rc, 0) 233 self.assertRegex(c, r"ombr_span_add\(sp, &ns, o_a, o_a_len, 6u, 4u, 0\)") 234 self.assertRegex(c, r"ombr_span_add\(sp, &ns, o_o, o_o_len, 6u, 4u, 1\)") 235 236 def test_const_not_ulong_refused(self): 237 # The compiler accepts a uint constant as a length; the binding reads only "const NAME ulong N". 238 rc, c = self.gen("const L uint 6\nfn k a view f32 L to void\nret\nend\n") 239 self.assertEqual((rc, c), (110, "")) 240 241 def test_f64_array_refused(self): 242 rc, c = self.gen("fn k a view f64 4 to void\nret\nend\n") 243 self.assertEqual((rc, c), (110, "")) 244 245 246 if __name__ == "__main__": 247 unittest.main()