omega-bridge
Omega-first language interoperability: checked conversion backends and native language bindings
Brought by drakestapleton
omega-bridge / max-cpu / omatmul.om
| 1 | note omatmul.om: the Omega kernel behind the MAX CPU custom op "omega_matmul" (max-cpu/README.md). |
| 2 | note C[M,N] = A[M,K] @ B[K,N], row-major. A and B arrive as bfloat16 bit patterns in ONE view ab |
| 3 | note (A's M*K elements, then B's K*N): bf16 to f32 is exact (the 16 bits become the high half), each |
| 4 | note product of two bf16 values is exact in f32, and the K-term sum accumulates in f32 in order |
| 5 | note p = 0..K-1, one rounding per add (RNE, no fused multiply-add). C is written as f32 bit patterns. |
| 6 | note s holds the shape [M, K, N]. A, B and C cannot be three separate views because OM-2 function |
| 7 | note mode has six parameter slots and an unsized view takes two (spec/omegese-om2.md section 4). |
| 8 | note Result codes (status 0): 0 done; 1 a dimension is 0 or above 4096; 2 len ab is not M*K + K*N; |
| 9 | note 3 len c is not M*N. C is untouched unless the result is 0. Every index is also checked (trap 3). |
| 10 | om2 |
| 11 | fn bdot ab view ushort * ai ulong bj ulong k ulong n ulong to uint |
| 12 | acc = f32 0.0 |
| 13 | for p ulong k |
| 14 | x = bitcast f32 shl uint get ab add ai p 16 |
| 15 | y = bitcast f32 shl uint get ab add bj mul p n 16 |
| 16 | acc = add acc mul x y |
| 17 | end |
| 18 | ret bitcast uint acc |
| 19 | end |
| 20 | fn brow ab view ushort * c edit uint * s view ulong 3 i ulong to void |
| 21 | k = get s 1 |
| 22 | n = get s 2 |
| 23 | ka = mul get s 0 k |
| 24 | ai = mul i k |
| 25 | ci = mul i n |
| 26 | for j ulong n |
| 27 | put c add ci j bdot ab ai add ka j k n |
| 28 | end |
| 29 | end |
| 30 | export fn omatmul ab view ushort * c edit uint * s view ulong 3 to ulong |
| 31 | m = get s 0 |
| 32 | k = get s 1 |
| 33 | n = get s 2 |
| 34 | if or or eq m 0 eq k 0 eq n 0 |
| 35 | ret 1 |
| 36 | end |
| 37 | if or or gt m 4096 gt k 4096 gt n 4096 |
| 38 | ret 1 |
| 39 | end |
| 40 | ka = mul m k |
| 41 | if ne len ab add ka mul k n |
| 42 | ret 2 |
| 43 | end |
| 44 | if ne len c mul m n |
| 45 | ret 3 |
| 46 | end |
| 47 | for i ulong m |
| 48 | brow ab c s i |
| 49 | end |
| 50 | ret 0 |
| 51 | end |