Spaces:
Running
Running
Encryptid EdgeAI from ai.encryptid.systems page, Hodge-5 weights from model repo
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- README.md+18-5
- bnz.jsAdded+721
- bnz4dec.jsAdded+144
- bnz4fetch.jsAdded+15
- bnz4load.jsAdded+287
- bnz4shaders.jsAdded+4
- bnzfetch.jsAdded+21
- bnzshare.jsAdded+700
- browse.jsAdded+443
- champ-worker.jsAdded+210
- chats.jsAdded+205
- chatui.jsAdded+116
- desk.jsAdded+104
- embed.jsAdded+198
- ext.jsAdded+587
- fastloader.jsAdded+141
- flow.jsAdded+87
- flowmap.jsAdded+290
- frame.jsAdded+100
- fzstd.jsAdded+754
- hkruntime.wasmAdded+3
- icons/icon-192.pngAdded
- icons/icon-512.pngAdded
- index.html
- iwa/ask.jsAdded+148
- iwa/boot.jsAdded+70
- iwa/index.htmlAdded+9
- iwa/manifest.webmanifestAdded+7
- kernels/attention.wgslAdded+84
- kernels/cellsum.wgslAdded+41
- kernels/dot4_native.wgslAdded+8
- kernels/dot4_soft.wgslAdded+11
- kernels/embed.wgslAdded+28
- kernels/encattn.wgslAdded+86
- kernels/encconv2d.wgslAdded+58
- kernels/encdwconv.wgslAdded+31
- kernels/encmatmul.wgslAdded+68
- kernels/encpool.wgslAdded+28
- kernels/encpos.wgslAdded+20
- kernels/encpost.wgslAdded+88
- kernels/encprep.wgslAdded+114
- kernels/encqk.wgslAdded+86
- kernels/encrelattn.wgslAdded+83
- kernels/encrelpos.wgslAdded+21
- kernels/flow.wgslAdded+71
- kernels/flowscale.wgslAdded+24
- kernels/hodgelinear.wgslAdded+77
- kernels/lmhead.wgslAdded+45
- kernels/norm.wgslAdded+126
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodels/hodge-5/tokenizer.json filter=lfs diff=lfs merge=lfs -text1234523456789101112131415161017181920212223---title: EdgeAIemoji: 🌖colorFrom: greencolorTo: bluetitle: Encryptid EdgeAIemoji: ⚡colorFrom: graycolorTo: indigosdk: staticpinned: falseshort_description: Hodge-5 running on your own device with WebGPUcustom_headers: cross-origin-embedder-policy: require-corp cross-origin-opener-policy: same-origin cross-origin-resource-policy: cross-originmodels: - EncryptidSystems/Hodge-5---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Encryptid EdgeAI
Hodge-5 runs in your browser on WebGPU. The weights stream from[EncryptidSystems/Hodge-5](https://huggingface.co/EncryptidSystems/Hodge-5).
Needs a browser with WebGPU (recent Chrome or Edge). Also live at[ai.encryptid.systems](https://ai.encryptid.systems).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721// BNZ2, the ternary safetensors codec (ternary U8 + BF16), in JS.// The ANS coder is constriction's default stack coder: 24-bit probabilities,// 32-bit words, 64-bit state, Categorical(perfect=False). Zstd frames wrap// the side tables. Gzip is not part of the container; the share layer gzips// each chunk on the wire.import { decompress as fzstdDecompress } from "./fzstd.js";
const PREC = 24;const PREC_MASK = (1 << PREC) - 1;const TOTAL = 1 << PREC;const TWO32 = 0x100000000;
function nodeZlib() { if (typeof process === "undefined" || !process.versions || !process.versions.node) return null; if (typeof process.getBuiltinModule !== "function") return null; return process.getBuiltinModule("zlib");}
function asBytes(b) { return b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? b : b.slice();}
export function zstdCompress(bytes) { const z = nodeZlib(); if (!z) throw new Error("bnz: zstd encode runs in node"); return new Uint8Array(z.zstdCompressSync(asBytes(bytes)));}
export function zstdDecompress(bytes) { const src = asBytes(bytes); const z = nodeZlib(); if (z) return new Uint8Array(z.zstdDecompressSync(src)); return fzstdDecompress(src);}
// --- sha256 (sync; the guest reads weights on the worker thread) ---const K256 = new Uint32Array([ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,]);
function rotr(x, n) { return (x >>> n) | (x << (32 - n)); }
export function sha256(data) { const bytes = data instanceof Uint8Array ? data : new Uint8Array(data); const bitLen = bytes.length * 8; const withPad = ((bytes.length + 9 + 63) >> 6) << 6; const buf = new Uint8Array(withPad); buf.set(bytes); buf[bytes.length] = 0x80; const dv = new DataView(buf.buffer); const hi = Math.floor(bitLen / TWO32); dv.setUint32(withPad - 8, hi, false); dv.setUint32(withPad - 4, bitLen >>> 0, false); let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a; let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19; const w = new Uint32Array(64); for (let i = 0; i < withPad; i += 64) { for (let t = 0; t < 16; t++) w[t] = dv.getUint32(i + t * 4, false); for (let t = 16; t < 64; t++) { const x = w[t - 15], y = w[t - 2]; const s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3); const s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10); w[t] = (w[t - 16] + s0 + w[t - 7] + s1) >>> 0; } let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7; for (let t = 0; t < 64; t++) { const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); const ch = (e & f) ^ (~e & g); const t1 = (h + S1 + ch + K256[t] + w[t]) >>> 0; const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); const maj = (a & b) ^ (a & c) ^ (b & c); const t2 = (S0 + maj) >>> 0; h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; } h0 = (h0 + a) >>> 0; h1 = (h1 + b) >>> 0; h2 = (h2 + c) >>> 0; h3 = (h3 + d) >>> 0; h4 = (h4 + e) >>> 0; h5 = (h5 + f) >>> 0; h6 = (h6 + g) >>> 0; h7 = (h7 + h) >>> 0; } return [h0, h1, h2, h3, h4, h5, h6, h7].map((x) => x.toString(16).padStart(8, "0")).join("");}
// --- fast categorical CDF, perfect=False ---// useF32 matches a float32 numpy array. bnz.py's count models are float64.export function cdfFast(probs, useF32) { const n = probs.length; const num = (x) => (useF32 ? Math.fround(x) : x); const free = TOTAL - n; let norm = num(0); for (let i = 0; i < n; i++) norm = num(norm + num(probs[i])); const scale = num(free / norm); const cdf = new Uint32Array(n + 1); let c = num(0); for (let i = 0; i < n; i++) { cdf[i] = (Math.trunc(num(c * scale)) + i) >>> 0; c = num(c + num(probs[i])); } cdf[n] = TOTAL; return cdf;}
// 64-bit / 32-bit. prob is below 2^24, so the intermediate product fits in a// safe integer. Returns [qHi, qLo, rem].export function divmod64(hi, lo, d) { hi >>>= 0; lo >>>= 0; d >>>= 0; if (hi === 0) return [0, Math.floor(lo / d) >>> 0, lo % d]; const qHi = Math.floor(hi / d); const rHi = hi % d; const q0 = Math.floor(TWO32 / d); const two32mod = TWO32 % d; const mid = rHi * two32mod + lo; const qRest = rHi * q0 + Math.floor(mid / d); const rem = mid % d; const qHiOut = (qHi + Math.floor(qRest / TWO32)) >>> 0; const qLoOut = (qRest % TWO32) >>> 0; return [qHiOut, qLoOut, rem];}
function shl24or(qHi, qLo, quantile) { const lo = ((qLo << 24) | quantile) >>> 0; const hi = ((qHi << 24) | (qLo >>> 8)) >>> 0; return [hi, lo];}
function mul32(a, b) { const aLo = a & 0xffff, aHi = a >>> 16; const bLo = b & 0xffff, bHi = b >>> 16; const p0 = aLo * bLo; const p1 = aLo * bHi; const p2 = aHi * bLo; const p3 = aHi * bHi; const mid = (p0 >>> 16) + (p1 & 0xffff) + (p2 & 0xffff); const lo = ((p0 & 0xffff) | ((mid & 0xffff) << 16)) >>> 0; const hi = (p3 + (p1 >>> 16) + (p2 >>> 16) + (mid >>> 16)) >>> 0; return [hi, lo];}
export class AnsCoder { constructor(words) { this.bulk = words ? words.slice() : []; this.hi = 0; this.lo = 0; if (words && words.length) this.#init(); }
#init() { const first = this.bulk.pop(); if ((first >>> 0) === 0) throw new Error("bnz: trailing zero word"); this.lo = first >>> 0; this.hi = 0; while (this.bulk.length) { const word = this.bulk.pop() >>> 0; this.hi = this.lo; this.lo = word; if (this.hi !== 0) break; } }
encodeSymbol(left, prob) { prob >>>= 0; left >>>= 0; if ((this.hi >>> 8) >= prob) { this.bulk.push(this.lo >>> 0); this.lo = this.hi >>> 0; this.hi = 0; } const [qHi, qLo, rem] = divmod64(this.hi, this.lo, prob); const st = shl24or(qHi, qLo, (left + rem) >>> 0); this.hi = st[0]; this.lo = st[1]; }
decodeSymbol(cdf) { const q = this.lo & PREC_MASK; let lo = 0, hi = cdf.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (cdf[mid] <= q) lo = mid + 1; else hi = mid; } const symbol = lo - 1; const left = cdf[symbol]; const prob = cdf[lo] - left; this.#mulAdd(prob, q - left); return symbol; }
#mulAdd(prob, add) { const sLo = ((this.lo >>> 24) | ((this.hi & 0xffffff) << 8)) >>> 0; const sHi = this.hi >>> 24; const [pHi, pLo] = mul32(sLo, prob); const sumLo = pLo + add; const rLo = sumLo >>> 0; const carry = sumLo >= TWO32 ? 1 : 0; this.hi = (pHi + sHi * prob + carry) >>> 0; this.lo = rLo; if (this.hi === 0 && this.bulk.length) { this.hi = this.lo; this.lo = this.bulk.pop() >>> 0; } }
getCompressed() { const extra = this.hi === 0 ? (this.lo === 0 ? [] : [this.lo >>> 0]) : [this.lo >>> 0, this.hi >>> 0]; return this.bulk.concat(extra); }}
export function encodeIid(symbols, probs, useF32) { const cdf = cdfFast(probs, useF32); const enc = new AnsCoder(); for (let i = symbols.length - 1; i >= 0; i--) { const s = symbols[i]; enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); } return enc.getCompressed();}
export function decodeIid(words, probs, n, useF32) { const cdf = cdfFast(probs, useF32); const dec = new AnsCoder(words); const out = new Array(n); for (let i = 0; i < n; i++) out[i] = dec.decodeSymbol(cdf); return out;}
export function encodeRows(rows, symbols, useF32) { const enc = new AnsCoder(); for (let i = symbols.length - 1; i >= 0; i--) { const cdf = cdfFast(rows[i], !!useF32); const s = symbols[i]; enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); } return enc.getCompressed();}
export function decodeRows(words, rows, useF32) { const dec = new AnsCoder(words); const out = new Array(rows.length); for (let i = 0; i < rows.length; i++) out[i] = dec.decodeSymbol(cdfFast(rows[i], !!useF32)); return out;}
function wordsToBytes(words) { const o = new Uint8Array(words.length * 4); const dv = new DataView(o.buffer); for (let i = 0; i < words.length; i++) dv.setUint32(i * 4, words[i] >>> 0, true); return o;}
function bytesToWords(b) { const n = b.length >> 2; const words = new Array(n); const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); for (let i = 0; i < n; i++) words[i] = dv.getUint32(i * 4, true); return words;}
function pk(parts) { let n = 0; for (const p of parts) n += 8 + p.length; const o = new Uint8Array(n); const dv = new DataView(o.buffer); let i = 0; for (const p of parts) { dv.setBigUint64(i, BigInt(p.length), true); i += 8; o.set(p, i); i += p.length; } return o;}
function upk(b) { const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); const out = []; let i = 0; while (i + 8 <= b.length) { const n = Number(dv.getBigUint64(i, true)); i += 8; out.push(b.subarray(i, i + n)); i += n; } return out;}
function u32bytes(arr) { const o = new Uint8Array(arr.length * 4); const dv = new DataView(o.buffer); for (let i = 0; i < arr.length; i++) dv.setUint32(i * 4, arr[i] >>> 0, true); return o;}
function bytesU32(b) { const n = b.length >> 2; const a = new Uint32Array(n); const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); for (let i = 0; i < n; i++) a[i] = dv.getUint32(i * 4, true); return a;}
// --- ternary U8: four 2-bit codes per byte, values 0..2 ---function splitTrits(raw, R, C) { const N = 4 * R; const t = new Int32Array(N * C); for (let r = 0; r < R; r++) { for (let c = 0; c < C; c++) { const a = raw[r * C + c]; for (let s = 0; s < 4; s++) { const v = (a >>> (2 * s)) & 3; if (v === 3) return null; t[(s * R + r) * C + c] = v; } } } return t;}
function tritCounts(t, N, C) { const rc = new Uint32Array(N * 3); const cc = new Uint32Array(C * 3); const total = N * C; for (let i = 0; i < total; i++) { const v = t[i]; const row = (i / C) | 0; const col = i - row * C; rc[row * 3 + v]++; cc[col * 3 + v]++; } const gc = new Float64Array(3); for (let r = 0; r < N; r++) for (let k = 0; k < 3; k++) gc[k] += rc[r * 3 + k]; return { rc, cc, gc };}
function probsAt(mode, rc, cc, gc, row, col) { const p = [0, 0, 0]; for (let k = 0; k < 3; k++) { if (mode === 0) p[k] = rc[row * 3 + k] + 0.5; else if (mode === 1) p[k] = cc[col * 3 + k] + 0.5; else p[k] = (rc[row * 3 + k] + 0.5) * (cc[col * 3 + k] + 0.5) / (gc[k] + 0.5); } return p;}
function cdfAt(mode, rc, cc, gc, row, col, cache) { if (mode === 0) { let hit = cache.row[row]; if (!hit) hit = cache.row[row] = cdfFast(probsAt(0, rc, cc, gc, row, 0), false); return hit; } if (mode === 1) { let hit = cache.col[col]; if (!hit) hit = cache.col[col] = cdfFast(probsAt(1, rc, cc, gc, 0, col), false); return hit; } return cdfFast(probsAt(2, rc, cc, gc, row, col), false);}
export function encTern(raw, shape, mode) { const R = shape[0], C = shape[1]; const t = splitTrits(raw, R, C); if (!t) return null; const N = 4 * R; const { rc, cc, gc } = tritCounts(t, N, C); const enc = new AnsCoder(); const cache = { row: new Array(N), col: new Array(C) }; const total = N * C; for (let i = total - 1; i >= 0; i--) { const row = (i / C) | 0; const col = i - row * C; const cdf = cdfAt(mode, rc, cc, gc, row, col, cache); const s = t[i]; enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); } const tab = u32bytes(rc); const both = new Uint8Array(tab.length + cc.length * 4); both.set(tab, 0); both.set(u32bytes(cc), tab.length); return pk([new Uint8Array([mode]), zstdCompress(both), wordsToBytes(enc.getCompressed())]);}
export function decTern(comp, shape) { const R = shape[0], C = shape[1]; const N = 4 * R; const parts = upk(comp); const mode = parts[0][0]; const tb = bytesU32(zstdDecompress(parts[1])); const rc = new Float64Array(N * 3); const cc = new Float64Array(C * 3); for (let i = 0; i < N * 3; i++) rc[i] = tb[i]; for (let i = 0; i < C * 3; i++) cc[i] = tb[N * 3 + i]; const gc = new Float64Array(3); for (let r = 0; r < N; r++) for (let k = 0; k < 3; k++) gc[k] += rc[r * 3 + k]; const rcU = rc, ccU = cc; const dec = new AnsCoder(bytesToWords(parts[2])); const cache = { row: new Array(N), col: new Array(C) }; const out = new Uint8Array(N * C); const total = N * C; for (let i = 0; i < total; i++) { const row = (i / C) | 0; const col = i - row * C; out[i] = dec.decodeSymbol(cdfAt(mode, rcU, ccU, gc, row, col, cache)); } const raw = new Uint8Array(R * C); for (let r = 0; r < R; r++) { for (let c = 0; c < C; c++) { let a = 0; for (let s = 0; s < 4; s++) a |= out[(s * R + r) * C + c] << (2 * s); raw[r * C + c] = a; } } return raw;}
// --- bf16: sign bits, per-column exponents, per-exponent mantissas ---function readU16(raw) { const n = raw.length >> 1; const v = new Uint16Array(n); for (let i = 0; i < n; i++) v[i] = raw[i * 2] | (raw[i * 2 + 1] << 8); return v;}
function packBits(bits) { const o = new Uint8Array((bits.length + 7) >> 3); for (let i = 0; i < bits.length; i++) if (bits[i]) o[i >> 3] |= 1 << (7 - (i & 7)); return o;}
function unpackBits(packed, n) { const o = new Uint8Array(n); for (let i = 0; i < n; i++) o[i] = (packed[i >> 3] >> (7 - (i & 7))) & 1; return o;}
function nonzeroCount(counts) { let nz = 0, only = 0; for (let i = 0; i < counts.length; i++) if (counts[i]) { nz++; only = i; } return [nz, only];}
function encodeCounts(enc, syms, counts) { if (syms.length === 0) return; const [nz] = nonzeroCount(counts); if (nz <= 1) return; let sum = 0; for (let i = 0; i < counts.length; i++) sum += counts[i]; const p = new Float64Array(counts.length); for (let i = 0; i < counts.length; i++) p[i] = counts[i] / sum; const cdf = cdfFast(p, false); for (let i = syms.length - 1; i >= 0; i--) { const s = syms[i]; enc.encodeSymbol(cdf[s], cdf[s + 1] - cdf[s]); }}
function decodeCounts(dec, n, counts) { const out = new Int32Array(n); if (n === 0) return out; const [nz, only] = nonzeroCount(counts); if (nz <= 1) { out.fill(only); return out; } let sum = 0; for (let i = 0; i < counts.length; i++) sum += counts[i]; const p = new Float64Array(counts.length); for (let i = 0; i < counts.length; i++) p[i] = counts[i] / sum; const cdf = cdfFast(p, false); for (let i = 0; i < n; i++) out[i] = dec.decodeSymbol(cdf); return out;}
export function encBf16(raw, shape) { const v = readU16(raw); const C = shape.length === 2 ? shape[shape.length - 1] : 1; const n = v.length; const Rr = n / C; let emin = 255, emax = 0; const ex = new Int32Array(n); const man = new Int32Array(n); const signBits = new Uint8Array(n); for (let i = 0; i < n; i++) { const x = v[i]; const e = (x >> 7) & 255; if (e < emin) emin = e; if (e > emax) emax = e; ex[i] = e; man[i] = x & 127; signBits[i] = x >> 15; } const K = emax - emin + 1; const exf = new Int32Array(n); for (let i = 0; i < n; i++) exf[i] = ex[i] - emin; const ecnt = new Uint32Array(C * K); for (let r = 0; r < Rr; r++) { for (let c = 0; c < C; c++) ecnt[c * K + exf[r * C + c]]++; } const mcnt = new Uint32Array(K * 128); for (let i = 0; i < n; i++) mcnt[exf[i] * 128 + man[i]]++; const groups = Array.from({ length: K }, () => []); for (let i = 0; i < n; i++) groups[exf[i]].push(man[i]); const enc = new AnsCoder(); for (let k = K - 1; k >= 0; k--) encodeCounts(enc, groups[k], mcnt.subarray(k * 128, (k + 1) * 128)); for (let c = C - 1; c >= 0; c--) { const col = []; for (let r = 0; r < Rr; r++) col.push(exf[r * C + c]); encodeCounts(enc, col, ecnt.subarray(c * K, (c + 1) * K)); } const hdr = new Uint8Array(12); const dv = new DataView(hdr.buffer); dv.setInt32(0, emin, true); dv.setInt32(4, K, true); dv.setUint32(8, C, true); const tab = new Uint8Array((C * K + K * 128) * 4); tab.set(u32bytes(ecnt), 0); tab.set(u32bytes(mcnt), C * K * 4); return pk([hdr, zstdCompress(tab), zstdCompress(packBits(signBits)), wordsToBytes(enc.getCompressed())]);}
export function decBf16(comp, shape) { const parts = upk(comp); const hv = new DataView(parts[0].buffer, parts[0].byteOffset, parts[0].byteLength); const emin = hv.getInt32(0, true); const K = hv.getInt32(4, true); const C = hv.getUint32(8, true); const n = shape.reduce((a, b) => a * b, 1); const Rr = n / C; const tb = bytesU32(zstdDecompress(parts[1])); const ecnt = tb.subarray(0, C * K); const mcnt = tb.subarray(C * K); const dec = new AnsCoder(bytesToWords(parts[3])); const exf = new Int32Array(n); for (let c = 0; c < C; c++) { const col = decodeCounts(dec, Rr, ecnt.subarray(c * K, (c + 1) * K)); for (let r = 0; r < Rr; r++) exf[r * C + c] = col[r]; } const man = new Int32Array(n); for (let k = 0; k < K; k++) { const idx = []; for (let i = 0; i < n; i++) if (exf[i] === k) idx.push(i); const got = decodeCounts(dec, idx.length, mcnt.subarray(k * 128, (k + 1) * 128)); for (let j = 0; j < idx.length; j++) man[idx[j]] = got[j]; } const sign = unpackBits(zstdDecompress(parts[2]), n); const o = new Uint8Array(n * 2); for (let i = 0; i < n; i++) { const v = (sign[i] << 15) | ((exf[i] + emin) << 7) | man[i]; o[i * 2] = v & 255; o[i * 2 + 1] = v >> 8; } return o;}
// --- container ---export const M_RAW = 0, M_ZSTD = 1, M_TERN = 2, M_BF16 = 3;const EMB_CHUNK_BYTES = 8192 * 2560 * 2;
function ownBytes(b) { return b.buffer instanceof SharedArrayBuffer ? new Uint8Array(b) : b;}function textOf(b) { return new TextDecoder().decode(ownBytes(b)); }
export function segmentsOf(data) { const dv = new DataView(data.buffer, data.byteOffset, data.byteLength); const n = Number(dv.getBigUint64(0, true)); const header = JSON.parse(textOf(data.subarray(8, 8 + n))); const base = 8 + n; const segs = [{ name: "header", dtype: null, shape: null, start: 0, end: base }]; const items = []; for (const k of Object.keys(header)) { if (k === "__metadata__") continue; items.push([header[k].data_offsets[0], k, header[k]]); } items.sort((a, b) => a[0] - b[0]); let pos = base; for (const [, k, v] of items) { const s = base + v.data_offsets[0]; const e = base + v.data_offsets[1]; if (s > pos) segs.push({ name: "gap", dtype: null, shape: null, start: pos, end: s }); if (v.dtype === "BF16" && v.shape.length === 2 && e - s > EMB_CHUNK_BYTES) { const rb = 2 * v.shape[1]; const rows = Math.max(1, Math.floor(EMB_CHUNK_BYTES / rb)); for (let r0 = 0; r0 < v.shape[0]; r0 += rows) { const r1 = Math.min(v.shape[0], r0 + rows); segs.push({ name: k + "[" + r0 + ":" + r1 + "]", dtype: "BF16", shape: [r1 - r0, v.shape[1]], start: s + r0 * rb, end: s + r1 * rb }); } } else { segs.push({ name: k, dtype: v.dtype, shape: v.shape, start: s, end: e }); } pos = e; } if (pos < data.length) segs.push({ name: "tail", dtype: null, shape: null, start: pos, end: data.length }); return segs;}
function pick(raw, dtype, shape) { const cands = [[M_RAW, raw]]; if (raw.length > 64) cands.push([M_ZSTD, zstdCompress(raw)]); if (dtype === "U8" && shape && shape.length === 2) { for (const mode of [0, 1, 2]) { const c = encTern(raw, shape, mode); if (c) cands.push([M_TERN, c]); } } if (dtype === "BF16" && raw.length >= 4096) cands.push([M_BF16, encBf16(raw, shape)]); let best = cands[0]; for (const c of cands) if (c[1].length < best[1].length) best = c; return best;}
export function compressSafetensors(data) { const segs = segmentsOf(data); const recs = []; for (const seg of segs) { const raw = data.subarray(seg.start, seg.end); if (typeof process !== "undefined" && process.stderr) { process.stderr.write("seg " + (recs.length + 1) + "/" + segs.length + " " + seg.name + " " + raw.length + "\n"); } const [method, comp] = pick(raw, seg.dtype, seg.shape); recs.push({ name: seg.name, method, raw_off: seg.start, raw_len: raw.length, shape: method === M_TERN || method === M_BF16 ? seg.shape : null, sha256: sha256(raw), comp, }); } let off = 0; const idx = []; for (const r of recs) { idx.push({ name: r.name, method: r.method, raw_off: r.raw_off, raw_len: r.raw_len, off, len: r.comp.length, shape: r.shape, sha256: r.sha256 }); off += r.comp.length; } const ij = new TextEncoder().encode(JSON.stringify({ orig_size: data.length, sha256: sha256(data), segments: idx })); const out = new Uint8Array(4 + 8 + ij.length + off); out.set([0x42, 0x4e, 0x5a, 0x32], 0); new DataView(out.buffer).setBigUint64(4, BigInt(ij.length), true); out.set(ij, 12); let p = 12 + ij.length; for (const r of recs) { out.set(r.comp, p); p += r.comp.length; } return out;}
export function parseBnz(bnz) { if (bnz.length < 12 || bnz[0] !== 0x42 || bnz[1] !== 0x4e || bnz[2] !== 0x5a || bnz[3] !== 0x32) { throw new Error("bnz: not a BNZ2 file"); } const n = Number(new DataView(bnz.buffer, bnz.byteOffset, bnz.byteLength).getBigUint64(4, true)); const index = JSON.parse(textOf(bnz.subarray(12, 12 + n))); return { index, base: 12 + n };}
export function decodeSeg(seg, comp) { let raw; if (seg.method === M_RAW) raw = asBytes(comp); else if (seg.method === M_ZSTD) raw = zstdDecompress(comp); else if (seg.method === M_TERN) raw = decTern(comp, seg.shape); else if (seg.method === M_BF16) raw = decBf16(comp, seg.shape); else throw new Error("bnz: bad method"); if (raw.length !== seg.raw_len) throw new Error("bnz: " + seg.name + " length"); if (sha256(raw) !== seg.sha256) throw new Error("bnz: " + seg.name + " hash"); return raw;}
export function decompressSafetensors(bnz) { const { index, base } = parseBnz(bnz); const out = new Uint8Array(index.orig_size); for (const seg of index.segments) { const raw = decodeSeg(seg, bnz.subarray(base + seg.off, base + seg.off + seg.len)); out.set(raw, seg.raw_off); } if (sha256(out) !== index.sha256) throw new Error("bnz: file hash"); return out;}
// A safetensors-sized view. readAt decodes one BNZ segment at a time.export function openBytes(bnz, ensure) { if (ensure) { ensure(0, Math.min(12, bnz.length)); const jsonLen = Number(new DataView(bnz.buffer, bnz.byteOffset, 12).getBigUint64(4, true)); ensure(0, Math.min(bnz.length, 12 + jsonLen)); } const { index, base } = parseBnz(bnz); const segs = index.segments; let cache = null; function find(pos) { let lo = 0, hi = segs.length - 1, ans = 0; while (lo <= hi) { const mid = (lo + hi) >> 1; if (segs[mid].raw_off <= pos) { ans = mid; lo = mid + 1; } else hi = mid - 1; } const seg = segs[ans]; if (pos < seg.raw_off || pos >= seg.raw_off + seg.raw_len) throw new Error("bnz: hole"); return seg; } return { size: index.orig_size, readAt(pos, n) { const out = new Uint8Array(n); let filled = 0; while (filled < n) { const seg = find(pos + filled); if (!cache || cache.seg !== seg) { if (ensure) ensure(base + seg.off, seg.len); cache = { seg, raw: decodeSeg(seg, ownBytes(bnz.subarray(base + seg.off, base + seg.off + seg.len))) }; } const inner = pos + filled - seg.raw_off; const take = Math.min(n - filled, seg.raw_len - inner); if (take <= 0) throw new Error("bnz: hole"); out.set(cache.raw.subarray(inner, inner + take), filled); filled += take; } return out; }, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144// bnz4dec.js: BNZ4 segment decoder that leaves the decoded tensor on the GPU.// From bnz-loader/js/bnz4dec.js (same kernels, same// container). decode() returns the device buffer holding the raw bytes and, with readRaw, the bytes// read back. Champ uses the read-back bytes: they are sha256-checked and land in the weight heap// (bnz4load.js), which the guest reads as model.safetensors.import { TERN_WGSL, BF16_WGSL } from './bnz4shaders.js';
const S = 0x80, CDST = 0x8, CSRC = 0x4;
function upk(b) { const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); const out = []; for (let i = 0; i < b.length;) { if (i + 8 > b.length) throw new Error('bad pack'); const n = Number(dv.getBigUint64(i, true)); i += 8; if (i + n > b.length) throw new Error('bad pack'); out.push(b.subarray(i, i + n)); i += n; } return out;}const u32 = (b) => new Uint32Array(b.buffer.slice(b.byteOffset, b.byteOffset + (b.byteLength & ~3)));const le32 = (b, o) => new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(o, true);
function ternW(rc, N) { const s = [0, 0, 0]; for (let n = 0; n < N; n++) for (let k = 0; k < 3; k++) s[k] += rc[3 * n + k]; const g2 = s.map((v) => 2n * BigInt(v) + 1n); const mn = g2.reduce((a, b) => (b < a ? b : a)); return g2.map((g) => Number((0xFFFFFFFFn * mn) / g));}
export async function sha256hex(b) { const h = new Uint8Array(await crypto.subtle.digest('SHA-256', b)); return Array.from(h, (x) => x.toString(16).padStart(2, '0')).join('');}
export class BNZ4Dec { constructor(device, zstd) { this.dev = device; this.zstd = zstd; this.tern = this.#mod(TERN_WGSL, 7, ['t_build', 't_decode']); this.bf = this.#mod(BF16_WGSL, 7, ['b_build', 'b_decode']); }
#mod(code, nstore, entries) { const module = this.dev.createShaderModule({ code }); const ents = [{ binding: 0, visibility: 4, buffer: { type: 'uniform' } }]; for (let i = 1; i <= nstore; i++) ents.push({ binding: i, visibility: 4, buffer: { type: 'storage' } }); const bgl = this.dev.createBindGroupLayout({ entries: ents }); const layout = this.dev.createPipelineLayout({ bindGroupLayouts: [bgl] }); const pipes = {}; for (const e of entries) pipes[e] = this.dev.createComputePipeline({ layout, compute: { module, entryPoint: e } }); return { bgl, pipes }; }
#buf(data, size = 0) { const n = Math.max(4, (Math.max(size, data ? data.byteLength : 0) + 3) & ~3); const b = this.dev.createBuffer({ size: n, usage: S | CDST | CSRC }); if (data && data.byteLength) { let d = data; if (d.byteLength & 3) { const p = new Uint8Array((d.byteLength + 3) & ~3); p.set(d); d = p; } this.dev.queue.writeBuffer(b, 0, d); } return b; }
#uniform(v) { const a = new Uint32Array((v.length + 3) & ~3); a.set(v); const b = this.dev.createBuffer({ size: a.byteLength, usage: 0x40 | CDST }); this.dev.queue.writeBuffer(b, 0, a); return b; }
#run(m, buffers, steps) { const bg = this.dev.createBindGroup({ layout: m.bgl, entries: buffers.map((buffer, binding) => ({ binding, resource: { buffer } })) }); const enc = this.dev.createCommandEncoder(); for (const [entry, threads] of steps) { const p = enc.beginComputePass(); p.setPipeline(m.pipes[entry]); p.setBindGroup(0, bg); const wgs = Math.max(1, Math.ceil(threads / 64)); const x = Math.min(wgs, 65535); p.dispatchWorkgroups(x, Math.ceil(wgs / x)); p.end(); } this.dev.queue.submit([enc.finish()]); }
async read(src, off, size) { const n = Math.max(4, (size + 3) & ~3); const st = this.dev.createBuffer({ size: n, usage: 0x1 | CDST }); const enc = this.dev.createCommandEncoder(); enc.copyBufferToBuffer(src, off, st, 0, n); this.dev.queue.submit([enc.finish()]); await st.mapAsync(1); const out = new Uint8Array(st.getMappedRange()).slice(0, size); st.unmap(); st.destroy(); return out; }
async #tern(c, R, C, readRaw) { const p = upk(c); if (p.length !== 4 || p[0].length !== 12) throw new Error('tern4: bad payload'); const mode = le32(p[0], 0), rpc = le32(p[0], 4), nch = le32(p[0], 8), N = 4 * R; const tv = u32(await this.zstd(p[1])); if (tv.length !== 3 * (N + C) || nch !== Math.ceil(R / rpc) || C % 4) throw new Error('tern4: bad tables'); const w = ternW(tv, N); const bufs = [this.#uniform([R, C, N, mode, rpc, nch, w[0], w[1], w[2], 0, N + C, 0]), this.#buf(null, R * C), this.#buf(tv), this.#buf(null, 4 * (N + C)), this.#buf(p[3]), this.#buf(p[2]), this.#buf(null, 4 * nch), this.#buf(null, 4)]; this.#run(this.tern, bufs, [['t_build', N + C], ['t_decode', nch]]); const status = u32(await this.read(bufs[6], 0, 4 * nch)); const raw = readRaw ? await this.read(bufs[1], 0, R * C) : null; bufs.forEach((b, i) => { if (i !== 1) b.destroy(); }); if (status.some((s) => s)) { bufs[1].destroy(); throw new Error('tern4: stream overrun'); } return { gpu: bufs[1], raw }; }
async #bf16(c, shape, readRaw) { const n = shape.reduce((a, b) => a * b, 1); const p = upk(c); if (p.length !== 5 || p[0].length !== 20) throw new Error('bf16x: bad payload'); const emin = le32(p[0], 0), K = le32(p[0], 4), C = le32(p[0], 8), epc = le32(p[0], 12), nch = le32(p[0], 16); const M = C * K + K * 128; const cnt = u32(await this.zstd(p[1])); const sign = await this.zstd(p[2]); if (cnt.length !== M || sign.length !== Math.ceil(n / 8) || nch !== Math.ceil(n / epc)) throw new Error('bf16x: bad tables'); const bufs = [this.#uniform([n, C, K, emin, epc, nch, 0, M]), this.#buf(null, 2 * n), this.#buf(cnt), this.#buf(null, 4 * (2 * M + C + K)), this.#buf(sign), this.#buf(p[4]), this.#buf(p[3]), this.#buf(null, 4 * (2 + nch))]; this.#run(this.bf, bufs, [['b_build', C + K], ['b_decode', nch]]); const status = u32(await this.read(bufs[7], 8, 4 * nch)); const raw = readRaw ? await this.read(bufs[1], 0, 2 * n) : null; bufs.forEach((b, i) => { if (i !== 1) b.destroy(); }); if (status.some((s) => s)) { bufs[1].destroy(); throw new Error('bf16x: stream overrun'); } return { gpu: bufs[1], raw }; }
// decode -> { gpu: GPUBuffer|null (methods 4/5), raw: Uint8Array|null }. // Methods 0/1 are CPU (raw only). With readRaw the GPU result is also read back. async decode(seg, payload, readRaw = true) { switch (seg.method) { case 0: return { gpu: null, raw: payload }; case 1: return { gpu: null, raw: this.zstd(payload) }; case 4: return this.#tern(payload, seg.shape[0], seg.shape[1], readRaw); case 5: return this.#bf16(payload, seg.shape, readRaw); default: throw new Error(`${seg.name}: method ${seg.method} not supported`); } }}123456789101112131415// Fills the weight heap with a BNZ4 model's decoded bytes (bnz4load.js), on this worker's own GPU// device. The guest reads the heap while later segments are still arriving.import { fillHeap4 } from "./bnz4load.js";
self.onmessage = async (e) => { const m = e.data || {}; try { await fillHeap4({ url: m.url, prefix: m.prefix, step: m.step, window: m.window || null }, { buffer: m.buf }, m.table, new Int32Array(m.flags), (p) => { self.postMessage({ type: "progress", p }); }); self.postMessage({ type: "done" }); } catch (err) { self.postMessage({ type: "error", text: err && err.message ? err.message : String(err) }); }};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287// BNZ4 weights into Champ's weight heap. From bnz-loader/js/bnz-loader.js: the 12-byte header and// JSON index first; verified segments cached in OPFS under bnz4/<sha256 of header+index>/; the// missing ones fetched as coalesced HTTP Range runs in file order (4 at a time, at most `budget`// bytes fetched but not yet decoded); methods 4 and 5 decoded on the GPU (bnz4dec.js), 0 and 1 on// the CPU; every segment sha256-checked against the index, and a bad one dropped and fetched again// on its own. Where bnz-loader copies into the runtime's GPU buffers, this lands each segment's raw// bytes in the heap at raw_off: the guest reads the heap as model.safetensors (bnzshare.js openRaw)// while later segments are still arriving, so its upload() is unchanged.import { BNZ4Dec, sha256hex } from "./bnz4dec.js";import { decompress } from "./fzstd.js";import { notePages } from "./bnzshare.js";
const MAGIC = "BNZ4";const KEEP = 3; // OPFS keeps the segments of this many models, the most recently used
async function rangeGet(url, a, n) { const r = await fetch(url, { headers: { Range: "bytes=" + a + "-" + (a + n - 1) } }); if (r.status !== 206) throw new Error("Range " + a + "+" + n + " answered " + r.status); const b = new Uint8Array(await r.arrayBuffer()); if (b.length !== n) throw new Error("Range " + a + "+" + n + " gave " + b.length + " bytes"); return b;}
function zstd(b) { return decompress(b.byteOffset === 0 && b.byteLength === b.buffer.byteLength ? b : b.slice());}
// The header and the JSON index: the heap's size comes from the index, so this runs first.export async function readIndex(url) { const head = await rangeGet(url, 0, 12); if (String.fromCharCode(head[0], head[1], head[2], head[3]) !== MAGIC) throw new Error("not a BNZ4 file"); const n = Number(new DataView(head.buffer).getBigUint64(4, true)); if (!(n > 0 && n < 64 << 20)) throw new Error("BNZ4: index size " + n); const body = await rangeGet(url, 12, n); const prefix = new Uint8Array(12 + n); prefix.set(head); prefix.set(body, 12); const index = JSON.parse(new TextDecoder().decode(body)); plan(index); return { prefix, index };}
// The segments in file order, checked to tile [0, orig_size) exactly: the heap's ready flags count// bytes, so a gap or an overlap would leave the guest waiting or reading a hole.function plan(index) { const size = index && index.orig_size; if (!Number.isSafeInteger(size) || size <= 0) throw new Error("BNZ4: orig_size"); const segs = (Array.isArray(index.segments) ? index.segments : []).map((s, i) => Object.assign({}, s, { i })); for (const s of segs) { for (const k of ["raw_off", "raw_len", "off", "len", "method"]) { if (!Number.isSafeInteger(s[k]) || s[k] < 0) throw new Error("BNZ4: segment " + s.i + " " + k); } if (!/^[0-9a-f]{64}$/.test(String(s.sha256 || ""))) throw new Error("BNZ4: segment " + s.i + " sha256"); } segs.sort((a, b) => a.raw_off - b.raw_off); let at = 0; for (const s of segs) { if (s.raw_off !== at) throw new Error("BNZ4: the segments do not cover byte " + at); at += s.raw_len; } if (at !== size) throw new Error("BNZ4: the segments end at " + at + ", not " + size); return segs;}
async function gpuDevice() { if (!navigator.gpu) throw new Error("BNZ4 needs WebGPU in this worker"); const ad = await navigator.gpu.requestAdapter(); if (!ad) throw new Error("BNZ4: no WebGPU adapter"); return ad.requestDevice({ requiredLimits: { maxStorageBufferBindingSize: ad.limits.maxStorageBufferBindingSize, maxBufferSize: ad.limits.maxBufferSize, }, });}
async function cacheTop() { if (!navigator.storage || !navigator.storage.getDirectory) return null; try { const root = await navigator.storage.getDirectory(); return await root.getDirectoryHandle("bnz4", { create: true }); } catch { return null; }}
// After a full load: mark this model used, and drop all but the KEEP most recently used.async function prune(top, keepName) { try { const mark = await (await top.getDirectoryHandle(keepName)).getFileHandle(".used", { create: true }); const w = await mark.createWritable(); await w.write(String(Date.now())); await w.close(); const used = []; for await (const [name, h] of top.entries()) { if (h.kind !== "directory") continue; let t = 0; try { t = Number(await (await (await h.getFileHandle(".used")).getFile()).text()) || 0; } catch { t = 0; } used.push([name, t]); } used.sort((a, b) => b[1] - a[1]); for (const [name] of used.slice(KEEP)) { if (name !== keepName) await top.removeEntry(name, { recursive: true }); } } catch { /* storage is a cache: a failure here only costs a later download */ }}
// spec: { url, prefix (header + index bytes), step }; mem.buffer is the heap; table its page table;// flags[i] is step i of the raw image: 0 missing, 1 ready, -1 failed.export async function fillHeap4(spec, mem, table, flags, onProgress, opts) { const o = Object.assign({ concurrency: 4, maxRun: 32 << 20, budget: 192 << 20, retries: 3 }, opts || {}); const prefix = spec.prefix; const index = JSON.parse(new TextDecoder().decode(prefix.subarray(12))); const segs = plan(index); const size = index.orig_size; const step = spec.step; const base = prefix.length; const win = spec.window || null; const viewLen = win ? win.bytes : size; const data = new Uint8Array(mem.buffer, 0, viewLen); const owners = win ? new Int32Array(win.owners) : null; const rel = win ? new Int32Array(win.ctrl) : null; const chunks = Math.ceil(size / step); const got = new Float64Array(chunks);
function failAll() { for (let i = 0; i < chunks; i++) { if (Atomics.load(flags, i) === 0) { Atomics.store(flags, i, -1); Atomics.notify(flags, i); } } } function claim(stepIndex) { const slot = stepIndex % win.slots; for (;;) { const owner = Atomics.load(owners, slot); if (owner === stepIndex) return slot; const done = Atomics.load(rel, 0); if (owner < 0 || owner < done) { if (Atomics.compareExchange(owners, slot, owner, stepIndex) === owner) { if (owner >= 0) Atomics.store(flags, owner, 0); return slot; } } else { const seen = Atomics.load(rel, 0); Atomics.wait(rel, 0, seen, 120000); } } } function land(raw, off) { if (!win) { data.set(raw, off); notePages(table, off, raw.length, size); } const end = off + raw.length; for (let pos = off; pos < end; ) { const i = Math.floor(pos / step); const stop = Math.min(end, (i + 1) * step); const n = stop - pos; if (win) { const within = pos - i * step; const slot = claim(i); data.set(raw.subarray(pos - off, pos - off + n), slot * step + within); notePages(table, slot * step + within, n, win.bytes); } got[i] += n; if (got[i] >= Math.min(step, size - i * step) && Atomics.load(flags, i) !== 1) { Atomics.store(flags, i, 1); Atomics.notify(flags, i); } pos = stop; } }
try { const dec = new BNZ4Dec(await gpuDevice(), zstd); const top = await cacheTop(); const key = await sha256hex(prefix); let dir = null; if (top) { try { dir = await top.getDirectoryHandle(key, { create: true }); } catch { dir = null; } } const cachedFile = async (seg) => { if (!dir) return null; try { const f = await (await dir.getFileHandle(String(seg.i))).getFile(); return f.size === seg.len ? f : null; } catch { return null; } };
// What OPFS has (sizes only; the bytes are read when the segment's turn comes), and the // network runs for the rest, in file order. const fromCache = new Set(); for (const s of segs) if (s.len && (await cachedFile(s))) fromCache.add(s.i); const wait = new Map(); const runs = []; let run = null; for (const s of segs) { if (!s.len || fromCache.has(s.i)) continue; let resolve, reject; const p = new Promise((a, b) => { resolve = a; reject = b; }); p.catch(() => {}); wait.set(s.i, { p, resolve, reject }); if (run && run.end === s.off && run.end - run.off + s.len <= o.maxRun) { run.segs.push(s); run.end += s.len; } else { run = { off: s.off, end: s.off + s.len, segs: [s] }; runs.push(run); } } let inflight = 0; const waiters = []; const release = (n) => { inflight -= n; waiters.splice(0).forEach((w) => w()); }; let next = 0; const fetcher = async () => { while (next < runs.length) { const r = runs[next++]; const n = r.end - r.off; while (inflight > 0 && inflight + n > o.budget) await new Promise((res) => waiters.push(res)); inflight += n; try { const b = await rangeGet(spec.url, base + r.off, n); for (const s of r.segs) wait.get(s.i).resolve(b.subarray(s.off - r.off, s.off - r.off + s.len)); } catch (e) { for (const s of r.segs) wait.get(s.i).reject(e); } } }; Promise.all(Array.from({ length: o.concurrency }, fetcher)).catch(() => {});
const total = segs.reduce((a, s) => a + s.len, 0) || 1; let done = 0; const writes = []; if (onProgress) onProgress(0); for (const seg of segs) { if (!seg.raw_len) continue; const fresh = !fromCache.has(seg.i); let payload; if (fresh) { payload = seg.len ? await wait.get(seg.i).p : new Uint8Array(0); } else { const f = await cachedFile(seg); payload = f ? new Uint8Array(await f.arrayBuffer()) : await rangeGet(spec.url, base + seg.off, seg.len); } for (let attempt = 0; ; attempt++) { try { const { gpu, raw } = await dec.decode(seg, payload, true); if (gpu) gpu.destroy(); if (!raw || raw.length !== seg.raw_len || (await sha256hex(raw)) !== seg.sha256) { throw new Error(seg.name + ": sha256 mismatch"); } land(raw, seg.raw_off); if ((fresh || attempt > 0) && dir) { const keep = payload; writes.push((async () => { const w = await (await dir.getFileHandle(String(seg.i), { create: true })).createWritable(); await w.write(keep); await w.close(); })().catch(() => {})); } break; } catch (e) { if (attempt >= o.retries) throw e; if (dir) { try { await dir.removeEntry(String(seg.i)); } catch { /* not cached */ } } payload = await rangeGet(spec.url, base + seg.off, seg.len); } } if (fresh) release(seg.len); done += seg.len; if (onProgress) onProgress(done / total); } await Promise.all(writes); if (top) await prune(top, key); } catch (err) { failAll(); throw err; }}1234// Generated by `go run ./cmd/genjs` from shaders/*.wgsl. Do not edit.export const TERN_WGSL = "// BNZ4 shared code: 32-bit rANS (L=2^23, byte renorm, 16-bit probs) and integer models.\n// Every module that includes this declares `st: array\u003cu32\u003e` (the byte stream / encode scratch).\n// u32 only, no u64, no floats.\n\nconst PT: u32 = 65536u; // probability total\nconst RL: u32 = 8388608u; // rANS lower bound 2^23\n\nfn mulhi(a: u32, b: u32) -\u003e u32 {\n let a0 = a \u0026 0xFFFFu; let a1 = a \u003e\u003e 16u;\n let b0 = b \u0026 0xFFFFu; let b1 = b \u003e\u003e 16u;\n let p00 = a0 * b0; let p01 = a0 * b1; let p10 = a1 * b0; let p11 = a1 * b1;\n let mid = (p00 \u003e\u003e 16u) + (p01 \u0026 0xFFFFu) + (p10 \u0026 0xFFFFu);\n return p11 + (p01 \u003e\u003e 16u) + (p10 \u003e\u003e 16u) + (mid \u003e\u003e 16u);\n}\n\n// f_k = 1 + a_k*(T-3)/S, a_k in [1, 2^16).\nfn quant3i(a0: u32, a1: u32, a2: u32) -\u003e vec2\u003cu32\u003e {\n let s = a0 + a1 + a2;\n return vec2\u003cu32\u003e(1u + (a0 * (PT - 3u)) / s, 1u + (a1 * (PT - 3u)) / s);\n}\n\nfn mode2f(r: vec3\u003cu32\u003e, c: vec3\u003cu32\u003e, w: vec3\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n let p0 = mulhi((2u * r.x + 1u) * (2u * c.x + 1u), w.x);\n let p1 = mulhi((2u * r.y + 1u) * (2u * c.y + 1u), w.y);\n let p2 = mulhi((2u * r.z + 1u) * (2u * c.z + 1u), w.z);\n let m = max(p0, max(p1, p2));\n let bl = 32u - countLeadingZeros(m);\n var sh = 0u;\n if (bl \u003e 15u) { sh = bl - 15u; }\n return quant3i((p0 \u003e\u003e sh) + 1u, (p1 \u003e\u003e sh) + 1u, (p2 \u003e\u003e sh) + 1u);\n}\n\n// ---- decoder: stream bytes [base, base+len) of st; reads past the end return 0 (as Go) ----\nstruct Dec { x: u32, pos: u32, base: u32, len: u32 }\n\nfn getb(d: ptr\u003cfunction, Dec\u003e) -\u003e u32 {\n var b = 0u;\n if ((*d).pos \u003c (*d).len) {\n let g = (*d).base + (*d).pos;\n b = (st[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u;\n }\n (*d).pos = (*d).pos + 1u;\n return b;\n}\n\nfn dec_init(base: u32, len: u32) -\u003e Dec {\n var d = Dec(0u, 0u, base, len);\n for (var i = 0u; i \u003c 4u; i++) { d.x = (d.x \u003c\u003c 8u) | getb(\u0026d); }\n return d;\n}\n\nfn dec_adv(d: ptr\u003cfunction, Dec\u003e, start: u32, f: u32) {\n var x = f * ((*d).x \u003e\u003e 16u) + ((*d).x \u0026 0xFFFFu) - start;\n while (x \u003c RL) { x = (x \u003c\u003c 8u) | getb(d); }\n (*d).x = x;\n}\n\n// ---- encoder: writes bytes downward into the thread's own scratch region of st ----\nstruct Enc { x: u32, p: u32 }\n\nfn putb(p: u32, b: u32) {\n let w = p \u003e\u003e 2u; let sh = (p \u0026 3u) * 8u;\n st[w] = (st[w] \u0026 ~(255u \u003c\u003c sh)) | (b \u003c\u003c sh);\n}\n\nfn enc_put(e: ptr\u003cfunction, Enc\u003e, start: u32, f: u32) {\n var x = (*e).x;\n let xmax = 32768u * f; // ((L \u003e\u003e 16) \u003c\u003c 8) * f\n while (x \u003e= xmax) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n (*e).x = (x / f) * PT + (x % f) + start;\n}\n\nfn enc_flush(e: ptr\u003cfunction, Enc\u003e) {\n var x = (*e).x;\n for (var i = 0u; i \u003c 4u; i++) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n}\n\n// BNZ4 method 4: chunked ternary. Chunk k = rows [k*rpc, min(R,(k+1)*rpc)), order r, c, plane s.\nstruct TP { R: u32, C: u32, N: u32, mode: u32, rpc: u32, nch: u32, w0: u32, w1: u32, w2: u32, cap: u32, loff: u32, pad: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: TP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e raw: array\u003cu32\u003e; // packed U8 R x C\n@group(0) @binding(2) var\u003cstorage, read_write\u003e tab: array\u003cu32\u003e; // rc[3N] ++ cc[3C]\n@group(0) @binding(3) var\u003cstorage, read_write\u003e ft: array\u003cu32\u003e; // rowF[N] ++ colF[C] ++ L[65537]\n@group(0) @binding(4) var\u003cstorage, read_write\u003e st: array\u003cu32\u003e; // streams / encode scratch\n@group(0) @binding(5) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e; // decode: dir[nch+1]; encode: lens[nch]\n@group(0) @binding(6) var\u003cstorage, read_write\u003e aux: array\u003cu32\u003e; // decode: status[nch]; cost: [3*nch]\n@group(0) @binding(7) var\u003cstorage, read_write\u003e flag: array\u003catomic\u003cu32\u003e\u003e;\n\nfn tid(g: vec3\u003cu32\u003e, nw: vec3\u003cu32\u003e) -\u003e u32 { return g.x + g.y * nw.x * 64u; }\n\nfn rbyte(r: u32, c: u32) -\u003e u32 { let i = r * P.C + c; return (raw[i \u003e\u003e 2u] \u003e\u003e ((i \u0026 3u) * 8u)) \u0026 255u; }\n\nfn freqs(mode: u32, n: u32, c: u32) -\u003e vec2\u003cu32\u003e {\n if (mode == 0u) { let v = ft[n]; return vec2\u003cu32\u003e(v \u0026 0xFFFFu, v \u003e\u003e 16u); }\n if (mode == 1u) { let v = ft[P.N + c]; return vec2\u003cu32\u003e(v \u0026 0xFFFFu, v \u003e\u003e 16u); }\n let a = 3u * n; let b = 3u * (P.N + c);\n return mode2f(vec3\u003cu32\u003e(tab[a], tab[a + 1u], tab[a + 2u]), vec3\u003cu32\u003e(tab[b], tab[b + 1u], tab[b + 2u]), vec3\u003cu32\u003e(P.w0, P.w1, P.w2));\n}\n\n// returns (start, freq) for trit t\nfn symfs(t: u32, f: vec2\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n if (t == 0u) { return vec2\u003cu32\u003e(0u, f.x); }\n if (t == 1u) { return vec2\u003cu32\u003e(f.x, f.y); }\n return vec2\u003cu32\u003e(f.x + f.y, PT - f.x - f.y);\n}\n\n@compute @workgroup_size(64)\nfn t_count_rows(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let r = tid(g, nw);\n if (r \u003e= P.R) { return; }\n var cnt: array\u003cu32, 12\u003e;\n var bad = 0u;\n for (var c = 0u; c \u003c P.C; c++) {\n let b = rbyte(r, c);\n for (var s = 0u; s \u003c 4u; s++) {\n let t = (b \u003e\u003e (2u * s)) \u0026 3u;\n if (t == 3u) { bad = 1u; } else { cnt[3u * s + t] += 1u; }\n }\n }\n for (var s = 0u; s \u003c 4u; s++) {\n for (var k = 0u; k \u003c 3u; k++) { tab[3u * (s * P.R + r) + k] = cnt[3u * s + k]; }\n }\n if (bad != 0u) { atomicOr(\u0026flag[0], 1u); }\n}\n\n@compute @workgroup_size(64)\nfn t_count_cols(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let c = tid(g, nw);\n if (c \u003e= P.C) { return; }\n var cnt = vec3\u003cu32\u003e(0u);\n for (var r = 0u; r \u003c P.R; r++) {\n let b = rbyte(r, c);\n for (var s = 0u; s \u003c 4u; s++) {\n let t = (b \u003e\u003e (2u * s)) \u0026 3u;\n if (t \u003c 3u) { cnt[t] += 1u; }\n }\n }\n let o = 3u * (P.N + c);\n tab[o] = cnt.x; tab[o + 1u] = cnt.y; tab[o + 2u] = cnt.z;\n}\n\n// count model -\u003e quantized f0|f1\u003c\u003c16 tables (rows then columns)\n@compute @workgroup_size(64)\nfn t_build(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let i = tid(g, nw);\n if (i \u003e= P.N + P.C) { return; }\n let o = 3u * i;\n let f = quant3i(2u * tab[o] + 1u, 2u * tab[o + 1u] + 1u, 2u * tab[o + 2u] + 1u);\n ft[i] = f.x | (f.y \u003c\u003c 16u);\n}\n\n@compute @workgroup_size(64)\nfn t_cost(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r1 = min(P.R, (k + 1u) * P.rpc);\n for (var mode = 0u; mode \u003c 3u; mode++) {\n var s = 0u;\n for (var r = k * P.rpc; r \u003c r1; r++) {\n for (var c = 0u; c \u003c P.C; c++) {\n let b = rbyte(r, c);\n for (var sp = 0u; sp \u003c 4u; sp++) {\n let fs = symfs((b \u003e\u003e (2u * sp)) \u0026 3u, freqs(mode, sp * P.R + r, c));\n s += ft[P.loff + fs.y];\n }\n }\n }\n aux[3u * k + mode] = s;\n }\n}\n\n@compute @workgroup_size(64)\nfn t_encode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r0 = k * P.rpc; let r1 = min(P.R, (k + 1u) * P.rpc);\n let end = (k + 1u) * P.cap;\n var e = Enc(RL, end);\n for (var r = r1; r \u003e r0; r--) {\n for (var c = P.C; c \u003e 0u; c--) {\n let b = rbyte(r - 1u, c - 1u);\n for (var sp = 4u; sp \u003e 0u; sp--) {\n let fs = symfs((b \u003e\u003e (2u * (sp - 1u))) \u0026 3u, freqs(P.mode, (sp - 1u) * P.R + r - 1u, c - 1u));\n enc_put(\u0026e, fs.x, fs.y);\n }\n }\n }\n enc_flush(\u0026e);\n offs[k] = end - e.p;\n}\n\n@compute @workgroup_size(64)\nfn t_decode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let r1 = min(P.R, (k + 1u) * P.rpc);\n var d = dec_init(offs[k], offs[k + 1u] - offs[k]);\n for (var r = k * P.rpc; r \u003c r1; r++) {\n for (var c4 = 0u; c4 \u003c P.C; c4 += 4u) {\n var word = 0u;\n for (var j = 0u; j \u003c 4u; j++) {\n var by = 0u;\n for (var sp = 0u; sp \u003c 4u; sp++) {\n let f = freqs(P.mode, sp * P.R + r, c4 + j);\n let x = d.x \u0026 0xFFFFu;\n var t = 2u;\n if (x \u003c f.x) { t = 0u; } else if (x \u003c f.x + f.y) { t = 1u; }\n let fs = symfs(t, f);\n dec_adv(\u0026d, fs.x, fs.y);\n by |= t \u003c\u003c (2u * sp);\n }\n word |= by \u003c\u003c (8u * j);\n }\n raw[(r * P.C + c4) \u003e\u003e 2u] = word;\n }\n }\n aux[k] = select(0u, 1u, d.pos \u003e d.len);\n}\n";export const BF16_WGSL = "// BNZ4 shared code: 32-bit rANS (L=2^23, byte renorm, 16-bit probs) and integer models.\n// Every module that includes this declares `st: array\u003cu32\u003e` (the byte stream / encode scratch).\n// u32 only, no u64, no floats.\n\nconst PT: u32 = 65536u; // probability total\nconst RL: u32 = 8388608u; // rANS lower bound 2^23\n\nfn mulhi(a: u32, b: u32) -\u003e u32 {\n let a0 = a \u0026 0xFFFFu; let a1 = a \u003e\u003e 16u;\n let b0 = b \u0026 0xFFFFu; let b1 = b \u003e\u003e 16u;\n let p00 = a0 * b0; let p01 = a0 * b1; let p10 = a1 * b0; let p11 = a1 * b1;\n let mid = (p00 \u003e\u003e 16u) + (p01 \u0026 0xFFFFu) + (p10 \u0026 0xFFFFu);\n return p11 + (p01 \u003e\u003e 16u) + (p10 \u003e\u003e 16u) + (mid \u003e\u003e 16u);\n}\n\n// f_k = 1 + a_k*(T-3)/S, a_k in [1, 2^16).\nfn quant3i(a0: u32, a1: u32, a2: u32) -\u003e vec2\u003cu32\u003e {\n let s = a0 + a1 + a2;\n return vec2\u003cu32\u003e(1u + (a0 * (PT - 3u)) / s, 1u + (a1 * (PT - 3u)) / s);\n}\n\nfn mode2f(r: vec3\u003cu32\u003e, c: vec3\u003cu32\u003e, w: vec3\u003cu32\u003e) -\u003e vec2\u003cu32\u003e {\n let p0 = mulhi((2u * r.x + 1u) * (2u * c.x + 1u), w.x);\n let p1 = mulhi((2u * r.y + 1u) * (2u * c.y + 1u), w.y);\n let p2 = mulhi((2u * r.z + 1u) * (2u * c.z + 1u), w.z);\n let m = max(p0, max(p1, p2));\n let bl = 32u - countLeadingZeros(m);\n var sh = 0u;\n if (bl \u003e 15u) { sh = bl - 15u; }\n return quant3i((p0 \u003e\u003e sh) + 1u, (p1 \u003e\u003e sh) + 1u, (p2 \u003e\u003e sh) + 1u);\n}\n\n// ---- decoder: stream bytes [base, base+len) of st; reads past the end return 0 (as Go) ----\nstruct Dec { x: u32, pos: u32, base: u32, len: u32 }\n\nfn getb(d: ptr\u003cfunction, Dec\u003e) -\u003e u32 {\n var b = 0u;\n if ((*d).pos \u003c (*d).len) {\n let g = (*d).base + (*d).pos;\n b = (st[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u;\n }\n (*d).pos = (*d).pos + 1u;\n return b;\n}\n\nfn dec_init(base: u32, len: u32) -\u003e Dec {\n var d = Dec(0u, 0u, base, len);\n for (var i = 0u; i \u003c 4u; i++) { d.x = (d.x \u003c\u003c 8u) | getb(\u0026d); }\n return d;\n}\n\nfn dec_adv(d: ptr\u003cfunction, Dec\u003e, start: u32, f: u32) {\n var x = f * ((*d).x \u003e\u003e 16u) + ((*d).x \u0026 0xFFFFu) - start;\n while (x \u003c RL) { x = (x \u003c\u003c 8u) | getb(d); }\n (*d).x = x;\n}\n\n// ---- encoder: writes bytes downward into the thread's own scratch region of st ----\nstruct Enc { x: u32, p: u32 }\n\nfn putb(p: u32, b: u32) {\n let w = p \u003e\u003e 2u; let sh = (p \u0026 3u) * 8u;\n st[w] = (st[w] \u0026 ~(255u \u003c\u003c sh)) | (b \u003c\u003c sh);\n}\n\nfn enc_put(e: ptr\u003cfunction, Enc\u003e, start: u32, f: u32) {\n var x = (*e).x;\n let xmax = 32768u * f; // ((L \u003e\u003e 16) \u003c\u003c 8) * f\n while (x \u003e= xmax) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n (*e).x = (x / f) * PT + (x % f) + start;\n}\n\nfn enc_flush(e: ptr\u003cfunction, Enc\u003e) {\n var x = (*e).x;\n for (var i = 0u; i \u003c 4u; i++) { (*e).p = (*e).p - 1u; putb((*e).p, x \u0026 255u); x = x \u003e\u003e 8u; }\n}\n\n// BNZ4 method 5: chunked bf16 split. Chunk k = elements [k*epc, min(n,(k+1)*epc)), exponent then mantissa.\nstruct BP { n: u32, C: u32, K: u32, emin: u32, epc: u32, nch: u32, cap: u32, M: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: BP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e raw: array\u003cu32\u003e; // bf16 pairs\n@group(0) @binding(2) var\u003cstorage, read_write\u003e cnt: array\u003catomic\u003cu32\u003e\u003e; // ecnt[C*K] ++ mcnt[K*128]\n@group(0) @binding(3) var\u003cstorage, read_write\u003e tb: array\u003cu32\u003e; // f[M] ++ cum[M] ++ meta[C+K]\n@group(0) @binding(4) var\u003cstorage, read_write\u003e sg: array\u003cu32\u003e; // sign bytes, MSB-first\n@group(0) @binding(5) var\u003cstorage, read_write\u003e st: array\u003cu32\u003e;\n@group(0) @binding(6) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e;\n@group(0) @binding(7) var\u003cstorage, read_write\u003e aux: array\u003catomic\u003cu32\u003e\u003e; // [0]=emin [1]=emax [2+k]=status\n\nfn tid(g: vec3\u003cu32\u003e, nw: vec3\u003cu32\u003e) -\u003e u32 { return g.x + g.y * nw.x * 64u; }\nfn nthreads(nw: vec3\u003cu32\u003e) -\u003e u32 { return nw.x * nw.y * 64u; }\nfn elem(i: u32) -\u003e u32 { return (raw[i \u003e\u003e 1u] \u003e\u003e ((i \u0026 1u) * 16u)) \u0026 0xFFFFu; }\n\n@compute @workgroup_size(64)\nfn b_minmax(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n var lo = 255u; var hi = 0u;\n for (var i = tid(g, nw); i \u003c P.n; i += nthreads(nw)) {\n let e = (elem(i) \u003e\u003e 7u) \u0026 255u; lo = min(lo, e); hi = max(hi, e);\n }\n atomicMin(\u0026aux[0], lo); atomicMax(\u0026aux[1], hi);\n}\n\n@compute @workgroup_size(64)\nfn b_hist(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n for (var i = tid(g, nw); i \u003c P.n; i += nthreads(nw)) {\n let x = elem(i);\n let e = ((x \u003e\u003e 7u) \u0026 255u) - P.emin;\n atomicAdd(\u0026cnt[(i % P.C) * P.K + e], 1u);\n atomicAdd(\u0026cnt[P.C * P.K + e * 128u + (x \u0026 127u)], 1u);\n }\n}\n\n@compute @workgroup_size(64)\nfn b_sign(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let nwd = (P.n + 31u) / 32u;\n for (var j = tid(g, nw); j \u003c nwd; j += nthreads(nw)) {\n var w = 0u;\n for (var q = 0u; q \u003c 32u; q++) {\n let i = 32u * j + q;\n if (i \u003c P.n \u0026\u0026 (elem(i) \u003e\u003e 15u) != 0u) { w |= (0x80u \u003e\u003e (q \u0026 7u)) \u003c\u003c (8u * (q \u003e\u003e 3u)); }\n }\n sg[j] = w;\n }\n}\n\n// floor(c * 2^16 / t) with c \u003c= t \u003c 2^31, by 48-step long division (no u64)\nfn qdiv(c: u32, t: u32) -\u003e u32 {\n var rem = 0u; var q = 0u;\n for (var b = 0u; b \u003c 48u; b++) {\n var bit = 0u;\n if (b \u003c 32u) { bit = (c \u003e\u003e (31u - b)) \u0026 1u; }\n rem = (rem \u003c\u003c 1u) | bit;\n q = q \u003c\u003c 1u;\n if (rem \u003e= t) { rem -= t; q |= 1u; }\n }\n return q;\n}\n\n// Quantize (same as Go rans.Quantize) for table t: counts at cnt[co..co+sz), output f at tb[co..]\n@compute @workgroup_size(64)\nfn b_build(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let t = tid(g, nw);\n if (t \u003e= P.C + P.K) { return; }\n var co = t * P.K; var sz = P.K;\n if (t \u003e= P.C) { co = P.C * P.K + (t - P.C) * 128u; sz = 128u; }\n var total = 0u; var nz = 0u; var only = 0xFFFFFFFFu;\n for (var i = 0u; i \u003c sz; i++) {\n let c = atomicLoad(\u0026cnt[co + i]);\n total += c;\n if (c \u003e 0u) { nz += 1u; if (only == 0xFFFFFFFFu) { only = i; } }\n }\n if (only == 0xFFFFFFFFu) { only = 0u; }\n if (nz \u003c 2u) {\n for (var i = 0u; i \u003c sz; i++) { tb[co + i] = 0u; tb[P.M + co + i] = 0u; }\n tb[2u * P.M + t] = only;\n return;\n }\n var sum = 0i;\n for (var i = 0u; i \u003c sz; i++) {\n let c = atomicLoad(\u0026cnt[co + i]);\n var v = 0u;\n if (c \u003e 0u) { v = max(1u, qdiv(c, total)); }\n tb[co + i] = v; sum += i32(v);\n }\n let T = i32(PT);\n while (sum != T) {\n var bi = 0u;\n for (var i = 1u; i \u003c sz; i++) { if (tb[co + i] \u003e tb[co + bi]) { bi = i; } }\n if (sum \u003c T) {\n tb[co + bi] += u32(T - sum); sum = T;\n } else {\n var d = sum - T;\n let fb = i32(tb[co + bi]);\n if (fb - 1 \u003c d) { d = fb - 1; }\n tb[co + bi] = u32(fb - d); sum -= d;\n }\n }\n var acc = 0u;\n for (var i = 0u; i \u003c sz; i++) { tb[P.M + co + i] = acc; acc += tb[co + i]; }\n tb[2u * P.M + t] = only | 0x80000000u;\n}\n\n@compute @workgroup_size(64)\nfn b_encode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let i0 = k * P.epc; let i1 = min(P.n, (k + 1u) * P.epc);\n let end = (k + 1u) * P.cap;\n var e = Enc(RL, end);\n for (var i = i1; i \u003e i0; i--) {\n let x = elem(i - 1u);\n let ex = ((x \u003e\u003e 7u) \u0026 255u) - P.emin;\n let mt = P.C + ex;\n if ((tb[2u * P.M + mt] \u003e\u003e 31u) != 0u) {\n let o = P.C * P.K + ex * 128u + (x \u0026 127u);\n enc_put(\u0026e, tb[P.M + o], tb[o]);\n }\n let et = (i - 1u) % P.C;\n if ((tb[2u * P.M + et] \u003e\u003e 31u) != 0u) {\n let o = et * P.K + ex;\n enc_put(\u0026e, tb[P.M + o], tb[o]);\n }\n }\n enc_flush(\u0026e);\n offs[k] = end - e.p;\n}\n\n// smallest i in [0,sz) with cum[i]+f[i] \u003e x\nfn find(co: u32, sz: u32, x: u32) -\u003e u32 {\n var lo = 0u; var hi = sz;\n while (lo \u003c hi) {\n let mid = (lo + hi) \u003e\u003e 1u;\n if (tb[P.M + co + mid] + tb[co + mid] \u003e x) { hi = mid; } else { lo = mid + 1u; }\n }\n return lo;\n}\n\n@compute @workgroup_size(64)\nfn b_decode(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let k = tid(g, nw);\n if (k \u003e= P.nch) { return; }\n let i0 = k * P.epc; let i1 = min(P.n, (k + 1u) * P.epc);\n var d = dec_init(offs[k], offs[k + 1u] - offs[k]);\n var word = 0u;\n for (var i = i0; i \u003c i1; i++) {\n let et = i % P.C;\n let me = tb[2u * P.M + et];\n var ex = me \u0026 0x7FFFFFFFu;\n if ((me \u003e\u003e 31u) != 0u) {\n let co = et * P.K;\n ex = find(co, P.K, d.x \u0026 0xFFFFu);\n dec_adv(\u0026d, tb[P.M + co + ex], tb[co + ex]);\n }\n let mm = tb[2u * P.M + P.C + ex];\n var s = mm \u0026 0x7FFFFFFFu;\n if ((mm \u003e\u003e 31u) != 0u) {\n let co = P.C * P.K + ex * 128u;\n s = find(co, 128u, d.x \u0026 0xFFFFu);\n dec_adv(\u0026d, tb[P.M + co + s], tb[co + s]);\n }\n var v = ((ex + P.emin) \u003c\u003c 7u) | s;\n let sb = (sg[i \u003e\u003e 5u] \u003e\u003e (8u * ((i \u003e\u003e 3u) \u0026 3u))) \u0026 255u;\n if ((sb \u0026 (0x80u \u003e\u003e (i \u0026 7u))) != 0u) { v |= 0x8000u; }\n if ((i \u0026 1u) == 0u) { word = v; } else { raw[i \u003e\u003e 1u] = word | (v \u003c\u003c 16u); }\n }\n atomicStore(\u0026aux[2u + k], select(0u, 1u, d.pos \u003e d.len));\n}\n";export const SCAN_WGSL = "// Prefix-sum of per-chunk encoded lengths + compaction of chunk streams into one blob.\nstruct SP { n: u32, cap: u32, nwords: u32, total: u32 }\n@group(0) @binding(0) var\u003cuniform\u003e P: SP;\n@group(0) @binding(1) var\u003cstorage, read_write\u003e lens: array\u003cu32\u003e; // [n]\n@group(0) @binding(2) var\u003cstorage, read_write\u003e offs: array\u003cu32\u003e; // [n+1] exclusive scan\n@group(0) @binding(3) var\u003cstorage, read_write\u003e src: array\u003cu32\u003e; // scratch: chunk k ends at (k+1)*cap\n@group(0) @binding(4) var\u003cstorage, read_write\u003e dst: array\u003cu32\u003e; // compacted streams\n\nvar\u003cworkgroup\u003e part: array\u003cu32, 256\u003e;\n\n@compute @workgroup_size(256)\nfn s_scan(@builtin(local_invocation_id) l: vec3\u003cu32\u003e) {\n let per = (P.n + 255u) / 256u;\n let a = min(P.n, l.x * per); let b = min(P.n, a + per);\n var s = 0u;\n for (var i = a; i \u003c b; i++) { s += lens[i]; }\n part[l.x] = s;\n workgroupBarrier();\n // Hillis-Steele inclusive scan over 256 partials\n for (var d = 1u; d \u003c 256u; d = d \u003c\u003c 1u) {\n var v = part[l.x];\n if (l.x \u003e= d) { v += part[l.x - d]; }\n workgroupBarrier();\n part[l.x] = v;\n workgroupBarrier();\n }\n var run = 0u;\n if (l.x \u003e 0u) { run = part[l.x - 1u]; }\n for (var i = a; i \u003c b; i++) { offs[i] = run; run += lens[i]; }\n if (l.x == 255u) { offs[P.n] = part[255]; }\n}\n\nfn sbyte(g: u32) -\u003e u32 { return (src[g \u003e\u003e 2u] \u003e\u003e ((g \u0026 3u) * 8u)) \u0026 255u; }\n\n@compute @workgroup_size(64)\nfn s_compact(@builtin(global_invocation_id) g: vec3\u003cu32\u003e, @builtin(num_workgroups) nw: vec3\u003cu32\u003e) {\n let stride = nw.x * nw.y * 64u;\n for (var w = g.x + g.y * nw.x * 64u; w \u003c P.nwords; w += stride) {\n var word = 0u;\n // chunk containing byte 4w: largest k with offs[k] \u003c= 4w\n var lo = 0u; var hi = P.n - 1u;\n while (lo \u003c hi) { let m = (lo + hi + 1u) \u003e\u003e 1u; if (offs[m] \u003c= 4u * w) { lo = m; } else { hi = m - 1u; } }\n var k = lo;\n for (var j = 0u; j \u003c 4u; j++) {\n let p = 4u * w + j;\n if (p \u003e= P.total) { break; }\n while (p \u003e= offs[k + 1u]) { k += 1u; }\n word |= sbyte((k + 1u) * P.cap - lens[k] + (p - offs[k])) \u003c\u003c (8u * j);\n }\n dst[w] = word;\n }\n}\n";123456789101112131415161718192021// Fills the wasm heap with BNZ chunks. The guest reads that memory while// later chunks are still arriving. The file itself is not a JS buffer.import { fillHeap } from "./bnzshare.js";
self.onmessage = async (e) => { const m = e.data || {}; try { await fillHeap({ url: m.url, size: m.size, step: m.step, etag: m.etag || "", room: m.room || "", }, { buffer: m.buf }, m.table, new Int32Array(m.flags), (p) => { self.postMessage({ type: "progress", p }); }); self.postMessage({ type: "done" }); } catch (err) { self.postMessage({ type: "error", text: err && err.message ? err.message : String(err) }); }};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700// Chunk delivery for a BNZ2 weight file. The container is the bnz codec.// Each WebRTC blob is that codec's bytes, gzipped again. The join side// gunzips, concatenates, and hands the BNZ2 bytes to openBytes.import { openBytes } from "./bnz.js";
export const RANGE_STEP = 2 * 1024 * 1024;
// HeapVM page table: one byte per wasm page over one memory block// (machwasm MachPageLookupTable + HvAllocateMemoryBlock). The block is a// WebAssembly.Memory, the Chrome heap, not a JS ArrayBuffer of the file.// The process row matches chrome.processes: private memory is this block,// and jsMemory stays 0 because the body is not on the V8 heap.export const HEAP_PAGE = 65536;
export function createWeightHeap(size) { const pages = Math.ceil(size / HEAP_PAGE); const mem = new WebAssembly.Memory({ initial: pages, maximum: pages, shared: true }); const table = new SharedArrayBuffer(pages); return { mem, table, size, pages, proc: { id: 1, image: "model.bnz", type: "gpu", tpt: 1, privateMemory: 0, jsMemoryAllocated: 0, jsMemoryUsed: 0 }, };}
// A phone cannot allocate a shared wasm memory the size of the decoded// safetensors image (Hodge-3.5 is 2.18 GB). The guest reads that image// front to back, twice (the header, then the upload), so a window a little// larger than the biggest segment is enough. owners[slot] is the file step// currently stored there, or -1. ctrl[0] is the first file step the guest// may still read; earlier steps can be overwritten.export function openWeightWindow(maxRaw, step) { if (step <= 0 || maxRaw <= 0) throw new Error("weight window"); let bytes = 64 * 1024 * 1024; const need = maxRaw + step; while (bytes < need) bytes += 64 * 1024 * 1024; if (bytes > 256 * 1024 * 1024) throw new Error("a weight segment is too large for this device"); const heap = createWeightHeap(bytes); const slots = bytes / step; const ctrlSab = new SharedArrayBuffer(4); const ownersSab = new SharedArrayBuffer(slots * 4); new Int32Array(ownersSab).fill(-1); return { heap, bytes, slots, ctrlSab, ownersSab };}
export function notePages(table, off, n, size) { const pages = new Uint8Array(table); const end = Math.min(size, off + n); if (end <= off) return; const a = Math.floor(off / HEAP_PAGE); const b = Math.floor((end - 1) / HEAP_PAGE); for (let i = a; i <= b; i++) pages[i] = 1;}
export function privateMemory(table, size) { const pages = new Uint8Array(table); let n = 0; for (let i = 0; i < pages.length; i++) { if (pages[i] !== 1) continue; const start = i * HEAP_PAGE; n += Math.min(size, start + HEAP_PAGE) - start; } return n;}
export function weightProcess(table, size) { return { id: 1, image: "model.bnz", type: "gpu", tpt: 1, privateMemory: privateMemory(table, size), jsMemoryAllocated: 0, jsMemoryUsed: 0, };}
export const MAX_BLOB = 16 * 1024;const FLAG_BLOB = 0x01;const FLAG_GZIP = 0x02;const ICE = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
export function encodeFrame(msg, blob, gzipped) { const js = new TextEncoder().encode(JSON.stringify(msg)); const n = blob ? blob.length : 0; const out = new Uint8Array(5 + js.length + n); out[0] = (n ? FLAG_BLOB : 0) | (gzipped ? FLAG_GZIP : 0); new DataView(out.buffer).setUint32(1, js.length, false); out.set(js, 5); if (n) out.set(blob, 5 + js.length); return out;}
export function decodeFrame(buf) { const u = buf instanceof Uint8Array ? buf : new Uint8Array(buf); if (u.length < 5) throw new Error("bnz: short frame"); const n = new DataView(u.buffer, u.byteOffset, u.byteLength).getUint32(1, false); const msg = JSON.parse(new TextDecoder().decode(u.subarray(5, 5 + n))); const blob = (u[0] & FLAG_BLOB) ? u.subarray(5 + n) : new Uint8Array(0); return { msg, blob, gzip: (u[0] & FLAG_GZIP) !== 0 };}
export async function gzipBytes(bytes) { const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip")); return new Uint8Array(await new Response(stream).arrayBuffer());}
export async function gunzipBytes(bytes) { const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")); return new Uint8Array(await new Response(stream).arrayBuffer());}
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
function waitGather(pc) { if (pc.iceGatheringState === "complete") return Promise.resolve(); return new Promise((resolve) => { const t = setTimeout(resolve, 2500); pc.addEventListener("icegatheringstatechange", () => { if (pc.iceGatheringState === "complete") { clearTimeout(t); resolve(); } }); });}
async function pace(dc) { while (dc.bufferedAmount > 1024 * 1024) await sleep(5);}
// Host: read model.bnz by HTTP Range and send gzip(bnz-slice) frames.export function startHost({ url, room, onStatus }) { const base = roomBase(room); const pc = new RTCPeerConnection(ICE); const dc = pc.createDataChannel("bnz", { ordered: true }); dc.binaryType = "arraybuffer"; let size = 0; const say = (s) => { if (onStatus) onStatus(s); };
dc.onopen = () => { dc.send(encodeFrame({ op: "hello", name: "bnz", proto: 1 })); }; dc.onmessage = (ev) => { const frame = decodeFrame(ev.data); const m = frame.msg; if (m.op === "hello") { dc.send(encodeFrame({ op: "hello_ok", name: "bnz", proto: 1 })); return; } if (m.op === "stat") { dc.send(encodeFrame({ op: "stat_ok", id: m.id, path: m.path, size })); return; } if (m.op === "get") { sendRange(dc, url, m).catch((e) => { dc.send(encodeFrame({ op: "error", id: m.id, error: String(e.message || e) })); }); } };
(async () => { const head = await fetch(url, { method: "HEAD" }); size = Number(head.headers.get("Content-Length")); if (!head.ok || !size) throw new Error("no weights"); const offer = await pc.createOffer(); await pc.setLocalDescription(offer); await waitGather(pc); await fetch(base + "/offer", { method: "POST", body: pc.localDescription.sdp }); say("Waiting for a client."); for (;;) { const r = await fetch(base + "/answer"); if (r.ok) { const sdp = await r.text(); if (sdp.includes("v=0")) { await pc.setRemoteDescription({ type: "answer", sdp }); say("Connected."); return; } } await sleep(200); } })().catch((e) => say(String(e.message || e)));
return { close() { pc.close(); }, };}
async function readRange(url, off, n) { const r = await fetch(url, { headers: { Range: "bytes=" + off + "-" + (off + n - 1) } }); if (r.status !== 206 && r.status !== 200) throw new Error("HTTP " + r.status); const b = new Uint8Array(await r.arrayBuffer()); if (r.status === 206 || b.length === n) return b; return b.subarray(off, off + n);}
async function sendRange(dc, url, m) { const end = m.off + m.size; dc.send(encodeFrame({ op: "get_ok", id: m.id, size: m.size })); for (let off = m.off; off < end; ) { const n = Math.min(MAX_BLOB, end - off); const raw = await readRange(url, off, n); const gz = await gzipBytes(raw); await pace(dc); dc.send(encodeFrame({ op: "chunk", id: m.id, off, last: off + n >= end }, gz, true)); off += n; }}
// Join: one offer check. No offer means the caller uses HTTP.export async function pullWebRTC({ room, onProgress }) { const base = roomBase(room); const offerRes = await fetch(base + "/offer"); if (!offerRes.ok) return null; const offer = await offerRes.text(); if (!offer.includes("v=0")) return null; const pc = new RTCPeerConnection(ICE); const got = new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error("weights timed out")), 15000); let seen = false; pc.ondatachannel = (ev) => { const dc = ev.channel; dc.binaryType = "arraybuffer"; let out = null; let filled = 0; let chain = Promise.resolve(); dc.onclose = () => { if (!out || filled < out.length) reject(new Error("weights closed")); }; dc.onmessage = (msgEv) => { const frame = decodeFrame(msgEv.data); chain = chain.then(async () => { const m = frame.msg; if (m.op === "hello") { if (!seen) { seen = true; clearTimeout(timer); } dc.send(encodeFrame({ op: "hello_ok", name: "champ", proto: 1 })); dc.send(encodeFrame({ op: "stat", id: "s", path: "model.bnz" })); return; } if (m.op === "stat_ok") { out = new Uint8Array(m.size); dc.send(encodeFrame({ op: "get", id: "g", path: "model.bnz", off: 0, size: m.size })); return; } if (m.op === "error") throw new Error(m.error || "weights"); if (m.op !== "chunk" || !out) return; const raw = frame.gzip ? await gunzipBytes(frame.blob) : frame.blob; out.set(raw, m.off); filled += raw.length; if (onProgress && out.length) onProgress(filled / out.length); if (m.last || filled >= out.length) { clearTimeout(timer); resolve(out); } }).catch((e) => { clearTimeout(timer); reject(e); }); }; }; }); await pc.setRemoteDescription({ type: "offer", sdp: offer }); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); await waitGather(pc); await fetch(base + "/answer", { method: "POST", body: pc.localDescription.sdp }); try { return await got; } finally { pc.close(); }}
// The site serves the one model's packed bytes in gzip slices at a fixed endpoint: no path in// the request, so it can only ever read that file.const MODEL_PATH = "/models/champ/model.bnz";const MODEL_BYTES = "/api/model/bytes";
// A WebRTC signaling room is a plain name, never a path.function roomBase(room) { if (!/^[a-z0-9-]{1,32}$/.test(room || "")) throw new Error("weights"); return "/api/bnz/" + room;}
async function pullGzipApi(size, onProgress) { const probe = await fetch(MODEL_BYTES + "?off=0&n=1"); if (!probe.ok) return null; const first = new Uint8Array(await probe.arrayBuffer()); if (first.length !== 1) return null; const out = new Uint8Array(size); out.set(first, 0); let done = first.length; let next = 1; async function worker() { for (;;) { const off = next; next += MAX_BLOB; if (off >= size) return; const n = Math.min(MAX_BLOB, size - off); const r = await fetch(MODEL_BYTES + "?off=" + off + "&n=" + n); if (!r.ok) throw new Error("weights"); const raw = new Uint8Array(await r.arrayBuffer()); if (raw.length !== n) throw new Error("weights"); out.set(raw, off); done += n; if (onProgress) onProgress(done / size); } } if (onProgress) onProgress(done / size); await Promise.all([worker(), worker(), worker(), worker()]); return out;}
// One redirect, then ranges against the final URL. A 1 MiB range against// the public link repeats the redirect for every piece.const RANGE_WORKERS = 6;
function bodySize(res) { const cr = res.headers.get("Content-Range") || ""; const total = Number((/\/(\d+)\s*$/.exec(cr) || [])[1]); const linked = Number(res.headers.get("X-Linked-Size")); const len = Number(res.headers.get("Content-Length")); return total || linked || len || 0;}
async function pullRange(url, size, onProgress) { const out = new Uint8Array(size); let next = 0; let done = 0; async function worker() { for (;;) { const off = next; next += RANGE_STEP; if (off >= size) return; const n = Math.min(RANGE_STEP, size - off); const raw = await readRange(url, off, n); if (raw.length !== n) throw new Error("weights"); out.set(raw, off); done += n; if (onProgress) onProgress(done / size); } } const jobs = []; for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); await Promise.all(jobs); return out;}
export async function pullHttp(url, onProgress, knownSize) { const page = new URL(url, location.href); const same = page.origin === location.origin; let size = knownSize || 0; if (same && size && page.pathname === MODEL_PATH) { const gz = await pullGzipApi(size, onProgress); if (gz) return gz; } if (!size) { const probe = await fetch(url, { headers: { Range: "bytes=0-0" } }); if (probe.status !== 206 && probe.status !== 200) throw new Error("weights"); size = bodySize(probe); await probe.arrayBuffer(); if (!size) throw new Error("weights"); url = probe.url || url; } return pullRange(url, size, onProgress);}
// Download into a SharedArrayBuffer the guest can read while bytes are// still arriving. flags[i] is 0 missing, 1 ready, -1 failed.const WEIGHT_CACHE = "champ-weights";
function chunkReq(etag, step, i) { return new Request("https://champ.invalid/bnz/" + etag + "/" + step + "/" + i);}
async function openWeightCache(etag) { if (!etag || typeof caches === "undefined") return null; try { return await caches.open(WEIGHT_CACHE); } catch { return null; }}
// Drop a previous Hugging Face file only after the new one is fully stored.async function dropOtherWeights(cache, etag) { if (!cache || !etag) return; try { const keys = await cache.keys(); await Promise.all(keys.map((req) => { if (!req.url.includes("/bnz/" + etag + "/")) return cache.delete(req); })); } catch { /* private mode or a full disk */ }}
async function cachedChunk(cache, etag, step, i, n) { if (!cache || !etag) return null; try { const hit = await cache.match(chunkReq(etag, step, i)); if (!hit) return null; const b = new Uint8Array(await hit.arrayBuffer()); return b.length === n ? b : null; } catch { return null; }}
function storeChunk(cache, etag, step, i, bytes) { if (!cache || !etag) return; const copy = bytes.slice(); cache.put(chunkReq(etag, step, i), new Response(copy, { headers: { "content-length": String(copy.length) }, })).catch(() => {});}
function landChunk(data, table, flags, step, size, got, off, raw) { data.set(raw, off); notePages(table, off, raw.length, size); const i = Math.floor(off / step); got[i] += raw.length; const need = Math.min(step, size - i * step); if (got[i] >= need && Atomics.load(flags, i) !== 1) { Atomics.store(flags, i, 1); Atomics.notify(flags, i); }}
async function streamWebRTC(spec, data, table, flags, step, onProgress) { const base = roomBase(spec.room); const offerRes = await fetch(base + "/offer"); if (!offerRes.ok) return false; const offer = await offerRes.text(); if (!offer.includes("v=0")) return false; const size = spec.size; const chunks = Math.ceil(size / step); const got = new Int32Array(chunks); const pc = new RTCPeerConnection(ICE); const done = new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error("weights timed out")), 20000); let seen = false; pc.ondatachannel = (ev) => { const dc = ev.channel; dc.binaryType = "arraybuffer"; let filled = 0; let chain = Promise.resolve(); dc.onclose = () => { if (filled < size) reject(new Error("weights closed")); }; dc.onmessage = (msgEv) => { const frame = decodeFrame(msgEv.data); chain = chain.then(async () => { const m = frame.msg; if (m.op === "hello") { if (!seen) { seen = true; clearTimeout(timer); } dc.send(encodeFrame({ op: "hello_ok", name: "champ", proto: 1 })); dc.send(encodeFrame({ op: "stat", id: "s", path: "model.bnz" })); return; } if (m.op === "stat_ok") { dc.send(encodeFrame({ op: "get", id: "g", path: "model.bnz", off: 0, size })); return; } if (m.op === "error") throw new Error(m.error || "weights"); if (m.op !== "chunk") return; const raw = frame.gzip ? await gunzipBytes(frame.blob) : frame.blob; landChunk(data, table, flags, step, size, got, m.off, raw); filled += raw.length; if (onProgress && size) onProgress(filled / size); if (m.last || filled >= size) { clearTimeout(timer); resolve(true); } }).catch((e) => { clearTimeout(timer); reject(e); }); }; }; }); await pc.setRemoteDescription({ type: "offer", sdp: offer }); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); await waitGather(pc); await fetch(base + "/answer", { method: "POST", body: pc.localDescription.sdp }); try { return await done; } finally { pc.close(); }}
async function streamRange(spec, data, table, flags, step, onProgress) { const size = spec.size; const chunks = Math.ceil(size / step); const got = new Int32Array(chunks); const cache = await openWeightCache(spec.etag || ""); let next = 0; let done = 0; function fail(err) { for (let i = 0; i < chunks; i++) { if (Atomics.load(flags, i) === 0) { Atomics.store(flags, i, -1); Atomics.notify(flags, i); } } throw err; } async function worker() { for (;;) { const i = next; next += 1; if (i >= chunks) return; const off = i * step; const n = Math.min(step, size - off); let raw = await cachedChunk(cache, spec.etag, step, i, n); if (!raw) { try { raw = await readRange(spec.url, off, n); } catch (err) { fail(err); return; } if (raw.length !== n) { fail(new Error("weights")); return; } storeChunk(cache, spec.etag, step, i, raw); } landChunk(data, table, flags, step, size, got, off, raw); done += n; if (onProgress) onProgress(done / size); } } const jobs = []; for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); await Promise.all(jobs); await dropOtherWeights(cache, spec.etag || "");}
// Chunks land in the wasm heap. A missing WebRTC host falls through to// range reads of the same block. The JS side holds one chunk, not the file.export async function fillHeap(spec, mem, table, flags, onProgress) { const data = new Uint8Array(mem.buffer, 0, spec.size); if (onProgress) onProgress(0); if (spec.room) { try { if (await streamWebRTC(spec, data, table, flags, spec.step, onProgress)) return; } catch { /* range fills the same heap */ } } await streamRange(spec, data, table, flags, spec.step, onProgress);}
function flagView(flags) { return flags instanceof Int32Array ? flags : new Int32Array(flags);}
export function openHeap(mem, flags, size, step) { const data = new Uint8Array(mem.buffer, 0, size); const words = flagView(flags); function ensure(off, len) { if (len <= 0) return; const last = Math.min(size, off + len); const a = Math.floor(off / step); const b = Math.floor((last - 1) / step); for (let i = a; i <= b; i++) { while (Atomics.load(words, i) === 0) { const woke = Atomics.wait(words, i, 0, 120000); if (woke === "timed-out" && Atomics.load(words, i) === 0) throw new Error("weights"); } if (Atomics.load(words, i) !== 1) throw new Error("weights"); } } return openBytes(data, ensure);}
// A heap that holds the model's raw safetensors bytes (BNZ4: bnz4load.js lands each decoded,// verified segment at its raw_off). readAt waits for the steps it touches, then copies them out.// win, when set, is the phone window from openWeightWindow: the memory is only win.bytes long// and file step i lives at slot i % win.slots. The guest reads twice from the start, so the// first pass (the header) does not release steps; after the second read at 0, steps behind// the cursor may be overwritten. A read larger than the window copies one step at a time.export function openRaw(mem, flags, size, step, win, embed) { const words = flagView(flags); const span = win ? win.bytes : size; const data = new Uint8Array(mem.buffer, 0, span); let passes = 0; function release(stepIndex) { if (!win || passes < 2) return; if (Atomics.load(win.ctrl, 0) === stepIndex) return; Atomics.store(win.ctrl, 0, stepIndex); Atomics.notify(win.ctrl, 0); } function waitStep(i) { while (Atomics.load(words, i) !== 1) { if (Atomics.load(words, i) < 0) throw new Error("weights"); const woke = Atomics.wait(words, i, 0, 120000); if (woke === "timed-out" && Atomics.load(words, i) !== 1) throw new Error("weights"); } } // The phone path keeps the embedding tensor in a file. Bytes of that tensor // are copied there as the guest reads them. embed is {base, bytes, reuse, writeAt}. function tee(pos, bytes) { if (!embed || embed.reuse || !bytes || !bytes.length) return; const from = Math.max(pos, embed.base); const to = Math.min(pos + bytes.length, embed.base + embed.bytes); if (to <= from) return; if (!embed.writeAt(from - embed.base, bytes.subarray(from - pos, to - pos))) { throw new Error("embedding store write failed"); } } return { size, readAt(pos, n) { if (pos < 0 || n <= 0) return new Uint8Array(0); const last = Math.min(size, pos + n); if (pos === 0) passes++; if (!win) { if (last > pos) { for (let i = Math.floor(pos / step); i <= Math.floor((last - 1) / step); i++) waitStep(i); } const out = data.slice(pos, last); tee(pos, out); return out; } const out = new Uint8Array(Math.max(0, last - pos)); for (let at = pos; at < last;) { const stepIndex = Math.floor(at / step); release(stepIndex); waitStep(stepIndex); const slot = stepIndex % win.slots; if (Atomics.load(win.owners, slot) !== stepIndex) throw new Error("weights"); const within = at - stepIndex * step; const ncopy = Math.min(last - at, step - within); out.set(data.subarray(slot * step + within, slot * step + within + ncopy), at - pos); at += ncopy; } tee(pos, out); return out; }, };}
export async function fillShared(url, sab, size, step, onProgress, etag) { const chunks = Math.ceil(size / step); const flags = new Int32Array(sab, 0, chunks); const data = new Uint8Array(sab, chunks * 4, size); const cache = await openWeightCache(etag || ""); let next = 0; let done = 0; function fail(err) { for (let i = 0; i < chunks; i++) { if (Atomics.load(flags, i) === 0) { Atomics.store(flags, i, -1); Atomics.notify(flags, i); } } throw err; } async function worker() { for (;;) { const i = next; next += 1; if (i >= chunks) return; const off = i * step; const n = Math.min(step, size - off); let raw = await cachedChunk(cache, etag, step, i, n); if (!raw) { try { raw = await readRange(url, off, n); } catch (err) { fail(err); return; } if (raw.length !== n) { fail(new Error("weights")); return; } storeChunk(cache, etag, step, i, raw); } data.set(raw, off); Atomics.store(flags, i, 1); Atomics.notify(flags, i); done += n; if (onProgress) onProgress(done / size); } } const jobs = []; for (let i = 0; i < RANGE_WORKERS; i++) jobs.push(worker()); await Promise.all(jobs); await dropOtherWeights(cache, etag || "");}
export function openShared(sab, size, step) { const chunks = Math.ceil(size / step); const flags = new Int32Array(sab, 0, chunks); const data = new Uint8Array(sab, chunks * 4, size); function ensure(off, len) { if (len <= 0) return; const last = Math.min(size, off + len); const a = Math.floor(off / step); const b = Math.floor((last - 1) / step); for (let i = a; i <= b; i++) { while (Atomics.load(flags, i) === 0) { const woke = Atomics.wait(flags, i, 0, 120000); if (woke === "timed-out" && Atomics.load(flags, i) === 0) throw new Error("weights"); } if (Atomics.load(flags, i) !== 1) throw new Error("weights"); } } return openBytes(data, ensure);}
// Bytes the guest can readAt. WebRTC (bnz + gzip) when a host is up,// otherwise HTTP. The view decodes one BNZ segment at a time.export async function openWeight(spec, onProgress) { let bytes = null; if (spec.room) { try { bytes = await pullWebRTC({ room: spec.room, onProgress }); } catch { bytes = null; } } if (!bytes) bytes = await pullHttp(spec.url, onProgress, spec.size || 0); return openBytes(bytes);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443// The person's browser makes the lookup. The terms already allow that.// Nothing here sets a User-Agent. The browser sends its own.// Wikipedia's API answers a page when the query includes origin=*.
const CHROME_RE = /\b(?:outdated browser|upgrade your browser|upgrade your web browser|enable javascript|javascript is (?:required|disabled)|turn on javascript)\b/i;
function fromCode(c) { if (!Number.isFinite(c) || c <= 0 || c > 0x10ffff) return ""; try { return String.fromCodePoint(c); } catch { return ""; }}
// Recipe pages store apostrophes as ’ and '. The quote is the page's words.function decodeEntities(s) { return String(s || "") .replace(/&/gi, "&") .replace(/&#x([0-9a-f]+);/gi, (_, h) => fromCode(parseInt(h, 16))) .replace(/&#(\d+);/g, (_, d) => fromCode(Number(d))) .replace(/</gi, "<") .replace(/>/gi, ">") .replace(/"/gi, '"') .replace(/'/gi, "'") .replace(/ /gi, " ") .replace(/’|‘/gi, "'") .replace(/”|“/gi, '"') .replace(/–|—/gi, "-");}
function clean(s) { return decodeEntities(String(s || "").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();}
function allowedPage(raw) { let u; try { u = new URL(String(raw)); } catch { return false; } if (u.username || u.password) return false; if (u.protocol !== "http:" && u.protocol !== "https:") return false; const host = u.hostname.toLowerCase().replace(/\.$/, ""); if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false; if (host === "metadata.google.internal") return false; if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.includes(":")) { if (host === "0.0.0.0" || host.startsWith("10.") || host.startsWith("127.") || host.startsWith("192.168.")) return false; if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)) return false; if (/^169\.254\./.test(host)) return false; if (host === "::1" || host.startsWith("fe80:") || host.startsWith("fc") || host.startsWith("fd")) return false; } return true;}
export function wikiTitle(raw) { let u; try { u = new URL(String(raw)); } catch { return ""; } const host = u.hostname.toLowerCase().replace(/^www\./, ""); if (host !== "en.wikipedia.org" || !u.pathname.startsWith("/wiki/")) return ""; let title = ""; try { title = decodeURIComponent(u.pathname.slice("/wiki/".length)); } catch { return ""; } title = title.replace(/_/g, " ").trim(); if (!title || title.includes(":")) return ""; return title;}
export function formatHits(hits) { const list = (hits || []).filter((h) => h && h.title && h.url).slice(0, 5); if (!list.length) return ""; const text = list.map((h, i) => { const bit = h.snippet ? "\n" + h.snippet : ""; return (i + 1) + ". " + h.title + "\n" + h.url + bit; }).join("\n\n"); return text.length > 1800 ? text.slice(0, 1800) : text;}
export function parseWikiSearch(data) { const rows = data && data.query && data.query.search; if (!Array.isArray(rows)) return []; const hits = []; for (const row of rows) { const title = clean(row && row.title).slice(0, 160); if (!title) continue; hits.push({ title, url: "https://en.wikipedia.org/wiki/" + encodeURIComponent(title.replace(/ /g, "_")), snippet: clean(row.snippet).slice(0, 180), }); if (hits.length >= 5) break; } return hits;}
export function parseWikiExtract(data) { const pages = data && data.query && data.query.pages; if (!pages) return ""; const page = Object.values(pages)[0]; const extract = page && page.extract; if (!extract || page.missing != null) return ""; const paras = []; for (const para of String(extract).split(/\n+/)) { const t = clean(para); if (!t || CHROME_RE.test(t)) continue; if (t.split(/\s+/).length < 6) continue; paras.push(t); } const body = paras.join("\n\n"); return body.length > 6000 ? body.slice(0, 6000) : body;}
const NOT_A_PAGE = /(?:wikipedia\.org|wikimedia\.org|wikidata\.org|duckduckgo\.com|web\.archive\.org|archive\.org|doi\.org|dx\.doi\.org|books\.google\.|google\.com\/books|d-nb\.info|id\.loc\.gov)/i;
export function parseWikiExtlinks(data) { const pages = data && data.query && data.query.pages; if (!pages) return []; const page = Object.values(pages)[0]; const rows = (page && page.extlinks) || []; const hits = []; const hosts = new Set(); for (const row of rows) { const url = String((row && (row["*"] || row.url)) || ""); if (!/^https:\/\//i.test(url) || NOT_A_PAGE.test(url)) continue; let host = ""; try { host = new URL(url).hostname.replace(/^www\./, ""); } catch { continue; } if (!host || hosts.has(host)) continue; hosts.add(host); hits.push({ title: host, url, snippet: "" }); if (hits.length >= 3) break; } return hits;}
function ddgUrl(href) { const raw = String(href || "").replace(/&/g, "&"); const m = /[?&]uddg=([^&]+)/.exec(raw); if (!m) return ""; try { return decodeURIComponent(m[1]); } catch { return ""; }}
export function parseDdgHtml(html) { const hits = []; const seen = new Set(); const re = /<a\b([^>]*\bclass="result__a"[^>]*)>([\s\S]*?)<\/a>/gi; let m; while ((m = re.exec(String(html || "")))) { const href = /href="([^"]+)"/i.exec(m[1]); const url = ddgUrl(href && href[1]); if (!/^https?:\/\//i.test(url) || seen.has(url) || NOT_A_PAGE.test(url)) continue; const title = clean(m[2]).slice(0, 160); if (!title) continue; seen.add(url); hits.push({ title, url, snippet: "" }); if (hits.length >= 5) break; } return hits;}
export function parseDdgInstant(data) { const hits = []; const seen = new Set(); function add(title, url, snippet) { const u = String(url || ""); const name = clean(title).slice(0, 160); if (!name || !/^https?:\/\//i.test(u) || seen.has(u) || NOT_A_PAGE.test(u)) return; seen.add(u); hits.push({ title: name, url: u, snippet: clean(snippet).slice(0, 180) }); } if (data && data.AbstractURL) add(data.Heading || data.AbstractURL, data.AbstractURL, data.AbstractText); const walk = (list) => { for (const item of list || []) { if (item && Array.isArray(item.Topics)) walk(item.Topics); else if (item) add(item.Text, item.FirstURL, ""); } }; walk(data && data.RelatedTopics); return hits.slice(0, 5);}
export function articleFromHTML(html) { const raw = String(html || "") .replace(/<script[\s\S]*?<\/script>/gi, " ") .replace(/<style[\s\S]*?<\/style>/gi, " ") .replace(/<(?:nav|header|footer|aside|form)\b[\s\S]*?<\/(?:nav|header|footer|aside|form)>/gi, " "); const blocks = []; const re = /<(p|li)\b[^>]*>([\s\S]*?)<\/\1>/gi; let m; while ((m = re.exec(raw))) { const t = clean(m[2]); if (!t || CHROME_RE.test(t)) continue; const words = t.split(/\s+/).length; const li = m[1].toLowerCase() === "li"; if (li ? words < 6 : words < 12 || !/[.!?]/.test(t)) continue; blocks.push(li ? "- " + t : t); if (blocks.length >= 40) break; } const body = blocks.join("\n\n"); if (!body || body.split(/\s+/).length < 12) return ""; return body.length > 6000 ? body.slice(0, 6000) : body;}
// The local frame (frame.html on this origin) runs offscreen_script.js.// method "fetch" is called with args[0]: { url, headers, request }.// The handler JSON.parses the body. The frame returns a page as {"text": page}.const OFFSCREEN_MAGIC = 91556947316803;let testFrame = null;let frameWait = null;
export function setLocalFrame(win) { testFrame = win || null; frameWait = null;}
function canFrame(fetchImpl) { if (testFrame) return true; return (!fetchImpl || fetchImpl === globalThis.fetch) && typeof document !== "undefined" && !!document.getElementById("local-frame");}
export function localFrameWindow() { if (testFrame) return Promise.resolve(testFrame); if (typeof document === "undefined") return Promise.resolve(null); const frame = document.getElementById("local-frame"); if (!frame) return Promise.resolve(null); let win = null; try { win = frame.contentWindow; } catch { win = null; } if (win && typeof win.frameFetch === "function") return Promise.resolve(win); if (frameWait) return frameWait; frameWait = new Promise((resolve) => { const timer = setTimeout(() => resolve(null), 4000); const done = () => { clearTimeout(timer); let ready = null; try { ready = frame.contentWindow; } catch { ready = null; } resolve(ready && typeof ready.frameFetch === "function" ? ready : null); }; frame.addEventListener("load", done, { once: true }); }); return frameWait;}
export function offscreenBody(raw) { const s = typeof raw === "string" ? raw : ""; if (!s) return ""; try { const j = JSON.parse(s); if (j && typeof j === "object" && !Array.isArray(j) && typeof j.text === "string" && Object.keys(j).length === 1) return j.text; } catch { /* the handler already returned the body */ } return s;}
function headerObject(src) { const headers = {}; if (!src) return headers; if (typeof src.forEach === "function") { src.forEach((v, k) => { headers[k] = String(v); }); } else { for (const [k, v] of Object.entries(src)) headers[k] = String(v); } for (const key of Object.keys(headers)) { const low = key.toLowerCase(); if (low === "user-agent" || low === "cookie" || low === "authorization") delete headers[key]; } return headers;}
export function offscreenMessage(url, init) { const headers = headerObject(init && init.headers); if (!headers.Accept && !headers.accept) headers.Accept = "text/html,application/json"; const request = { method: (init && init.method) || "GET", credentials: "omit", cache: "no-store", }; if (init && init.body != null) request.body = typeof init.body === "string" ? init.body : String(init.body); return { magic: OFFSCREEN_MAGIC, host: "*", method: "fetch", args: [{ url, headers, request }], };}
export async function offscreenRead(url, init) { const win = await localFrameWindow(); if (!win || typeof win.frameFetch !== "function") return null; let href = ""; try { const base = typeof location !== "undefined" && location.href ? location.href : "https://ai.encryptid.systems/"; href = new URL(String(url), base).href; } catch { return null; } if (!/^https:\/\//i.test(href)) return null; const reply = await win.frameFetch(offscreenMessage(href, init)); const result = reply && reply.result; if (!result || result.ok === false && !result.text) return null; return { ok: !!result.ok, status: Number(result.status) || 0, headers: result.headers && typeof result.headers === "object" ? result.headers : {}, text: offscreenBody(result.text), };}
function asResponse(got) { if (!got) { return { ok: false, status: 0, headers: { get() { return ""; } }, text: async () => "", json: async () => null }; } const text = got.text || ""; const table = got.headers || {}; return { ok: !!got.ok && got.status >= 200 && got.status < 300, status: got.status, headers: { get(name) { const want = String(name || "").toLowerCase(); for (const [k, v] of Object.entries(table)) { if (String(k).toLowerCase() === want) return String(v); } return ""; }, }, text: async () => text, json: async () => JSON.parse(text), };}
// duck.ai and Gemini run in the local frame. The frame's script does the fetch.export function pageFetch(fetchImpl) { const base = fetchImpl || globalThis.fetch; if (base !== globalThis.fetch) return base; return async (input, init) => { const url = typeof input === "string" ? input : (input && input.url) || ""; const got = await offscreenRead(url, init); if (got && (got.text || got.ok)) return asResponse(got); try { return await base(input, init); } catch { return asResponse(null); } };}
// The site search is the same origin. It is used when the browser cannot read the page.async function serverLookup(path, params, fetchImpl) { const f = fetchImpl || fetch; const u = new URL(path, "http://champ.local"); for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); try { const r = await f(u.pathname + u.search, { headers: { Accept: "application/json" }, cache: "no-store" }); if (!r || !r.ok || typeof r.json !== "function") return ""; const j = await r.json(); if (!j || j.ok === false || typeof j.output !== "string") return ""; return j.output; } catch { return ""; }}
async function browserJSON(url, fetchImpl) { const f = fetchImpl || fetch; const r = await f(url, { headers: { Accept: "application/json" }, cache: "no-store" }); if (!r || !r.ok || typeof r.json !== "function") return null; return r.json();}
// The host did not send a CORS header, so this origin reads the page and hands the text back.async function originRead(url, init) { if (typeof location === "undefined" || !location.origin) return null; let href = ""; try { href = new URL(String(url), location.href).href; } catch { return null; } if (!/^https:\/\//i.test(href)) return null; try { const r = await fetch(location.origin + "/api/read", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, cache: "no-store", body: JSON.stringify({ url: href, method: (init && init.method) || "GET", headers: headerObject(init && init.headers), body: init && init.body != null ? String(init.body) : "", }), }); if (!r.ok || typeof r.json !== "function") return null; const j = await r.json(); if (!j || typeof j.text !== "string") return null; return j; } catch { return null; }}
async function browserText(url, fetchImpl) { const f = fetchImpl || fetch; try { const r = await f(url, { headers: { Accept: "text/html,application/json" }, cache: "no-store" }); if (r && r.ok && typeof r.text === "function") return await r.text(); } catch { /* this page cannot read the host */ } if (f === globalThis.fetch) { const got = await originRead(url); if (got && got.status >= 200 && got.status < 300 && got.text) return got.text; } return "";}
export async function browserSearch(source, q, fetchImpl) { const query = clean(q).slice(0, 200); if (!query) return ""; const kind = String(source || "").trim().toLowerCase(); try { if (kind === "wiki" || kind === "wikipedia") { const url = "https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&origin=*&srlimit=5&srnamespace=0&srprop=snippet&srsearch=" + encodeURIComponent(query); const found = parseWikiSearch(await browserJSON(url, fetchImpl)); return formatHits(found.slice(0, 1)); } if (kind === "duckduckgo" || kind === "ddg") { const htmlURL = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query); let htmlHits = parseDdgHtml(await browserText(htmlURL, fetchImpl)); if (!htmlHits.length && canFrame(fetchImpl)) { const got = await offscreenRead(htmlURL); if (got && got.ok) htmlHits = parseDdgHtml(got.text); } if (htmlHits.length) return formatHits(htmlHits); const url = "https://api.duckduckgo.com/?q=" + encodeURIComponent(query) + "&format=json&no_html=1&no_redirect=1&skip_disambig=1"; const instant = formatHits(parseDdgInstant(await browserJSON(url, fetchImpl))); if (instant) return instant; // This host already searches when the browser cannot read the results page. return serverLookup("/api/ext/search", { q: query, source: "duckduckgo" }, fetchImpl); } } catch { return ""; } return "";}
export async function browserGather(raw, fetchImpl) { const title = wikiTitle(raw); try { if (title) { const url = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&explaintext=1&exsectionformat=plain&redirects=1&format=json&origin=*&titles=" + encodeURIComponent(title); const text = parseWikiExtract(await browserJSON(url, fetchImpl)); return { output: text, exit_code: text ? 0 : 1 }; } if (!allowedPage(raw)) return { output: "That address is not available.", exit_code: 1 }; let text = articleFromHTML(await browserText(raw, fetchImpl)); if (!text && canFrame(fetchImpl)) { const got = await offscreenRead(raw); if (got && got.text) text = articleFromHTML(got.text); } if (!text) text = await serverLookup("/api/ext/gather", { url: raw }, fetchImpl); return { output: text, exit_code: text ? 0 : 1 }; } catch { return { output: "", exit_code: 1 }; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210// Champ worker. Same boot as WASMJsLoader/guest-worker.js, plus a BNZ weight// view built on this thread before the guest starts. readAt stays here: a// function cannot cross postMessage.import { instantiate, run } from "/loader.js";import * as gpu from "/webgpu/webgpu-exec.js";import { createWeightHeap, fillHeap, openHeap, openRaw, openWeight, openWeightWindow, RANGE_STEP, weightProcess } from "./bnzshare.js";import { readIndex } from "./bnz4load.js";
// One download worker filling `heap`; resolves at its first progress (the guest may start reading).function heapWorker(script, msg, heap, size) { const dl = new Worker(new URL(script, import.meta.url), { type: "module" }); const started = new Promise((resolve, reject) => { dl.onmessage = (ev) => { const m = ev.data || {}; if (m.type === "progress") { self.postMessage({ type: "progress", p: m.p }); resolve(); } else if (m.type === "error") { self.postMessage({ type: "err", text: "weights: " + (m.text || "failed") }); reject(new Error(m.text || "weights")); } else if (m.type === "done") { const proc = weightProcess(heap.table, size); self.postMessage({ type: "heap", privateMemory: proc.privateMemory, jsMemory: proc.jsMemoryUsed }); resolve(); } }; dl.onerror = () => reject(new Error("weights")); }); dl.postMessage(msg); return started;}
function maxRawOf(index) { let n = 0; const segs = index.segments || []; for (let i = 0; i < segs.length; i++) if (segs[i].raw_len > n) n = segs[i].raw_len; return n;}
// The embedding tensor is one contiguous run of decoded safetensors bytes.function embedRange(index) { let base = -1; let bytes = 0; const segs = index.segments || []; for (let i = 0; i < segs.length; i++) { if (String(segs[i].name || "").indexOf("model.embed_tokens.weight") !== 0) continue; const off = segs[i].raw_off; if (base < 0 || off < base) base = off; bytes += segs[i].raw_len; } if (base < 0 || bytes <= 0) throw new Error("the checkpoint has no embedding table"); return { base, bytes };}
// The embedding table is 1.42 GB. A phone keeps it in OPFS and the guest reads// one tile at a time, instead of allocating that table on the GPU. A matching// stamp from a previous load skips writing it again.async function prepareEmbed(files, sha, range) { const raw = files["model/config.json"]; if (!raw) throw new Error("model config is missing"); const cfg = JSON.parse(new TextDecoder().decode(raw)); const vocab = cfg.vocab_size | 0; const hidden = cfg.hidden_size | 0; if (vocab < 1 || hidden < 1) throw new Error("model config has no vocabulary"); if (cfg.tie_word_embeddings === false) throw new Error("this phone path needs tied embeddings"); const bytes = vocab * hidden * 2; if (range.bytes !== bytes) throw new Error("embedding size does not match the checkpoint"); if (!navigator.storage || !navigator.storage.getDirectory) throw new Error("This phone cannot store the embedding table."); const root = await navigator.storage.getDirectory(); const fh = await root.getFileHandle("hodge-embed.bf16", { create: true }); const markFh = await root.getFileHandle("hodge-embed.sha", { create: true }); let handle, mark; try { handle = await fh.createSyncAccessHandle({ mode: "readwrite" }); mark = await markFh.createSyncAccessHandle({ mode: "readwrite" }); } catch (e) { try { handle = await fh.createSyncAccessHandle(); } catch { /* reported below */ } try { mark = await markFh.createSyncAccessHandle(); } catch { /* reported below */ } if (!handle || !mark) throw new Error("This phone cannot store the embedding table. " + (e && e.message ? e.message : "")); } let reuse = false; try { const got = new Uint8Array(mark.getSize()); if (got.byteLength) mark.read(got, { at: 0 }); reuse = handle.getSize() === bytes && new TextDecoder().decode(got) === sha; } catch { reuse = false; } if (!reuse) handle.truncate(bytes); let written = 0; let stamped = reuse; function stamp() { if (stamped) return; stamped = true; const b = new TextEncoder().encode(sha); mark.truncate(b.length); mark.write(b, { at: 0 }); mark.flush(); handle.flush(); } files["model/embed.ready"] = new TextEncoder().encode(reuse ? "1" : "0"); const store = { base: range.base, bytes, reuse, size: bytes, readAt(pos, n) { const out = new Uint8Array(n); let off = 0; while (off < n) { const k = handle.read(out.subarray(off), { at: pos + off }); if (k <= 0) throw new Error("embedding read failed"); off += k; } return out; }, writeAt(pos, src) { let off = 0; while (off < src.length) { const k = handle.write(src.subarray(off), { at: pos + off }); if (k <= 0) return false; off += k; } written += src.length; if (!reuse && written >= bytes) stamp(); return true; }, flush() { handle.flush(); }, }; files["model/embed.bf16"] = store; return store;}
self.onmessage = async (e) => { const msg = e.data; if (msg && msg.type === "vgpu-canvas") { gpu.canvasAnswer(msg); return; } if (!msg || msg.type !== "boot") return; try { const files = msg.files || {}; const w = files["model/model.safetensors"]; const wasmTask = msg.bytes ? Promise.resolve(msg.bytes) : fetch(msg.wasm).then((r) => r.arrayBuffer()); let weight = null; let wasmBytes = null; if (w && w.codec === "bnz4" && w.url) { // BNZ4: the heap is the decoded safetensors image, filled segment by segment (bnz4fetch.js). const { prefix, index } = await readIndex(w.url); const size = index.orig_size; const step = RANGE_STEP; const heap = createWeightHeap(size); const flags = new SharedArrayBuffer(Math.ceil(size / step) * 4); const started = heapWorker("./bnz4fetch.js", { url: w.url, prefix, buf: heap.mem.buffer, table: heap.table, flags, step, }, heap, size); const ready = await Promise.all([wasmTask, started]); wasmBytes = ready[0]; weight = openRaw(heap.mem, flags, size, step); } else if (w && w.codec === "bnz" && w.url && w.size) { const step = RANGE_STEP; const chunks = Math.ceil(w.size / step); const heap = createWeightHeap(w.size); const flags = new SharedArrayBuffer(chunks * 4); const dl = new Worker(new URL("./bnzfetch.js", import.meta.url), { type: "module" }); const started = new Promise((resolve, reject) => { dl.onmessage = (ev) => { const m = ev.data || {}; if (m.type === "progress") { self.postMessage({ type: "progress", p: m.p }); resolve(); } else if (m.type === "error") reject(new Error(m.text || "weights")); else if (m.type === "done") { const proc = weightProcess(heap.table, w.size); self.postMessage({ type: "heap", privateMemory: proc.privateMemory, jsMemory: proc.jsMemoryUsed }); resolve(); } }; dl.onerror = () => reject(new Error("weights")); }); dl.postMessage({ url: w.url, buf: heap.mem.buffer, table: heap.table, flags, size: w.size, step, etag: w.etag || "", room: w.room || "", }); const bytesEarly = await Promise.all([wasmTask, started]); weight = openHeap(heap.mem, flags, w.size, step); wasmBytes = bytesEarly[0]; } else if (w && w.codec === "bnz") { weight = await openWeight(w, (p) => { self.postMessage({ type: "progress", p }); }); } const bytes = wasmBytes || await wasmTask; if (weight) files["model/model.safetensors"] = weight; const inst = await instantiate(bytes, { args: msg.args || ["guest.wasm"], env: msg.env || [], files, stdinSab: msg.sab || null, stdout: (t) => self.postMessage({ type: "out", text: t }), stderr: (t) => self.postMessage({ type: "err", text: t }), webgpu: gpu, }); const code = await run(inst); self.postMessage({ type: "exit", code }); } catch (err) { self.postMessage({ type: "err", text: err && err.stack ? err.stack : String(err) }); self.postMessage({ type: "exit", code: -1 }); }};
self.postMessage({ type: "worker-ready" });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205// Chats in Champ's MVCC store, and the context that carries a chat across// reloads and past a full context window.//// page "chat": <id>/meta {title, created, updated} ("" = deleted)// <id>/m/<seq> {role, text, card?, at} ("" = removed)// page "sum": <id>/seg/<n> {from, to, text} one summary per stretch of turns// <id>/roll the whole chat in a few sentences; every// update is a new version (history() has them all)//// gather() builds what the model sees when its context is rebuilt: the rolling// summary, the segment summaries closest to the new message, and the recent// turns that no summary covers yet, inside a character budget.
const MSG_LIMIT = 32000;const pad = (n, w) => String(n).padStart(w, "0");
export function newChatId() { const r = Math.floor(Math.random() * 0x1000000).toString(36); return Date.now().toString(36) + r;}
export function titleOf(text) { const t = String(text || "").replace(/\s+/g, " ").trim().replace(/^\/\w+\s*/, ""); if (!t) return "New chat"; return t.length > 48 ? t.slice(0, 47).trimEnd() + "…" : t;}
function parse(v) { if (!v) return null; try { return JSON.parse(v); } catch { return null; }}
export function createChats(mind, opts) { const now = (opts && opts.now) || (() => Date.now());
function meta(id) { return parse(mind.read("chat", id + "/meta")); } function putMeta(id, m) { mind.commit("chat", id + "/meta", JSON.stringify(m), MSG_LIMIT); } function messages(id) { return mind.scan("chat", id + "/m/") .map((r) => { const m = parse(r.value); return m && Object.assign({ seq: Number(r.key.slice(id.length + 3)) }, m); }) .filter(Boolean) .sort((a, b) => a.seq - b.seq); } function nextSeq(id) { const all = mind.scan("chat", id + "/m/"); let n = 0; for (const r of all) n = Math.max(n, Number(r.key.slice(id.length + 3)) + 1); return n; } function segments(id) { return mind.scan("sum", id + "/seg/") .map((r) => { const s = parse(r.value); return s && Object.assign({ n: Number(r.key.slice(id.length + 5)) }, s); }) .filter(Boolean) .sort((a, b) => a.n - b.n); }
return { list() { const out = []; for (const r of mind.scan("chat", "")) { if (!r.key.endsWith("/meta")) continue; const m = parse(r.value); if (m) out.push(Object.assign({ id: r.key.slice(0, -5) }, m)); } return out.sort((a, b) => b.updated - a.updated); }, meta, create(firstText) { const id = newChatId(); const t = now(); putMeta(id, { title: titleOf(firstText), created: t, updated: t }); return id; }, rename(id, title) { const m = meta(id); if (!m) return; putMeta(id, Object.assign(m, { title: titleOf(title), updated: m.updated })); }, remove(id) { mind.commit("chat", id + "/meta", ""); }, messages, // msg: {role: "user"|"assistant"|"card"|"link", text, card, via, link} // via: the model that answered; link: a hand-off from one model to another (the continuity chain). add(id, msg) { const seq = nextSeq(id); const rec = { role: msg.role, text: String(msg.text || ""), at: now() }; if (msg.card) rec.card = msg.card; if (msg.via) rec.via = msg.via; if (msg.link) rec.link = msg.link; mind.commit("chat", id + "/m/" + pad(seq, 6), JSON.stringify(rec), MSG_LIMIT); const m = meta(id); if (m) putMeta(id, Object.assign(m, { updated: rec.at })); return seq; }, // Removes messages seq >= from (edit and regenerate). Older versions stay in the log. truncate(id, from) { for (const m of messages(id)) if (m.seq >= from) mind.commit("chat", id + "/m/" + pad(m.seq, 6), ""); for (const s of segments(id)) if (s.to >= from) mind.commit("sum", id + "/seg/" + pad(s.n, 4), ""); }, segments, roll(id) { return mind.read("sum", id + "/roll") || ""; }, rollHistory(id) { return mind.history("sum", id + "/roll").map((r) => r.value).filter(Boolean); }, setRoll(id, text) { mind.commit("sum", id + "/roll", String(text || "").trim(), 4000); }, // The answer being built. Each commit is a new version of one key. // The page shows read(), not the generation buffer. draft(id) { return mind.read("chat", id + "/draft") || ""; }, setDraft(id, text) { return mind.commit("chat", id + "/draft", String(text || ""), MSG_LIMIT); }, clearDraft(id) { mind.commit("chat", id + "/draft", ""); }, addSegment(id, from, to, text) { const segs = segments(id); const n = segs.length ? segs[segs.length - 1].n + 1 : 0; mind.commit("sum", id + "/seg/" + pad(n, 4), JSON.stringify({ from, to, text: String(text || "").trim() }), 4000); return n; }, // The last message seq any segment summary covers, or -1. covered(id) { let to = -1; for (const s of segments(id)) to = Math.max(to, s.to); return to; }, // Context for a rebuilt model: summaries plus the recent, unsummarized turns. // before: messages with seq >= before are left out (the message being sent). gather(id, query, before, budget) { const max = budget || 1800; const parts = []; let used = 0; const roll = this.roll(id); if (roll) { parts.push("Summary of this chat so far: " + roll); used += roll.length; } const segs = segments(id).filter((s) => s.text && s.text !== roll); if (segs.length) { const qv = mind.embed(query || ""); const ranked = segs.map((s) => ({ s, score: mind.cosine(qv, mind.embed(s.text)) })) .sort((a, b) => b.score - a.score).slice(0, 2); const lines = []; for (const { s } of ranked) { if (used + s.text.length > max * 0.6) break; lines.push("- " + s.text); used += s.text.length; } if (lines.length) parts.push("Earlier parts of this chat:\n" + lines.join("\n")); } const from = this.covered(id) + 1; const recent = messages(id).filter((m) => m.seq >= from && (before == null || m.seq < before) && m.role !== "card" && m.text); const kept = []; for (let i = recent.length - 1; i >= 0; i--) { const line = (recent[i].role === "user" ? "You: " : "Hodge-3.5: ") + recent[i].text.replace(/\s+/g, " ").trim(); const clipped = line.length > 600 ? line.slice(0, 599) + "…" : line; if (used + clipped.length > max) break; kept.unshift(clipped); used += clipped.length; } if (kept.length) parts.push("Recent messages:\n" + kept.join("\n")); return parts.join("\n\n"); }, };}
// The text of turns, for a summary written from the store (no model context left).export function transcript(msgs, maxChars) { const max = maxChars || 2400; const lines = []; let used = 0; for (let i = msgs.length - 1; i >= 0; i--) { const m = msgs[i]; if (m.role === "card" || !m.text) continue; const line = (m.role === "user" ? "You: " : "Hodge-3.5: ") + m.text.replace(/\s+/g, " ").trim(); if (used + line.length > max) break; lines.unshift(line); used += line.length; } return lines.join("\n");}
// Asked inside the model's own context, which already holds the turns.export function inContextSummaryPrompt() { return "Summarize our conversation so far in at most four sentences for your own notes. Keep names, numbers, decisions and open questions. Do not use a tool.";}
export function segmentPrompt(turns) { return "Summarize this part of a chat in at most four sentences. Keep names, numbers, decisions and open questions. Do not use a tool.\n\n" + turns;}
export function rollPrompt(prev, seg) { return "Merge these two summaries of one chat into a single summary of at most five sentences. Keep names, numbers, decisions and open questions. Do not use a tool.\n\nEarlier: " + prev + "\n\nLater: " + seg;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116// The chat list in the side bar and the actions under each message.
import { copyText } from "./markdown.js";
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e;}
function groupOf(t, now) { const d0 = new Date(now); d0.setHours(0, 0, 0, 0); const day = 86400000; if (t >= d0.getTime()) return "Today"; if (t >= d0.getTime() - day) return "Yesterday"; if (t >= d0.getTime() - 7 * day) return "Previous 7 days"; if (t >= d0.getTime() - 30 * day) return "Previous 30 days"; return "Older";}
// items: [{id, title, updated}], newest first. h: {open(id), rename(id, title), remove(id)}export function renderChatList(box, items, current, h, filter) { box.textContent = ""; const f = String(filter || "").trim().toLowerCase(); const shown = f ? items.filter((c) => (c.title || "").toLowerCase().includes(f)) : items; if (!shown.length) { box.append(el("p", "chats-empty", f ? "No chats match." : "Your chats appear here.")); return; } const now = Date.now(); let group = ""; for (const c of shown) { const g = groupOf(c.updated || c.created || now, now); if (g !== group) { group = g; box.append(el("div", "chats-group", g)); } const row = el("div", "chat-row" + (c.id === current ? " on" : "")); const open = el("button", "chat-open", c.title || "New chat"); open.type = "button"; open.title = c.title || ""; open.onclick = () => h.open(c.id); const ren = el("button", "chat-act", "✎"); ren.type = "button"; ren.title = "Rename"; ren.setAttribute("aria-label", "Rename chat"); ren.onclick = (e) => { e.stopPropagation(); const input = el("input", "chat-edit"); input.value = c.title || ""; row.replaceChildren(input); input.focus(); input.select(); let done = false; const finish = (save) => { if (done) return; done = true; if (save && input.value.trim()) h.rename(c.id, input.value.trim()); else h.refresh(); }; input.onkeydown = (ev) => { if (ev.key === "Enter") finish(true); if (ev.key === "Escape") finish(false); }; input.onblur = () => finish(true); }; const del = el("button", "chat-act", "🗑"); del.type = "button"; del.title = "Delete"; del.setAttribute("aria-label", "Delete chat"); del.onclick = (e) => { e.stopPropagation(); if (del.dataset.armed) { h.remove(c.id); return; } del.dataset.armed = "1"; del.textContent = "Delete?"; del.classList.add("armed"); setTimeout(() => { if (!del.isConnected) return; delete del.dataset.armed; del.textContent = "🗑"; del.classList.remove("armed"); }, 2500); }; row.append(open, ren, del); box.append(row); }}
// The row of actions under a message. a: {text, edit?(), regen?()}export function messageActions(row, a) { row.querySelector(".acts-msg")?.remove(); const bar = el("div", "acts-msg"); const copy = el("button", "", "Copy"); copy.type = "button"; copy.onclick = () => copyText(a.text || "", copy); bar.append(copy); if (a.edit) { const b = el("button", "", "Edit"); b.type = "button"; b.onclick = a.edit; bar.append(b); } if (a.regen) { const b = el("button", "", "Regenerate"); b.type = "button"; b.onclick = a.regen; bar.append(b); } row.append(bar); return bar;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104// Champ's desk: what the tools show on the page. Tool cards in the thread// and the "run this?" confirm for exec.// Every text the model or a service returns is set with textContent.
import { renderMarkdown } from "./markdown.js";
const TITLES = { notes: "Notes", tasks: "Tasks", canvas: "Canvas", exec: "EncryptidVM" };
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e;}
function head(card) { const a = card.args || {}; const op = String(a.op || "").toLowerCase(); if (card.tool === "exec") return (card.data && card.data.command) || a.cmd || a.command || ""; if (card.tool === "notes") return [op || "list", a.path || ""].filter(Boolean).join(" "); if (card.tool === "tasks") return [op || "list", a.title || a.id || a.state || ""].filter(Boolean).join(" "); if (card.tool === "canvas") return a.title || "Canvas"; return op;}
// The card shows the blocks the canvas stored, not the raw string it was given.function canvasMarkdown(d) { if (Array.isArray(d.blocks) && d.blocks.length) { return d.blocks.map((b) => { const t = String(b.type || ""); const c = String(b.content || ""); if (t === "heading1") return "# " + c; if (t === "heading2") return "## " + c; if (t === "heading3") return "### " + c; if (t === "bullet") return "- " + c; if (t === "quote") return "> " + c; if (t === "code") return "```\n" + c + "\n```"; if (t === "todo") return "- [" + (b.checked ? "x" : " ") + "] " + c; return c; }).join("\n\n"); } return String(d.text || "");}
// A tool's result as one card. Placed before `before` (Champ's answer) or at the end.export function renderCard(thread, card, before) { const box = el("div", "tool" + (card.tool === "canvas" ? " canvas" : "") + (card.exit_code ? " bad" : "")); const top = el("div", "tool-top"); top.append(el("b", "", TITLES[card.tool] || card.tool), el("span", "tool-what", head(card))); box.append(top); const d = card.data || {}; if (card.tool === "canvas" && (d.text || (Array.isArray(d.blocks) && d.blocks.length))) { box.append(renderMarkdown(canvasMarkdown(d))); } else if (card.tool === "tasks" && Array.isArray(d.tasks) && d.tasks.length) { const ul = el("ul", "tasks"); for (const t of d.tasks) { const li = el("li", "task " + (t.state || "")); li.append(el("span", "task-key", t.key || ""), el("span", "task-state", t.state || ""), el("span", "", t.title || "")); ul.append(li); } box.append(ul); } else if (card.output) { box.append(el("pre", "", card.output)); } if (before && before.parentNode === thread) thread.insertBefore(box, before); else thread.append(box); thread.parentElement.scrollTop = thread.parentElement.scrollHeight; return box;}
// Ask before a command runs in the sandbox. Resolves true for Run.// "Allow for this chat" skips the question until the chat is reset.let allowAll = false;export function resetAllow() { allowAll = false; }
export function askConfirm(thread, command) { if (allowAll) return Promise.resolve(true); return new Promise((resolve) => { const box = el("div", "tool ask"); const top = el("div", "tool-top"); top.append(el("b", "", "Run in EncryptidVM?")); box.append(top, el("pre", "", command)); const acts = el("div", "acts"); const run = el("button", "go", "Run"); const always = el("button", "", "Allow for this chat"); const no = el("button", "", "Don't run"); for (const b of [run, always, no]) b.type = "button"; acts.append(run, always, no); box.append(acts); thread.append(box); thread.parentElement.scrollTop = thread.parentElement.scrollHeight; const done = (ok, remember) => { if (remember) allowAll = true; acts.remove(); box.classList.add(ok ? "ran" : "skipped"); top.firstChild.textContent = ok ? "Running in EncryptidVM" : "Not run"; resolve(ok); }; run.onclick = () => done(true, false); always.onclick = () => done(true, true); no.onclick = () => done(false, false); run.focus(); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198// On-device embedder. No outside embedding model.// A fixed ternary LUT, packed like the WGSL weight codes, then one discrete// exterior step on the token path: coboundary, Laplacian smooth, mean.// The LUT is stored as a BNZ2 module so new weights use the same codec.
import { decompressSafetensors, sha256 } from "./bnz.js";
export const DIM = 32;export const BUCKETS = 256;
function mix(n) { n >>>= 0; n = Math.imul(n ^ (n >>> 16), 0x7feb352d) >>> 0; n = Math.imul(n ^ (n >>> 15), 0x846ca68b) >>> 0; return (n ^ (n >>> 16)) >>> 0;}
export function buildLut() { const words = new Uint32Array(BUCKETS * (DIM / 16)); for (let b = 0; b < BUCKETS; b++) { for (let d = 0; d < DIM; d++) { const code = mix(Math.imul(b, 131) + Math.imul(d, 17) + 0x9e3779b9) % 3; const idx = b * DIM + d; words[(idx / 16) | 0] |= code << ((idx % 16) * 2); } } return words;}
export function codeAt(words, bucket, d) { const idx = bucket * DIM + d; const w = words[(idx / 16) | 0]; return ((w >>> ((idx % 16) * 2)) & 3) - 1;}
export function tokensOf(text) { const words = String(text || "").toLowerCase().match(/[a-z0-9]+/g); if (!words || !words.length) return [0]; return words.slice(0, 64).map((word) => { let h = 0x811c9dc5; for (let i = 0; i < word.length; i++) { h ^= word.charCodeAt(i); h = Math.imul(h, 0x01000193); } return (h >>> 0) % BUCKETS; });}
export function embedRaw(ids, lut) { const n = ids.length || 1; const acc = new Float32Array(DIM); for (let d = 0; d < DIM; d++) { let sum = 0; for (let i = 0; i < ids.length; i++) { const v = codeAt(lut, ids[i], d); let lv = 0; if (ids.length > 1) { if (i === 0) lv = v - codeAt(lut, ids[1], d); else if (i + 1 === ids.length) lv = v - codeAt(lut, ids[i - 1], d); else lv = 2 * v - codeAt(lut, ids[i - 1], d) - codeAt(lut, ids[i + 1], d); } sum += v - 0.5 * lv; } acc[d] = sum / n; } return acc;}
export function normalize(acc) { let norm = 0; for (let i = 0; i < acc.length; i++) norm += acc[i] * acc[i]; norm = Math.sqrt(norm) || 1; const out = new Float32Array(acc.length); for (let i = 0; i < acc.length; i++) out[i] = acc[i] / norm; return out;}
export function embedTokens(ids, lut) { return normalize(embedRaw(ids, lut));}
export function embedText(text, lut) { return embedTokens(tokensOf(text), lut);}
export function cosine(a, b) { let dot = 0, na = 0, nb = 0; const n = Math.min(a.length, b.length); for (let i = 0; i < n; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } return dot / Math.sqrt(na * nb + 1e-12);}
function safetensorU8(name, bytes, shape) { const header = {}; header[name] = { dtype: "U8", shape, data_offsets: [0, bytes.length] }; const json = new TextEncoder().encode(JSON.stringify(header)); const out = new Uint8Array(8 + json.length + bytes.length); new DataView(out.buffer).setBigUint64(0, BigInt(json.length), true); out.set(json, 8); out.set(bytes, 8 + json.length); return out;}
export function lutBytes(lut) { return new Uint8Array(lut.buffer, lut.byteOffset, lut.byteLength);}
function packRawModule(raw) { const body = { orig_size: raw.length, sha256: sha256(raw), segments: [{ name: "embed.lut", method: 0, raw_off: 0, raw_len: raw.length, off: 0, len: raw.length, shape: null, sha256: sha256(raw), }], }; const ij = new TextEncoder().encode(JSON.stringify(body)); const out = new Uint8Array(12 + ij.length + raw.length); out.set([0x42, 0x4e, 0x5a, 0x32], 0); new DataView(out.buffer).setBigUint64(4, BigInt(ij.length), true); out.set(ij, 12); out.set(raw, 12 + ij.length); return out;}
export function packEmbedModule(lut) { const bytes = lutBytes(lut); const safe = safetensorU8("embed.lut", bytes, [BUCKETS, DIM / 4]); return packRawModule(safe);}
export function unpackEmbedModule(bnz) { const safe = decompressSafetensors(bnz); const n = Number(new DataView(safe.buffer, safe.byteOffset, safe.byteLength).getBigUint64(0, true)); const payload = safe.subarray(8 + n); const copy = payload.slice(); return new Uint32Array(copy.buffer, copy.byteOffset, copy.byteLength / 4);}
export async function embedGpu(ids, lut, shader) { if (!navigator.gpu) throw new Error("no gpu"); const adapter = await navigator.gpu.requestAdapter(); if (!adapter) throw new Error("no adapter"); const device = await adapter.requestDevice(); const module = device.createShaderModule({ code: shader }); const info = await module.getCompilationInfo(); const bad = info.messages.filter((m) => m.type === "error"); if (bad.length) throw new Error(bad.map((m) => m.message).join("\n")); const tokens = new Uint32Array(ids); const tokenBuf = device.createBuffer({ size: Math.max(16, tokens.byteLength), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); const lutBuf = device.createBuffer({ size: lut.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST }); const outBuf = device.createBuffer({ size: DIM * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC }); const readBuf = device.createBuffer({ size: DIM * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); device.queue.writeBuffer(tokenBuf, 0, tokens); device.queue.writeBuffer(lutBuf, 0, lut); const bind = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } }, { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: "read-only-storage" } }, { binding: 2, visibility: GPUShaderStage.COMPUTE, buffer: { type: "storage" } }, ], }); const layout = device.createPipelineLayout({ bindGroupLayouts: [bind] }); const pipe = device.createComputePipeline({ layout, compute: { module, entryPoint: "main", constants: { N: ids.length } }, }); const group = device.createBindGroup({ layout: bind, entries: [ { binding: 0, resource: { buffer: tokenBuf } }, { binding: 1, resource: { buffer: lutBuf } }, { binding: 2, resource: { buffer: outBuf } }, ], }); const enc = device.createCommandEncoder(); const pass = enc.beginComputePass(); pass.setPipeline(pipe); pass.setBindGroup(0, group); pass.dispatchWorkgroups(1); pass.end(); enc.copyBufferToBuffer(outBuf, 0, readBuf, 0, DIM * 4); device.queue.submit([enc.finish()]); await readBuf.mapAsync(GPUMapMode.READ); const raw = new Float32Array(readBuf.getMappedRange()).slice(); readBuf.unmap(); return normalize(raw);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587// Champ extensions. A tool call is one JSON object. It may be the whole reply// or sitting inside one. While it is still arriving, the page shows a loader// (router.js: a tool beat routes to "load") and does not print the JSON.// Anything that is not a tool call stays on screen as words.//// notes, tasks and canvas run in this page (GitMesh, TodoTraq and MotionKB,// brought into the browser by localsvc.js): no sign-in, and what they keep// stays on this device. exec runs in an EncryptidVM sandbox on this machine,// after the person allows it.
import { createServices } from "./localsvc.js";import { toolsFor } from "./router.js";import { browserGather, browserSearch } from "./browse.js";import { executeRequest, frameEcho, serviceScript } from "./frame.js?v=iwa";
const AGENT = new Set(["notes", "tasks", "canvas", "exec"]);const FRAME = new Set(["duck", "duck.ai", "gemini", "gemini.google.com"]);const TOOLS = new Set(["datetime", "search", "gather", ...AGENT]);const WRITES = new Set(["write", "save", "put", "rm", "remove", "delete", "add", "new", "create", "update", "set", "done", "start", "close", "comment", "draw"]);const MAX_ROUNDS = 4;
export function isAgentTool(tool) { return AGENT.has(tool);}
// Direct commands, so a tool works without the model writing JSON:// /run <command> /notes [prefix] /note <path>[⏎text] /rm <path>// /tasks [todo|doing|done] /task <title> /done <id> /start <id>// /canvas <title>[⏎markdown] /canvasesexport function slashCall(text) { const s = String(text || ""); const m = /^\/([a-z]+)(?:[ \t]+([^\n]*))?(?:\n([\s\S]*))?$/i.exec(s.trim()); if (!m) return null; const verb = m[1].toLowerCase(); const arg = (m[2] || "").trim(); const body = m[3]; const call = (tool, args) => ({ type: "tool_call", tool, args }); switch (verb) { case "run": case "exec": return arg || body ? call("exec", { cmd: (arg + (body ? "\n" + body : "")).trim() }) : null; case "notes": return call("notes", { op: "list", path: arg }); case "note": return arg ? call("notes", body != null ? { op: "write", path: arg, text: body } : { op: "read", path: arg }) : null; case "rm": return arg ? call("notes", { op: "rm", path: arg }) : null; case "tasks": return call("tasks", { op: "list", state: arg }); case "task": return arg ? call("tasks", { op: "add", title: arg, body: body || "" }) : null; case "done": return arg ? call("tasks", { op: "done", id: arg }) : null; case "start": return arg ? call("tasks", { op: "start", id: arg }) : null; case "canvas": return arg ? call("canvas", body != null ? { op: "write", title: arg, text: body } : { op: "read", title: arg }) : null; case "canvases": return call("canvas", { op: "list" }); default: return null; }}
export function clockText() { return new Date().toLocaleString(undefined, { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", second: "2-digit", timeZoneName: "short", });}
const TOOL_NAMES = ["datetime", "search", "gather", "shell", "notes", "tasks", "canvas", "exec"];
function argsOf(obj) { let raw = obj.args != null ? obj.args : (obj.arguments != null ? obj.arguments : obj.parameters); if (typeof raw === "string") { try { raw = JSON.parse(raw); } catch { raw = null; } } if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; return raw;}
// One reply, already trimmed to a single object or the datetime shortcut.function parseCall(text) { let s = (text || "").trim(); const fence = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(s); if (fence) s = fence[1].trim(); s = s.replace(/^\s*champ\s*[,:]\s*/i, ""); if (s === "tool:datetime") return { type: "tool_call", tool: "datetime", args: {} }; if (!s.startsWith("{") || !s.endsWith("}")) return null; let obj = null; try { obj = JSON.parse(s); } catch { obj = null; } if (obj && typeof obj === "object") { const tool = typeof obj.tool === "string" ? obj.tool : (typeof obj.name === "string" ? obj.name : ""); const typed = obj.type === "tool_call"; if (tool && (typed || TOOLS.has(tool))) { if (!TOOLS.has(tool)) return { type: "tool_call", tool, args: {} }; const args = argsOf(obj); if (!typed && !args) return null; return { type: "tool_call", tool, args: args || {} }; } } if (!/tool_call/.test(s)) return null; const named = /tool\s*[:=]\s*"?(datetime|search|gather|shell|notes|tasks|canvas|exec)"?/i.exec(s); if (!named) return null; const tool = named[1].toLowerCase(); if (tool === "notes") { const args = noteFields(s); if (!args) return null; return { type: "tool_call", tool, args }; } const q = /"(?:q|query)"\s*:\s*"([^"]*)"/.exec(s); const url = /"url"\s*:\s*"(https?:[^"]*)"/.exec(s); return { type: "tool_call", tool, args: { q: q ? q[1] : "", url: url ? url[1] : "" }, };}
// A notes call the page can run. An empty object is the model reaching for// the tool with nothing to save, open, or list.function fieldOf(s, key) { const quoted = new RegExp('"' + key + '"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"').exec(s); if (quoted) return quoted[1].replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\"); const bare = new RegExp("\\b" + key + "\\s*[:=]\\s*\"?([^\"\\n,}]+)").exec(s); return bare ? bare[1].trim() : "";}
function noteFields(s) { const op = fieldOf(s, "op").toLowerCase(); const path = fieldOf(s, "path"); const text = fieldOf(s, "text"); if (!op && !path && !text) return null; const args = {}; if (op) args.op = op; if (path) args.path = path; if (text) args.text = text; return args;}
export function noteUseful(call) { if (!call || call.tool !== "notes") return false; const a = call.args || {}; if (String(a.path || "").trim()) return true; if (String(a.text || "").trim()) return true; const op = String(a.op || "").toLowerCase(); return op === "list" || op === "ls" || op === "read" || op === "open" || op === "write" || op === "save" || op === "rm";}
// The person asked to use the notes kept on this device. A draft they want// to read in the chat is not one of those.export function wantsSavedNotes(text) { return /\b(save|keep|store|put)\b.{0,40}\bnotes?\b|\bmy notes\b|\b(list|show|open|read)\b.{0,24}\bnotes?\b/i.test(String(text || ""));}
// Words already in a notes call: a sentence before the JSON, the text field,// then a sentence after it. "..." is the prompt's placeholder, not a note.export function noteWords(call, lead, trail) { const text = call && call.args ? String(call.args.text || "").trim() : ""; const body = text === "..." || text === "…" ? "" : text; const parts = [String(lead || "").trim(), body, String(trail || "").trim()].filter(Boolean); return parts.join("\n\n");}
// A short reply when the model answered a draft with an empty notes call.// The person asked to read words here.export function draftText(ask) { const q = String(ask || "").replace(/\s+/g, " ").trim(); if (/\bsummar/i.test(q)) { return "A plan in a few sentences: name the outcome, name the next step, and name what can wait."; } if (/\b(draft|write|note|plan)\b/i.test(q)) { return "A short note.\n\nOne thing to do today, one thing to remember, and one thing to leave for later."; } return "Here is a reply you can read here.";}
// The words to show for a notes-shaped reply. "" when the reply is not notes,// so a real save, list, or other tool still runs.export function chatNote(raw, ask) { const view = toolStream(raw); const notes = (view.call && view.call.tool === "notes") || view.tool === "notes"; if (!notes) return ""; const src = String(raw || ""); const at = toolStart(src); let trail = ""; if (at >= 0) { const rest = src.slice(at); const obj = rest[0] === "{" ? takeObject(rest) : ""; if (obj) trail = cleanLead(rest.slice(obj.length)); } return noteWords(view.call, view.lead, trail) || draftText(ask);}
// The first balanced {...} in s, or "" when the brace has not closed yet.function takeObject(s) { if (!s || s[0] !== "{") return ""; let depth = 0; let str = false; let esc = false; for (let i = 0; i < s.length; i++) { const c = s[i]; if (str) { if (esc) esc = false; else if (c === "\\") esc = true; else if (c === '"') str = false; continue; } if (c === '"') { str = true; continue; } if (c === "{") depth++; else if (c === "}") { depth--; if (depth === 0) return s.slice(0, i + 1); } } return "";}
function objectsIn(text) { const s = String(text || ""); const out = []; let str = false; let esc = false; for (let i = 0; i < s.length; i++) { const c = s[i]; if (str) { if (esc) esc = false; else if (c === "\\") esc = true; else if (c === '"') str = false; continue; } if (c === '"') { str = true; continue; } if (c !== "{") continue; const obj = takeObject(s.slice(i)); if (!obj) break; out.push(obj); i += obj.length - 1; } return out;}
export function toolCallOf(text) { const direct = parseCall(text); if (direct) return direct; let raw = String(text || "").trim().replace(/^\s*champ\s*[,:]\s*/i, ""); const opened = /^```(?:json)?\s*/i.exec(raw); if (opened) { raw = raw.slice(opened[0].length).replace(/\s*```\s*$/, "").trim(); const inner = parseCall(raw); if (inner) return inner; } for (const obj of objectsIn(text)) { const inner = parseCall(obj); if (inner) return inner; } return null;}
function cleanLead(s) { return String(s || "") .replace(/^\s*champ\s*[,:]\s*/i, "") .replace(/```(?:json)?[ \t]*$/i, "") .trim();}
// compact form, so a pretty-printed call matches the same prefix as one line.function squash(s) { return String(s || "").replace(/\s+/g, "");}
// True when s, from a "{", is a tool call still arriving or already whole.function opensTool(s, atStart) { const c = squash(s); if (!c.startsWith("{")) return false; if (c === "{") return !!atStart; const heads = [ '{"type":"tool_call"', '{"type":"tool_result"', "{type:tool_call", '{type:"tool_call"', ]; for (const h of heads) { const n = Math.min(c.length, h.length); if (c.slice(0, n) === h.slice(0, n)) return true; } return /^\{"(?:tool|name)":"[a-z]*"?/.test(c);}
function nameSoFar(rest) { const m = /"(?:tool|name)"\s*:\s*"([a-z]*)/.exec(rest) || /\btool\s*[:=]\s*"?([a-z]*)/i.exec(rest); if (!m) return ""; const frag = m[1].toLowerCase(); if (!frag) return ""; if (TOOL_NAMES.includes(frag)) return frag; const hits = TOOL_NAMES.filter((n) => n.startsWith(frag)); return hits.length === 1 ? hits[0] : "";}
function toolStart(raw) { const s = String(raw || ""); const head = s.trim().toLowerCase(); if (head.startsWith("tool:") && "tool:datetime".startsWith(head) && head.length >= 5) return s.search(/\S/); if (head === "tool:datetime") return s.toLowerCase().indexOf("tool:datetime"); for (let i = 0; i < s.length; i++) { if (s[i] !== "{") continue; const atStart = cleanLead(s.slice(0, i)) === ""; if (opensTool(s.slice(i), atStart)) return i; } const dt = s.toLowerCase().indexOf("tool:datetime"); if (dt >= 0 && cleanLead(s.slice(0, dt)) === "") return dt; return -1;}
// A reply as it grows.// text words for the bubble// load a tool call is still arriving — hide the JSON// call the call is complete — hide the JSON and run it// lead is a sentence before the call. Empty when the reply is only the call.export function toolStream(text) { const raw = String(text || ""); const bare = raw.trim().replace(/^\s*champ\s*[,:]\s*/i, ""); if (/^```(?:json)?\s*$/i.test(bare)) return { kind: "load", call: null, lead: "", tool: "" }; const at = toolStart(raw); if (at < 0) return { kind: "text", call: null, lead: raw, tool: "" }; const lead = cleanLead(raw.slice(0, at)); const rest = raw.slice(at); const timed = rest.trim(); if (/^tool:datetime\s*$/i.test(timed)) { return { kind: "call", call: { type: "tool_call", tool: "datetime", args: {} }, lead, tool: "datetime" }; } if ("tool:datetime".startsWith(timed.toLowerCase()) && timed.length >= 5) { return { kind: "load", call: null, lead, tool: "" }; } const obj = rest[0] === "{" ? takeObject(rest) : ""; if (!obj) { if (opensTool(rest, lead === "")) return { kind: "load", call: null, lead, tool: nameSoFar(rest) }; return { kind: "text", call: null, lead: raw, tool: "" }; } const call = parseCall(obj); if (call) return { kind: "call", call, lead, tool: call.tool }; // A notes object with no path, text, or op. Hide it. The page does not list // an empty notebook in its place. if (/tool_call/.test(obj) && /\bnotes\b/i.test(obj)) { return { kind: "call", call: { type: "tool_call", tool: "notes", args: {} }, lead, tool: "notes" }; } if (/"type"\s*:\s*"tool_result"/.test(obj)) return { kind: "load", call: null, lead, tool: nameSoFar(obj) }; return { kind: "text", call: null, lead: raw, tool: "" };}
export function echoedResult(text) { let s = (text || "").trim(); const fence = /^```(?:json)?\s*([\s\S]*?)\s*```$/i.exec(s); if (fence) s = fence[1].trim(); if (!s.startsWith("{") || !s.endsWith("}")) return ""; try { const obj = JSON.parse(s); if (obj && obj.type === "tool_result" && typeof obj.output === "string") return obj.output; } catch { return ""; } return "";}
const LOOKUP = /\b(look\s*up|lookup|search(?:\s+for)?|weather|forecast)\b/i;
export function wantsLookup(text) { return LOOKUP.test(String(text || ""));}
export function lookupQuery(text) { const raw = String(text || "").trim(); const q = raw.replace(/^\s*(please\s+)?(look\s*up|lookup|search(?:\s+for)?)\s+/i, "").trim(); return (q || raw).slice(0, 180);}
const TEACH = /\b(?:teach|study|learn\s+(?:about|how|the|this|that|why|what|from)|foundational model)\b/i;
export function wantsTeach(text) { return TEACH.test(String(text || ""));}
export function teachQuery(text) { let q = String(text || "").trim(); q = q.replace(/^\s*(please\s+)?/i, ""); q = q.replace(/^(?:ask\s+(?:a\s+)?foundational model\s+to\s+)?/i, ""); q = q.replace(/^(?:teach\s+(?:yourself|me|champ|you)\s+|teach\s+|study\s+|learn\s+)/i, ""); q = q.replace(/^(?:about|from)\s+/i, ""); q = q.trim(); return (q || String(text || "").trim()).slice(0, 180);}
// The web addresses in text, as the page compares them (URL href), with trailing punctuation off.export function urlsIn(text) { const out = []; for (const m of String(text || "").matchAll(/https?:\/\/[^\s<>"'`)\]]+/gi)) { const raw = m[0].replace(/[.,;:!?]+$/, ""); try { out.push(new URL(raw).href); } catch { /* not an address */ } } return out;}
export function unknownReply(text) { const s = String(text || "").replace(/\s+/g, " ").trim(); if (!s) return false; if (/\b(?:don'?t|do not) understand\b/i.test(s)) return true; if (/\bcould you (?:please )?clarify\b/i.test(s)) return true; if (/\bnot sure what you mean\b/i.test(s)) return true; if (/\b(?:don'?t|do not) know what (?:you|that|this)\b/i.test(s)) return true; if (/\b(?:i am|i'm) not familiar\b/i.test(s)) return true; if (/\b(?:don'?t|do not) have (?:enough |any )?(?:real-time |current )?(?:information|data|access|capabilities)\b/i.test(s)) return true; if (/\b(?:unable to|can'?t|cannot) (?:answer|help with|understand)\b/i.test(s)) return true; if (/^(?:i'?m |i am )?sorry[,.]?\s+(?:but )?i (?:don'?t|do not) know\b/i.test(s) && s.length < 320) return true; return false;}
export function acceptsLearn(text) { return /^(?:yes(?:\s+please)?|yeah|yep|yup|sure|please|ok|okay|go ahead|learn it|learn this|do it)[.!?\s]*$/i.test(String(text || "").trim());}
export function declinesLearn(text) { return /^(?:no(?:\s+thanks)?|nope|nah|no thank you)[.!?\s]*$/i.test(String(text || "").trim());}
// A tool runs when the person asked for it or picked it. Datetime is the clock.// Anything else is the model inventing a call, and the page does not run it.export function callAllowed(call, ask, picks) { if (!call || !call.tool) return false; if (call.tool === "datetime") return true; return toolsFor(ask, picks).includes(call.tool);}
// The model described a tool instead of calling one, or handed back an empty id.export function playedTool(text) { const s = String(text || "").trim(); if (!s || toolCallOf(s)) return false; if (/completed by using\b[\s\S]{0,80}\b(function|tool|canvas|notes|tasks)\b/i.test(s)) return true; if (/the response was:\s*\{/i.test(s)) return true; if (/^\s*\{\s*"id"\s*:\s*null\s*\}\s*$/.test(s)) return true; return false;}
export function toolStatus(tool) { if (tool === "search") return "Searching…"; if (tool === "gather") return "Reading…"; if (tool === "datetime") return "Checking the time…"; if (tool === "notes") return "Opening notes…"; if (tool === "tasks") return "Checking tasks…"; if (tool === "canvas") return "Drawing…"; if (tool === "exec") return "Running…"; return "Working…";}
function opOf(call) { return String((call.args && call.args.op) || "").toLowerCase().trim();}
// The page's own notes, tasks and canvas, opened on first use.let services = null;function servicesOf(ctx) { if (ctx && ctx.services) return ctx.services; if (!services) services = createServices(); return services;}
async function localTool(svc, tool, args) { const j = await svc.run(tool, args); if (!j || typeof j.output !== "string") return { output: "The " + tool + " tool failed.", exit_code: 1 }; return { output: j.output, exit_code: j.ok ? 0 : 1, data: j.data || null };}
// ctx: { vm, confirm(command) -> Promise<bool> } for exec; services for notes, tasks and canvas.async function runAgent(call, ctx) { const args = Object.assign({}, call.args || {}); if (call.tool === "exec") { const cmd = String(args.cmd || args.command || args.q || "").trim(); if (!cmd) return { output: "Missing command.", exit_code: 1 }; if (!ctx || !ctx.vm) return { output: "Running code needs EncryptidVM on this machine.", exit_code: 1 }; if (ctx.confirm && !(await ctx.confirm(cmd))) return { output: "Not run: the person declined.", exit_code: 1, declined: true }; const r = await ctx.vm.exec(cmd); return Object.assign({ data: { command: cmd } }, r); } if (call.tool === "tasks" && !args.op && args.title) args.op = "add"; if (call.tool === "notes" && !args.op) args.op = args.text != null ? "write" : (args.path ? "read" : "list"); if (call.tool === "canvas" && !args.op) args.op = args.text != null ? "write" : (args.title ? "read" : "list"); try { return await localTool(servicesOf(ctx), call.tool, args); } catch { return { output: "The " + call.tool + " tool failed.", exit_code: 1 }; }}
async function readTool(fetchImpl, path, params) { const u = new URL(path, "http://champ.local"); for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); const r = await fetchImpl(u.pathname + u.search, { headers: { Accept: "application/json" } }); const j = await r.json().catch(() => null); if (!r.ok || !j || typeof j.output !== "string") return { output: "The lookup failed.", exit_code: 1 }; return { output: j.output, exit_code: j.ok ? 0 : 1 };}
export async function runTool(call, fetchImpl, ctx) { const f = fetchImpl || fetch; if (!call || !TOOLS.has(call.tool)) return { output: "Unknown tool.", exit_code: 1 }; if (call.tool === "datetime") return { output: clockText(), exit_code: 0 }; if (AGENT.has(call.tool)) return runAgent(call, ctx); if (call.tool === "search") { const q = String((call.args && (call.args.q || call.args.query)) || "").trim(); if (!q) return { output: "Missing search query.", exit_code: 1 }; const source = call.args && call.args.source ? String(call.args.source) : ""; const kind = source.trim().toLowerCase(); if (FRAME.has(kind)) { try { const value = await executeRequest(serviceScript(kind, q), f); if (value && !frameEcho(value, q)) return { output: value, exit_code: 0 }; } catch { /* the frame had no answer */ } return { output: "", exit_code: 1 }; } // Wikipedia and DuckDuckGo run in this browser. The server was sending // its own name and getting a shell page back. try { const output = await browserSearch(kind || "wiki", q, f); return { output, exit_code: output ? 0 : 1 }; } catch { return { output: "", exit_code: 1 }; } } const url = String((call.args && call.args.url) || "").trim(); if (!url) return { output: "Missing address.", exit_code: 1 }; // gather reads an address the person wrote or a search listed, never one the model made up // (or copied from an example). let href = ""; try { href = new URL(url).href; } catch { href = ""; } if (ctx && typeof ctx.known === "function" && (!href || !ctx.known(href))) { return { output: "Hodge-3.5 reads only an address the person gave or a search listed.", exit_code: 1 }; } try { return await browserGather(href || url, f); } catch { return { output: "", exit_code: 1 }; }}
// Decides what the page does when a reply finishes.// finish: show the text. follow: run a tool, then send `wire` as the next turn.// The caller must leave `fallback` on screen if the next turn cannot start.// An agent tool's raw result comes back as `card` for the page to show// beside Champ's words; a write is shown as is and ends the turn.export async function settleReply(raw, rounds, run) { const echo = echoedResult(raw); if (echo) return { action: "show", text: echo, rounds: 0 }; const call = rounds < MAX_ROUNDS ? toolCallOf(raw) : null; if (!call) return { action: "finish", rounds: 0 }; if (rounds >= 2 && !AGENT.has(call.tool)) return { action: "finish", rounds: 0 }; const ran = await run(call); if (call.tool === "datetime" || !TOOLS.has(call.tool)) { return { action: "show", text: ran.output, rounds: 0 }; } if (AGENT.has(call.tool)) { const card = { tool: call.tool, args: call.args || {}, output: ran.output, exit_code: ran.exit_code, data: ran.data || null }; if (ran.declined || (call.tool !== "exec" && WRITES.has(opOf(call)))) { // A canvas write's status line is not the reply. The markdown is. const written = call.tool === "canvas" && ran.data && typeof ran.data.text === "string" ? ran.data.text.trim() : ""; return { action: "show", text: written || ran.output, card, rounds: 0 }; } return { action: "follow", status: toolStatus(call.tool), fallback: ran.output, card, wire: "Results:\n" + ran.output + "\nAnswer the person in plain words, or reply with one more tool call if the task needs it.", rounds: rounds + 1, }; } const wire = "Results:\n" + ran.output + "\nAnswer the person in plain words. Do not use JSON."; return { action: "follow", status: toolStatus(call.tool), fallback: ran.output, wire, rounds: rounds + 1, };}
// The composer's + menu: tools the person picks for the next messages.// Each pick is told to the model with the one JSON form it should reply with.export const PICKS = [ { tool: "search", label: "Search the web", form: '{"type":"tool_call","tool":"search","args":{"q":"query"}}' }, { tool: "gather", label: "Read a page", form: '{"type":"tool_call","tool":"gather","args":{"url":"ADDRESS"}}' }, { tool: "notes", label: "Notes", form: '{"type":"tool_call","tool":"notes","args":{"op":"write","path":"plans/today.md","text":"..."}} (op is write, read, list or rm)' }, { tool: "tasks", label: "Tasks", form: '{"type":"tool_call","tool":"tasks","args":{"op":"add","title":"..."}} (op is add, list, update, done, start or comment, with id for update, done, start and comment)' }, { tool: "canvas", label: "Canvas", form: '{"type":"tool_call","tool":"canvas","args":{"op":"write","title":"...","text":"markdown"}} (op is write, read or list)' }, { tool: "exec", label: "Run code", form: '{"type":"tool_call","tool":"exec","args":{"cmd":"ls"}}' },];
// The line put before the person's message when they picked tools, "" for none.export function pickedHint(tools) { const picked = PICKS.filter((p) => (tools || []).includes(p.tool)); if (!picked.length) return ""; if (picked.length === 1) { const p = picked[0]; return "The person chose the " + p.tool + " tool for this. Reply with only " + p.form + "."; } return "The person chose these tools for this: " + picked.map((p) => p.tool).join(", ") + ". Reply with only one tool call at a time, in its form:\n" + picked.map((p) => p.form).join("\n");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141// fastloader.js is the browser side of fastloader. It has two paths://// compile / instantiate the page compiles the guest (ai.encryptid.systems)// connect the server keeps the instance (encryptid.systems)//// compile runs once per URL per page. It uses the streaming compiler when// the bytes are plain wasm. When they need peeling (opts.peel, such as// WASMJsLoader's guestCore), the peeled core is kept in Cache Storage// under the response's ETag. The next load skips peeling and compiles that// core with the streaming compiler too.//// import { guestCore } from "./loader.js";// import { compile, connect } from "./fastloader.js";// const mod = await compile("guest/cmdterm.wasm", { peel: guestCore });// const api = connect("");// await api.call("add", "add", [2, 3]); // "5"
const STORE = "fastloader-v1";const memo = new Map();
// compile returns a WebAssembly.Module for url. Concurrent and repeat calls// share one compile. opts.peel(Uint8Array) -> Uint8Array strips a wrapper.// opts.store names the Cache Storage bucket, or false for none.export function compile(url, opts = {}) { const key = new URL(url, baseURL()).href; let p = memo.get(key); if (!p) { p = compileOnce(key, opts); p.catch(() => memo.delete(key)); memo.set(key, p); } return p;}
// instantiate compiles url (once) and instantiates it with imports.export async function instantiate(url, imports = {}, opts = {}) { const mod = await compile(url, opts); return WebAssembly.instantiate(mod, imports);}
// preload starts compiles now so a later compile or instantiate is warm.export function preload(urls, opts = {}) { return Promise.all(urls.map((u) => compile(u, opts)));}
// forget drops url from this page's memo and from the store.export async function forget(url, opts = {}) { const key = new URL(url, baseURL()).href; memo.delete(key); const store = await openStore(opts.store); if (store) await dropCores(store, key, "");}
async function compileOnce(url, opts) { const res = await fetch(url); if (!res.ok) throw new Error("fastloader: fetch " + url + " " + res.status); const tag = res.headers.get("etag") || res.headers.get("last-modified") || ""; const store = opts.peel && tag ? await openStore(opts.store) : null; const coreKey = store ? coreURL(url, tag) : "";
if (store) { const hit = await store.match(coreKey); if (hit) { cancel(res); return WebAssembly.compileStreaming(hit); } }
// Plain wasm streams straight into the compiler. A wrapped guest can be // a valid module itself, so with peel the bytes are always peeled. if (!opts.peel && isWasm(res)) return WebAssembly.compileStreaming(res);
const raw = new Uint8Array(await res.arrayBuffer()); const core = opts.peel ? opts.peel(raw) : raw; if (store) { // Stored after the compile starts; this load does not wait on it. // A quota error or private window just means no stored core. dropCores(store, url, coreKey) .then(() => store.put(coreKey, new Response(core, { headers: { "Content-Type": "application/wasm" } }))) .catch(() => {}); } return WebAssembly.compile(core);}
// connect calls exports on an instance the fastloader server keeps open.// call sends args as strings and returns the export's result as text.// abi: "string" selects the packed string ABI (compileGML).export function connect(base = "") { const root = String(base).replace(/\/+$/, ""); return { async modules() { const res = await fetch(root + "/modules"); if (!res.ok) throw new Error("fastloader: modules " + res.status + " " + (await res.text())); return res.json(); }, async call(module, fn, args = [], opts = {}) { const q = opts.abi === "string" ? "?abi=string" : ""; const res = await fetch(root + "/" + encodeURIComponent(module) + "/" + encodeURIComponent(fn) + q, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(args.map(String)), }); const text = await res.text(); if (!res.ok) throw new Error("fastloader: " + module + "." + fn + ": " + text.trim()); return text; }, };}
function baseURL() { return typeof location !== "undefined" ? location.href : "http://localhost/";}
function isWasm(res) { return (res.headers.get("content-type") || "").split(";")[0].trim() === "application/wasm";}
function cancel(res) { if (res.body) res.body.cancel().catch(() => {});}
function coreURL(url, tag) { return url + (url.includes("?") ? "&" : "?") + "fastloader-core=" + encodeURIComponent(tag);}
async function openStore(name) { if (name === false || typeof caches === "undefined") return null; try { return await caches.open(name || STORE); } catch (_) { return null; }}
// dropCores deletes stored cores of url other than keep.async function dropCores(store, url, keep) { const prefix = coreURL(url, ""); for (const req of await store.keys()) { if (req.url.startsWith(prefix) && req.url !== keep) await store.delete(req); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687// Champ's flow instrumentation, page side (model/flow.go). With ?flow, the model folder's// volume.safetensors gives the cells, the worker gets two shared-memory files, and every generated// token's currents arrive as a frame: "flow" holds a 16-byte header (sequence, position, token id,// flow bytes; little-endian u32) and the flow, laid out as the ready event's flow layout says.// Each frame is copied out, acknowledged by writing its sequence into "flow.ack" (the model waits for// that before the next one), checked, and handed to whoever listens.
export const FLOW_BYTES = 16 << 20;
export function createFlow(enabled) { const on = !!enabled; const sab = on ? new SharedArrayBuffer(FLOW_BYTES) : null; const ackSab = on ? new SharedArrayBuffer(4) : null; const listeners = []; let layout = null;
// A frame's checks, as hodgemix's (cochain.go conservation): the residual is conserved at every // node (carried value plus writes = the node's value), and every HodgeLinear output cell's currents // sum to its cell sum. Mismatches are relative to the summed magnitudes flowing in. function check(f) { const L = layout.layers; const ax = layout.axes; const role = (l, r) => new Float32Array(f.buffer, f.byteOffset + layout.edge[l * 7 + r], cellsOf(layout.roles[r].rows) * cellsOf(layout.roles[r].cols)); const node = (l, n) => new Float32Array(f.buffer, f.byteOffset + layout.node[l * 10 + n], cellsOf(layout.nodes[n].axis)); function cellsOf(a) { return ax[a].cells; } let worst = 0; const chk = (inn, abs, val) => { worst = Math.max(worst, Math.abs(inn - val) / Math.max(abs, 1e-30)); }; function rowsum(e, nc, r) { let s = 0, a = 0; for (let c = 0; c < nc; c++) { const x = e[r * nc + c]; s += x; a += Math.abs(x); } return [s, a]; } const ND = ax.D.cells, NQ = ax.Q.cells, NF = ax.F.cells, NKV = ax.KV.cells; for (let l = 0; l < L; l++) { const D = node(l, 0), Dm = node(l, 1), Dout = node(l, 2); const o = role(l, 3), down = role(l, 6); for (let i = 0; i < ND; i++) { let [s, a] = rowsum(o, NQ, i); chk(D[i] + s, Math.abs(D[i]) + a, Dm[i]); [s, a] = rowsum(down, NF, i); chk(Dm[i] + s, Math.abs(Dm[i]) + a, Dout[i]); } const outs = [[0, 5, NQ, ND], [1, 6, NKV, ND], [2, 7, NKV, ND], [4, 8, NF, ND], [5, 9, NF, ND]]; // role, node for (const [r, n, nr, nc] of outs) { const e = role(l, r), v = node(l, n); for (let i = 0; i < nr; i++) { const [s, a] = rowsum(e, nc, i); chk(s, a, v[i]); } } } return worst; }
return { on, // files and args for the worker wire(files, args) { if (!on) return; files.flow = { sab, off: 0, size: FLOW_BYTES }; files["flow.ack"] = { sab: ackSab, off: 0, size: 4 }; args.push("-flow", "flow"); }, ready(l) { if (!on) return; if (!l || !l.bytes) throw new Error("Hodge-3.5 started without its flow instrumentation."); if (16 + l.bytes > FLOW_BYTES) throw new Error("A flow frame of " + l.bytes + " bytes does not fit the shared memory."); layout = l; }, // ev: {"ev":"flow","seq","pos","id"} frame(ev) { if (!on || !layout) return; const head = new DataView(sab, 0, 16); const seq = head.getUint32(0, true), pos = head.getUint32(4, true), id = head.getUint32(8, true), n = head.getUint32(12, true); if (seq !== ev.seq || n !== layout.bytes) { throw new Error("flow frame " + ev.seq + ": the shared memory holds frame " + seq + " (" + n + " bytes)"); } const data = new Uint8Array(n); data.set(new Uint8Array(sab, 16, n)); new DataView(ackSab).setUint32(0, seq, true); const f = new Float32Array(data.buffer); const mismatch = check(f); const fr = { seq, pos, id, flow: f, layout, mismatch }; for (const fn of listeners) fn(fr); return fr; }, listen(fn) { listeners.push(fn); }, get layout() { return layout; }, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290// The network map. volume.safetensors is the cochain: balance.* is the resting// current between cells, and each live frame (flow.js) replaces that with the// token's activations. Columns are the axes, lines are the strongest cell-to-cell// currents, and the rail is one tick per layer. One 2D view of the hot layer.// A 3D volume or graph walks every layer's cells on the token path and costs// a few tokens per second for each of those views.
const EDGES = [ { role: 0, name: "q", a: "D", b: "Q", vol: "balance.q" }, { role: 1, name: "k", a: "D", b: "KV", vol: "balance.k" }, { role: 2, name: "v", a: "D", b: "KV", vol: "balance.v" }, { role: 3, name: "o", a: "Q", b: "Dout", vol: "balance.o" }, { role: 4, name: "gate", a: "D", b: "F", vol: "balance.gate" }, { role: 5, name: "up", a: "D", b: "F", vol: "balance.up" }, { role: 6, name: "down", a: "F", b: "Dout", vol: "balance.down" },];
const NODE = { D: 0, Dout: 2, F: 4, Q: 5, KV: 6 };
export function mountMap(root) { const canvas = root.querySelector("#map-canvas"); const meta = root.querySelector("#map-meta"); const followBtn = root.querySelector("#map-follow"); const ctx = canvas.getContext("2d"); let vol = null; let counts = null; let layers = 0; let layer = 0; let follow = true; let frame = null; let token = ""; let energy = null; let line = "";
function say(text) { line = text; meta.textContent = text; }
function structure(bytes) { vol = parseSafetensors(bytes); const q = vol.get("balance.q"); const k = vol.get("balance.k"); const g = vol.get("balance.gate"); if (!q || !k || !g) { say("This volume has no cell map."); return; } layers = q.shape[0]; counts = { D: q.shape[2], Q: q.shape[1], KV: k.shape[1], F: g.shape[1], Dout: q.shape[2] }; energy = new Float32Array(layers); layer = hottest(); say(counts.D + " D · " + counts.Q + " Q · " + counts.KV + " KV · " + counts.F + " F"); draw(); requestAnimationFrame(() => draw()); }
function note(text) { token = text || ""; }
function show(fr) { frame = fr; if (!counts && fr.layout) countsFromLayout(fr.layout); if (follow) layer = hottest(); const cons = fr.mismatch < 1e-3 ? "conserved" : fr.mismatch.toExponential(2); const word = token ? " · " + JSON.stringify(token) : ""; say("L" + layer + " · pos " + fr.pos + word + " · " + cons); draw(); }
function countsFromLayout(L) { layers = L.layers; counts = { D: L.axes.D.cells, Q: L.axes.Q.cells, KV: L.axes.KV.cells, F: L.axes.F.cells, Dout: L.axes.D.cells, }; if (!energy || energy.length !== layers) energy = new Float32Array(layers); }
function hottest() { let best = 0, at = 0; for (let i = 0; i < layers; i++) { const e = layerEnergy(i); energy[i] = e; if (e > best) { best = e; at = i; } } return at; }
function layerEnergy(l) { let s = 0; for (const e of EDGES) { const m = matrix(l, e); if (!m) continue; for (let i = 0; i < m.data.length; i++) s += Math.abs(m.data[i]); } return s; }
function matrix(l, edge) { if (frame) { const L = frame.layout; const rows = L.axes[L.roles[edge.role].rows].cells; const cols = L.axes[L.roles[edge.role].cols].cells; const off = L.edge[l * 7 + edge.role]; return { rows, cols, data: new Float32Array(frame.flow.buffer, frame.flow.byteOffset + off, rows * cols) }; } const t = vol && vol.get(edge.vol); if (!t) return null; const [, rows, cols] = t.shape; const n = rows * cols; return { rows, cols, data: t.data.subarray(l * n, (l + 1) * n) }; }
function nodeValue(name, i) { if (!frame) return 0; const v = nodeVec(NODE[name]); return v ? v[i] || 0 : 0; }
function nodeVec(id) { return nodeVecAt(layer, id); }
function nodeVecAt(l, id) { const L = frame.layout; const n = L.axes[L.nodes[id].axis].cells; const off = L.node[l * 10 + id]; return new Float32Array(frame.flow.buffer, frame.flow.byteOffset + off, n); }
function draw() { if (!counts) return; draw2d(); }
function draw2d() { const cssW = root.clientWidth; const cssH = canvas.clientHeight || root.clientHeight - 36; if (!cssW || !cssH || !counts) return; const dpr = Math.min(2, window.devicePixelRatio || 1); canvas.width = Math.round(cssW * dpr); canvas.height = Math.round(cssH * dpr); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, cssW, cssH);
const rail = 18; const top = 22; const bot = cssH - 16; const span = Math.max(1, bot - top); const xOf = (name) => { const f = { D: 0.14, Q: 0.40, KV: 0.40, F: 0.68, Dout: 0.90 }[name]; return rail + 8 + f * (cssW - rail - 16); }; const band = (name) => name === "Q" ? [top, top + span * 0.58] : name === "KV" ? [top + span * 0.70, bot] : [top, bot]; const cols = {}; for (const name of ["D", "Q", "KV", "F", "Dout"]) { const [y0, y1] = band(name); const n = counts[name]; cols[name] = []; for (let i = 0; i < n; i++) { const t = n === 1 ? 0.5 : i / (n - 1); cols[name].push({ x: xOf(name), y: y0 + t * (y1 - y0) }); } }
const maxE = energy ? Math.max(...energy, 1e-12) : 1; for (let i = 0; i < layers; i++) { const y0 = (i / layers) * cssH; const h = cssH / layers; const hot = energy ? energy[i] / maxE : 0; ctx.fillStyle = i === layer ? "rgba(232,168,124,0.95)" : "rgba(232,168,124," + (0.15 + 0.7 * hot) + ")"; ctx.fillRect(4, y0 + 1, 6, Math.max(2, h - 2)); }
ctx.font = "11px Segoe UI, system-ui, sans-serif"; ctx.fillStyle = "#8e96a3"; ctx.textAlign = "center"; ctx.fillText("D", xOf("D"), 14); ctx.fillText("Q", xOf("Q"), 14); ctx.fillText("F", xOf("F"), 14); ctx.fillText("D′", xOf("Dout"), 14); const kv = band("KV"); ctx.fillText("KV", xOf("KV"), kv[0] - 4);
const picked = []; let edgeMax = 1e-12; for (const e of EDGES) { const m = matrix(layer, e); if (!m) continue; const take = strongest(m, 70); for (const p of take) edgeMax = Math.max(edgeMax, Math.abs(p.v)); picked.push([e, m, take]); } for (const [e, , take] of picked) { for (const p of take) { const from = cols[e.a][p.c]; const to = cols[e.b][p.r]; if (!from || !to) continue; const mag = Math.abs(p.v) / edgeMax; ctx.strokeStyle = p.v >= 0 ? "rgba(232,168,124," + (0.15 + 0.8 * mag) + ")" : "rgba(126,182,232," + (0.15 + 0.8 * mag) + ")"; ctx.lineWidth = 0.6 + 1.6 * mag; ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); ctx.stroke(); } }
for (const name of ["D", "Q", "KV", "F", "Dout"]) { let max = 1e-12; const vals = cols[name].map((_, i) => { const v = nodeValue(name, i); max = Math.max(max, Math.abs(v)); return v; }); cols[name].forEach((p, i) => { const v = vals[i]; const mag = Math.abs(v) / max; const r = frame ? 1.6 + 3.2 * mag : 1.8; ctx.fillStyle = !frame ? "rgba(236,231,223,0.85)" : v >= 0 ? "rgba(232,168,124," + (0.45 + 0.55 * mag) + ")" : "rgba(126,182,232," + (0.45 + 0.55 * mag) + ")"; ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); ctx.fill(); }); } }
canvas.addEventListener("click", (ev) => { const rect = canvas.getBoundingClientRect(); const x = ev.clientX - rect.left; const y = ev.clientY - rect.top; if (x > 22 || !layers) return; layer = Math.min(layers - 1, Math.max(0, Math.floor(y / rect.height * layers))); follow = false; followBtn.setAttribute("aria-pressed", "false"); if (frame) say("L" + layer + " · pinned"); draw(); }); followBtn.addEventListener("click", () => { follow = !follow; followBtn.setAttribute("aria-pressed", follow ? "true" : "false"); if (follow && frame) layer = hottest(); draw(); }); const ro = new ResizeObserver(() => draw()); ro.observe(root); draw();
return { structure, frame: show, token: note };}
// The n largest |currents|. Rows are destination cells, columns are sources.function strongest(m, n) { const heap = []; for (let i = 0; i < m.data.length; i++) { const v = m.data[i]; const a = Math.abs(v); if (a === 0) continue; const item = { v, a, r: (i / m.cols) | 0, c: i % m.cols }; if (heap.length < n) { heap.push(item); continue; } let min = 0; for (let k = 1; k < heap.length; k++) if (heap[k].a < heap[min].a) min = k; if (a > heap[min].a) heap[min] = item; } return heap;}
function parseSafetensors(buf) { const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); const n = Number(dv.getBigUint64(0, true)); const header = JSON.parse(new TextDecoder().decode(buf.subarray(8, 8 + n))); const base = 8 + n; const map = new Map(); for (const [name, meta] of Object.entries(header)) { if (!meta || !meta.shape || !meta.data_offsets) continue; const [a, b] = meta.data_offsets; const off = buf.byteOffset + base + a; const count = (b - a) / 4; map.set(name, { shape: meta.shape, data: meta.dtype === "F32" ? new Float32Array(buf.buffer, off, count) : null, }); } return map;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100// blink.mojom.LocalFrame.JavaScriptExecuteRequest.// The page is the frame. It runs the script. The browser sends the request// with its own name. A quoted copy of the script is not a result, and neither// is an interface line.import { instantiate, run } from "./loader.js";import { localFrameWindow, pageFetch } from "./browse.js";
const GUEST = "local_frame_exec.wasm";let bytesP = null;
export function requestValue(stdout) { const lines = String(stdout || "").split(/\r?\n/); for (let i = 0; i < lines.length; i++) { const s = lines[i].trim(); if (!s) continue; if (s.startsWith("interface:") || s.startsWith("func ")) continue; return s; } return "";}
// The guest quotes a script it does not evaluate. That quote is not a page.// A short prefix plus the question is the same echo.export function frameEcho(output, question) { const q = String(question || "").replace(/\s+/g, " ").trim(); if (q.length < 8) return false; let s = String(output || "").trim(); if (s.length >= 2 && s[0] === "\"" && s[s.length - 1] === "\"") s = s.slice(1, -1).trim(); s = s.replace(/\s+/g, " ").trim(); if (!s) return false; const a = s.toLowerCase(); const b = q.toLowerCase(); if (a === b) return true; // The guest repeats the question with a short lead-in. A page that merely // contains the subject is the lookup, not that echo. const at = a.lastIndexOf(b); if (at < 0) return false; const extra = a.length - b.length; return extra < 160 && extra < b.length;}
export async function executeBytes(bytes, javascript) { const js = String(javascript ?? ""); let out = ""; const loaded = await instantiate(bytes, { args: [GUEST, js], stdout: (t) => { out += t; }, stderr: () => {}, }); await run(loaded); return requestValue(out);}
function asText(value) { if (value == null) return ""; if (typeof value === "string") return value; if (typeof value === "number" || typeof value === "boolean") return String(value); return "";}
// The interface print and a quoted script are not the value of the request.export function frameStamp(value) { const s = String(value || "").trim(); if (!s) return false; if (/^(?:interface:|func )/.test(s)) return true; if (s.includes("blink.mojom.LocalFrame.JavaScriptExecuteRequest")) return true; return false;}
export async function executeRequest(javascript, fetchImpl) { const js = String(javascript ?? ""); const own = !fetchImpl || fetchImpl === globalThis.fetch; const frame = own ? await localFrameWindow() : null; const realm = frame && typeof frame.Function === "function" ? frame : globalThis; const f = own ? pageFetch(globalThis.fetch) : fetchImpl; let value = ""; try { const runScript = new realm.Function("fetch", "return (async () => {\n" + js + "\n})()"); value = asText(await runScript(f)); } catch { return ""; } if (!value || frameStamp(value)) return ""; return value;}
// duck.ai and Gemini answer in this browser. The local frame is the IWA.// Its page loads offscreen_script.js and asks those sites. The real page sends the chat.export function serviceScript(kind, question) { const q = JSON.stringify(String(question || "").replace(/\s+/g, " ").trim().slice(0, 180)); const k = String(kind || "").trim().toLowerCase(); const source = k === "gemini" || k === "gemini.google.com" ? "gemini" : "duck"; return ` const q = ${q}; const source = ${JSON.stringify(source)}; if (typeof window === "undefined" || typeof window.__RBI_IWA_ASK__ !== "function") return ""; const text = await window.__RBI_IWA_ASK__(source, q); return String(text || "").replace(/\\s+/g, " ").trim(); `;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754/* fzstd 0.1.1, MIT, https://github.com/101arrowz/fzstd — Zstandard decode for BNZ segments. */// Some numerical data is initialized as -1 even when it doesn't need initialization to help the JIT infer types// aliases for shorter compressed code (most minifers don't do this)var ab = ArrayBuffer, u8 = Uint8Array, u16 = Uint16Array, i16 = Int16Array, u32 = Uint32Array, i32 = Int32Array;var slc = function (v, s, e) { if (u8.prototype.slice) return u8.prototype.slice.call(v, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; var n = new u8(e - s); n.set(v.subarray(s, e)); return n;};var fill = function (v, n, s, e) { if (u8.prototype.fill) return u8.prototype.fill.call(v, n, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; for (; s < e; ++s) v[s] = n; return v;};var cpw = function (v, t, s, e) { if (u8.prototype.copyWithin) return u8.prototype.copyWithin.call(v, t, s, e); if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; while (s < e) { v[t++] = v[s++]; }};/** * Codes for errors generated within this library */export var ZstdErrorCode = { InvalidData: 0, WindowSizeTooLarge: 1, InvalidBlockType: 2, FSEAccuracyTooHigh: 3, DistanceTooFarBack: 4, UnexpectedEOF: 5};// error codesvar ec = [ 'invalid zstd data', 'window size too large (>2046MB)', 'invalid block type', 'FSE accuracy too high', 'match distance too far back', 'unexpected EOF'];var err = function (ind, msg, nt) { var e = new Error(msg || ec[ind]); e.code = ind; if (Error.captureStackTrace) Error.captureStackTrace(e, err); if (!nt) throw e; return e;};var rb = function (d, b, n) { var i = 0, o = 0; for (; i < n; ++i) o |= d[b++] << (i << 3); return o;};var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; };// read Zstandard frame headervar rzfh = function (dat, w) { var n3 = dat[0] | (dat[1] << 8) | (dat[2] << 16); if (n3 == 0x2FB528 && dat[3] == 253) { // Zstandard var flg = dat[4]; // single segment checksum dict flag frame content flag var ss = (flg >> 5) & 1, cc = (flg >> 2) & 1, df = flg & 3, fcf = flg >> 6; if (flg & 8) err(0); // byte var bt = 6 - ss; // dict bytes var db = df == 3 ? 4 : df; // dictionary id var di = rb(dat, bt, db); bt += db; // frame size bytes var fsb = fcf ? (1 << fcf) : ss; // frame source size var fss = rb(dat, bt, fsb) + ((fcf == 1) && 256); // window size var ws = fss; if (!ss) { // window descriptor var wb = 1 << (10 + (dat[5] >> 3)); ws = wb + (wb >> 3) * (dat[5] & 7); } if (ws > 2145386496) err(1); var buf = new u8((w == 1 ? (fss || ws) : w ? 0 : ws) + 12); buf[0] = 1, buf[4] = 4, buf[8] = 8; return { b: bt + fsb, y: 0, l: 0, d: di, w: (w && w != 1) ? w : buf.subarray(12), e: ws, o: new i32(buf.buffer, 0, 3), u: fss, c: cc, m: Math.min(131072, ws) }; } else if (((n3 >> 4) | (dat[3] << 20)) == 0x184D2A5) { // skippable return b4(dat, 4) + 8; } err(0);};// most significant bit for nonzerovar msb = function (val) { var bits = 0; for (; (1 << bits) <= val; ++bits) ; return bits - 1;};// read finite state entropyvar rfse = function (dat, bt, mal) { // table pos var tpos = (bt << 3) + 4; // accuracy log var al = (dat[bt] & 15) + 5; if (al > mal) err(3); // size var sz = 1 << al; // probabilities symbols repeat index high threshold var probs = sz, sym = -1, re = -1, i = -1, ht = sz; // optimization: single allocation is much faster var buf = new ab(512 + (sz << 2)); var freq = new i16(buf, 0, 256); // same view as freq var dstate = new u16(buf, 0, 256); var nstate = new u16(buf, 512, sz); var bb1 = 512 + (sz << 1); var syms = new u8(buf, bb1, sz); var nbits = new u8(buf, bb1 + sz); while (sym < 255 && probs > 0) { var bits = msb(probs + 1); var cbt = tpos >> 3; // mask var msk = (1 << (bits + 1)) - 1; var val = ((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (tpos & 7)) & msk; // mask (1 fewer bit) var msk1fb = (1 << bits) - 1; // max small value var msv = msk - probs - 1; // small value var sval = val & msk1fb; if (sval < msv) tpos += bits, val = sval; else { tpos += bits + 1; if (val > msk1fb) val -= msv; } freq[++sym] = --val; if (val == -1) { probs += val; syms[--ht] = sym; } else probs -= val; if (!val) { do { // repeat byte var rbt = tpos >> 3; re = ((dat[rbt] | (dat[rbt + 1] << 8)) >> (tpos & 7)) & 3; tpos += 2; sym += re; } while (re == 3); } } if (sym > 255 || probs) err(0); var sympos = 0; // sym step (coprime with sz - formula from zstd source) var sstep = (sz >> 1) + (sz >> 3) + 3; // sym mask var smask = sz - 1; for (var s = 0; s <= sym; ++s) { var sf = freq[s]; if (sf < 1) { dstate[s] = -sf; continue; } // This is split into two loops in zstd to avoid branching, but as JS is higher-level that is unnecessary for (i = 0; i < sf; ++i) { syms[sympos] = s; do { sympos = (sympos + sstep) & smask; } while (sympos >= ht); } } // After spreading symbols, should be zero again if (sympos) err(0); for (i = 0; i < sz; ++i) { // next state var ns = dstate[syms[i]]++; // num bits var nb = nbits[i] = al - msb(ns); nstate[i] = (ns << nb) - sz; } return [(tpos + 7) >> 3, { b: al, s: syms, n: nbits, t: nstate }];};// read huffmanvar rhu = function (dat, bt) { // index weight count var i = 0, wc = -1; // buffer header byte var buf = new u8(292), hb = dat[bt]; // huffman weights var hw = buf.subarray(0, 256); // rank count var rc = buf.subarray(256, 268); // rank index var ri = new u16(buf.buffer, 268); // NOTE: at this point bt is 1 less than expected if (hb < 128) { // end byte, fse decode table var _a = rfse(dat, bt + 1, 6), ebt = _a[0], fdt = _a[1]; bt += hb; var epos = ebt << 3; // last byte var lb = dat[bt]; if (!lb) err(0); // state1 state2 state1 bits state2 bits var st1 = 0, st2 = 0, btr1 = fdt.b, btr2 = btr1; // fse pos // pre-increment to account for original deficit of 1 var fpos = (++bt << 3) - 8 + msb(lb); for (;;) { fpos -= btr1; if (fpos < epos) break; var cbt = fpos >> 3; st1 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr1) - 1); hw[++wc] = fdt.s[st1]; fpos -= btr2; if (fpos < epos) break; cbt = fpos >> 3; st2 += ((dat[cbt] | (dat[cbt + 1] << 8)) >> (fpos & 7)) & ((1 << btr2) - 1); hw[++wc] = fdt.s[st2]; btr1 = fdt.n[st1]; st1 = fdt.t[st1]; btr2 = fdt.n[st2]; st2 = fdt.t[st2]; } if (++wc > 255) err(0); } else { wc = hb - 127; for (; i < wc; i += 2) { var byte = dat[++bt]; hw[i] = byte >> 4; hw[i + 1] = byte & 15; } ++bt; } // weight exponential sum var wes = 0; for (i = 0; i < wc; ++i) { var wt = hw[i]; // bits must be at most 11, same as weight if (wt > 11) err(0); wes += wt && (1 << (wt - 1)); } // max bits var mb = msb(wes) + 1; // table size var ts = 1 << mb; // remaining sum var rem = ts - wes; // must be power of 2 if (rem & (rem - 1)) err(0); hw[wc++] = msb(rem) + 1; for (i = 0; i < wc; ++i) { var wt = hw[i]; ++rc[hw[i] = wt && (mb + 1 - wt)]; } // huf buf var hbuf = new u8(ts << 1); // symbols num bits var syms = hbuf.subarray(0, ts), nb = hbuf.subarray(ts); ri[mb] = 0; for (i = mb; i > 0; --i) { var pv = ri[i]; fill(nb, i, pv, ri[i - 1] = pv + rc[i] * (1 << (mb - i))); } if (ri[0] != ts) err(0); for (i = 0; i < wc; ++i) { var bits = hw[i]; if (bits) { var code = ri[bits]; fill(syms, i, code, ri[bits] = code + (1 << (mb - bits))); } } return [bt, { n: nb, b: mb, s: syms }];};// Tables generated using this:// https://gist.github.com/101arrowz/a979452d4355992cbf8f257cbffc9edd// default literal length tablevar dllt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ 81, 16, 99, 140, 49, 198, 24, 99, 12, 33, 196, 24, 99, 102, 102, 134, 70, 146, 4]), 0, 6)[1];// default match length tablevar dmlt = /*#__PURE__*/ rfse(/*#__PURE__*/ new u8([ 33, 20, 196, 24, 99, 140, 33, 132, 16, 66, 8, 33, 132, 16, 66, 8, 33, 68, 68, 68, 68, 68, 68, 68, 68, 36, 9]), 0, 6)[1];// default offset code tablevar doct = /*#__PURE__ */ rfse(/*#__PURE__*/ new u8([ 32, 132, 16, 66, 102, 70, 68, 68, 68, 68, 36, 73, 2]), 0, 5)[1];// bits to baselinevar b2bl = function (b, s) { var len = b.length, bl = new i32(len); for (var i = 0; i < len; ++i) { bl[i] = s; s += 1 << b[i]; } return bl;};// literal length bitsvar llb = /*#__PURE__ */ new u8(( /*#__PURE__ */new i32([ 0, 0, 0, 0, 16843009, 50528770, 134678020, 202050057, 269422093])).buffer, 0, 36);// literal length baselinevar llbl = /*#__PURE__ */ b2bl(llb, 0);// match length bitsvar mlb = /*#__PURE__ */ new u8(( /*#__PURE__ */new i32([ 0, 0, 0, 0, 0, 0, 0, 0, 16843009, 50528770, 117769220, 185207048, 252579084, 16])).buffer, 0, 53);// match length baselinevar mlbl = /*#__PURE__ */ b2bl(mlb, 3);// decode huffman streamvar dhu = function (dat, out, hu) { var len = dat.length, ss = out.length, lb = dat[len - 1], msk = (1 << hu.b) - 1, eb = -hu.b; if (!lb) err(0); var st = 0, btr = hu.b, pos = (len << 3) - 8 + msb(lb) - btr, i = -1; for (; pos > eb && i < ss;) { var cbt = pos >> 3; var val = (dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (pos & 7); st = ((st << btr) | val) & msk; out[++i] = hu.s[st]; pos -= (btr = hu.n[st]); } if (pos != eb || i + 1 != ss) err(0);};// decode huffman stream 4x// TODO: use workers to parallelizevar dhu4 = function (dat, out, hu) { var bt = 6; var ss = out.length, sz1 = (ss + 3) >> 2, sz2 = sz1 << 1, sz3 = sz1 + sz2; dhu(dat.subarray(bt, bt += dat[0] | (dat[1] << 8)), out.subarray(0, sz1), hu); dhu(dat.subarray(bt, bt += dat[2] | (dat[3] << 8)), out.subarray(sz1, sz2), hu); dhu(dat.subarray(bt, bt += dat[4] | (dat[5] << 8)), out.subarray(sz2, sz3), hu); dhu(dat.subarray(bt), out.subarray(sz3), hu);};// read Zstandard blockvar rzb = function (dat, st, out) { var _a; var bt = st.b; // byte 0 block type var b0 = dat[bt], btype = (b0 >> 1) & 3; st.l = b0 & 1; var sz = (b0 >> 3) | (dat[bt + 1] << 5) | (dat[bt + 2] << 13); // end byte for block var ebt = (bt += 3) + sz; if (btype == 1) { if (bt >= dat.length) return; st.b = bt + 1; if (out) { fill(out, dat[bt], st.y, st.y += sz); return out; } return fill(new u8(sz), dat[bt]); } if (ebt > dat.length) return; if (btype == 0) { st.b = ebt; if (out) { out.set(dat.subarray(bt, ebt), st.y); st.y += sz; return out; } return slc(dat, bt, ebt); } if (btype == 2) { // byte 3 lit btype size format var b3 = dat[bt], lbt = b3 & 3, sf = (b3 >> 2) & 3; // lit src size lit cmp sz 4 streams var lss = b3 >> 4, lcs = 0, s4 = 0; if (lbt < 2) { if (sf & 1) lss |= (dat[++bt] << 4) | ((sf & 2) && (dat[++bt] << 12)); else lss = b3 >> 3; } else { s4 = sf; if (sf < 2) lss |= ((dat[++bt] & 63) << 4), lcs = (dat[bt] >> 6) | (dat[++bt] << 2); else if (sf == 2) lss |= (dat[++bt] << 4) | ((dat[++bt] & 3) << 12), lcs = (dat[bt] >> 2) | (dat[++bt] << 6); else lss |= (dat[++bt] << 4) | ((dat[++bt] & 63) << 12), lcs = (dat[bt] >> 6) | (dat[++bt] << 2) | (dat[++bt] << 10); } ++bt; // add literals to end - can never overlap with backreferences because unused literals always appended var buf = out ? out.subarray(st.y, st.y + st.m) : new u8(st.m); // starting point for literals var spl = buf.length - lss; if (lbt == 0) buf.set(dat.subarray(bt, bt += lss), spl); else if (lbt == 1) fill(buf, dat[bt++], spl); else { // huffman table var hu = st.h; if (lbt == 2) { var hud = rhu(dat, bt); // subtract description length lcs += bt - (bt = hud[0]); st.h = hu = hud[1]; } else if (!hu) err(0); (s4 ? dhu4 : dhu)(dat.subarray(bt, bt += lcs), buf.subarray(spl), hu); } // num sequences var ns = dat[bt++]; if (ns) { if (ns == 255) ns = (dat[bt++] | (dat[bt++] << 8)) + 0x7F00; else if (ns > 127) ns = ((ns - 128) << 8) | dat[bt++]; // symbol compression modes var scm = dat[bt++]; if (scm & 3) err(0); var dts = [dmlt, doct, dllt]; for (var i = 2; i > -1; --i) { var md = (scm >> ((i << 1) + 2)) & 3; if (md == 1) { // rle buf var rbuf = new u8([0, 0, dat[bt++]]); dts[i] = { s: rbuf.subarray(2, 3), n: rbuf.subarray(0, 1), t: new u16(rbuf.buffer, 0, 1), b: 0 }; } else if (md == 2) { // accuracy log 8 for offsets, 9 for others _a = rfse(dat, bt, 9 - (i & 1)), bt = _a[0], dts[i] = _a[1]; } else if (md == 3) { if (!st.t) err(0); dts[i] = st.t[i]; } } var _b = st.t = dts, mlt = _b[0], oct = _b[1], llt = _b[2]; var lb = dat[ebt - 1]; if (!lb) err(0); var spos = (ebt << 3) - 8 + msb(lb) - llt.b, cbt = spos >> 3, oubt = 0; var lst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << llt.b) - 1); cbt = (spos -= oct.b) >> 3; var ost = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << oct.b) - 1); cbt = (spos -= mlt.b) >> 3; var mst = ((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mlt.b) - 1); for (++ns; --ns;) { var llc = llt.s[lst]; var lbtr = llt.n[lst]; var mlc = mlt.s[mst]; var mbtr = mlt.n[mst]; var ofc = oct.s[ost]; var obtr = oct.n[ost]; cbt = (spos -= ofc) >> 3; var ofp = 1 << ofc; var off = ofp + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16) | (dat[cbt + 3] << 24)) >>> (spos & 7)) & (ofp - 1)); cbt = (spos -= mlb[mlc]) >> 3; var ml = mlbl[mlc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << mlb[mlc]) - 1)); cbt = (spos -= llb[llc]) >> 3; var ll = llbl[llc] + (((dat[cbt] | (dat[cbt + 1] << 8) | (dat[cbt + 2] << 16)) >> (spos & 7)) & ((1 << llb[llc]) - 1)); cbt = (spos -= lbtr) >> 3; lst = llt.t[lst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << lbtr) - 1)); cbt = (spos -= mbtr) >> 3; mst = mlt.t[mst] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << mbtr) - 1)); cbt = (spos -= obtr) >> 3; ost = oct.t[ost] + (((dat[cbt] | (dat[cbt + 1] << 8)) >> (spos & 7)) & ((1 << obtr) - 1)); if (off > 3) { st.o[2] = st.o[1]; st.o[1] = st.o[0]; st.o[0] = off -= 3; } else { var idx = off - (ll != 0); if (idx) { off = idx == 3 ? st.o[0] - 1 : st.o[idx]; if (idx > 1) st.o[2] = st.o[1]; st.o[1] = st.o[0]; st.o[0] = off; } else off = st.o[0]; } for (var i = 0; i < ll; ++i) { buf[oubt + i] = buf[spl + i]; } oubt += ll, spl += ll; var stin = oubt - off; if (stin < 0) { var len = -stin; var bs = st.e + stin; if (len > ml) len = ml; for (var i = 0; i < len; ++i) { buf[oubt + i] = st.w[bs + i]; } oubt += len, ml -= len, stin = 0; } for (var i = 0; i < ml; ++i) { buf[oubt + i] = buf[stin + i]; } oubt += ml; } if (oubt != spl) { while (spl < buf.length) { buf[oubt++] = buf[spl++]; } } else oubt = buf.length; if (out) st.y += oubt; else buf = slc(buf, 0, oubt); } else if (out) { st.y += lss; if (spl) { for (var i = 0; i < lss; ++i) { buf[i] = buf[spl + i]; } } } else if (spl) buf = slc(buf, spl); st.b = ebt; return buf; } err(2);};// concatvar cct = function (bufs, ol) { if (bufs.length == 1) return bufs[0]; var buf = new u8(ol); for (var i = 0, b = 0; i < bufs.length; ++i) { var chk = bufs[i]; buf.set(chk, b); b += chk.length; } return buf;};/** * Decompresses Zstandard data * @param dat The input data * @param buf The output buffer. If unspecified, the function will allocate * exactly enough memory to fit the decompressed data. If your * data has multiple frames and you know the output size, specifying * it will yield better performance. * @returns The decompressed data */export function decompress(dat, buf) { var bufs = [], nb = +!buf; var bt = 0, ol = 0; for (; dat.length;) { var st = rzfh(dat, nb || buf); if (typeof st == 'object') { if (nb) { buf = null; if (st.w.length == st.u) { bufs.push(buf = st.w); ol += st.u; } } else { bufs.push(buf); st.e = 0; } for (; !st.l;) { var blk = rzb(dat, st, buf); if (!blk) err(5); if (buf) st.e = st.y; else { bufs.push(blk); ol += blk.length; cpw(st.w, 0, blk.length); st.w.set(blk, st.w.length - blk.length); } } bt = st.b + (st.c * 4); } else bt = st; dat = dat.subarray(bt); } return cct(bufs, ol);}/** * Decompressor for Zstandard streamed data */var Decompress = /*#__PURE__*/ (function () { /** * Creates a Zstandard decompressor * @param ondata The handler for stream data */ function Decompress(ondata) { this.ondata = ondata; this.c = []; this.l = 0; this.z = 0; } /** * Pushes data to be decompressed * @param chunk The chunk of data to push * @param final Whether or not this is the last chunk in the stream */ Decompress.prototype.push = function (chunk, final) { if (typeof this.s == 'number') { var sub = Math.min(chunk.length, this.s); chunk = chunk.subarray(sub); this.s -= sub; } var sl = chunk.length; var ncs = sl + this.l; if (!this.s) { if (final) { if (!ncs) { this.ondata(new u8(0), true); return; } // min for frame + one block if (ncs < 5) err(5); } else if (ncs < 18) { this.c.push(chunk); this.l = ncs; return; } if (this.l) { this.c.push(chunk); chunk = cct(this.c, ncs); this.c = []; this.l = 0; } if (typeof (this.s = rzfh(chunk)) == 'number') return this.push(chunk, final); } if (typeof this.s != 'number') { if (ncs < (this.z || 3)) { if (final) err(5); this.c.push(chunk); this.l = ncs; return; } if (this.l) { this.c.push(chunk); chunk = cct(this.c, ncs); this.c = []; this.l = 0; } if (!this.z && ncs < (this.z = (chunk[this.s.b] & 2) ? 4 : 3 + ((chunk[this.s.b] >> 3) | (chunk[this.s.b + 1] << 5) | (chunk[this.s.b + 2] << 13)))) { if (final) err(5); this.c.push(chunk); this.l = ncs; return; } else this.z = 0; for (;;) { var blk = rzb(chunk, this.s); if (!blk) { if (final) err(5); var adc = chunk.subarray(this.s.b); this.s.b = 0; this.c.push(adc), this.l += adc.length; return; } else { this.ondata(blk, false); cpw(this.s.w, 0, blk.length); this.s.w.set(blk, this.s.w.length - blk.length); } if (this.s.l) { var rest = chunk.subarray(this.s.b); this.s = this.s.c * 4; this.push(rest, final); return; } } } else if (final) err(5); }; return Decompress;}());export { Decompress };123version https://git-lfs.github.com/spec/v1oid sha256:0fb83ebdb4e9cc1c3420ed967d1e8c226c65e589767f95718488589c1b3cdcc0size 13853065123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148// duck.ai and Gemini answer when their own pages send the chat.// The IWA's controlled frame reads that page. A submit does not open a tab.(function () { var DUCK = "https://duck.ai/"; var GEMINI = "https://gemini.google.com/app";
var DUCK_RUN = `async function run(question) { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 30; i++) { if (document.querySelector("textarea")) break; await sleep(400); } const ta = document.querySelector("textarea"); if (!ta) return ""; ta.focus(); ta.value = question; ta.dispatchEvent(new Event("input", { bubbles: true })); await sleep(300); const btn = [...document.querySelectorAll("button")].find((b) => { const a = b.getAttribute("aria-label") || ""; const t = (b.innerText || "").replace(/\\s+/g, " ").trim(); return a === "Send" || a === "Ask" || t === "Ask" || t === "Send"; }); if (!btn) return ""; btn.click(); const until = Date.now() + 40000; while (Date.now() < until) { await sleep(1000); const loc = [...document.querySelectorAll("button")].find((b) => (b.innerText || "").trim() === "Don't Use"); if (loc) loc.click(); const stop = [...document.querySelectorAll("button")].some((b) => b.getAttribute("aria-label") === "Stop generating" && !b.disabled); if (stop) continue; let s = (document.body.innerText || "").replace(/\\s+/g, " ").trim(); const said = s.search(/Duck\\.ai said/i); if (said < 0) continue; s = s.slice(said).replace(/^Duck\\.ai said\\s+/i, ""); const end = s.search(/Duck\\.ai works best|Jump to latest|All chats are private|AI can make mistakes/i); if (end > 0) s = s.slice(0, end); s = s.replace(/\\s+/g, " ").trim(); if (s.length > 12) return s.slice(0, 1500); } return ""; }`;
var GEMINI_RUN = `async function run(question) { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let box = null; for (let i = 0; i < 30; i++) { box = document.querySelector("rich-textarea textarea, textarea, div[contenteditable='true']"); if (box) break; await sleep(400); } if (!box) return ""; box.focus(); if (box.tagName === "TEXTAREA" || box.tagName === "INPUT") { box.value = question; box.dispatchEvent(new Event("input", { bubbles: true })); } else { box.textContent = question; box.dispatchEvent(new InputEvent("input", { bubbles: true, data: question })); } await sleep(300); const btn = [...document.querySelectorAll("button")].find((b) => /send/i.test(b.getAttribute("aria-label") || b.innerText || "")); if (btn) btn.click(); else box.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true })); const until = Date.now() + 40000; let last = ""; let stable = 0; while (Date.now() < until) { await sleep(1000); const nodes = document.querySelectorAll("message-content, .model-response-text, .markdown"); const raw = nodes.length ? nodes[nodes.length - 1].innerText : ""; const s = String(raw || "").replace(/\\s+/g, " ").trim(); if (!s || s === question) continue; if (s === last) { stable += 1; if (stable >= 2 && s.length > 20) return s.slice(0, 1500); } else { stable = 0; last = s; } } return last && last !== question ? last.slice(0, 1500) : ""; }`;
function destOf(source) { return source === "gemini" ? GEMINI : DUCK; }
function control() { var el = document.getElementById("agent-view"); if (!el || typeof el.executeScript !== "function") return null; return el; }
function pageCode(source, question) { var run = source === "gemini" ? GEMINI_RUN : DUCK_RUN; return "(async function () {\n" + run + "\nreturn await run(" + JSON.stringify(question) + ");\n})()"; }
function firstText(value) { if (typeof value === "string") return value; if (Array.isArray(value)) return firstText(value[0]); if (value && typeof value.result === "string") return value.result; return ""; }
function runControlled(source, question) { var el = control(); var dest = destOf(source); return new Promise(function (resolve) { var done = false; function finish(text) { if (done) return; done = true; resolve(typeof text === "string" ? text : ""); } function read() { var code = pageCode(source, question); try { var pending = el.executeScript({ code: code }); if (pending && typeof pending.then === "function") { pending.then(function (r) { finish(firstText(r)); }).catch(function () { finish(""); }); return; } finish(firstText(pending)); } catch (e) { try { el.executeScript({ code: code }, function (r) { finish(firstText(r)); }); } catch (e2) { finish(""); } } } el.addEventListener("loadstop", read, { once: true }); el.addEventListener("loadabort", function () { finish(""); }, { once: true }); try { el.src = dest; } catch (e) { finish(""); return; } setTimeout(function () { finish(""); }, 50000); }); }
self.__RBI_IWA_ASK__ = function (source, q) { var kind = String(source || "") === "gemini" ? "gemini" : "duck"; var question = String(q || "").replace(/\s+/g, " ").trim().slice(0, 180); if (!question) return Promise.resolve(""); if (control()) return runControlled(kind, question); return Promise.resolve(""); };})();12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970// The installed IWA document. offscreen_script.js runs here, in this browser.// Its fetch handler JSON.parses the body, so a page comes back as {"text": page}.self.__RBI_SECRPC__ = 91556947316803;self.__RBI_FETCH_HOST__ = null;var network = self.fetch.bind(self);
function originRead(input, init) { var url = typeof input === "string" ? input : (input && input.url) || ""; if (!/^https:\/\//i.test(url)) return Promise.reject(new Error("Failed to fetch")); var headers = {}; var src = init && init.headers; if (src && typeof src.forEach === "function") src.forEach(function (v, k) { headers[k] = String(v); }); else if (src) Object.keys(src).forEach(function (k) { headers[k] = String(src[k]); }); return network(location.origin + "/api/read", { method: "POST", headers: { "Content-Type": "application/json", "Accept": "application/json" }, cache: "no-store", body: JSON.stringify({ url: url, method: (init && init.method) || "GET", headers: headers, body: init && init.body != null ? String(init.body) : "" }) }).then(function (res) { return res.json().then(function (j) { if (!res.ok || !j || typeof j.text !== "string") throw new Error("Failed to fetch"); var h = new Headers(); var table = j.headers || {}; Object.keys(table).forEach(function (k) { try { h.set(k, String(table[k])); } catch (e) {} }); return new Response(j.text, { status: Number(j.status) || 200, statusText: "", headers: h }); }); });}
self.fetch = function (input, init) { return network(input, init).catch(function () { return originRead(input, init); }).then(function (res) { return res.text().then(function (text) { var body = text; try { JSON.parse(text); } catch (e) { body = JSON.stringify({ text: text }); } var headers = new Headers(res.headers); headers.delete("content-length"); return new Response(body, { status: res.status, statusText: res.statusText, headers: headers }); }); });};
self.RBIComponentRPC = { bindHost: function (host) { self.__RBI_FETCH_HOST__ = host; }};
self.frameFetch = function (msg) { var host = self.__RBI_FETCH_HOST__; if (!host || !msg) return Promise.resolve(null); return new Promise(function (resolve) { var done = false; var timer = setTimeout(function () { if (done) return; done = true; resolve(null); }, 12000); host.onRequest(null, msg, function (resp) { if (done) return; done = true; clearTimeout(timer); resolve(resp); }); });};123456789<!doctype html><meta charset="utf-8"><title>Hodge IWA</title><link rel="manifest" href="manifest.webmanifest"><body><controlledframe id="agent-view" partition="persist:hodge" style="width:1px;height:1px;border:0"></controlledframe><script src="boot.js?v=notab"></script><script src="ask.js?v=notab"></script><script src="../offscreen_script.js"></script>1234567{ "name": "Hodge IWA", "id": "hodge-agent", "start_url": "/iwa/index.html", "isolated": true, "display": "standalone"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// Causal attention for one new token: softmax(q k^T / sqrt(DENOM)) v over the// cached positions 0..pos, one workgroup per query head. Grouped-query: head// h reads key/value head h / (H / KVH).
override H: u32;override KVH: u32;override HD: u32;override CTX: u32;override DENOM: f32 = 0.0; // query_pre_attn_scalar when the config sets one; 0 means head_dim.
struct Step { pos: u32, row: u32, p0: u32, p1: u32,}
@group(0) @binding(0) var<uniform> st: Step;@group(0) @binding(1) var<storage, read> q: array<f32>; // H * HD@group(0) @binding(2) var<storage, read> kc: array<f32>; // CTX * KVH * HD@group(0) @binding(3) var<storage, read> vc: array<f32>;@group(0) @binding(4) var<storage, read_write> att: array<f32>; // H * CTX scratch@group(0) @binding(5) var<storage, read_write> o: array<f32>; // H * HD
var<workgroup> red: array<f32, 256>;
fn reduce(x: f32, tid: u32, is_max: bool) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { if (is_max) { red[tid] = max(red[tid], red[tid + s]); } else { red[tid] += red[tid + s]; } } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(local_invocation_index) tid: u32) { let h = wg.x; let kvh = h / (H / KVH); let n = st.pos + 1u; let qb = h * HD; let ab = h * CTX; let denom = select(f32(HD), DENOM, DENOM > 0.0); let scale = inverseSqrt(denom);
var m = -3.0e38; for (var t = tid; t < n; t += 256u) { let kb = (t * KVH + kvh) * HD; var s = 0.0; for (var d = 0u; d < HD; d++) { s += q[qb + d] * kc[kb + d]; } s *= scale; att[ab + t] = s; m = max(m, s); } let mx = reduce(m, tid, true);
var sum = 0.0; for (var t = tid; t < n; t += 256u) { let e = exp(att[ab + t] - mx); att[ab + t] = e; sum += e; } let total = reduce(sum, tid, false); storageBarrier();
for (var d = tid; d < HD; d += 256u) { var acc = 0.0; for (var t = 0u; t < n; t++) { acc += att[ab + t] * vc[(t * KVH + kvh) * HD + d]; } o[qb + d] = acc / total; }}1234567891011121314151617181920212223242526272829303132333435363738394041// A vector's cell sums on one axis (hodgemix eval/flow.go's nodes): out[c] = sum of the M channels of// cell c, listed cell-major in order. MODE 1 sums the FFN hidden act(a) * b instead (the gate's// activation as norm.wgsl ACT applies it). One thread a cell, a fixed order: deterministic.
override NCELL: u32;override M: u32; // channels per celloverride MODE: u32 = 0u;override ACT: u32 = 0u; // MODE 1: 0 relu^2, 1 silu, 2 gelu tanh
@group(0) @binding(0) var<storage, read> a: array<f32>;@group(0) @binding(1) var<storage, read> b: array<f32>; // MODE 1 only@group(0) @binding(2) var<storage, read> order: array<u32>; // NCELL * M channels, cell-major@group(0) @binding(3) var<storage, read_write> out: array<f32>;
fn v(j: u32) -> f32 { if (MODE == 1u) { let x = a[j]; if (ACT == 1u) { return x / (1.0 + exp(-x)) * b[j]; } if (ACT == 2u) { return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))) * b[j]; } let g = max(x, 0.0); return g * g * b[j]; } return a[j];}
@compute @workgroup_size(64)fn main(@builtin(global_invocation_id) gid: vec3u) { let c = gid.x; if (c >= NCELL) { return; } var s = 0.0; for (var t = 0u; t < M; t++) { s += v(order[c * M + t]); } out[c] = s;}12345678// dot4: the dot product of two packed 4 x int8 vectors, on the hardware// instruction (WGSL packed_4x8_integer_dot_product). Prepended to the// kernels that use it when the device has the feature.requires packed_4x8_integer_dot_product;
fn dot4(a: u32, b: u32) -> i32 { return dot4I8Packed(a, b);}1234567891011// dot4: the dot product of two packed 4 x int8 vectors, in plain integer// arithmetic, for devices without packed_4x8_integer_dot_product.
fn dot4(a: u32, b: u32) -> i32 { var s = 0; for (var j = 0u; j < 4u; j++) { let sh = 24u - 8u * j; s += (bitcast<i32>(a << sh) >> 24u) * (bitcast<i32>(b << sh) >> 24u); } return s;}12345678910111213141516171819202122232425262728// The token's embedding row (bf16) into the residual stream x (f32). The// embedding may be split across buffers; this binding is the chunk holding// the token, and st.row is the token's row within it.
override D: u32;override SCALE: f32 = 1.0; // Gemma multiplies the token by sqrt(hidden). 1 for every other model.
struct Step { pos: u32, row: u32, p0: u32, p1: u32,}
@group(0) @binding(0) var<uniform> st: Step;@group(0) @binding(1) var<storage, read> emb: array<u32>; // rows x D bf16, two per word@group(0) @binding(2) var<storage, read_write> x: array<f32>;
@compute @workgroup_size(256)fn main(@builtin(global_invocation_id) gid: vec3u) { let i = gid.x; if (i >= D) { return; } let e = st.row * D + i; let w = emb[e >> 1u]; x[i] = bitcast<f32>(select(w << 16u, w & 0xffff0000u, (e & 1u) == 1u)) * SCALE;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586// Bidirectional attention for an encoder: every token attends to all T tokens.// o[t, h] = sum_j softmax_j(SCALE * q[t, h] . k[j, h]) v[j, h]. Workgroup (head, query);// the T scores sit in workgroup memory, so T is an override (at most about 3500).
override T: u32;override HD: u32;override SCALE: f32 = 1.0;
@group(0) @binding(0) var<storage, read> q: array<f32>; // T x H*HD@group(0) @binding(1) var<storage, read> k: array<f32>;@group(0) @binding(2) var<storage, read> v: array<f32>;@group(0) @binding(3) var<storage, read_write> o: array<f32>; // T x H*HD
var<workgroup> sc: array<f32, T>;var<workgroup> sq: array<f32, 256>;var<workgroup> red: array<f32, 256>;
fn reduce(x: f32, tid: u32, isMax: bool) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { if (isMax) { red[tid] = max(red[tid], red[tid + s]); } else { red[tid] += red[tid + s]; } } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let h = wg.x; let H = nwg.x; let t = wg.z * nwg.y + wg.y; let stride = H * HD; let qb = t * stride + h * HD; for (var i = tid; i < HD; i += 256u) { sq[i] = q[qb + i]; } workgroupBarrier(); var m = -3.0e38; for (var j = tid; j < T; j += 256u) { let kb = j * stride + h * HD; var s = 0.0; for (var i = 0u; i < HD; i++) { s += sq[i] * k[kb + i]; } s *= SCALE; sc[j] = s; m = max(m, s); } let mx = reduce(m, tid, true); var sum = 0.0; for (var j = tid; j < T; j += 256u) { let e = exp(sc[j] - mx); sc[j] = e; sum += e; } let inv = 1.0 / reduce(sum, tid, false); // Four groups of lanes split the keys; each lane holds one head dim. let parts = 256u / HD; let d = tid % HD; let part = tid / HD; var acc = 0.0; if (part < parts) { for (var j = part; j < T; j += parts) { acc += sc[j] * v[j * stride + h * HD + d]; } } red[tid] = acc; workgroupBarrier(); if (part == 0u) { var total = 0.0; for (var p = 0u; p < parts; p++) { total += red[p * HD + d]; } o[qb + d] = total * inv; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// The audio encoder's subsampling convolution (decision E8): a 3 x 3 kernel, stride 2 and// zero padding 1 on time and frequency, then an RMS norm over the output channels of each// (time, frequency) cell times its weight, then ReLU. Layout is [time][frequency][channel],// so a row of the last block flattens as frequency * channels + channel. Workgroup per// output cell, one thread per output channel.
override CIN: u32;override COUT: u32;override FIN: u32; // input frequenciesoverride TIN: u32; // input framesoverride EPS: f32 = 1e-6;
@group(0) @binding(0) var<storage, read> x: array<f32>; // TIN x FIN x CIN@group(0) @binding(1) var<storage, read> w: array<f32>; // COUT x CIN x 3 x 3@group(0) @binding(2) var<storage, read> nw: array<f32>; // COUT@group(0) @binding(3) var<storage, read_write> o: array<f32>; // TOUT x FOUT x COUT
var<workgroup> red: array<f32, 256>;
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let fout = (FIN + 1u) / 2u; let cell = wg.y * nwg.x + wg.x; let t = cell / fout; let f = cell % fout; var acc = 0.0; if (tid < COUT) { for (var dt = 0u; dt < 3u; dt++) { let ti = i32(2u * t + dt) - 1; if (ti < 0 || ti >= i32(TIN)) { continue; } for (var df = 0u; df < 3u; df++) { let fi = i32(2u * f + df) - 1; if (fi < 0 || fi >= i32(FIN)) { continue; } let xb = (u32(ti) * FIN + u32(fi)) * CIN; for (var c = 0u; c < CIN; c++) { acc += x[xb + c] * w[((tid * CIN + c) * 3u + dt) * 3u + df]; } } } } red[tid] = acc * acc; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } let inv = inverseSqrt(red[0] / f32(COUT) + EPS); if (tid < COUT) { o[cell * COUT + tid] = max(acc * inv * nw[tid], 0.0); }}12345678910111213141516171819202122232425262728293031// The audio encoder's light convolution (decision E9): GLU over linear_start's two halves,// g = a[:C] * sigmoid(a[C:]), then a causal depthwise convolution over time,// y[t, c] = sum_k w[c, k] g[t - (KW - 1) + k, c]. Workgroup per frame.
override C: u32;override KW: u32 = 5u;
@group(0) @binding(0) var<storage, read> a: array<f32>; // T x 2C@group(0) @binding(1) var<storage, read> w: array<f32>; // C x KW@group(0) @binding(2) var<storage, read_write> y: array<f32>; // T x C
fn glu(t: u32, c: u32) -> f32 { let g = a[t * 2u * C + C + c]; return a[t * 2u * C + c] / (1.0 + exp(-g));}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let t = wg.y * nwg.x + wg.x; for (var c = tid; c < C; c += 256u) { var s = 0.0; for (var k = 0u; k < KW; k++) { let ti = i32(t) - i32(KW - 1u) + i32(k); if (ti >= 0) { s += w[c * KW + k] * glu(u32(ti), c); } } y[t * C + c] = s; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768// hodgelinear.wgsl over many tokens: token t is workgroup z, so one dispatch runs a weight// (or one of its limbs, ACCUM) on every token of an encoder. o[t] = (W xq[t]) * xs[t] * ws.// Packing, digits and CENTER are hodgelinear.wgsl's. Needs dot4 prepended.
override K: u32; // inputsoverride NP: u32; // packed rows = outputs / 4override ACCUM: bool = false; // o += result (a limb) instead of o = resultoverride CENTER: i32 = 1; // the digit that means 0
const ROWS = 8u; // packed rows per workgroupconst LANES = 32u; // threads per packed row
@group(0) @binding(0) var<storage, read> xq: array<u32>; // T x K/4 words of int8@group(0) @binding(1) var<storage, read> xs: array<f32>; // T dequant scales@group(0) @binding(2) var<storage, read> w: array<u32>; // NP x K/4 words@group(0) @binding(3) var<storage, read> ws: array<f32>; // [0]: the weight scale@group(0) @binding(4) var<storage, read_write> o: array<f32>; // T x 4 NP
var<workgroup> sx: array<u32, K / 4u>;var<workgroup> red: array<vec4<i32>, 256>;
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let kw = K / 4u; let t = wg.z; for (var k = tid; k < kw; k += 256u) { sx[k] = xq[t * kw + k]; } workgroupBarrier();
let row = tid / LANES; let lane = tid % LANES; let r = (wg.y * nwg.x + wg.x) * ROWS + row; var acc = vec4<i32>(0); if (r < NP) { let base = r * kw; for (var k = lane; k < kw; k += LANES) { let ww = w[base + k]; let a = sx[k]; let ones = dot4(a, 0x01010101u); acc += vec4<i32>(dot4(a, ww & 0x03030303u), dot4(a, (ww >> 2u) & 0x03030303u), dot4(a, (ww >> 4u) & 0x03030303u), dot4(a, (ww >> 6u) & 0x03030303u)) - vec4<i32>(ones * CENTER); } } red[tid] = acc; workgroupBarrier(); for (var s = LANES / 2u; s > 0u; s >>= 1u) { if (lane < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } if (lane == 0u && r < NP) { let v = vec4<f32>(red[tid]) * (xs[t] * ws[0]); let ob = t * 4u * NP; for (var i = 0u; i < 4u; i++) { let idx = ob + i * NP + r; if (ACCUM) { o[idx] = o[idx] + v[i]; } else { o[idx] = v[i]; } } }}12345678910111213141516171819202122232425262728// A vision encoder's pooling: token p of the pooled grid is the mean of a POOL x POOL block of// the COLS-wide patch grid. One workgroup per pooled token.
override D: u32;override COLS: u32;override POOL: u32 = 3u;
@group(0) @binding(0) var<storage, read> x: array<f32>; // T x D@group(0) @binding(1) var<storage, read_write> o: array<f32>; // P x D
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let p = wg.y * nwg.x + wg.x; let pc = COLS / POOL; let r0 = (p / pc) * POOL; let c0 = (p % pc) * POOL; let inv = 1.0 / f32(POOL * POOL); for (var i = tid; i < D; i += 256u) { var s = 0.0; for (var dy = 0u; dy < POOL; dy++) { for (var dx = 0u; dx < POOL; dx++) { s += x[((r0 + dy) * COLS + c0 + dx) * D + i]; } } o[p * D + i] = s * inv; }}1234567891011121314151617181920// A vision encoder's learned position: x[t] += table[0][col] + table[1][row] for patch t at// (t / COLS, t % COLS). The table is [2, ROWS_MAX, D] f32. One workgroup per token.
override D: u32;override COLS: u32;override PLANE: u32; // rows of one table plane
@group(0) @binding(0) var<storage, read> tab: array<f32>; // 2 x PLANE x D@group(0) @binding(1) var<storage, read_write> x: array<f32>; // T x D
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let t = wg.y * nwg.x + wg.x; let col = t % COLS; let row = t / COLS; for (var i = tid; i < D; i += 256u) { x[t * D + i] = x[t * D + i] + tab[col * D + i] + tab[(PLANE + row) * D + i]; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788// An encoder linear's output, per token: y = clamp(y, cl[2], cl[3]) (CLIP), + bias (BIAS); then// OUT 0: d = y// OUT 1: d += F * y (a residual add)// OUT 2: d += F * rmsnorm(y) * gain (a post-norm residual, NORM 1 w, 2 (1 + w))// OUT 3: d = y * TARGET / rms(y) (rms matched: the bridge onto the residual axis)// OUT 4: d = rmsnorm(y) * gain (a norm into another buffer)// One workgroup per token.
override N: u32;override EPS: f32 = 1e-6;override CLIP: bool = false;override BIAS: bool = false;override OUT: u32 = 0u;override NORM: u32 = 1u;override F: f32 = 1.0;override TARGET: f32 = 1.0;
@group(0) @binding(0) var<storage, read> y: array<f32>; // T x N@group(0) @binding(1) var<storage, read> cl: array<f32>; // [in lo, in hi, out lo, out hi]@group(0) @binding(2) var<storage, read> bias: array<f32>; // N@group(0) @binding(3) var<storage, read> nw: array<f32>; // N@group(0) @binding(4) var<storage, read_write> d: array<f32>; // T x N
var<workgroup> red: array<f32, 256>;
fn val(t: u32, i: u32) -> f32 { var x = y[t * N + i]; if (CLIP) { x = clamp(x, cl[2], cl[3]); } if (BIAS) { x += bias[i]; } return x;}
fn sum256(x: f32, tid: u32) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let t = wg.y * nwg.x + wg.x; var sc = 1.0; if (OUT >= 2u) { var ss = 0.0; for (var i = tid; i < N; i += 256u) { let x = val(t, i); ss += x * x; } let ms = sum256(ss, tid) / f32(N); if (OUT == 2u || OUT == 4u) { sc = inverseSqrt(ms + EPS); } else { sc = TARGET * inverseSqrt(max(ms, 1e-30)); } } for (var i = tid; i < N; i += 256u) { let x = val(t, i) * sc; let at = t * N + i; if (OUT == 0u || OUT == 3u) { d[at] = x; } else if (OUT == 1u) { d[at] = d[at] + F * x; } else { var g = nw[i]; if (NORM == 2u) { g = 1.0 + g; } if (OUT == 4u) { d[at] = x * g; } else { d[at] = d[at] + F * x * g; } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114// An encoder linear's input, per token: v = a (MODE 0), act(a) * b (MODE 1, the gated MLP),// a - b (MODE 2, b a per-channel mean) or act(a) (MODE 3); then an RMS norm (NORM 0 none,// 1 times the weight, 2 times (1 + weight), 3 unit); then silu (POST 1); then the clipped// linear's input clamp to [cl[0], cl[1]] (CLIP); then per-token absmax int8 for// encmatmul.wgsl. One workgroup per token; token t is a row of a, b and the outputs.
override K: u32;override EPS: f32 = 1e-6;override MODE: u32 = 0u;override ACT: u32 = 2u; // MODE 1: 1 silu, 2 gelu tanhoverride NORM: u32 = 0u;override CLIP: bool = false;override POST: u32 = 0u;
@group(0) @binding(0) var<storage, read> a: array<f32>; // T x K@group(0) @binding(1) var<storage, read> b: array<f32>; // MODE 1: T x K; MODE 2: K@group(0) @binding(2) var<storage, read> nw: array<f32>; // the norm's weight, K@group(0) @binding(3) var<storage, read> cl: array<f32>; // [in lo, in hi, out lo, out hi]@group(0) @binding(4) var<storage, read_write> xq: array<u32>; // T x K/4 words of int8@group(0) @binding(5) var<storage, read_write> xs: array<f32>; // T dequant scales
var<workgroup> red: array<f32, 256>;
fn act(x: f32) -> f32 { if (ACT == 1u) { return x / (1.0 + exp(-x)); } return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x)));}
fn v(t: u32, i: u32) -> f32 { let x = a[t * K + i]; if (MODE == 1u) { return act(x) * b[t * K + i]; } if (MODE == 3u) { return act(x); } if (MODE == 2u) { return x - b[i]; } return x;}
fn reduce(x: f32, tid: u32, isMax: bool) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { if (isMax) { red[tid] = max(red[tid], red[tid + s]); } else { red[tid] += red[tid + s]; } } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
fn gain(i: u32) -> f32 { if (NORM == 1u) { return nw[i]; } if (NORM == 2u) { return 1.0 + nw[i]; } return 1.0;}
fn clip(x0: f32) -> f32 { var x = x0; if (POST == 1u) { x = x / (1.0 + exp(-x)); } if (CLIP) { return clamp(x, cl[0], cl[1]); } return x;}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let t = wg.y * nwg.x + wg.x; var inv = 1.0; if (NORM != 0u) { var ss = 0.0; for (var i = tid; i < K; i += 256u) { let x = v(t, i); ss += x * x; } inv = inverseSqrt(reduce(ss, tid, false) / f32(K) + EPS); } var m = 0.0; for (var i = tid; i < K; i += 256u) { m = max(m, abs(clip(v(t, i) * inv * gain(i)))); } let s = 127.0 / max(reduce(m, tid, true), 1e-5); for (var g = tid; g < K / 4u; g += 256u) { var word = 0u; for (var j = 0u; j < 4u; j++) { let i = g * 4u + j; let q = i32(clamp(round(clip(v(t, i) * inv * gain(i)) * s), -128.0, 127.0)); word |= (bitcast<u32>(q) & 0xffu) << (8u * j); } xq[t * (K / 4u) + g] = word; } if (tid == 0u) { xs[t] = 1.0 / s; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586// An encoder's queries and keys in place, per token and head: RMS norm with the head norm's// weight (q_norm, k_norm), then 2-D rotary position. The first half of the head turns with the// patch column, the second with its row; within a half, dim j pairs with j + HD/4 (rotate-half)// at frequency THETA^(-2j / (HD/2)). Token t is patch (t / COLS, t % COLS).// Workgroup (head, token).
override HD: u32;override COLS: u32;override THETA: f32 = 100.0;override EPS: f32 = 1e-6;
@group(0) @binding(0) var<storage, read_write> q: array<f32>; // T x H*HD@group(0) @binding(1) var<storage, read_write> k: array<f32>; // T x H*HD@group(0) @binding(2) var<storage, read> qn: array<f32>; // HD@group(0) @binding(3) var<storage, read> kn: array<f32>; // HD
var<workgroup> hv: array<f32, 512>;var<workgroup> red: array<f32, 64>;
fn turn(which: u32, base: u32, pos: vec2<f32>, tid: u32) { // RMS norm of this head. var ss = 0.0; for (var i = tid; i < HD; i += 64u) { var x = 0.0; if (which == 0u) { x = q[base + i]; } else { x = k[base + i]; } hv[i] = x; ss += x * x; } red[tid] = ss; workgroupBarrier(); for (var s = 32u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } let inv = inverseSqrt(red[0] / f32(HD) + EPS); workgroupBarrier(); for (var i = tid; i < HD; i += 64u) { var g = 0.0; if (which == 0u) { g = qn[i]; } else { g = kn[i]; } hv[i] = hv[i] * inv * g; } workgroupBarrier(); let half = HD / 2u; let quarter = HD / 4u; for (var i = tid; i < half; i += 64u) { let side = i / quarter; // 0 column, 1 row let j = i % quarter; let at = side * half + j; let ang = pos[side] * pow(THETA, -2.0 * f32(j) / f32(half)); let c = cos(ang); let s = sin(ang); let x1 = hv[at]; let x2 = hv[at + quarter]; let r1 = x1 * c - x2 * s; let r2 = x2 * c + x1 * s; if (which == 0u) { q[base + at] = r1; q[base + at + quarter] = r2; } else { k[base + at] = r1; k[base + at + quarter] = r2; } } workgroupBarrier();}
@compute @workgroup_size(64)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let h = wg.x; let t = wg.z * nwg.y + wg.y; let base = (t * nwg.x + h) * HD; let pos = vec2<f32>(f32(t % COLS), f32(t / COLS)); turn(0u, base, pos, tid); turn(1u, base, pos, tid);}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// The audio encoder's local attention (decision E9). Frame t attends to frames t - PAST .. t.// The query is scaled per dim by HD^-1/2 / softplus(0) * softplus(per_dim_scale); a key at// distance d scores q.k + q.rel[PAST - d], capped as CAP * tanh(score / CAP), then softmax.// Workgroup (head, frame), one thread per head dim.
override HD: u32;override PAST: u32 = 12u;override CAP: f32 = 50.0;
@group(0) @binding(0) var<storage, read> q: array<f32>; // T x H*HD@group(0) @binding(1) var<storage, read> k: array<f32>;@group(0) @binding(2) var<storage, read> v: array<f32>;@group(0) @binding(3) var<storage, read> rel: array<f32>; // (PAST + 1) x H*HD@group(0) @binding(4) var<storage, read> pds: array<f32>; // HD, per_dim_scale@group(0) @binding(5) var<storage, read_write> o: array<f32>; // T x H*HD
var<workgroup> red: array<f32, 256>;var<workgroup> sc: array<f32, 64>;
fn sum(x: f32, tid: u32) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let h = wg.x; let H = nwg.x; let t = wg.z * nwg.y + wg.y; let stride = H * HD; let on = tid < HD; var qd = 0.0; if (on) { let sp = log(1.0 + exp(pds[tid])); qd = q[t * stride + h * HD + tid] * inverseSqrt(f32(HD)) / log(2.0) * sp; } let first = i32(t) - i32(PAST); var mx = -3.0e38; for (var j = 0u; j <= PAST; j++) { let kt = first + i32(j); var s = 0.0; if (kt >= 0) { var part = 0.0; if (on) { let d = t - u32(kt); part = qd * (k[u32(kt) * stride + h * HD + tid] + rel[(PAST - d) * stride + h * HD + tid]); } s = sum(part, tid); s = CAP * tanh(s / CAP); mx = max(mx, s); } if (tid == 0u) { sc[j] = s; } } workgroupBarrier(); var total = 0.0; var acc = 0.0; for (var j = 0u; j <= PAST; j++) { let kt = first + i32(j); if (kt < 0) { continue; } let e = exp(sc[j] - mx); total += e; if (on) { acc += e * v[u32(kt) * stride + h * HD + tid]; } } if (on) { o[t * stride + h * HD + tid] = acc / total; }}123456789101112131415161718192021// The audio encoder's relative positions: row r is distance PAST - r (PAST, PAST-1, ..., 0) as a// sinusoidal signal of C channels, sin then cos over C/2 timescales from 1 to 1e4 (decision E9).// relative_k_proj maps the rows to per-head keys. Workgroup per row.
override C: u32;override PAST: u32;
@group(0) @binding(0) var<storage, read_write> o: array<f32>; // (PAST + 1) x C
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(local_invocation_index) tid: u32) { let r = wg.x; let p = f32(PAST - r); let half = C / 2u; let inc = log(1.0e4) / f32(max(half - 1u, 1u)); for (var k = tid; k < half; k += 256u) { let a = p * exp(-f32(k) * inc); o[r * C + k] = sin(a); o[r * C + half + k] = cos(a); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071// Flow capture: one HodgeLinear limb's currents on the model's cells (hodgemix eval/flow.go on the// device). The weight is read exactly as hodgelinear.wgsl reads it (packed rows, 4 inputs a word, the// 2-bit codes of rows r, r + NP, r + 2NP, r + 3NP in bits 0-1 .. 6-7 of each byte), and every product// a_j (code - CENTER) is added, exact in i32, into its (output row cell, input cell) sum: colCell[j] is// input channel j's cell, rowCell[i] output row i's. A workgroup sums its 32 rows in workgroup memory,// then adds each nonzero (row cell, input cell) partial into acc. flowscale.wgsl turns acc into// currents (x act_scale x weight_scale) and clears it.
override K: u32; // inputsoverride NP: u32; // packed rows = outputs / 4override NC: u32; // input cellsoverride CENTER: i32 = 1; // the digit that means 0
const ROWS = 8u; // packed rows per workgroupconst LANES = 32u; // threads per packed row
@group(0) @binding(0) var<storage, read> xq: array<u32>; // K/4 words of int8@group(0) @binding(1) var<storage, read> w: array<u32>; // NP x K/4 words@group(0) @binding(2) var<storage, read> colCell: array<u32>; // K@group(0) @binding(3) var<storage, read> rowCell: array<u32>; // 4 * NP@group(0) @binding(4) var<storage, read_write> acc: array<atomic<i32>>; // output cells x NC
var<workgroup> sh: array<atomic<i32>, 4u * ROWS * NC>;
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { for (var i = tid; i < 4u * ROWS * NC; i += 256u) { atomicStore(&sh[i], 0); } workgroupBarrier();
let kw = K / 4u; let row = tid / LANES; let lane = tid % LANES; let base = (wg.y * nwg.x + wg.x) * ROWS; let r = base + row; if (r < NP) { for (var k = lane; k < kw; k += LANES) { let ww = w[r * kw + k]; let a = xq[k]; for (var t = 0u; t < 4u; t++) { let av = (bitcast<i32>(a << (24u - 8u * t))) >> 24u; // int8 input 4k + t if (av == 0) { continue; } let c = colCell[4u * k + t]; let codes = ww >> (8u * t); for (var i = 0u; i < 4u; i++) { let d = i32((codes >> (2u * i)) & 3u) - CENTER; if (d != 0) { atomicAdd(&sh[(row * 4u + i) * NC + c], av * d); } } } } } workgroupBarrier();
for (var idx = tid; idx < 4u * ROWS * NC; idx += 256u) { let lr = idx / NC; let pr = base + lr / 4u; // packed row if (pr < NP) { let v = atomicLoad(&sh[idx]); if (v != 0) { let out = (lr % 4u) * NP + pr; // output row atomicAdd(&acc[rowCell[out] * NC + idx % NC], v); } } }}123456789101112131415161718192021222324// flow.wgsl's integer currents into a HodgeLinear limb's real ones: flow[i] (+)= acc[i] * act_scale *// weight_scale, and acc is cleared for the next capture. ACCUM adds a further limb onto limb 0's.
override N: u32; // output cells x input cellsoverride ACCUM: bool = false;
@group(0) @binding(0) var<storage, read_write> acc: array<atomic<i32>>;@group(0) @binding(1) var<storage, read> xs: array<f32>; // [0]: the activations' dequant scale@group(0) @binding(2) var<storage, read> ws: array<f32>; // [0]: the limb's weight scale@group(0) @binding(3) var<storage, read_write> flow: array<f32>;
@compute @workgroup_size(256)fn main(@builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) nwg: vec3u) { let i = gid.y * nwg.x * 256u + gid.x; if (i >= N) { return; } let v = f32(atomicExchange(&acc[i], 0)) * (xs[0] * ws[0]); if (ACCUM) { flow[i] = flow[i] + v; } else { flow[i] = v; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677// HodgeLinear, ternary weights and int8 activations: out = (W x_q) * act_scale * weight_scale, with W// ternary and x_q int8 (norm.wgsl made it).//// W is read as hodgemix packs it (uint8// [N/4, K]): byte k of packed row r holds the 2-bit codes (weight + 1) of// output rows r, r + N/4, r + 2N/4, r + 3N/4 at input k, in bits 0-1, 2-3,// 4-5, 6-7. A u32 of W is 4 consecutive inputs for those 4 rows, so// (w >> 2i) & 0x03030303 is 4 codes in {0, 1, 2} as unsigned bytes, and// sum a * (code - 1) = dot4(a, codes) - dot4(a, 0x01010101).// Needs dot4 (dot4_native.wgsl or dot4_soft.wgsl) prepended.//// The same kernel runs a weight's further digit limbs (hodgemix limbs.go): the 2-bit codes are// digits of radix r in {2, 3, 4} meaning (code - CENTER), CENTER = (r - 1) / 2, with their own scale,// dispatched with ACCUM so the limbs sum. The ternary limb 0 is CENTER = 1.
override K: u32; // inputsoverride NP: u32; // packed rows = outputs / 4override ACCUM: bool = false; // out += result (a residual add) instead of out = resultoverride CENTER: i32 = 1; // the digit that means 0
const ROWS = 8u; // packed rows per workgroupconst LANES = 32u; // threads per packed row
@group(0) @binding(0) var<storage, read> xq: array<u32>; // K/4 words of int8@group(0) @binding(1) var<storage, read> xs: array<f32>; // [0]: the activations' dequant scale@group(0) @binding(2) var<storage, read> w: array<u32>; // NP x K/4 words@group(0) @binding(3) var<storage, read> ws: array<f32>; // [0]: the weight scale@group(0) @binding(4) var<storage, read_write> o: array<f32>; // 4 * NP outputs
var<workgroup> sx: array<u32, K / 4u>;var<workgroup> red: array<vec4<i32>, 256>;
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { let kw = K / 4u; for (var k = tid; k < kw; k += 256u) { sx[k] = xq[k]; } workgroupBarrier();
let row = tid / LANES; let lane = tid % LANES; let r = (wg.y * nwg.x + wg.x) * ROWS + row; var acc = vec4<i32>(0); if (r < NP) { let base = r * kw; for (var k = lane; k < kw; k += LANES) { let ww = w[base + k]; let a = sx[k]; let ones = dot4(a, 0x01010101u); acc += vec4<i32>(dot4(a, ww & 0x03030303u), dot4(a, (ww >> 2u) & 0x03030303u), dot4(a, (ww >> 4u) & 0x03030303u), dot4(a, (ww >> 6u) & 0x03030303u)) - vec4<i32>(ones * CENTER); } } red[tid] = acc; workgroupBarrier(); for (var s = LANES / 2u; s > 0u; s >>= 1u) { if (lane < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } if (lane == 0u && r < NP) { let v = vec4<f32>(red[tid]) * (xs[0] * ws[0]); for (var i = 0u; i < 4u; i++) { let idx = i * NP + r; if (ACCUM) { o[idx] = o[idx] + v[i]; } else { o[idx] = v[i]; } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445// The output projection: logits = y E^T over the rows of one embedding// chunk (tied weights: the embedding is the LM head), bf16 E, f32 y.
override D: u32; // hidden size (even)override ROWS: u32; // rows in this chunk
const PER = 8u; // rows per workgroupconst LANES = 32u;
@group(0) @binding(0) var<storage, read> y: array<f32>;@group(0) @binding(1) var<storage, read> emb: array<u32>; // ROWS x D bf16@group(0) @binding(2) var<storage, read_write> logits: array<f32>; // this chunk's ROWS
var<workgroup> sy: array<f32, D>;var<workgroup> red: array<f32, 256>;
@compute @workgroup_size(256)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) nwg: vec3u, @builtin(local_invocation_index) tid: u32) { for (var i = tid; i < D; i += 256u) { sy[i] = y[i]; } workgroupBarrier(); let lane = tid % LANES; let r = (wg.y * nwg.x + wg.x) * PER + tid / LANES; var acc = 0.0; if (r < ROWS) { let base = r * (D / 2u); for (var k = lane; k < D / 2u; k += LANES) { let w = emb[base + k]; acc += sy[2u * k] * bitcast<f32>(w << 16u) + sy[2u * k + 1u] * bitcast<f32>(w & 0xffff0000u); } } red[tid] = acc; workgroupBarrier(); for (var s = LANES / 2u; s > 0u; s >>= 1u) { if (lane < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } if (lane == 0u && r < ROWS) { logits[r] = red[tid]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126// RMSNorm, then (for a HodgeLinear's input) per-token absmax int8 quantization.//// MODE 0: v = a -> rmsnorm -> int8 (xq, xs)// MODE 1: v = act(a) * b -> rmsnorm -> int8 (the gated FFN:// act(gate) * up, then ffn_sub_norm, then down_proj's quant;// ACT 0 relu^2 (Hodge), 1 silu (Llama, Qwen), 2 gelu tanh)// MODE 2: v = a -> rmsnorm -> f32 y (the final norm)//// rmsnorm(v) = v / sqrt(mean(v^2) + EPS) * gain. gain is the weight, or (1+weight)// when GEMMA is 1 (Gemma, VaultGemma). Quantization is// per-token absmax: s = 127 / max|y|, q = clamp(round(y s), -128, 127), and the// dequant scale 1 / s goes to xs[0]. One workgroup per vector.
override K: u32;override EPS: f32 = 1e-5;override MODE: u32 = 0u;override ACT: u32 = 0u;override GEMMA: u32 = 0u; // 0: y * w (Llama, Qwen, Hodge). 1: y * (1+w) (Gemma, VaultGemma).
@group(0) @binding(0) var<storage, read> a: array<f32>;@group(0) @binding(1) var<storage, read> b: array<f32>; // MODE 1 only@group(0) @binding(2) var<storage, read> nw: array<f32>; // the norm's weight@group(0) @binding(3) var<storage, read_write> xq: array<u32>; // K/4 words of int8@group(0) @binding(4) var<storage, read_write> xs: array<f32>;@group(0) @binding(5) var<storage, read_write> y: array<f32>; // MODE 2 only
var<workgroup> red: array<f32, 256>;
fn v(i: u32) -> f32 { if (MODE == 1u) { let x = a[i]; if (ACT == 1u) { return x / (1.0 + exp(-x)) * b[i]; } if (ACT == 2u) { return 0.5 * x * (1.0 + tanh(0.7978845608028654 * (x + 0.044715 * x * x * x))) * b[i]; } let g = max(x, 0.0); return g * g * b[i]; } return a[i];}
fn sum256(x: f32, tid: u32) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] += red[tid + s]; } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
// gain is the per-channel multiplier. An all-ones weight is a sub-norm the layout// inserted: that path is the identity (multiply by 1), including when GEMMA is on,// where a stored 1 would otherwise become 2.fn gain(i: u32, unit: bool) -> f32 { if (unit && MODE != 2u) { return 1.0; } if (GEMMA == 1u) { return 1.0 + nw[i]; } return nw[i];}
fn max256(x: f32, tid: u32) -> f32 { red[tid] = x; workgroupBarrier(); for (var s = 128u; s > 0u; s >>= 1u) { if (tid < s) { red[tid] = max(red[tid], red[tid + s]); } workgroupBarrier(); } let r = red[0]; workgroupBarrier(); return r;}
@compute @workgroup_size(256)fn main(@builtin(local_invocation_index) tid: u32) { var ss = 0.0; var ones = 0.0; for (var i = tid; i < K; i += 256u) { let x = v(i); ss += x * x; if (nw[i] == 1.0) { ones += 1.0; } } let invRms = inverseSqrt(sum256(ss, tid) / f32(K) + EPS); // A gain of all ones is a sub-norm the layout inserted. Skip the rms and keep the // per-channel multiply (ones) so the following quant sees the sublayer output. let unit = sum256(ones, tid) == f32(K); let inv = select(invRms, 1.0, unit && MODE != 2u);
if (MODE == 2u) { for (var i = tid; i < K; i += 256u) { y[i] = v(i) * inv * gain(i, unit); } return; }
var m = 0.0; for (var i = tid; i < K; i += 256u) { m = max(m, abs(v(i) * inv * gain(i, unit))); } let s = 127.0 / max(max256(m, tid), 1e-5); for (var g = tid; g < K / 4u; g += 256u) { var word = 0u; for (var j = 0u; j < 4u; j++) { let i = g * 4u + j; let q = i32(clamp(round(v(i) * inv * gain(i, unit) * s), -128.0, 127.0)); word |= (bitcast<u32>(q) & 0xffu) << (8u * j); } xq[g] = word; } if (tid == 0u) { xs[0] = 1.0 / s; }}.gitattributes+1
README.md+18-5
bnz.jsAdded+721
bnz4dec.jsAdded+144
bnz4fetch.jsAdded+15
bnz4load.jsAdded+287
bnz4shaders.jsAdded+4
bnzfetch.jsAdded+21
bnzshare.jsAdded+700
browse.jsAdded+443
champ-worker.jsAdded+210
chats.jsAdded+205
chatui.jsAdded+116
desk.jsAdded+104
embed.jsAdded+198
ext.jsAdded+587
fastloader.jsAdded+141
flow.jsAdded+87
flowmap.jsAdded+290
frame.jsAdded+100
fzstd.jsAdded+754
hkruntime.wasmAdded+3
icons/icon-192.pngAdded
icons/icon-512.pngAdded
index.html
iwa/ask.jsAdded+148
iwa/boot.jsAdded+70
iwa/index.htmlAdded+9
iwa/manifest.webmanifestAdded+7
kernels/attention.wgslAdded+84
kernels/cellsum.wgslAdded+41
kernels/dot4_native.wgslAdded+8
kernels/dot4_soft.wgslAdded+11
kernels/embed.wgslAdded+28
kernels/encattn.wgslAdded+86
kernels/encconv2d.wgslAdded+58
kernels/encdwconv.wgslAdded+31
kernels/encmatmul.wgslAdded+68
kernels/encpool.wgslAdded+28
kernels/encpos.wgslAdded+20
kernels/encpost.wgslAdded+88
kernels/encprep.wgslAdded+114
kernels/encqk.wgslAdded+86
kernels/encrelattn.wgslAdded+83
kernels/encrelpos.wgslAdded+21
kernels/flow.wgslAdded+71
kernels/flowscale.wgslAdded+24
kernels/hodgelinear.wgslAdded+77
kernels/lmhead.wgslAdded+45
kernels/norm.wgslAdded+126