interplane.Get Omega
Read in your language

omega-dnn

aien-dev/omega-dnn

Brought by drakestapleton

branch main Branches Tags History

omega-dnn / tests / test_ops.py

215 lines · 11038 bytes Raw Blame History
1"""Randomized check of every omega-dnn op against torch float64 (docs/TOLERANCE.md).
2
3Usage: python tests/test_ops.py [cases_per_op] [seed]
4Prints one line per op (cases, worst err/tol, violations) and exits 1 on any violation.
5Each element must satisfy |y - ref| <= U32*|ref| + 2*gamma(n + 64)*M + 2^-149, with n and M per op.
6"""
7import os
8import sys
9
10import torch
11import torch.nn.functional as F
12
13sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "python"))
14import omega_dnn as od # noqa: E402
15
16U32 = 2.0 ** -24
17U64 = 2.0 ** -53
18TINY = 2.0 ** -149
19# Negative control only: OMEGA_DNN_TOL_SCALE=0.5 halves every bound and must produce violations.
20TOL_SCALE = float(os.environ.get("OMEGA_DNN_TOL_SCALE", "1"))
21
22
23def gamma(n):
24 return n * U64 / (1 - n * U64)
25
26
27class Checker:
28 def __init__(self):
29 self.rows = {}
30
31 def check(self, name, y, ref, n, mag):
32 y = y.double().reshape(ref.shape)
33 tol = (U32 * ref.abs() + 2 * gamma(n + 64) * mag + TINY) * TOL_SCALE
34 err = (y - ref).abs()
35 bad = int((~(err <= tol)).sum())
36 ratio = float((err / tol).max()) if err.numel() else 0.0
37 c, w, b = self.rows.get(name, (0, 0.0, 0))
38 self.rows[name] = (c + 1, max(w, ratio), b + bad)
39
40 def report(self):
41 total = 0
42 for name, (c, w, b) in self.rows.items():
43 print(f"{name:14s} cases={c:4d} worst_err/tol={w:.3f} violations={b}")
44 total += b
45 print(f"TOTAL ops={len(self.rows)} violations={total}")
46 return total
47
48
49def ri(g, lo, hi):
50 return int(torch.randint(lo, hi + 1, (1,), generator=g))
51
52
53def rn(g, *shape, scale=1.0):
54 return torch.randn(*shape, generator=g) * scale
55
56
57def run(cases, seed):
58 g = torch.Generator().manual_seed(seed)
59 ck = Checker()
60 for _ in range(cases):
61 # norms and softmax
62 R, C = ri(g, 1, 6), ri(g, 1, 300)
63 x = rn(g, R, C, scale=float(torch.rand(1, generator=g)) * 8 + 0.1)
64 w, b = rn(g, C), rn(g, C)
65 xd = x.double()
66 r = xd / torch.sqrt((xd * xd).mean(-1, keepdim=True) + 1e-6) * w.double()
67 ck.check("rms_norm", od.rms_norm(x, w, 1e-6), r, C, r.abs())
68 r = F.layer_norm(xd, (C,), w.double(), b.double(), 1e-5)
69 sd = torch.sqrt(xd.var(-1, unbiased=False, keepdim=True) + 1e-5)
70 mag = r.abs() + (xd.abs().amax(-1, keepdim=True) / sd) * w.double().abs() + b.double().abs()
71 ck.check("layer_norm", od.layer_norm(x, w, b), r, C, mag)
72 r = torch.softmax(xd, -1)
73 span = (xd - xd.amax(-1, keepdim=True)).abs()
74 ck.check("softmax", od.softmax(x), r, C, r * (1 + span) + r.amax(-1, keepdim=True) * span.amax(-1, keepdim=True))
75 xl = x * 300 # logits far past exp overflow: only a max-subtracted softmax survives
76 r = torch.softmax(xl.double(), -1)
77 span = (xl.double() - xl.double().amax(-1, keepdim=True)).abs()
78 ck.check("softmax_large", od.softmax(xl), r, C, r * (1 + span) + r.amax(-1, keepdim=True) * span.amax(-1, keepdim=True))
79 # elementwise
80 n = ri(g, 1, 5000)
81 a, bb = rn(g, n, scale=4), rn(g, n, scale=4)
82 ad, bd = a.double(), bb.double()
83 for nm, op, kw, ref in (
84 ("silu", od.SILU, {}, F.silu(ad)),
85 ("gelu_erf", od.GELU, {}, F.gelu(ad)),
86 ("gelu_tanh", od.GELU, {"gelu_tanh": True}, F.gelu(ad, approximate="tanh")),
87 ("relu", od.RELU, {}, torch.relu(ad)),
88 ):
89 ck.check(nm, od.elementwise(op, a, **kw), ref, 1, ref.abs() + ad.abs())
90 for nm, op, ref in (("swiglu", od.SWIGLU, F.silu(ad) * bd), ("add", od.ADD, ad + bd), ("mul", od.MUL, ad * bd)):
91 ck.check(nm, od.elementwise(op, a, bb), ref, 1, ref.abs() + ad.abs() * (1 + bd.abs()))
92 cols = ri(g, 1, 64)
93 a2, bias = rn(g, ri(g, 1, 20) * cols), rn(g, cols)
94 ref = (a2.double().view(-1, cols) + bias.double()).reshape(-1)
95 ck.check("bias", od.elementwise(od.BIAS, a2, bias, cols=cols), ref, 1, ref.abs())
96 # rope
97 B, H, S, D = ri(g, 1, 3), ri(g, 1, 4), ri(g, 1, 9), 2 * ri(g, 1, 32)
98 rot = 2 * ri(g, 1, D // 2)
99 maxp = ri(g, S, 64)
100 xr, cos, sin = rn(g, B, H, S, D), rn(g, maxp, rot // 2), rn(g, maxp, rot // 2)
101 pos = torch.randint(0, maxp, (B, S), generator=g)
102 for inter in (False, True):
103 xrd = xr.double()
104 c, s = cos.double()[pos][:, None], sin.double()[pos][:, None]
105 xp, rest = xrd[..., :rot], xrd[..., rot:]
106 x1, x2 = (xp[..., 0::2], xp[..., 1::2]) if inter else (xp[..., : rot // 2], xp[..., rot // 2:])
107 y1, y2 = x1 * c - x2 * s, x2 * c + x1 * s
108 yp = torch.stack([y1, y2], -1).reshape(xp.shape) if inter else torch.cat([y1, y2], -1)
109 ref = torch.cat([yp, rest], -1)
110 m1, m2 = x1.abs() * c.abs() + x2.abs() * s.abs(), x2.abs() * c.abs() + x1.abs() * s.abs()
111 mp = torch.stack([m1, m2], -1).reshape(xp.shape) if inter else torch.cat([m1, m2], -1)
112 mag = torch.cat([mp, rest.abs()], -1)
113 ck.check("rope_interleaved" if inter else "rope", od.rope(xr, cos, sin, pos, rot=rot, interleaved=inter), ref, 2, mag)
114 # matmul
115 M, N, K = ri(g, 1, 17), ri(g, 1, 70), ri(g, 1, 300)
116 A, Bm, bv = rn(g, M, K), rn(g, K, N), rn(g, N)
117 tb = bool(ri(g, 0, 1))
118 ref = A.double() @ Bm.double() + bv.double()
119 mag = A.double().abs() @ Bm.double().abs() + bv.double().abs()
120 ck.check("matmul", od.matmul(A, Bm.t().contiguous() if tb else Bm, bv, trans_b=tb), ref, K, mag)
121 # attention prefill (GQA, causal top-left)
122 B, Hkv = ri(g, 1, 2), ri(g, 1, 3)
123 Hq = Hkv * ri(g, 1, 3)
124 Sq, Skv, D = ri(g, 1, 20), ri(g, 1, 40), ri(g, 1, 96)
125 causal = bool(ri(g, 0, 1))
126 if causal:
127 Skv = max(Skv, Sq)
128 q, k, v = rn(g, B, Hq, Sq, D), rn(g, B, Hkv, Skv, D), rn(g, B, Hkv, Skv, D)
129 rep = Hq // Hkv
130 kd, vd = k.double().repeat_interleave(rep, 1), v.double().repeat_interleave(rep, 1)
131 scale = D ** -0.5
132 logits = q.double() @ kd.transpose(-1, -2) * scale
133 if causal:
134 logits = logits.masked_fill(torch.ones(Sq, Skv, dtype=torch.bool).triu(1), float("-inf"))
135 p = torch.softmax(logits, -1)
136 ref = p @ vd
137 lmag = (q.double().abs() @ kd.abs().transpose(-1, -2) * scale).amax(-1, keepdim=True)
138 mag = (p @ vd.abs()) * (1 + 2 * lmag) + ref.abs()
139 ck.check("attention", od.attention(q, k, v, causal=causal, block=ri(g, 1, 64)), ref, D + Skv, mag)
140 # paged decode
141 B, Hkv, D, bs = ri(g, 1, 3), ri(g, 1, 2), ri(g, 1, 64), ri(g, 1, 16)
142 Hq = Hkv * ri(g, 1, 4)
143 maxb, nblk = ri(g, 1, 5), 12
144 lens = torch.randint(1, maxb * bs + 1, (B,), generator=g)
145 table = torch.stack([torch.randperm(nblk, generator=g)[:maxb] for _ in range(B)])
146 qd, kc, vc = rn(g, B, Hq, D), rn(g, nblk, bs, Hkv, D), rn(g, nblk, bs, Hkv, D)
147 out = od.paged_decode(qd, kc, vc, table, lens)
148 rr, mm = [], []
149 for i in range(B):
150 Kb = kc[table[i]].reshape(-1, Hkv, D)[: lens[i]].double().repeat_interleave(Hq // Hkv, 1).transpose(0, 1)
151 Vb = vc[table[i]].reshape(-1, Hkv, D)[: lens[i]].double().repeat_interleave(Hq // Hkv, 1).transpose(0, 1)
152 lg = (qd[i].double()[:, None] @ Kb.transpose(-1, -2)) * D ** -0.5
153 pp = torch.softmax(lg, -1)
154 rr.append((pp @ Vb)[:, 0])
155 lm = (qd[i].double().abs()[:, None] @ Kb.abs().transpose(-1, -2) * D ** -0.5).amax(-1, keepdim=True)
156 mm.append(((pp @ Vb.abs()) * (1 + 2 * lm))[:, 0])
157 ref = torch.stack(rr)
158 ck.check("paged_decode", out, ref, D + maxb * bs, torch.stack(mm) + ref.abs())
159 # conv2d, both algorithms
160 gr = ri(g, 1, 3)
161 Cg, Og = ri(g, 1, 4), ri(g, 1, 4)
162 kh, kw, sh, sw = ri(g, 1, 4), ri(g, 1, 4), ri(g, 1, 3), ri(g, 1, 3)
163 ph, pw, dh, dw = ri(g, 0, kh // 2), ri(g, 0, kw // 2), ri(g, 1, 2), ri(g, 1, 2)
164 Hh, Ww = ri(g, dh * (kh - 1) + 1, 20), ri(g, dw * (kw - 1) + 1, 20)
165 xi, wi, bi = rn(g, ri(g, 1, 2), Cg * gr, Hh, Ww), rn(g, Og * gr, Cg, kh, kw), rn(g, Og * gr)
166 cargs = dict(stride=(sh, sw), padding=(ph, pw), dilation=(dh, dw), groups=gr)
167 ref = F.conv2d(xi.double(), wi.double(), bi.double(), **cargs)
168 mag = F.conv2d(xi.double().abs(), wi.double().abs(), bi.double().abs(), **cargs)
169 for al in (0, 1):
170 ck.check(f"conv2d_algo{al}", od.conv2d(xi, wi, bi, (sh, sw), (ph, pw), (dh, dw), gr, al), ref, Cg * kh * kw, mag)
171 # pooling
172 kh, kw = ri(g, 1, 4), ri(g, 1, 4)
173 sh, sw, ph, pw = ri(g, 1, 3), ri(g, 1, 3), ri(g, 0, kh // 2), ri(g, 0, kw // 2)
174 xp = rn(g, ri(g, 1, 2), ri(g, 1, 5), ri(g, kh, 18), ri(g, kw, 18))
175 pa = ((kh, kw), (sh, sw), (ph, pw))
176 ref = F.max_pool2d(xp.double(), *pa)
177 ck.check("maxpool", od.pool2d(xp, *pa), ref, 1, ref.abs())
178 cip = bool(ri(g, 0, 1))
179 ref = F.avg_pool2d(xp.double(), *pa, count_include_pad=cip)
180 ck.check("avgpool", od.pool2d(xp, *pa, avg=True, count_include_pad=cip), ref, kh * kw,
181 F.avg_pool2d(xp.double().abs(), *pa, count_include_pad=cip))
182 ref = xp.double().mean((2, 3), keepdim=True)
183 ck.check("global_avgpool", od.global_avg_pool(xp), ref, xp.shape[2] * xp.shape[3],
184 xp.double().abs().mean((2, 3), keepdim=True))
185 # fusion: MatMul -> bias -> SwiGLU in one pass, against f64 and against the unfused list
186 M, N, K = ri(g, 1, 8), ri(g, 1, 40), ri(g, 1, 80)
187 A, W, bv, Gt = rn(g, M, K), rn(g, K, N), rn(g, N), rn(g, M, N)
188 gph = od.Graph()
189 ia, iw, ib, ig = gph.input(A), gph.input(W), gph.input(bv), gph.input(Gt)
190 y1, y2, y3 = gph.empty(M * N), gph.empty(M * N), gph.empty(M * N)
191 gph.node(od.MATMUL, {1: ia, 2: iw, 3: y1, 4: M, 5: N, 6: K, 7: od.NONE, 8: 0})
192 gph.node(od.BIAS, {1: y1, 2: ib, 3: y2, 4: M * N, 5: N})
193 gph.node(od.SWIGLU, {1: y2, 2: ig, 3: y3, 4: M * N}, keep=True)
194 gph.materialize()
195 start = gph.arena.clone()
196 passes = gph.run(True)
197 fused = gph.out(y3, (M, N)).clone()
198 gph.arena.copy_(start)
199 passes0 = gph.run(False)
200 h = A.double() @ W.double() + bv.double()
201 ref = F.silu(h) * Gt.double()
202 mag = ((A.double().abs() @ W.double().abs() + bv.double().abs()) * (1 + h.abs()) + ref.abs()) * (1 + Gt.double().abs())
203 ck.check("fused_mm_bias_swiglu", fused, ref, K, mag)
204 if (passes, passes0) != (1, 3):
205 ck.rows["fusion_passes"] = (1, float("inf"), 1)
206 else:
207 c, w_, b_ = ck.rows.get("fusion_passes", (0, 0.0, 0))
208 ck.rows["fusion_passes"] = (c + 1, 0.0, b_)
209 return ck.report()
210
211
212if __name__ == "__main__":
213 cases = int(sys.argv[1]) if len(sys.argv) > 1 else 20
214 seed = int(sys.argv[2]) if len(sys.argv) > 2 else 20261027
215 sys.exit(1 if run(cases, seed) else 0)