File size: 8,879 Bytes
e060bf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
// VeroLM site runner for NoTokenLM-Gen-3.6 (byte-level transformer).
// Mirrors modeling_notoken_gen36.py: byte embedding + causal depthwise conv (residual),
// N x [RMSNorm -> attention(RoPE, QK-norm, value residual, per-head sigmoid gate); RMSNorm -> SwiGLU],
// final RMSNorm, tied output head, optional tanh logit cap.
// Runs on the CPU in plain JavaScript with a KV cache (same maths as the full recompute, just faster).
// Structural sizes (d_model, heads, layers, d_ff, conv kernel) are read from the weight shapes;
// rope_base / logit_cap / block_size / eod_token_id come from config.json in the repo.

const EPS = 1e-6;

export async function load({ baseUrl, tensors, tools, manifest, onProgress }) {
  let cfg = {};
  try { cfg = await (await fetch(baseUrl + "config.json")).json(); } catch (e) {}
  manifest = manifest || {};

  const keys = [...tensors.keys()];
  const embKey = keys.find(k => k.endsWith("emb.weight"));
  if (!embKey) throw new Error("emb.weight not found in model.safetensors");
  const pre = embKey.slice(0, embKey.length - "emb.weight".length);
  const T = n => { const t = tensors.get(pre + n); if (!t) throw new Error("Missing tensor " + pre + n); return t; };
  const W = n => tools.toFloat32(T(n));

  const emb = W("emb.weight"), [V, d] = T("emb.weight").shape;
  const convT = T("conv.w"), cw = tools.toFloat32(convT), K = convT.shape[2];
  let nLayer = 0; while (tensors.has(pre + "blocks." + nLayer + ".n1.w")) nLayer++;
  if (!nLayer) throw new Error("No transformer blocks found.");
  const hd = T("blocks.0.attn.qn.w").shape[0], nHead = d / hd, ff = T("blocks.0.ff.w1.weight").shape[0];
  if (!Number.isInteger(nHead)) throw new Error("Head size doesn’t divide d_model.");

  const ropeBase = cfg.rope_base ?? manifest.rope_base;
  if (ropeBase == null) throw new Error('config.json has no "rope_base". Add it there (or in verolm.json).');
  const logitCap = cfg.logit_cap ?? manifest.logit_cap ?? 0;
  const block = cfg.block_size ?? manifest.block_size ?? 1024;
  const eod = cfg.eod_token_id ?? manifest.eod_token_id ?? 0;

  const layers = [];
  for (let l = 0; l < nLayer; l++) {
    const p = "blocks." + l + ".";
    layers.push({
      n1: W(p + "n1.w"), qkv: W(p + "attn.qkv.weight"), o: W(p + "attn.o.weight"),
      qn: W(p + "attn.qn.w"), kn: W(p + "attn.kn.w"), gW: W(p + "attn.gate.weight"), gB: W(p + "attn.gate.bias"),
      lam: l > 0 ? W(p + "attn.lam")[0] : 0,
      n2: W(p + "n2.w"), w1: W(p + "ff.w1.weight"), w3: W(p + "ff.w3.weight"), w2: W(p + "ff.w2.weight")
    });
    if (onProgress) onProgress(((l + 1) / nLayer) * 100, "preparing");
  }
  const nf = W("nf.w");

  // rotary tables (float32, interleaved pairs)
  const half = hd / 2, cosT = new Float32Array(block * half), sinT = new Float32Array(block * half);
  const inv = new Float32Array(half);
  for (let i = 0; i < half; i++) inv[i] = 1 / Math.pow(ropeBase, (2 * i) / hd);
  for (let t = 0; t < block; t++) for (let i = 0; i < half; i++) {
    const a = Math.fround(t * inv[i]); cosT[t * half + i] = Math.cos(a); sinT[t * half + i] = Math.sin(a);
  }

  // scratch + cache
  const x = new Float32Array(d), h = new Float32Array(d), qkv = new Float32Array(3 * d), y = new Float32Array(d);
  const ao = new Float32Array(d), g = new Float32Array(nHead), a1 = new Float32Array(ff), a3 = new Float32Array(ff);
  const logits = new Float32Array(V), sc = new Float32Array(block);
  let E, V1, Kc, Vc;
  const reset = () => {
    E = new Float32Array(block * d); V1 = new Float32Array(block * d);
    Kc = layers.map(() => new Float32Array(block * d)); Vc = layers.map(() => new Float32Array(block * d));
  };

  function matvec(M, outN, inN, v, out) {
    for (let o = 0, b = 0; o < outN; o++, b += inN) { let s = 0; for (let i = 0; i < inN; i++) s += M[b + i] * v[i]; out[o] = s; }
  }
  function rms(src, so, w, n, dst, doff) {
    let ss = 0; for (let i = 0; i < n; i++) ss += src[so + i] * src[so + i];
    const r = 1 / Math.sqrt(ss / n + EPS);
    for (let i = 0; i < n; i++) dst[doff + i] = src[so + i] * r * w[i];
  }
  const tmp = new Float32Array(hd);
  function rmsHead(arr, off, w) { rms(arr, off, w, hd, tmp, 0); for (let i = 0; i < hd; i++) arr[off + i] = tmp[i]; }
  function rope(arr, off, p) {
    for (let i = 0; i < half; i++) {
      const c = cosT[p * half + i], s = sinT[p * half + i], x1 = arr[off + 2 * i], x2 = arr[off + 2 * i + 1];
      arr[off + 2 * i] = x1 * c - x2 * s; arr[off + 2 * i + 1] = x1 * s + x2 * c;
    }
  }

  // one position through the whole network; returns logits when wanted
  function step(tok, p, wantLogits) {
    E.set(emb.subarray(tok * d, tok * d + d), p * d);
    for (let c = 0; c < d; c++) {
      let s = E[p * d + c];
      for (let j = 0; j < K; j++) { const q = p - (K - 1) + j; if (q >= 0) s += cw[c * K + j] * E[q * d + c]; }
      x[c] = s;
    }
    const scale = 1 / Math.sqrt(hd);
    for (let l = 0; l < nLayer; l++) {
      const L = layers[l];
      rms(x, 0, L.n1, d, h, 0);
      matvec(L.qkv, 3 * d, d, h, qkv);
      const q = qkv.subarray(0, d), k = qkv.subarray(d, 2 * d), v = qkv.subarray(2 * d, 3 * d);
      if (l === 0) V1.set(v, p * d); else for (let i = 0; i < d; i++) v[i] += L.lam * V1[p * d + i];
      for (let hh = 0; hh < nHead; hh++) {
        const off = hh * hd;
        rmsHead(q, off, L.qn); rmsHead(k, off, L.kn); rope(q, off, p); rope(k, off, p);
      }
      Kc[l].set(k, p * d); Vc[l].set(v, p * d);
      const Kl = Kc[l], Vl = Vc[l];
      for (let hh = 0; hh < nHead; hh++) {
        const off = hh * hd; let mx = -Infinity;
        for (let j = 0; j <= p; j++) {
          let s = 0; for (let i = 0; i < hd; i++) s += q[off + i] * Kl[j * d + off + i];
          s *= scale; sc[j] = s; if (s > mx) mx = s;
        }
        let den = 0; for (let j = 0; j <= p; j++) { sc[j] = Math.exp(sc[j] - mx); den += sc[j]; }
        for (let i = 0; i < hd; i++) y[off + i] = 0;
        for (let j = 0; j <= p; j++) { const w = sc[j] / den; for (let i = 0; i < hd; i++) y[off + i] += w * Vl[j * d + off + i]; }
      }
      matvec(L.gW, nHead, d, h, g);
      for (let hh = 0; hh < nHead; hh++) {
        const gv = 1 / (1 + Math.exp(-(g[hh] + L.gB[hh])));
        for (let i = 0; i < hd; i++) y[hh * hd + i] *= gv;
      }
      matvec(L.o, d, d, y, ao);
      for (let i = 0; i < d; i++) x[i] += ao[i];
      rms(x, 0, L.n2, d, h, 0);
      matvec(L.w1, ff, d, h, a1); matvec(L.w3, ff, d, h, a3);
      for (let i = 0; i < ff; i++) { const u = a1[i]; a1[i] = (u / (1 + Math.exp(-u))) * a3[i]; }
      matvec(L.w2, d, ff, a1, ao);
      for (let i = 0; i < d; i++) x[i] += ao[i];
    }
    if (!wantLogits) return null;
    rms(x, 0, nf, d, h, 0);
    for (let o = 0; o < V; o++) {
      let s = 0; const b = o * d; for (let i = 0; i < d; i++) s += emb[b + i] * h[i];
      logits[o] = logitCap > 0 ? logitCap * Math.tanh(s / logitCap) : s;
    }
    return logits;
  }

  function sample(lg, temperature, topK) {
    const n = lg.length;
    if (!(temperature > 0)) { let b = 0; for (let i = 1; i < n; i++) if (lg[i] > lg[b]) b = i; return b; }
    const z = Array.from(lg, v => v / temperature);
    if (topK > 0 && topK < n) {
      const kth = [...z].sort((a, b) => b - a)[topK - 1];
      for (let i = 0; i < n; i++) if (z[i] < kth) z[i] = -Infinity;
    }
    let mx = -Infinity; for (const v of z) if (v > mx) mx = v;
    let den = 0; const pr = z.map(v => { const e = Math.exp(v - mx); den += e; return e; });
    let r = Math.random() * den;
    for (let i = 0; i < n; i++) { r -= pr[i]; if (r <= 0) return i; }
    return n - 1;
  }

  return {
    // logits after feeding `ids` (array of byte values); exposed for testing
    _forward(ids) { reset(); let lg; for (let p = 0; p < ids.length; p++) lg = step(ids[p], p, p === ids.length - 1); return Array.from(lg); },

    async generate(prompt, { onToken, maxTokens }) {
      const temperature = manifest.temperature ?? 0.5, topK = manifest.top_k ?? 40;
      let ids = Array.from(new TextEncoder().encode(prompt));
      if (!ids.length) ids = [10];
      if (ids.length >= block) ids = ids.slice(-(block - 1));
      reset();
      let lg; for (let p = 0; p < ids.length; p++) lg = step(ids[p], p, p === ids.length - 1);
      const dec = new TextDecoder("utf-8"); let pos = ids.length, text = "";
      for (let n = 0; n < (maxTokens || 256); n++) {
        const tok = sample(lg, temperature, topK);
        if (tok === eod) break;
        const piece = dec.decode(Uint8Array.of(tok), { stream: true });
        if (piece) { onToken(piece); text += piece; }
        if (pos >= block) break;            // context is full (block_size bytes)
        lg = step(tok, pos, true); pos++;
        if (n % 4 === 0) await new Promise(r => setTimeout(r, 0));   // keep the page responsive
      }
      const tail = dec.decode(); if (tail) { onToken(tail); text += tail; }
      return text;
    }
  };
}