File size: 2,207 Bytes
7592937
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// µAI-32 inference in JavaScript: the forward pass of uai32.c, reading the audited model file byte-for-byte.
// File format (little-endian): u16 magic 0xA132, u16 NI, u16 NH, u16 NO, float32 mean[NI], float32 scale[NI],
// then bfloat16 W1[NH][NI+1] and W2[NO][NH+1] (last column = bias). Float32 arithmetic, as in the C program.
function uaiLoad(bytes) {
  const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  if (dv.getUint16(0, true) !== 0xA132) throw new Error("bad magic");
  const NI = dv.getUint16(2, true), NH = dv.getUint16(4, true), NO = dv.getUint16(6, true);
  const nw = NH * (NI + 1) + NO * (NH + 1);
  if (bytes.byteLength !== 8 + 8 * NI + 2 * nw) throw new Error("file size does not match header");
  const mean = new Float32Array(NI), scale = new Float32Array(NI), w = new Float32Array(nw), u = new Uint32Array(1), f = new Float32Array(u.buffer);
  for (let i = 0; i < NI; i++) { mean[i] = dv.getFloat32(8 + 4 * i, true); scale[i] = dv.getFloat32(8 + 4 * NI + 4 * i, true); }
  for (let i = 0; i < nw; i++) { u[0] = dv.getUint16(8 + 8 * NI + 2 * i, true) << 16; w[i] = f[0]; }
  return { NI, NH, NO, mean, scale, W1: w.subarray(0, NH * (NI + 1)), W2: w.subarray(NH * (NI + 1)), params: nw, bytes: bytes.byteLength };
}
function uaiPredict(m, x) {
  const f = Math.fround, xn = new Float32Array(m.NI), h = new Float32Array(m.NH), z = new Float64Array(m.NO);
  for (let i = 0; i < m.NI; i++) xn[i] = f(f(x[i] - m.mean[i]) * m.scale[i]);
  for (let j = 0; j < m.NH; j++) {
    const r = j * (m.NI + 1); let s = m.W1[r + m.NI];
    for (let i = 0; i < m.NI; i++) s = f(s + f(m.W1[r + i] * xn[i]));
    h[j] = s > 0 ? s : 0;
  }
  let mx = -Infinity;
  for (let k = 0; k < m.NO; k++) {
    const r = k * (m.NH + 1); let s = m.W2[r + m.NH];
    for (let j = 0; j < m.NH; j++) s = f(s + f(m.W2[r + j] * h[j]));
    z[k] = s; if (s > mx) mx = s;
  }
  let sum = 0; const p = new Array(m.NO);
  for (let k = 0; k < m.NO; k++) { p[k] = Math.exp(z[k] - mx); sum += p[k]; }
  let best = 0;
  for (let k = 0; k < m.NO; k++) { p[k] /= sum; if (p[k] > p[best]) best = k; }
  return { cls: best, p };
}
if (typeof module !== "undefined") module.exports = { uaiLoad, uaiPredict };