File size: 10,268 Bytes
8246b15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Falcon-H1-Tiny-90M inference + exact widening, pure JS (Float32). No training, no dependencies.
export function parseSafetensors(buf) {
  const dv = new DataView(buf);
  const hlen = Number(dv.getBigUint64(0, true));
  const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 8, hlen)));
  const base = 8 + hlen, out = {};
  for (const [name, m] of Object.entries(header)) {
    if (name === '__metadata__') continue;
    const [s, e] = m.data_offsets, n = (e - s) / (m.dtype === 'F32' ? 4 : 2);
    const f = new Float32Array(n);
    if (m.dtype === 'BF16') {
      const u = new Uint16Array(buf.slice(base + s, base + e)), t = new Uint32Array(f.buffer);
      for (let i = 0; i < n; i++) t[i] = u[i] << 16;
    } else if (m.dtype === 'F32') f.set(new Float32Array(buf.slice(base + s, base + e)));
    else throw new Error('dtype ' + m.dtype);
    out[name] = { data: f, shape: m.shape };
  }
  return out;
}

export function buildModel(raw, cfg) {
  const L = [];
  for (let l = 0; l < cfg.num_hidden_layers; l++) {
    const p = `model.layers.${l}.`, g = n => raw[p + n].data;
    L.push({
      ln1: g('input_layernorm.weight'), ln2: g('pre_ff_layernorm.weight'),
      q: g('self_attn.q_proj.weight'), k: g('self_attn.k_proj.weight'), v: g('self_attn.v_proj.weight'), o: g('self_attn.o_proj.weight'),
      inp: g('mamba.in_proj.weight'), convW: g('mamba.conv1d.weight'), convB: g('mamba.conv1d.bias'),
      A_log: g('mamba.A_log'), D: g('mamba.D'), dtb: g('mamba.dt_bias'), outp: g('mamba.out_proj.weight'),
      gate: g('feed_forward.gate_proj.weight'), up: g('feed_forward.up_proj.weight'), down: g('feed_forward.down_proj.weight'),
    });
  }
  return {
    d: { H: cfg.hidden_size, nL: cfg.num_hidden_layers, nA: cfg.num_attention_heads, nKV: cfg.num_key_value_heads, hd: cfg.head_dim,
         I: cfg.intermediate_size, dssm: cfg.mamba_d_ssm, nM: cfg.mamba_n_heads, dhM: cfg.mamba_d_head, N: cfg.mamba_d_state,
         V: cfg.vocab_size, kc: cfg.mamba_d_conv, eps: cfg.rms_norm_eps, rope: cfg.rope_theta ?? cfg.rope_parameters?.rope_theta,
         embM: cfg.embedding_multiplier, lmM: cfg.lm_head_multiplier },
    E: raw['model.embed_tokens.weight'].data, fn: raw['model.final_layernorm.weight'].data, L,
  };
}

// ---- exact widening: every op is a copy or a 1/k (or k) scaling of existing weights ----
const rep = (a, k) => { const o = new Float32Array(a.length * k); for (let i = 0; i < k; i++) o.set(a, i * a.length); return o; };
const concat = parts => { const o = new Float32Array(parts.reduce((s, a) => s + a.length, 0)); let p = 0; for (const a of parts) { o.set(a, p); p += a.length; } return o; };
const scaled = (W, s) => { const o = new Float32Array(W.length); for (let i = 0; i < W.length; i++) o[i] = W[i] * s; return o; };
function repCols(W, rows, cols, k, s) {   // [rows,cols] -> [rows,k*cols], times s
  const o = new Float32Array(rows * cols * k);
  for (let r = 0; r < rows; r++) { const src = r * cols, dst = r * cols * k; for (let j = 0; j < k; j++) for (let c = 0; c < cols; c++) o[dst + j * cols + c] = W[src + c] * s; }
  return o;
}

export function widen(M, axes, k) {
  if (k === 1 || !axes.length) return M;
  const d = { ...M.d }; let E = M.E, fn = M.fn;
  const L = M.L.map(l => ({ ...l }));
  for (const ax of axes) {
    if (ax === 'mlp') {
      for (const l of L) { l.gate = rep(l.gate, k); l.up = rep(l.up, k); l.down = repCols(l.down, d.H, d.I, k, 1 / k); }
      d.I *= k;
    } else if (ax === 'attn') {
      for (const l of L) { l.q = rep(l.q, k); l.k = rep(l.k, k); l.v = rep(l.v, k); l.o = repCols(l.o, d.H, d.nA * d.hd, k, 1 / k); }
      d.nA *= k; d.nKV *= k;
    } else if (ax === 'heads') {
      const D = d.dssm, N = d.N, H = d.H, nM = d.nM, kc = d.kc;
      for (const l of L) {
        const W = l.inp, part = (a, b) => W.subarray(a * H, b * H);
        l.inp = concat([rep(part(0, D), k), rep(part(D, 2 * D), k), part(2 * D, 2 * D + 2 * N), rep(part(2 * D + 2 * N, 2 * D + 2 * N + nM), k)]);
        const cw = l.convW, cb = l.convB;
        l.convW = concat([rep(cw.subarray(0, D * kc), k), cw.subarray(D * kc)]);
        l.convB = concat([rep(cb.subarray(0, D), k), cb.subarray(D)]);
        l.A_log = rep(l.A_log, k); l.D = rep(l.D, k); l.dtb = rep(l.dtb, k);
        l.outp = repCols(l.outp, H, D, k, 1 / k);
      }
      d.dssm *= k; d.nM *= k;
    } else if (ax === 'dstate') {
      const D = d.dssm, N = d.N, H = d.H, kc = d.kc;
      for (const l of L) {
        const W = l.inp, part = (a, b) => W.subarray(a * H, b * H);
        l.inp = concat([part(0, 2 * D), rep(part(2 * D, 2 * D + N), k), rep(part(2 * D + N, 2 * D + 2 * N), k), part(2 * D + 2 * N, W.length / H)]);
        const cw = l.convW, cb = l.convB;
        l.convW = concat([cw.subarray(0, D * kc), rep(cw.subarray(D * kc, (D + N) * kc), k), rep(cw.subarray((D + N) * kc), k)]);
        l.convB = concat([cb.subarray(0, D), rep(cb.subarray(D, D + N), k), rep(cb.subarray(D + N), k)]);
        l.D = scaled(l.D, k);            // y = k*(C.h) + k*D*x ; out_proj/k restores C.h + D*x
        l.outp = scaled(l.outp, 1 / k);
      }
      d.N *= k;
    } else if (ax === 'res') {
      E = repCols(E, d.V, d.H, k, 1); fn = rep(fn, k);
      for (const l of L) {
        l.ln1 = rep(l.ln1, k); l.ln2 = rep(l.ln2, k);
        const inRows = { q: d.nA * d.hd, k: d.nKV * d.hd, v: d.nKV * d.hd, inp: l.inp.length / d.H, gate: d.I, up: d.I };
        for (const n of Object.keys(inRows)) l[n] = repCols(l[n], inRows[n], d.H, k, 1 / k);
        l.o = rep(l.o, k); l.outp = rep(l.outp, k); l.down = rep(l.down, k);
      }
      d.H *= k; d.lmM = d.lmM / k;
    } else throw new Error('axis ' + ax);
  }
  return { d, E, fn, L };
}

// ---- inference (single token step, recurrent form for the SSM) ----
function matvec(W, out, inn, x, y) {
  for (let r = 0; r < out; r++) { let s = 0; const o = r * inn; for (let c = 0; c < inn; c++) s += W[o + c] * x[c]; y[r] = s; }
}
function rmsnorm(x, w, eps, y) {
  let s = 0; for (let i = 0; i < x.length; i++) s += x[i] * x[i];
  const r = 1 / Math.sqrt(s / x.length + eps); for (let i = 0; i < x.length; i++) y[i] = w[i] * (x[i] * r);
}
const silu = v => v / (1 + Math.exp(-v));
const softplus = v => v > 20 ? v : Math.log1p(Math.exp(v));

export function newState(M) {
  const d = M.d;
  return { pos: 0, layers: M.L.map(() => ({ conv: new Float32Array((d.dssm + 2 * d.N) * (d.kc - 1)), h: new Float32Array(d.nM * d.dhM * d.N), K: [], V: [] })) };
}

export function step(M, S, tok) {
  const d = M.d, H = d.H, pos = S.pos;
  const x = new Float32Array(H); for (let i = 0; i < H; i++) x[i] = M.E[tok * H + i] * d.embM;
  const xn = new Float32Array(H);
  const qd = d.nA * d.hd, kvd = d.nKV * d.hd, cd = d.dssm + 2 * d.N, pj = 2 * d.dssm + 2 * d.N + d.nM;
  const q = new Float32Array(qd), kk = new Float32Array(kvd), vv = new Float32Array(kvd), ao = new Float32Array(qd);
  const proj = new Float32Array(pj), xbc = new Float32Array(cd), yv = new Float32Array(d.dssm), mo = new Float32Array(H), atto = new Float32Array(H);
  const hg = new Float32Array(d.I), hu = new Float32Array(d.I), mlp = new Float32Array(H);
  const half = d.hd / 2, cosv = new Float32Array(half), sinv = new Float32Array(half);
  for (let i = 0; i < half; i++) { const f = pos * Math.pow(d.rope, -(2 * i) / d.hd); cosv[i] = Math.cos(f); sinv[i] = Math.sin(f); }
  const nrep = d.nA / d.nKV, scale = 1 / Math.sqrt(d.hd), kc = d.kc;
  for (let li = 0; li < d.nL; li++) {
    const l = M.L[li], st = S.layers[li];
    rmsnorm(x, l.ln1, d.eps, xn);
    matvec(l.inp, pj, H, xn, proj);                                   // Mamba2 branch
    for (let c = 0; c < cd; c++) {
      const base = c * (kc - 1); let s = l.convB[c];
      for (let j = 0; j < kc - 1; j++) s += l.convW[c * kc + j] * st.conv[base + j];
      s += l.convW[c * kc + kc - 1] * proj[d.dssm + c];
      for (let j = 0; j < kc - 2; j++) st.conv[base + j] = st.conv[base + j + 1];
      st.conv[base + kc - 2] = proj[d.dssm + c];
      xbc[c] = silu(s);
    }
    const Boff = d.dssm, Coff = d.dssm + d.N;
    for (let h = 0; h < d.nM; h++) {
      const dt = softplus(proj[2 * d.dssm + 2 * d.N + h] + l.dtb[h]), dA = Math.exp(dt * -Math.exp(l.A_log[h]));
      for (let e = 0; e < d.dhM; e++) {
        const xi = xbc[h * d.dhM + e], hb = (h * d.dhM + e) * d.N; let y = 0;
        for (let n = 0; n < d.N; n++) { const v = st.h[hb + n] * dA + dt * xbc[Boff + n] * xi; st.h[hb + n] = v; y += xbc[Coff + n] * v; }
        yv[h * d.dhM + e] = (y + l.D[h] * xi) * silu(proj[h * d.dhM + e]);
      }
    }
    matvec(l.outp, H, d.dssm, yv, mo);
    matvec(l.q, qd, H, xn, q); matvec(l.k, kvd, H, xn, kk); matvec(l.v, kvd, H, xn, vv);   // attention branch
    const rot = (a, nh) => { for (let h = 0; h < nh; h++) for (let i = 0; i < half; i++) { const o = h * d.hd, x1 = a[o + i], x2 = a[o + half + i]; a[o + i] = x1 * cosv[i] - x2 * sinv[i]; a[o + half + i] = x2 * cosv[i] + x1 * sinv[i]; } };
    rot(q, d.nA); rot(kk, d.nKV);
    st.K.push(Float32Array.from(kk)); st.V.push(Float32Array.from(vv));
    const T = st.K.length, sc = new Float32Array(T);
    for (let h = 0; h < d.nA; h++) {
      const g = Math.floor(h / nrep); let mx = -Infinity;
      for (let t = 0; t < T; t++) { let s = 0; for (let i = 0; i < d.hd; i++) s += q[h * d.hd + i] * st.K[t][g * d.hd + i]; sc[t] = s * scale; if (sc[t] > mx) mx = sc[t]; }
      let z = 0; for (let t = 0; t < T; t++) { sc[t] = Math.exp(sc[t] - mx); z += sc[t]; }
      for (let i = 0; i < d.hd; i++) { let s = 0; for (let t = 0; t < T; t++) s += sc[t] * st.V[t][g * d.hd + i]; ao[h * d.hd + i] = s / z; }
    }
    matvec(l.o, H, qd, ao, atto);
    for (let i = 0; i < H; i++) x[i] += mo[i] + atto[i];
    rmsnorm(x, l.ln2, d.eps, xn);                                     // MLP
    matvec(l.gate, d.I, H, xn, hg); matvec(l.up, d.I, H, xn, hu);
    for (let i = 0; i < d.I; i++) hu[i] *= silu(hg[i]);
    matvec(l.down, H, d.I, hu, mlp);
    for (let i = 0; i < H; i++) x[i] += mlp[i];
  }
  rmsnorm(x, M.fn, d.eps, xn);
  const logits = new Float32Array(d.V); matvec(M.E, d.V, H, xn, logits);
  for (let i = 0; i < d.V; i++) logits[i] *= d.lmM;
  S.pos++;
  return logits;
}
export const argmax = a => { let b = 0; for (let i = 1; i < a.length; i++) if (a[i] > a[b]) b = i; return b; };