aien-train
AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished.
Brought by drakestapleton
aien-train / tests / adtrain / gradient.wl
| 1 | (* SPDX-License-Identifier: AGPL-3.0-only *) |
| 2 | (* adtrain exact-rational gradient oracle (Wolfram Language; verification only). |
| 3 | Inputs, prepended by the caller from one run of the suite: |
| 4 | gbits = {58 integers} bit patterns of the `G <i> <bits>` rows (run/G.stdout) |
| 5 | kref = {10 integers} the `K <i> <k>` rows (run/D.stdout) |
| 6 | l0bits = integer the `L 0 <bits>` row (run/T.stdout) |
| 7 | Regenerates the seed-17 data and initial parameters exactly, fixes the relu |
| 8 | pattern (x > 0, the tape's rule) from the exact forward, differentiates the |
| 9 | exact loss symbolically, and compares every tape value against the declared |
| 10 | bound |om - exact| <= 2^-16 Max[1, |exact|]. *) |
| 11 | mask64 = 2^64 - 1; |
| 12 | xs[x_] := Module[{y = x}, |
| 13 | y = BitXor[y, BitAnd[BitShiftLeft[y, 13], mask64]]; |
| 14 | y = BitXor[y, BitShiftRight[y, 7]]; |
| 15 | BitXor[y, BitAnd[BitShiftLeft[y, 17], mask64]]]; |
| 16 | ks = Mod[Rest[NestList[xs, 17, 96]], 17] - 8; |
| 17 | xv = Partition[ks[[1 ;; 32]]/8, 4]; |
| 18 | tv = Partition[ks[[33 ;; 48]]/8, 2]; |
| 19 | w1v = Partition[ks[[49 ;; 80]]/16, 8]; |
| 20 | w2v = Partition[ks[[81 ;; 96]]/16, 2]; |
| 21 | w1s = Array[a, {4, 8}]; b1s = Array[b, 8]; w2s = Array[c, {8, 2}]; b2s = Array[d, 2]; |
| 22 | params = Join[Flatten[w1s], b1s, Flatten[w2s], b2s]; |
| 23 | point = Thread[params -> Join[Flatten[w1v], ConstantArray[0, 8], Flatten[w2v], ConstantArray[0, 2]]]; |
| 24 | pre = xv . w1s + ConstantArray[b1s, 8]; |
| 25 | preV = pre /. point; |
| 26 | relu = Map[Boole[# > 0] &, preV, {2}]; |
| 27 | y = (relu*pre) . w2s + ConstantArray[b2s, 8]; |
| 28 | loss = Total[(y - tv)^2, 2]; |
| 29 | gex = D[loss, {params}] /. point; |
| 30 | lex = loss /. point; |
| 31 | f32[u_] := Module[{s = BitShiftRight[u, 31], e = BitAnd[BitShiftRight[u, 23], 255], |
| 32 | m = BitAnd[u, 2^23 - 1]}, |
| 33 | (-1)^s If[e == 0, m 2^-149, (2^23 + m) 2^(e - 150)]]; |
| 34 | gom = f32 /@ gbits; |
| 35 | bound = 2^-16 Max[1, Abs[#]] & /@ gex; |
| 36 | diff = Abs[gom - gex]; |
| 37 | lom = f32[l0bits]; |
| 38 | <|"kMatch" -> (ks[[1 ;; 10]] === kref), |
| 39 | "zeroPreActivations" -> Count[Flatten[preV], 0], |
| 40 | "reluActive" -> Total[Flatten[relu]], |
| 41 | "n" -> Length[gex], |
| 42 | "allWithin" -> And @@ Thread[diff <= bound], |
| 43 | "exactEqual" -> Count[diff, 0], |
| 44 | "maxDiffOverBound" -> N[Max[diff/bound]], |
| 45 | "maxAbsDiff" -> N[Max[diff]], |
| 46 | "lossExact" -> lex, "lossOm" -> lom, |
| 47 | "lossWithin" -> (Abs[lom - lex] <= 2^-16 Max[1, Abs[lex]]), |
| 48 | "lossRelErr" -> N[Abs[lom - lex]/Abs[lex]]|> |