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 / kernels / softmax.om

72 lines · 1833 bytes Raw Blame History
1note softmax: o[R,C] = exp(x - rowmax) / rowsum over the last dimension (aten._softmax, dim -1,
2note half_to_float false), row-major f32. Exponentials and sums are f64, each output rounded once to
3note f32. A row holding NaN gives NaN. The caller supplies const lines R C RC before this text.
4note expd: e^x in f64. x = k ln2 + r with k the nearest integer to x/ln2 and |r| <= ln2/2; e^r by the
5note degree-13 Taylor polynomial in Horner form (s = 1 + r s / n, n = 13 .. 1), whose truncation is
6note below 5.9e-18 relative (Wolfram: (Log[2]/2)^14/14! Exp[Log[2]/2] = 5.85e-18); then times 2^k
7note built from its exponent bits. Below -746 the result is 0 (e^x < 2^-1075, Wolfram: Log[2^-1074] =
8note -744.44); above 709.79 it is infinity (Log[$MaxMachineNumber] = 709.7827).
9fn expd x f64 to f64
10if ne x x
11ret x
12end
13if lt x -746.0f64
14ret 0.0f64
15end
16if gt x 709.79f64
17ret div 1.0f64 0.0f64
18end
19kf = mul x 1.442695040888963387f64
20ki = long kf
21fr = sub kf f64 ki
22if gt fr 0.5f64
23ki = add ki 1
24end
25if lt fr -0.5f64
26ki = sub ki 1
27end
28r = sub x mul f64 ki 0.6931471805599453094f64
29s = 1.0f64
30for j ulong 13
31n = f64 sub 13 j
32s = add 1.0f64 div mul r s n
33end
34sc = 1.0f64
35if lt ki -1000
36sc = bitcast f64 shl ulong 423 52
37ki = add ki 600
38end
39if gt ki 1000
40sc = bitcast f64 shl ulong 1623 52
41ki = sub ki 600
42end
43e = bitcast f64 shl ulong add ki 1023 52
44ret mul mul s e sc
45end
46note smrow: softmax of row i into o, through the f64 scratch row t.
47fn smrow x view f32 RC o edit f32 RC t edit f64 C i ulong to void
48b = mul i C
49m = get x b
50for j ulong C
51v = get x add b j
52if gt v m
53m = v
54end
55end
56mf = f64 m
57s = 0.0f64
58for j ulong C
59e = expd sub f64 get x add b j mf
60put t j e
61s = add s e
62end
63for j ulong C
64put o add b j f32 div get t j s
65end
66end
67fn softmax x view f32 RC o edit f32 RC to void
68t = new f64 C 0.0f64
69for i ulong R
70smrow x o t i
71end
72end