Spaces:
Running

File size: 14,064 Bytes
2fbd1b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// محرّك Jobter في المتصفح (JavaScript خالص، بلا مكتبات): أوزان int8 + توليد رمزًا رمزًا.
// كل كتلة لها ذاكرتها الخاصة: W ⇒ مفاتيح/قيم الانتباه، S ⇒ مصفوفة المشابك + حالة الالتفاف.
// النتيجة مطابقة لنموذج PyTorch عند عدد دورات ثابت (مع فرق تكميم int8 صغير).

// matvec.c مُترجَم إلى WebAssembly SIMD (clang --target=wasm32 -O3 -msimd128)
const MATVEC_WASM = "AGFzbQEAAAABCgFgBn9/f39/fwACDwEDZW52Bm1lbW9yeQIAAgMCAQAGCAF/AUGAiAQLBwoBBm1hdHZlYwAACv8HAfwHBQh/AXsCfwJ7AX0CQCAEQQFIDQACQCAFQRBIDQAgBUEBcSEGIAVB8P///wdxIgdBAXIhCCACIAdBAnRqIQlBACEKIAcgBUF/akYhCyAAIQwDQCAAIAogBWxqIQ39DAAAAAAAAAAAAAAAAAAAAAAhDkEQIQ8gAiEQA0AgEEEwav0AAAAgDCAPakFwav0AAAAiEf2IASIS/agB/foB/eYBIBBBIGr9AAAAIBL9pwH9+gH95gEgEEEQav0AAAAgEf2HASIR/agB/foB/eYBIA4gEP0AAAAgEf2nAf36Af3mAf3kAf3kAf3kAf3kASEOIBBBwABqIRAgD0EQaiIPIAVMDQALIA79HwMgDv0fAiAO/R8AIA79HwGSkpIhEwJAIAcgBU4NAAJAAkAgBg0AIAchDwwBCyANIAdqLAAAsiAJKgIAlCATkiETIAghDwsgCw0AIAIgD0ECdGohEANAIAwgD2oiDUEBaiwAALIgEEEEaioCAJQgDSwAALIgECoCAJQgE5KSIRMgEEEIaiEQIAUgD0ECaiIPRw0ACwsgAyAKQQJ0IhBqIBMgASAQaioCAJQ4AgAgDCAFaiEMIApBAWoiCiAERw0ADAILCwJAIAVBAUgNACAFQf7///8HcSEKIAVBAXEhBkEAIQcgACENA0BDAAAAACETQQAhDwJAIAVBAUYNAEEAIQ9DAAAAACETIAIhEANAIA0gD2oiDEEBaiwAALIgEEEEaioCAJQgDCwAALIgECoCAJQgE5KSIRMgEEEIaiEQIAogD0ECaiIPRw0ACwsCQCAGRQ0AIAAgByAFbGogD2osAACyIAIgD0ECdGoqAgCUIBOSIRMLIAMgB0ECdCIQaiATIAEgEGoqAgCUOAIAIA0gBWohDSAHQQFqIgcgBEcNAAwCCwtBACEMAkAgBEEESQ0AIAMgAWtBEEkNACAEQfz///8HcSIMIQUgAyEQIAEhDwNAIBAgD/0AAgD9DAAAAAAAAAAAAAAAAAAAAAD95gH9CwIAIBBBEGohECAPQRBqIQ8gBUF8aiIFDQALIAwgBEYNAQsgDCENAkAgBEEDcSIFRQ0AIAwgBWohDSABIAxBAnQiD2ohECADIA9qIQ8DQCAPIBAqAgBDAAAAAJQ4AgAgEEEEaiEQIA9BBGohDyAFQX9qIgUNAAsLIAwgBGtBfEsNACANQQJ0IQUgBCANayEMA0AgAyAFaiIQIAEgBWoiDyoCAEMAAAAAlDgCACAQQQRqIA9BBGoqAgBDAAAAAJQ4AgAgEEEIaiAPQQhqKgIAQwAAAACUOAIAIBBBDGogD0EMaioCAEMAAAAAlDgCACABQRBqIQEgA0EQaiEDIAxBfGoiDA0ACwsLAC4EbmFtZQAIB212Lndhc20BCQEABm1hdHZlYwcSAQAPX19zdGFja19wb2ludGVyADgJcHJvZHVjZXJzAQxwcm9jZXNzZWQtYnkBDFVidW50dSBjbGFuZxExOC4xLjMgKDF1YnVudHUxKQA1D3RhcmdldF9mZWF0dXJlcwMrD211dGFibGUtZ2xvYmFscysIc2lnbi1leHQrB3NpbWQxMjg=";

export class Jobter {
  static async load(base, onProgress) {
    const get = async (f) => (await fetch(base + f)).json();
    const [cfg, man] = await Promise.all([get("config.json"), get("manifest.json")]);
    const res = await fetch(base + "weights.bin");
    const total = man.bytes, buf = new Uint8Array(total);
    const reader = res.body.getReader();
    let got = 0;
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;
      buf.set(value, got); got += value.length;
      onProgress && onProgress(got / total);
    }
    return new Jobter(cfg, man.tensors, buf.buffer);
  }

  static fromBuffer(cfg, tensors, arrayBuffer) { return new Jobter(cfg, tensors, arrayBuffer); }

  constructor(cfg, tensors, src) {
    this.cfg = cfg;
    this.W = {};
    // الأوزان داخل ذاكرة WebAssembly مباشرة + منطقة عمل للمتّجهات (بلا نموّ لاحق)
    const nbytes = src.byteLength, scratch = 4 * (8192 + 32768);
    let ab = src;
    try {
      const mem = new WebAssembly.Memory({ initial: Math.ceil((nbytes + scratch + 64) / 65536) });
      new Uint8Array(mem.buffer).set(new Uint8Array(src));
      const bin = Uint8Array.from(atob(MATVEC_WASM), (c) => c.charCodeAt(0));
      const inst = new WebAssembly.Instance(new WebAssembly.Module(bin), { env: { memory: mem } });
      const xo = (nbytes + 15) & ~15;
      this.wasm = { fn: inst.exports.matvec, xo, oo: xo + 4 * 8192,
                    X: new Float32Array(mem.buffer, xo, 8192), O: new Float32Array(mem.buffer, xo + 4 * 8192, 32768) };
      ab = mem.buffer;
    } catch (e) { this.wasm = null; }
    for (const [name, t] of Object.entries(tensors)) {
      const n = t.shape.reduce((a, b) => a * b, 1);
      if (t.dtype === "i8") {
        this.W[name] = { q: new Int8Array(ab, t.offset, n), s: new Float32Array(ab, t.scale, t.shape[0]),
                         rows: t.shape[0], cols: t.shape[1] };
      } else {
        this.W[name] = new Float32Array(ab, t.offset, n);
      }
    }
    const c = cfg;
    this.d = c.d_model; this.hd = c.d_model / c.n_heads;
    this.cycles = 3;
    this.blocks = { thal: [...c.prelude], col: [...c.core], motor: [...c.coda] };
    const half = this.hd / 2;
    this.invFreq = new Float32Array(half);
    for (let i = 0; i < half; i++) this.invFreq[i] = 1 / Math.pow(c.rope_theta, (2 * i) / this.hd);
    this.reset();
  }

  reset() {
    const c = this.cfg, T = c.max_seq_len;
    const mk = (kind) => kind === "W"
      ? { K: new Float32Array(T * c.n_kv_heads * this.hd), V: new Float32Array(T * c.n_kv_heads * this.hd) }
      : { S: new Float32Array(c.mem_heads * c.mem_head_dim * c.mem_head_dim),
          conv: new Float32Array((c.conv_size - 1) * 3 * c.mem_heads * c.mem_head_dim) };
    this.cache = {
      thal: this.blocks.thal.map(mk),
      col: Array.from({ length: this.cycles }, () => this.blocks.col.map(mk)),
      motor: this.blocks.motor.map(mk),
    };
    this.pos = 0;
  }

  // ------------------------------------------------------------------ أدوات
  matvec(name, x, out) {
    const w = this.W[name];
    if (this.wasm) {
      const W = this.wasm;
      W.X.set(x);
      W.fn(w.q.byteOffset, w.s.byteOffset, W.xo, W.oo, w.rows, w.cols);
      out = out || new Float32Array(w.rows);
      out.set(W.O.subarray(0, w.rows));
      return out;
    }
    const q = w.q, s = w.s, n = w.cols;
    out = out || new Float32Array(w.rows);
    for (let o = 0, base = 0; o < w.rows; o++, base += n) {
      let a0 = 0, a1 = 0, a2 = 0, a3 = 0, i = 0;
      for (; i + 3 < n; i += 4) {
        a0 += q[base + i] * x[i]; a1 += q[base + i + 1] * x[i + 1];
        a2 += q[base + i + 2] * x[i + 2]; a3 += q[base + i + 3] * x[i + 3];
      }
      for (; i < n; i++) a0 += q[base + i] * x[i];
      out[o] = (a0 + a1 + a2 + a3) * s[o];
    }
    return out;
  }
  // مصفوفة صغيرة f32 (صفوف × أعمدة) + انحياز اختياري
  smallvec(name, x, rows, bias) {
    const w = this.W[name], n = x.length, out = new Float32Array(rows), b = bias ? this.W[bias] : null;
    for (let o = 0; o < rows; o++) {
      let a = b ? b[o] : 0;
      for (let i = 0; i < n; i++) a += w[o * n + i] * x[i];
      out[o] = a;
    }
    return out;
  }
  rms(x, wname, eps = this.cfg.rms_norm_eps) {
    let ss = 0; for (let i = 0; i < x.length; i++) ss += x[i] * x[i];
    const r = 1 / Math.sqrt(ss / x.length + eps), w = this.W[wname], out = new Float32Array(x.length);
    for (let i = 0; i < x.length; i++) out[i] = x[i] * r * w[i];
    return out;
  }
  static silu(v) { return v / (1 + Math.exp(-v)); }

  // ------------------------------------------------------------------ الكتل
  workspace(p, h, cache) {
    const c = this.cfg, hd = this.hd, nh = c.n_heads, nkv = c.n_kv_heads, rep = nh / nkv;
    const q = this.matvec(p + "wq.weight", h), k = this.matvec(p + "wk.weight", h), v = this.matvec(p + "wv.weight", h);
    const pos = this.pos, half = hd / 2;
    const rope = (vec, heads) => {
      for (let hh = 0; hh < heads; hh++) for (let i = 0; i < half; i++) {
        const ang = pos * this.invFreq[i], cs = Math.cos(ang), sn = Math.sin(ang);
        const a = vec[hh * hd + 2 * i], b = vec[hh * hd + 2 * i + 1];
        vec[hh * hd + 2 * i] = a * cs - b * sn; vec[hh * hd + 2 * i + 1] = a * sn + b * cs;
      }
    };
    rope(q, nh); rope(k, nkv);
    const stride = nkv * hd;
    cache.K.set(k, pos * stride); cache.V.set(v, pos * stride);
    const T = pos + 1, o = new Float32Array(nh * hd), sc = new Float32Array(T), scale = 1 / Math.sqrt(hd);
    for (let hh = 0; hh < nh; hh++) {
      const kv = Math.floor(hh / rep);
      let m = -Infinity;
      for (let t = 0; t < T; t++) {
        let a = 0; const kb = t * stride + kv * hd;
        for (let i = 0; i < hd; i++) a += q[hh * hd + i] * cache.K[kb + i];
        sc[t] = a * scale; if (sc[t] > m) m = sc[t];
      }
      let z = 0; for (let t = 0; t < T; t++) { sc[t] = Math.exp(sc[t] - m); z += sc[t]; }
      for (let t = 0; t < T; t++) {
        const wgt = sc[t] / z, vb = t * stride + kv * hd;
        for (let i = 0; i < hd; i++) o[hh * hd + i] += wgt * cache.V[vb + i];
      }
    }
    return this.matvec(p + "wo.weight", o);
  }

  synaptic(p, h, cache) {
    const c = this.cfg, H = c.mem_heads, hd = c.mem_head_dim, I = H * hd, K = c.conv_size;
    const z = this.matvec(p + "qkv.weight", h);                 // (3I)
    const conv = this.W[p + "conv"], st = cache.conv, act = new Float32Array(3 * I);
    for (let ch = 0; ch < 3 * I; ch++) {
      let a = conv[ch * K + (K - 1)] * z[ch];
      for (let j = 0; j < K - 1; j++) a += conv[ch * K + j] * st[j * 3 * I + ch];
      act[ch] = Jobter.silu(a);
    }
    st.copyWithin(0, 3 * I); st.set(z, (K - 2) * 3 * I);       // انزلاق نافذة الالتفاف
    const beta = this.smallvec(p + "beta_proj.weight", h, H, p + "beta_proj.bias");
    const dec = this.smallvec(p + "decay_proj.weight", h, H, p + "decay_proj.bias");
    const A = this.W[p + "A_log"], dtb = this.W[p + "dt_bias"], S = cache.S;
    const o = new Float32Array(I), on = this.W[p + "out_norm.weight"], qs = 1 / Math.sqrt(hd);
    for (let hh = 0; hh < H; hh++) {
      const q = act.subarray(hh * hd, hh * hd + hd), k = act.subarray(I + hh * hd, I + hh * hd + hd);
      const v = act.subarray(2 * I + hh * hd, 2 * I + hh * hd + hd);
      let nq = 0, nk = 0;
      for (let i = 0; i < hd; i++) { nq += q[i] * q[i]; nk += k[i] * k[i]; }
      nq = 1 / Math.max(Math.sqrt(nq), 1e-12); nk = 1 / Math.max(Math.sqrt(nk), 1e-12);
      const b = 1 / (1 + Math.exp(-beta[hh]));
      const x = dec[hh] + dtb[hh], sp = x > 20 ? x : Math.log1p(Math.exp(x));
      const alpha = Math.exp(-Math.exp(A[hh]) * sp);
      const Sb = hh * hd * hd;
      for (let i = 0; i < hd * hd; i++) S[Sb + i] *= alpha;
      const vold = new Float32Array(hd);
      for (let i = 0; i < hd; i++) { const ki = k[i] * nk; for (let j = 0; j < hd; j++) vold[j] += S[Sb + i * hd + j] * ki; }
      for (let i = 0; i < hd; i++) {
        const ki = b * k[i] * nk;
        for (let j = 0; j < hd; j++) S[Sb + i * hd + j] += ki * (v[j] - vold[j]);
      }
      let ss = 0;
      for (let j = 0; j < hd; j++) {
        let a = 0; for (let i = 0; i < hd; i++) a += S[Sb + i * hd + j] * q[i] * nq * qs;
        o[hh * hd + j] = a; ss += a * a;
      }
      const r = 1 / Math.sqrt(ss / hd + c.rms_norm_eps);
      for (let j = 0; j < hd; j++) o[hh * hd + j] *= r * on[j];
    }
    const g = this.matvec(p + "gate.weight", h);
    for (let i = 0; i < I; i++) o[i] *= Jobter.silu(g[i]);
    return this.matvec(p + "wo.weight", o);
  }

  neurons(p, h, td) {
    const basal = this.matvec(p + "basal.weight", h);
    const n = this.W[p + "apical.weight"].rows, b = basal.length / n;
    let a_in = h;
    if (td && this.W[p + "td_norm.weight"]) {
      const t = this.rms(td, p + "td_norm.weight"); a_in = new Float32Array(h.length);
      for (let i = 0; i < h.length; i++) a_in[i] = h[i] + t[i];
    }
    const ap = this.matvec(p + "apical.weight", a_in), y = new Float32Array(n);
    for (let j = 0; j < n; j++) {
      let s = basal[j * b]; for (let c = 1; c < b; c++) s = Math.max(s, basal[j * b + c]);
      y[j] = s * Jobter.silu(ap[j]);
    }
    return this.matvec(p + "out.weight", y);
  }

  block(prefix, kind, x, cache, td) {
    const h = this.rms(x, prefix + "norm1.weight");
    const lat = kind === "W" ? this.workspace(prefix + "lateral.", h, cache) : this.synaptic(prefix + "lateral.", h, cache);
    const x1 = new Float32Array(x.length);
    for (let i = 0; i < x.length; i++) x1[i] = x[i] + lat[i];
    const nr = this.neurons(prefix + "neurons.", this.rms(x1, prefix + "norm2.weight"), td);
    for (let i = 0; i < x.length; i++) x1[i] += nr[i];
    return x1;
  }

  // يقرأ رمزًا واحدًا ويُرجِع الحالة النهائية المطبَّعة
  step(id) {
    if (this.pos >= this.cfg.max_seq_len) throw new Error("context full");
    const d = this.d, E = this.W["tok_emb.weight"];
    let x = new Float32Array(d);
    for (let i = 0; i < d; i++) x[i] = E.q[id * d + i] * E.s[id];
    this.blocks.thal.forEach((k, i) => { x = this.block(`thalamus.${i}.`, k, x, this.cache.thal[i]); });
    const e = this.rms(x, "drive_norm.weight");
    let s = x;
    const cat = new Float32Array(2 * d);
    for (let r = 0; r < this.cycles; r++) {
      cat.set(this.rms(s, "state_norm.weight"), 0); cat.set(e, d);
      let h = this.matvec("inject.weight", cat);
      this.blocks.col.forEach((k, i) => { h = this.block(`column.${i}.`, k, h, this.cache.col[r][i], s); });
      s = h;
    }
    this.blocks.motor.forEach((k, i) => { s = this.block(`motor.${i}.`, k, s, this.cache.motor[i]); });
    this.pos++;
    return this.rms(s, "norm.weight");
  }

  logits(h) { return this.matvec("tok_emb.weight", h); }

  judge(h) {
    const w = this.W["judge.weight"], b = this.W["judge.bias"];
    let a = b[0]; for (let i = 0; i < h.length; i++) a += w[i] * h[i];
    return 1 / (1 + Math.exp(-a));
  }

  sample(logits, recent, { temperature = 0.3, topK = 40, topP = 0.9, repPenalty = 1.2 } = {}) {
    const l = Float32Array.from(logits);
    for (const t of new Set(recent)) l[t] = l[t] > 0 ? l[t] / repPenalty : l[t] * repPenalty;
    const idx = Array.from(l.keys()).sort((a, b) => l[b] - l[a]).slice(0, topK);
    const m = l[idx[0]];
    let ps = idx.map((i) => Math.exp((l[i] - m) / Math.max(temperature, 1e-5)));
    const z = ps.reduce((a, b) => a + b, 0); ps = ps.map((p) => p / z);
    let cum = 0, cut = idx.length;
    for (let i = 0; i < idx.length; i++) { cum += ps[i]; if (cum >= topP) { cut = i + 1; break; } }
    const zz = ps.slice(0, cut).reduce((a, b) => a + b, 0);
    let r = Math.random() * zz;
    for (let i = 0; i < cut; i++) { r -= ps[i]; if (r <= 0) return idx[i]; }
    return idx[0];
  }
}