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