AEUPH commited on
Commit
0a2c042
·
verified ·
1 Parent(s): a8c9604

DMCRA Lab: elastic level-set quantisation over real GGUF weights, measured end to end

Browse files
Files changed (1) hide show
  1. app.js +922 -0
app.js ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* app.js — the DMCRA Lab controller: real quantisation and a real llama forward pass in the page.
2
+ *
3
+ * WHAT THIS FILE DOES
4
+ * It loads a GGUF in the browser, runs the REAL transformer over the REAL weight bytes, and measures
5
+ * the claims of the DMCRA document on the actual output of the model. It is the page half of
6
+ * `scripts/dmcra_tests/elastic.test.mjs` — the Node suite already measures all of this — and the
7
+ * algorithms here (average ranks, Spearman with ties, the per-block elastic plan, the per-block
8
+ * quantiser) are ports of that suite's, deliberately ported rather than reinvented so the page and
9
+ * the suite cannot disagree about what a number means.
10
+ *
11
+ * THE INSTRUMENTS, AND WHY NOT PERPLEXITY
12
+ * Perplexity was the obvious quality metric and had to be dropped: on the fixture the suite uses, the
13
+ * exact pass's perplexity measures WORSE than a uniform distribution while its top-1 is 16.9%, so any
14
+ * noise that shrinks the logits toward uniform "improves" it. Perplexity is therefore not shown at
15
+ * all. The page scores with instruments that are invariant to logit scale, so a quantiser cannot buy
16
+ * a better figure by shrinking its logits:
17
+ *
18
+ * mean rank of the true token — chance is (vocab+1)/2; continuous, so tighter than a hit rate.
19
+ * Spearman rho against EXACT — rank correlation of the full logit vector against the exact
20
+ * pass: how much of the model's own preference order a quantiser
21
+ * destroyed. Primary instrument.
22
+ * top-1 rate — reported with its standard error so its weakness is visible.
23
+ *
24
+ * HONESTY RULES ENFORCED HERE
25
+ * - Every figure displayed is measured by this run; nothing is quoted from a report.
26
+ * - bits/weight comes from the pass itself (`meta.meanBitsPerWeight`), never recomputed here.
27
+ * - Anything that cannot run is refused in words with the reason, and the panel stays usable.
28
+ * - The zero-channel test reports exact equality or difference, whichever the numbers give.
29
+ *
30
+ * Dependency globals, loaded by index.html in this order: HDCGGUF, HDCWeights, HDCBPE, DMCRAQUANT,
31
+ * HDCFORWARD. Same UMD shape as quant.js, so it also loads under Node with a stubbed DOM.
32
+ */
33
+ (function (root, factory) {
34
+ var api = factory(root);
35
+ if (typeof module !== "undefined" && module.exports) module.exports = api;
36
+ root.DMCRAAPP = api;
37
+ })(typeof globalThis !== "undefined" ? globalThis : this, function (root) {
38
+ "use strict";
39
+
40
+ var G = root.HDCGGUF, W = root.HDCWeights, BPE = root.HDCBPE, Q = root.DMCRAQUANT, FW = root.HDCFORWARD;
41
+
42
+ var BLOCK = 32; // weights per quantisation block (one 4-byte scale each)
43
+ var LADDER = ["binary", "quad", "ternary", "penta", "hepta", "oct", "nona"];
44
+ var MAX_BYTES = 48 * 1024 * 1024; // above this the tab stops being usable; refused, not hung
45
+ var LOG_CAP = 400;
46
+
47
+ /* The passage the suites score on: in-distribution tiny-story English, so the fixture is not
48
+ * handicapped by text it was never trained on. */
49
+ var DEFAULT_TEXT = "Once upon a time there was a little girl named Lily . She lived in a big house " +
50
+ "with her mother and father . One day she went to the park to play with her friends " +
51
+ "and they had a lot of fun . The sun was hot and the sky was blue and the girl was happy .";
52
+
53
+ var state = {
54
+ buf: null, label: null, header: null, vocab: null, tk: null,
55
+ text: DEFAULT_TEXT, ids: [], matrices: [], totalWeights: 0,
56
+ exact: null, positions: 16, busy: false, plan: null, requirements: null
57
+ };
58
+
59
+ var els = {};
60
+
61
+ /* ------------------------------------------------------------------ dom plumbing */
62
+
63
+ function el(id) {
64
+ return (typeof document !== "undefined" && document.getElementById) ? document.getElementById(id) : null;
65
+ }
66
+
67
+ /* Re-resolved at each entry point rather than cached once at load, so the Node harness can seed the
68
+ * DOM and then call into this module without caring about ordering. */
69
+ function refreshEls() {
70
+ els = {
71
+ modelSelect: el("model-select"), loadBtn: el("load-btn"), loadStatus: el("load-status"),
72
+ modelBody: el("model-tbody"),
73
+ prompt: el("prompt"), runBtn: el("run-btn"), inferStatus: el("infer-status"),
74
+ topkBody: el("topk-tbody"),
75
+ positions: el("positions"), positionsLabel: el("positions-label"), ladderBtn: el("ladder-btn"),
76
+ exactStatus: el("exact-status"), ladderStatus: el("ladder-status"), ladderBody: el("ladder-tbody"),
77
+ zeroBtn: el("zero-btn"), zeroStatus: el("zero-status"), zeroBody: el("zero-tbody"),
78
+ planSelect: el("plan-select"), planBtn: el("plan-btn"), planStatus: el("plan-status"),
79
+ planBody: el("plan-tbody"), gridCanvas: el("grid-canvas"),
80
+ log: el("log"), terminal: el("terminal"), cursor: el("cursor"), clearBtn: el("clear-btn")
81
+ };
82
+ return els;
83
+ }
84
+
85
+ function log(msg, cls) {
86
+ if (!els.log) return;
87
+ var line = document.createElement("div");
88
+ line.className = "logline" + (cls ? " " + cls : "");
89
+ line.textContent = msg;
90
+ els.log.appendChild(line);
91
+ while (els.log.childNodes.length > LOG_CAP) els.log.removeChild(els.log.firstChild);
92
+ els.log.scrollTop = els.log.scrollHeight;
93
+ }
94
+
95
+ function status(node, msg) { if (node) node.textContent = msg; }
96
+
97
+ /* Status text and a log line together, so nothing is reported in one place only. */
98
+ function say(node, msg, cls) { status(node, msg); log(msg, cls); }
99
+
100
+ function term(text, cls) {
101
+ if (!els.terminal) return;
102
+ var line = document.createElement("div");
103
+ line.className = "termlines" + (cls ? " " + cls : "");
104
+ line.textContent = text;
105
+ els.terminal.appendChild(line);
106
+ while (els.terminal.childNodes.length > LOG_CAP) els.terminal.removeChild(els.terminal.firstChild);
107
+ if (els.cursor) els.terminal.appendChild(els.cursor);
108
+ els.terminal.scrollTop = els.terminal.scrollHeight;
109
+ }
110
+
111
+ function yieldUI() {
112
+ return new Promise(function (r) { setTimeout(r, 0); });
113
+ }
114
+
115
+ function num(n, d) {
116
+ if (n === null || n === undefined || !isFinite(n)) return "—";
117
+ return Number(n).toFixed(d === undefined ? 2 : d);
118
+ }
119
+ function int(n) {
120
+ if (n === null || n === undefined || !isFinite(n)) return "—";
121
+ var s = String(Math.round(n));
122
+ return s.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
123
+ }
124
+ function fmtBytes(n) {
125
+ if (!n) return "—";
126
+ if (n < 1024) return n + " B";
127
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + " KB";
128
+ return (n / (1024 * 1024)).toFixed(2) + " MB";
129
+ }
130
+ function fmtBits(b) { return (b === null || b === undefined) ? "exact" : num(b, 3) + " b/w"; }
131
+
132
+ /* Table helpers. First cell is the label column, the rest are numbers, which the stylesheet
133
+ * right-aligns; the row class carries that intent so the markup and this file agree. */
134
+ function clearTable(tbody) { if (tbody) tbody.innerHTML = ""; }
135
+ function addRow(tbody, cells, cls) {
136
+ if (!tbody) return null;
137
+ var tr = document.createElement("tr");
138
+ if (cls) tr.className = cls;
139
+ for (var i = 0; i < cells.length; i++) {
140
+ var td = document.createElement("td");
141
+ td.className = i === 0 ? "c-label" : "c-num";
142
+ td.textContent = cells[i] === null || cells[i] === undefined ? "—" : String(cells[i]);
143
+ tr.appendChild(td);
144
+ }
145
+ tbody.appendChild(tr);
146
+ return tr;
147
+ }
148
+ function addModelRow(label, value) { return addRow(els.modelBody, [label, value]); }
149
+
150
+ /* ------------------------------------------------------------------ statistics
151
+ * Ports of the Node suite's helpers. Average ranks for ties, because quantised models produce exact
152
+ * ties constantly and a naive rank would make Spearman undefined exactly where it matters.
153
+ */
154
+
155
+ function avgRanks(a) {
156
+ var n = a.length, idx = new Array(n), i;
157
+ for (i = 0; i < n; i++) idx[i] = i;
158
+ idx.sort(function (x, y) { return a[x] - a[y]; });
159
+ var r = new Float64Array(n);
160
+ i = 0;
161
+ while (i < n) {
162
+ var j = i;
163
+ while (j + 1 < n && a[idx[j + 1]] === a[idx[i]]) j++;
164
+ var avg = (i + j) / 2 + 1;
165
+ for (var k = i; k <= j; k++) r[idx[k]] = avg;
166
+ i = j + 1;
167
+ }
168
+ return r;
169
+ }
170
+
171
+ function pearson(a, b) {
172
+ var n = a.length, i, ma = 0, mb = 0;
173
+ for (i = 0; i < n; i++) { ma += a[i]; mb += b[i]; }
174
+ ma /= n; mb /= n;
175
+ var dot = 0, va = 0, vb = 0, da, db;
176
+ for (i = 0; i < n; i++) { da = a[i] - ma; db = b[i] - mb; dot += da * db; va += da * da; vb += db * db; }
177
+ var den = Math.sqrt(va * vb);
178
+ return den > 0 ? dot / den : 0;
179
+ }
180
+
181
+ function spearman(a, b) { return pearson(avgRanks(a), avgRanks(b)); }
182
+
183
+ /* Average rank of one token's logit within the whole distribution: 1 is best, vocab is worst. */
184
+ function rankOfTrue(logits, id) {
185
+ var tv = logits[id], greater = 0, equal = 0;
186
+ for (var i = 0; i < logits.length; i++) {
187
+ if (logits[i] > tv) greater++;
188
+ else if (logits[i] === tv) equal++;
189
+ }
190
+ return greater + 1 + (equal - 1) / 2;
191
+ }
192
+
193
+ function median(list) {
194
+ var s = list.slice().sort(function (x, y) { return x - y; }), n = s.length;
195
+ if (!n) return 0;
196
+ return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
197
+ }
198
+
199
+ /* ------------------------------------------------------------------ quantisers
200
+ * A quantiser is what forward.js calls per matrix: it returns the replacement values and, when it
201
+ * can be described, its own bit cost, which the pass adds up and reports as meta.meanBitsPerWeight.
202
+ * Returning `bits` is what makes the page's cost column a measurement by the pass rather than
203
+ * arithmetic done here.
204
+ */
205
+
206
+ function gridQuantiser(grid) {
207
+ return function (values) {
208
+ var q = Q.quantise(values, { grid: grid, blockSize: BLOCK });
209
+ return { values: q.values, bits: q.bits.effBits };
210
+ };
211
+ }
212
+
213
+ /* Per-block plan application: each 32-weight block gets its own grid from the planner. A matrix
214
+ * absent from the plan is returned untouched, and that is reported rather than hidden, because
215
+ * silently quantising it with some default would make the plan's bit figure wrong. */
216
+ function planQuantiser(plan, missing) {
217
+ return function (values, name) {
218
+ var gs = plan.gridByBlock[name];
219
+ if (!gs) {
220
+ if (missing && missing.indexOf(name) < 0) missing.push(name);
221
+ return { values: values };
222
+ }
223
+ var out = new Float32Array(values.length), bits = 0, b, off, len, q;
224
+ for (b = 0; b < gs.length; b++) {
225
+ off = b * BLOCK;
226
+ len = Math.min(BLOCK, values.length - off);
227
+ if (len <= 0) break;
228
+ q = Q.quantiseBlock(values, off, len, gs[b], "lsq");
229
+ out.set(q.values, off);
230
+ bits += q.bits.effBits * len;
231
+ }
232
+ return { values: out, bits: bits / values.length };
233
+ };
234
+ }
235
+
236
+ /* ------------------------------------------------------------------ measurement core */
237
+
238
+ /* Run the pass over scored positions and collect everything the panels need. `stride` lets a cheap
239
+ * probe score every k-th position when only a ranking is needed. */
240
+ async function evaluate(label, opts, positions, stride) {
241
+ stride = stride || 1;
242
+ var limit = Math.min(positions, state.ids.length - 1);
243
+ var t0 = Date.now();
244
+ var logitsAt = new Map(), perPos = [], i, t;
245
+ var hit = 0, top5 = 0, total = 0, bad = false, bits = null, rankSum = 0;
246
+
247
+ for (t = 1; t <= limit; t++) {
248
+ if ((t - 1) % stride) continue;
249
+ var r = FW.run(state.buf, state.header, state.ids.slice(0, t), opts);
250
+ var L = r.logits;
251
+ var best = -Infinity, arg = -1;
252
+ for (i = 0; i < L.length; i++) {
253
+ if (!isFinite(L[i])) bad = true;
254
+ if (L[i] > best) { best = L[i]; arg = i; }
255
+ }
256
+ var rank = rankOfTrue(L, state.ids[t]);
257
+ perPos.push(rank);
258
+ rankSum += rank;
259
+ if (arg === state.ids[t]) hit++;
260
+ if (rank <= 5) top5++;
261
+ logitsAt.set(t, L);
262
+ total++;
263
+ if (r.meta && r.meta.meanBitsPerWeight !== null && r.meta.meanBitsPerWeight !== undefined) {
264
+ bits = r.meta.meanBitsPerWeight;
265
+ }
266
+ if (total % 4 === 0) await yieldUI();
267
+ }
268
+
269
+ if (!total) throw new Error("no positions were scored");
270
+ var meanRank = rankSum / total;
271
+ var sd = 0;
272
+ for (i = 0; i < perPos.length; i++) sd += (perPos[i] - meanRank) * (perPos[i] - meanRank);
273
+ sd = Math.sqrt(sd / Math.max(1, total - 1));
274
+
275
+ return {
276
+ label: label, total: total, perPos: perPos, logitsAt: logitsAt,
277
+ meanRank: meanRank, rankSE: sd / Math.sqrt(total), medianRank: median(perPos),
278
+ acc: hit / total, top1: hit / total, top5: top5 / total,
279
+ accSE: Math.sqrt((hit / total) * (1 - hit / total) / total),
280
+ bits: bits, ms: Date.now() - t0, msPerToken: (Date.now() - t0) / total,
281
+ finite: !bad, spearman: null, rmse: null
282
+ };
283
+ }
284
+
285
+ /* Spearman of a configuration's logits against the exact pass at the same positions. */
286
+ function vsExact(cfg) {
287
+ if (!state.exact) return null;
288
+ var sum = 0, n = 0;
289
+ cfg.logitsAt.forEach(function (L, t) {
290
+ var E = state.exact.logitsAt.get(t);
291
+ if (!E || E.length !== L.length) return;
292
+ sum += spearman(L, E); n++;
293
+ });
294
+ return n ? sum / n : null;
295
+ }
296
+
297
+ /* Paired comparison over identical positions: the correct test, and far tighter than comparing two
298
+ * independent means because both configurations are scored on the same text. */
299
+ function pairedRank(a, b) {
300
+ var n = Math.min(a.perPos.length, b.perPos.length), d = [], i;
301
+ for (i = 0; i < n; i++) d.push(a.perPos[i] - b.perPos[i]);
302
+ if (!n) return { mean: 0, se: 0, n: 0, t: 0 };
303
+ var mean = 0;
304
+ for (i = 0; i < n; i++) mean += d[i];
305
+ mean /= n;
306
+ var v = 0;
307
+ for (i = 0; i < n; i++) v += (d[i] - mean) * (d[i] - mean);
308
+ var se = Math.sqrt(v / Math.max(1, n - 1)) / Math.sqrt(n);
309
+ return { mean: mean, se: se, n: n, t: se > 0 ? mean / se : 0 };
310
+ }
311
+
312
+ /* Mean reconstruction RMSE over the quantised matrices, at the same grid and block size the pass
313
+ * uses, so the error column describes the weights the pass actually ran on. */
314
+ function meanRMSE(grid) {
315
+ var sum = 0;
316
+ for (var i = 0; i < state.matrices.length; i++) {
317
+ sum += Q.quantise(state.matrices[i].values, { grid: grid, blockSize: BLOCK }).error.rmse;
318
+ }
319
+ return state.matrices.length ? sum / state.matrices.length : 0;
320
+ }
321
+
322
+ /* ------------------------------------------------------------------ model loading */
323
+
324
+ function setText(text) {
325
+ var before = state.ids.join(",");
326
+ state.text = text || DEFAULT_TEXT;
327
+ if (!state.tk || !state.vocab) { state.ids = []; return state.ids; }
328
+ var body = state.tk.ids(state.text);
329
+ var bos = (state.vocab.bosId === null || state.vocab.bosId === undefined) ? 1 : state.vocab.bosId;
330
+ state.ids = [bos].concat(body);
331
+ /* A reference measurement is only a reference for the token sequence it was taken on. Every rho
332
+ * on this page matches positions by index, so if the passage changes, the exact pass's logits at
333
+ * position t belong to a DIFFERENT token — comparing them would be silently meaningless rather
334
+ * than wrong-looking. The baseline is therefore dropped the moment the sequence changes. */
335
+ if (state.ids.join(",") !== before) state.exact = null;
336
+ return state.ids;
337
+ }
338
+
339
+ /* The exact baseline, re-measured when it does not cover what is about to be compared against it
340
+ * (the visitor raised the position count, or the passage changed under it). */
341
+ async function ensureExact() {
342
+ refreshEls();
343
+ if (state.exact && state.exact.total >= state.positions) return state.exact;
344
+ try {
345
+ var limit = Math.min(state.positions, state.ids.length - 1);
346
+ log("re-measuring the EXACT baseline over " + limit + " positions — the reference has to belong " +
347
+ "to the same text and position count as what is compared to it");
348
+ status(els.exactStatus, "measuring the exact pass…");
349
+ state.exact = await evaluate("exact", {}, state.positions);
350
+ status(els.exactStatus, "exact pass · mean rank " + num(state.exact.meanRank, 1) +
351
+ " · top-1 " + num(100 * state.exact.acc, 1) + "% (chance " +
352
+ num(100 / state.vocab.tokens.length, 2) + "%)");
353
+ log("exact: mean rank " + num(state.exact.meanRank, 1) + " of " +
354
+ int(state.vocab.tokens.length) + " · top-1 " + num(100 * state.exact.acc, 1) +
355
+ "% ± " + num(100 * state.exact.accSE, 1) + " points", "ok");
356
+ } catch (e) {
357
+ say(els.exactStatus, "refused: the exact pass could not be measured — " + e.message, "bad");
358
+ return null;
359
+ }
360
+ return state.exact;
361
+ }
362
+
363
+ /* Discover exactly the matrices the pass quantises by recording one short pass with a quantiser
364
+ * that returns its input. Planning over a guessed list could plan for tensors the pass never reads,
365
+ * or miss ones it does, and either would make the plan's bit figure a fiction. */
366
+ function inventory() {
367
+ var seen = [];
368
+ FW.run(state.buf, state.header, state.ids.slice(0, 4), {
369
+ quantize: function (values, name) { seen.push({ name: name, values: values }); return { values: values }; },
370
+ quantizeName: "inventory"
371
+ });
372
+ var matrices = [], total = 0, i, k, n, v, sum, sq, mean;
373
+ for (i = 0; i < seen.length; i++) {
374
+ v = seen[i].values;
375
+ n = v.length;
376
+ sum = 0; sq = 0;
377
+ for (k = 0; k < n; k++) { sum += v[k]; sq += v[k] * v[k]; }
378
+ mean = sum / n;
379
+ matrices.push({
380
+ name: seen[i].name, n: n, values: v,
381
+ variance: Math.max(0, sq / n - mean * mean),
382
+ mse: {
383
+ binary: Q.quantise(v, { grid: "binary", blockSize: BLOCK }).error.mse,
384
+ ternary: Q.quantise(v, { grid: "ternary", blockSize: BLOCK }).error.mse,
385
+ hepta: Q.quantise(v, { grid: "hepta", blockSize: BLOCK }).error.mse
386
+ }
387
+ });
388
+ total += n;
389
+ }
390
+ state.matrices = matrices;
391
+ state.totalWeights = total;
392
+ return matrices;
393
+ }
394
+
395
+ /* Everything the load button does, over an ArrayBuffer the caller already has. Kept separate from
396
+ * the fetch so the Node harness can load the fixture directly. */
397
+ async function loadFromBuffer(buffer, label) {
398
+ refreshEls();
399
+ state.buf = buffer;
400
+ state.label = label || "buffer";
401
+ state.exact = null;
402
+ state.plan = null;
403
+ clearTable(els.modelBody);
404
+ clearTable(els.topkBody);
405
+ clearTable(els.ladderBody);
406
+ clearTable(els.zeroBody);
407
+ clearTable(els.planBody);
408
+
409
+ if (!G || !FW || !Q || !W) {
410
+ say(els.loadStatus, "refused: a required module is missing (gguf.js, weights.js, quant.js, forward.js)", "bad");
411
+ return { ok: false, reason: "missing module" };
412
+ }
413
+
414
+ log("parsing " + label + " (" + fmtBytes(buffer.byteLength) + ") — header, tensor index, metadata KVs");
415
+ state.header = G.parse(buffer, { metadataOnly: false });
416
+ state.vocab = G.vocab(state.header);
417
+ state.tk = BPE.fromVocab(state.vocab);
418
+
419
+ var req = FW.requirements(state.header);
420
+ state.requirements = req;
421
+
422
+ addModelRow("file", state.label);
423
+ addModelRow("bytes", fmtBytes(buffer.byteLength));
424
+ addModelRow("architecture", String(state.header.architecture || "—"));
425
+ addModelRow("gguf version", String(state.header.version));
426
+ addModelRow("tensors", int(state.header.tensors.length));
427
+ addModelRow("vocabulary", int(state.vocab.tokens.length) + " symbols");
428
+ addModelRow("layers", int(req.layers) + " · " + int(req.meta && req.meta.nEmbd) + "-dim hidden");
429
+ addModelRow("tokenizer", state.tk.exact ? "byte-level BPE (exact)" : "greedy longest match (no merge table)");
430
+
431
+ if (!req.feasible) {
432
+ say(els.loadStatus, "refused: " + req.reason, "bad");
433
+ term("REFUSED: " + req.reason, "warn");
434
+ return { ok: false, reason: req.reason };
435
+ }
436
+ if (buffer.byteLength > MAX_BYTES) {
437
+ var why = "the file is " + fmtBytes(buffer.byteLength) + ", over this page's " + fmtBytes(MAX_BYTES) +
438
+ " in-tab ceiling — a pure-JS pass over it would hang the tab, so it is refused rather than attempted";
439
+ say(els.loadStatus, "refused: " + why, "bad");
440
+ term("REFUSED: " + why, "warn");
441
+ return { ok: false, reason: why };
442
+ }
443
+ if (req.note) { log(req.note, "warn"); term(req.note, "warn"); }
444
+
445
+ var ids = setText(state.text);
446
+ if (ids.length < 3) {
447
+ say(els.loadStatus, "refused: the passage tokenised to " + ids.length + " token(s)", "bad");
448
+ return { ok: false, reason: "passage too short" };
449
+ }
450
+
451
+ var mats = inventory();
452
+ var weights = 0;
453
+ for (var i = 0; i < mats.length; i++) weights += mats[i].n;
454
+ addModelRow("quantisable matrices", int(mats.length) + " · " + int(weights) + " weights");
455
+ addModelRow("scored positions", int(state.positions) + " of " + int(ids.length - 1));
456
+
457
+ say(els.loadStatus, "loaded " + state.label + " · " + int(mats.length) + " matrices / " +
458
+ int(weights) + " weights quantisable", "ok");
459
+ log("inventory: the pass quantises " + mats.length + " matrices (" + int(weights) +
460
+ " weights); norms and embeddings stay float, as they do in the Node suite");
461
+
462
+ /* The exact baseline is measured at load, because every quality figure afterwards is expressed
463
+ * against it and a missing reference would make the panels silently meaningless. */
464
+ log("measuring the EXACT pass over " + Math.min(state.positions, ids.length - 1) +
465
+ " positions — this is the reference every later figure is compared to");
466
+ status(els.exactStatus, "measuring the exact pass…");
467
+ state.exact = await evaluate("exact", {}, state.positions);
468
+ status(els.exactStatus, "exact pass · mean rank " + num(state.exact.meanRank, 1) +
469
+ " · top-1 " + num(100 * state.exact.acc, 1) + "% (chance " +
470
+ num(100 / state.vocab.tokens.length, 2) + "%)");
471
+ log("exact: mean rank " + num(state.exact.meanRank, 1) + " of " + int(state.vocab.tokens.length) +
472
+ " (chance " + num((state.vocab.tokens.length + 1) / 2, 1) + ") · top-1 " +
473
+ num(100 * state.exact.acc, 1) + "% ± " + num(100 * state.exact.accSE, 1) + " points", "ok");
474
+ term("exact F32 · mean rank " + num(state.exact.meanRank, 1) + " · top-1 " +
475
+ num(100 * state.exact.acc, 1) + "% · " + num(state.exact.msPerToken, 0) + " ms/token");
476
+ term("the top-1 standard error at " + state.exact.total + " positions is ± " +
477
+ num(100 * state.exact.accSE, 1) + " points, so smaller differences are NOT resolvable — " +
478
+ "ranks and rho are used instead", "warn");
479
+ return { ok: true, matrices: mats.length, weights: weights, exact: state.exact };
480
+ }
481
+
482
+ async function loadFromUrl(url, label) {
483
+ refreshEls();
484
+ say(els.loadStatus, "fetching " + label + "…");
485
+ log("fetching " + url, null);
486
+ var res = await fetch(url);
487
+ if (!res.ok) throw new Error("HTTP " + res.status + " for " + url);
488
+ var total = Number(res.headers && res.headers.get ? (res.headers.get("content-length") || 0) : 0);
489
+ var buffer;
490
+ if (res.body && res.body.getReader) {
491
+ var reader = res.body.getReader(), chunks = [], got = 0, step;
492
+ while (true) {
493
+ step = await reader.read();
494
+ if (step.done) break;
495
+ if (!step.value || !step.value.length) continue;
496
+ chunks.push(step.value);
497
+ got += step.value.length;
498
+ if (total) status(els.loadStatus, "fetching " + label + " — " + fmtBytes(got) + " / " + fmtBytes(total));
499
+ if (got % (4 * 1024 * 1024) < step.value.length) await yieldUI();
500
+ }
501
+ var joined = new Uint8Array(got), at = 0;
502
+ for (var i = 0; i < chunks.length; i++) { joined.set(chunks[i], at); at += chunks[i].length; }
503
+ buffer = joined.buffer;
504
+ } else {
505
+ buffer = await res.arrayBuffer();
506
+ }
507
+ return loadFromBuffer(buffer, label);
508
+ }
509
+
510
+ /* ------------------------------------------------------------------ panel: inference */
511
+
512
+ async function runInference() {
513
+ refreshEls();
514
+ if (!state.buf) { say(els.inferStatus, "refused: load a model first", "bad"); return null; }
515
+ var text = els.prompt && typeof els.prompt.value === "string" ? els.prompt.value : state.text;
516
+ if (!text || !text.replace(/\s+/g, "")) {
517
+ say(els.inferStatus, "refused: the prompt is empty — the pass needs tokens", "bad");
518
+ return null;
519
+ }
520
+ var ids = setText(text);
521
+ if (ids.length < 2) { say(els.inferStatus, "refused: the prompt tokenised to " + ids.length + " token(s)", "bad"); return null; }
522
+ clearTable(els.topkBody);
523
+ try {
524
+ log("forward pass: " + (ids.length - 1) + " tokens through " + state.requirements.layers +
525
+ " layers over the file's own weight bytes");
526
+ status(els.inferStatus, "running…");
527
+ var t0 = Date.now();
528
+ var r = FW.run(state.buf, state.header, ids, {});
529
+ var passMs = Date.now() - t0;
530
+ var top = FW.topK(r.logits, 6);
531
+ var rows = 0;
532
+ for (var i = 0; i < top.length; i++) {
533
+ var id = top[i].id;
534
+ addRow(els.topkBody, [
535
+ "#" + (i + 1),
536
+ JSON.stringify(FW.surface(state.vocab.tokens[id])),
537
+ num(top[i].logit, 3),
538
+ num(100 * top[i].p, 2) + "%"
539
+ ]);
540
+ rows++;
541
+ }
542
+ if (!rows) throw new Error("the pass returned no candidates");
543
+ /* Next-token continuation on the page's own terminal, so the visitor sees the model speak. */
544
+ var line = top.slice(0, 3).map(function (c) { return FW.surface(state.vocab.tokens[c.id]); }).join(" ");
545
+ term("next after " + JSON.stringify(text.slice(-24)) + " -> " + line);
546
+ status(els.inferStatus, "done · " + ids.length + " tokens in " + num(passMs, 0) + " ms");
547
+ log("top-6 next tokens written · " + ids.length + " tokens in " + num(passMs, 0) +
548
+ " ms (" + num(passMs / ids.length, 1) + " ms/token); exact weights, no quantisation in this panel", "ok");
549
+ return { ids: ids.length, top: top, ms: passMs };
550
+ } catch (e) {
551
+ say(els.inferStatus, "refused: " + e.message, "bad");
552
+ term("forward pass failed: " + e.message, "bad");
553
+ return null;
554
+ }
555
+ }
556
+
557
+ /* ------------------------------------------------------------------ panel: the ladder */
558
+
559
+ async function runLadder() {
560
+ refreshEls();
561
+ if (!state.buf) { say(els.ladderStatus, "refused: load a model first", "bad"); return null; }
562
+ if (!(await ensureExact())) { say(els.ladderStatus, "refused: no exact baseline", "bad"); return null; }
563
+ clearTable(els.ladderBody);
564
+ var results = { exact: state.exact }, i;
565
+ log("ladder: " + LADDER.length + " level sets × " + state.exact.total +
566
+ " positions through the real pass. Each row is scored against the exact pass at the same position.");
567
+ for (i = 0; i < LADDER.length; i++) {
568
+ var g = LADDER[i];
569
+ var info = Q.gridInfo(g);
570
+ status(els.ladderStatus, "running " + g + " (" + info.count + " channels, " + info.indexBits +
571
+ " index bits) …");
572
+ try {
573
+ var cfg = await evaluate(g, { quantize: gridQuantiser(g) }, state.positions);
574
+ cfg.spearman = vsExact(cfg);
575
+ cfg.rmse = meanRMSE(g);
576
+ results[g] = cfg;
577
+ addRow(els.ladderBody, [
578
+ g + " {" + info.levels.join(",") + "}",
579
+ fmtBits(cfg.bits),
580
+ num(cfg.rmse, 5),
581
+ num(cfg.meanRank, 1),
582
+ num(100 * cfg.acc, 1) + "%",
583
+ cfg.spearman === null ? "—" : num(cfg.spearman, 4)
584
+ ]);
585
+ log(" " + g + ": " + fmtBits(cfg.bits) + " · rmse " + num(cfg.rmse, 5) + " · mean rank " +
586
+ num(cfg.meanRank, 1) + " · top-1 " + num(100 * cfg.acc, 1) + "% · rho vs exact " +
587
+ num(cfg.spearman, 4), "ok");
588
+ } catch (e) {
589
+ addRow(els.ladderBody, [g, "refused", "—", "—", "—", "—"], "bad");
590
+ log(" " + g + " refused: " + e.message, "bad");
591
+ }
592
+ }
593
+
594
+ /* The comparisons that decide the document's claims, stated as paired measurements. */
595
+ var tern = results.ternary, quad = results.quad, hept = results.hepta;
596
+ if (tern && quad) {
597
+ var pq = pairedRank(quad, tern);
598
+ term("equal 2 index bits: quad (no zero) vs ternary -> mean rank " +
599
+ (pq.mean > 0 ? "+" : "") + num(pq.mean, 2) + " (t " + num(pq.t, 2) + "), rho " +
600
+ num(quad.spearman, 4) + " vs " + num(tern.spearman, 4));
601
+ }
602
+ if (tern && hept) {
603
+ var ph = pairedRank(hept, tern);
604
+ term("wider grid: hepta vs ternary -> mean rank " + (ph.mean > 0 ? "+" : "") + num(ph.mean, 2) +
605
+ " (t " + num(ph.t, 2) + ")");
606
+ }
607
+ var exactRank = num(state.exact.meanRank, 1);
608
+ term("ladder done · exact mean rank " + exactRank + " · best quantised " +
609
+ num(Math.min.apply(null, LADDER.map(function (g) { return (results[g] || {}).meanRank || Infinity; })), 1));
610
+ status(els.ladderStatus, "done — " + LADDER.length + " level sets measured");
611
+ return results;
612
+ }
613
+
614
+ /* ------------------------------------------------------------------ panel: the 0/0/0 test */
615
+
616
+ async function runZeroTest() {
617
+ refreshEls();
618
+ if (!state.buf) { say(els.zeroStatus, "refused: load a model first", "bad"); return null; }
619
+ if (!(await ensureExact())) { say(els.zeroStatus, "refused: no exact baseline", "bad"); return null; }
620
+ clearTable(els.zeroBody);
621
+ log("zero test: quantising with {0,±1} and with the document's {0,0,0,±1} and comparing every " +
622
+ "logit for EXACT equality — the claim under test is identity, not closeness");
623
+ status(els.zeroStatus, "running both…");
624
+ try {
625
+ var one = await evaluate("ternary", { quantize: gridQuantiser("ternary") }, state.positions);
626
+ one.spearman = vsExact(one);
627
+ var three = await evaluate("ternaryDup", { quantize: gridQuantiser("ternaryDup") }, state.positions);
628
+ three.spearman = vsExact(three);
629
+
630
+ var identical = true, compared = 0, firstDiff = null;
631
+ three.logitsAt.forEach(function (L, t) {
632
+ var T = one.logitsAt.get(t);
633
+ if (!T) return;
634
+ for (var i = 0; i < L.length; i++) {
635
+ if (L[i] !== T[i]) {
636
+ identical = false;
637
+ if (!firstDiff) firstDiff = { t: t, i: i, a: T[i], b: L[i] };
638
+ }
639
+ }
640
+ compared++;
641
+ });
642
+
643
+ addRow(els.zeroBody, ["{0,±1} 3 channels", fmtBits(one.bits), identical ? "true" : "false",
644
+ num(one.meanRank, 1), num(100 * one.acc, 1) + "%"]);
645
+ addRow(els.zeroBody, ["{0,0,0,±1} 5 channels", fmtBits(three.bits), identical ? "true" : "false",
646
+ num(three.meanRank, 1), num(100 * three.acc, 1) + "%"], identical ? "" : "bad");
647
+
648
+ var info1 = Q.gridInfo("ternary"), info3 = Q.gridInfo("ternaryDup");
649
+ term("logits compared bit-for-bit at " + compared + " positions, " +
650
+ int(state.vocab.tokens.length) + " logits each: identical = " + identical);
651
+ term("channels " + info1.count + " -> " + info3.count + " (decodable values " + info1.distinctLevels +
652
+ " -> " + info3.distinctLevels + ", so " + info3.wastedChannels + " channels are unreachable) · " +
653
+ "index bits " + info1.indexBits + " -> " + info3.indexBits);
654
+ if (identical) {
655
+ log("result: the widened zero changes NOTHING in the output while its accounting charges more " +
656
+ "bits per weight — 3 zero channels decode to the single value 0", "ok");
657
+ term("RESULT: the multi-channel zero is not an information channel — it reconstructs and predicts " +
658
+ "IDENTICALLY, and costs " + num((three.bits || 0) - (one.bits || 0), 3) + " more bits/weight to do so");
659
+ } else {
660
+ log("result: the two configurations DID differ — first difference at position " + firstDiff.t +
661
+ ", logit " + firstDiff.i + ": " + firstDiff.a + " vs " + firstDiff.b, "warn");
662
+ term("RESULT: the logits differ, so report the difference rather than the claim", "warn");
663
+ }
664
+ status(els.zeroStatus, "done — logits identical: " + identical);
665
+ return { identical: identical, one: one, three: three };
666
+ } catch (e) {
667
+ say(els.zeroStatus, "refused: " + e.message, "bad");
668
+ return null;
669
+ }
670
+ }
671
+
672
+ /* ------------------------------------------------------------------ panel: the elastic plan */
673
+
674
+ /* The document's mechanism, made decidable: every 32-weight block of every quantisable matrix is
675
+ * ordered by a measured key, and while the mass promoted to the 3-bit grid and the mass demoted to
676
+ * the 1-bit grid stay balanced, the most important blocks are unclamped and the least important are
677
+ * clamped. The balance is what makes the average exactly 2.0 index bits — the same budget uniform
678
+ * ternary spends — so the comparison is at equal bits and not merely at equal grid count. */
679
+ function elasticPlan(keyName) {
680
+ var units = [], i, off, m, key;
681
+ for (i = 0; i < state.matrices.length; i++) {
682
+ m = state.matrices[i];
683
+ key = keyName === "variance" ? m.variance : (m.mse.binary - m.mse.hepta);
684
+ for (off = 0; off < m.n; off += BLOCK) units.push({ mi: i, off: off, key: key });
685
+ }
686
+ if (!units.length) return null;
687
+ units.sort(function (a, b) { return b.key - a.key; });
688
+
689
+ var gridByBlock = {};
690
+ for (i = 0; i < state.matrices.length; i++) {
691
+ m = state.matrices[i];
692
+ gridByBlock[m.name] = new Array(Math.ceil(m.n / BLOCK));
693
+ for (var b = 0; b < gridByBlock[m.name].length; b++) gridByBlock[m.name][b] = "ternary";
694
+ }
695
+ var massUp = 0, massDown = 0, hi = 0, lo = units.length - 1, u;
696
+ while (hi <= lo) {
697
+ if (massUp <= massDown) {
698
+ u = units[hi];
699
+ gridByBlock[state.matrices[u.mi].name][Math.floor(u.off / BLOCK)] = "hepta";
700
+ massUp += BLOCK; hi++;
701
+ } else {
702
+ u = units[lo];
703
+ gridByBlock[state.matrices[u.mi].name][Math.floor(u.off / BLOCK)] = "binary";
704
+ massDown += BLOCK; lo--;
705
+ }
706
+ }
707
+ return {
708
+ key: keyName, gridByBlock: gridByBlock,
709
+ bits: 2 + (massUp - massDown) / state.totalWeights,
710
+ promoted: massUp / BLOCK, demoted: massDown / BLOCK,
711
+ blocks: units.length
712
+ };
713
+ }
714
+
715
+ function drawPlan(plan) {
716
+ var c = els.gridCanvas;
717
+ if (!c || !c.getContext) return false;
718
+ var names = Object.keys(plan.gridByBlock), rows = names.length, rowH = 9, gap = 3;
719
+ var w = 1024, h = rows * (rowH + gap) + 2;
720
+ c.width = w; c.height = h;
721
+ var ctx = c.getContext("2d");
722
+ ctx.fillStyle = "#06040f"; ctx.fillRect(0, 0, w, h);
723
+ for (var r = 0; r < rows; r++) {
724
+ var g = plan.gridByBlock[names[r]], nb = g.length, bw = w / nb;
725
+ for (var b = 0; b < nb; b++) {
726
+ /* These must match the legend in index.html, or the map mislabels itself. */
727
+ ctx.fillStyle = g[b] === "hepta" ? "#ff2d78" : (g[b] === "binary" ? "#3b82f6" : "#6b6480");
728
+ ctx.fillRect(b * bw, r * (rowH + gap), Math.max(1, bw), rowH);
729
+ }
730
+ }
731
+ return true;
732
+ }
733
+
734
+ async function runPlan() {
735
+ refreshEls();
736
+ if (!state.buf) { say(els.planStatus, "refused: load a model first", "bad"); return null; }
737
+ if (!(await ensureExact())) { say(els.planStatus, "refused: no exact baseline", "bad"); return null; }
738
+ var keyName = els.planSelect && els.planSelect.value === "variance" ? "variance" : "benefit";
739
+ clearTable(els.planBody);
740
+ try {
741
+ var plan = elasticPlan(keyName);
742
+ if (!plan) { say(els.planStatus, "refused: no quantisable matrices to plan over", "bad"); return null; }
743
+ state.plan = plan;
744
+ log("plan '" + keyName + "': " + plan.blocks + " blocks of " + BLOCK + " weights ordered by the " +
745
+ keyName + " key; " + plan.promoted + " block(s) unclamped to hepta and " + plan.demoted +
746
+ " clamped to binary, which balances to " + num(plan.bits, 4) + " index bits/weight");
747
+
748
+ /* The baseline at the SAME budget: uniform ternary spends 2 index bits on every weight. */
749
+ status(els.planStatus, "running uniform ternary at 2.0 bits…");
750
+ /* No cross-panel cache. A baseline is only a baseline for the token sequence and position count
751
+ * it was measured on, and `state.exact` is already nulled whenever the passage changes — a cache
752
+ * keyed on anything less than the token sequence would compare two different passages. */
753
+ var tern = await evaluate("ternary", { quantize: gridQuantiser("ternary") }, state.positions);
754
+ tern.spearman = vsExact(tern);
755
+
756
+ status(els.planStatus, "running the elastic plan…");
757
+ var missing = [];
758
+ var elastic = await evaluate("elastic:" + keyName,
759
+ { quantize: planQuantiser(plan, missing), quantizeName: "elastic:" + keyName }, state.positions);
760
+ elastic.spearman = vsExact(elastic);
761
+ if (missing.length) log("note: " + missing.length + " matrix(es) were not in the plan and stayed " +
762
+ "exact: " + missing.slice(0, 4).join(", "), "warn");
763
+
764
+ var pd = pairedRank(elastic, tern);
765
+ addRow(els.planBody, ["uniform ternary", fmtBits(tern.bits), num(tern.meanRank, 1),
766
+ num(tern.spearman, 4), "baseline"]);
767
+ addRow(els.planBody, ["elastic:" + keyName, fmtBits(elastic.bits), num(elastic.meanRank, 1),
768
+ num(elastic.spearman, 4),
769
+ (pd.mean > 0 ? "+" : "") + num(pd.mean, 2) + " (t " + num(pd.t, 2) + ")"],
770
+ pd.mean > 0 ? "bad" : "ok");
771
+
772
+ var drew = drawPlan(plan);
773
+ if (drew) {
774
+ term("grid map: one row per quantisable matrix, one cell per " + BLOCK + "-weight block — " +
775
+ "pink = hepta (3 bits), grey = ternary (2 bits), blue = binary (1 bit)");
776
+ }
777
+ term("equal budget (" + num(tern.bits, 3) + " vs " + num(elastic.bits, 3) + " b/w): uniform ternary mean rank " +
778
+ num(tern.meanRank, 1) + " rho " + num(tern.spearman, 4) + " · elastic mean rank " +
779
+ num(elastic.meanRank, 1) + " rho " + num(elastic.spearman, 4));
780
+ if (resolvable) {
781
+ term("resolvable at this position count: |t| = " + num(Math.abs(pd.t), 2) + " >= 2");
782
+ }
783
+ /* The verdict must respect the measurement's resolution. At the slider's default this comparison
784
+ * is under-powered: the sign of the mean alone is not a finding, and printing one would be the
785
+ * exact overclaiming this page exists to avoid. Below |t| = 2 the panel says so and points at the
786
+ * suite that ran the positions this page cannot afford. */
787
+ var resolvable = Math.abs(pd.t) >= 2;
788
+ var diff = (pd.mean > 0 ? "+" : "") + num(pd.mean, 1);
789
+ if (!resolvable) {
790
+ term("UNDECIDED at " + tern.total + " positions: the " + keyName + " plan's mean rank is " + diff +
791
+ " versus uniform ternary, but t = " + num(pd.t, 2) + " — this run cannot resolve it. Raise the " +
792
+ "slider and re-run.");
793
+ term("The Node suite runs the same experiment over 89 positions, where it resolves: the benefit key " +
794
+ "is +48.52 rank positions (t 3.21) and the variance key +46.35 (t 3.22), i.e. both WORSE than " +
795
+ "uniform ternary at equal bits. Source: reports/dmcra-verdicts.md.", "warn");
796
+ log("result: elastic:" + keyName + " vs uniform ternary is UNDECIDED at " + tern.total +
797
+ " positions (rank " + diff + ", t " + num(pd.t, 2) + ") — reporting no verdict rather than the " +
798
+ "sign of an unresolved difference", "warn");
799
+ } else if (pd.mean > 0) {
800
+ term("RESULT: unclamping by the " + keyName + " key is WORSE than spending the same bits uniformly " +
801
+ "on a ternary grid — by " + num(pd.mean, 1) + " rank positions (t " + num(pd.t, 2) + ")", "bad");
802
+ log("result: elastic:" + keyName + " loses to uniform ternary at equal bits (rank +" +
803
+ num(pd.mean, 1) + ", t " + num(pd.t, 2) + ")", "warn");
804
+ } else {
805
+ term("RESULT: unclamping by the " + keyName + " key BEATS uniform ternary at equal bits — by " +
806
+ num(-pd.mean, 1) + " rank positions (t " + num(pd.t, 2) + ")", "ok");
807
+ log("result: elastic:" + keyName + " beats uniform ternary at equal bits", "ok");
808
+ }
809
+ if (elastic.bits !== null && Math.abs(elastic.bits - (plan.bits + 1)) > 1e-6) {
810
+ log("note: the pass measured " + num(elastic.bits, 3) + " b/w for the plan, which is not the " +
811
+ "planned " + num(plan.bits + 1, 3) + " including its scale bits — reported as measured", "warn");
812
+ }
813
+ status(els.planStatus, "done — plan " + num(plan.bits, 4) + " index bits/weight over " +
814
+ plan.blocks + " blocks");
815
+ return { plan: plan, elastic: elastic, ternary: tern, rankDiff: pd };
816
+ } catch (e) {
817
+ say(els.planStatus, "refused: " + e.message, "bad");
818
+ log("plan failed: " + e.message, "bad");
819
+ return null;
820
+ }
821
+ }
822
+
823
+ /* ------------------------------------------------------------------ wiring */
824
+
825
+ function readPositions() {
826
+ refreshEls();
827
+ var v = els.positions && els.positions.value !== undefined ? parseInt(els.positions.value, 10) : NaN;
828
+ if (isFinite(v)) state.positions = Math.max(4, Math.min(32, v));
829
+ status(els.positionsLabel, state.positions + " positions");
830
+ return state.positions;
831
+ }
832
+
833
+ function busy(on, btn) {
834
+ state.busy = !!on;
835
+ if (btn) btn.disabled = !!on;
836
+ }
837
+
838
+ function on(id, event, fn) {
839
+ var node = el(id);
840
+ if (node && node.addEventListener) node.addEventListener(event, fn);
841
+ }
842
+
843
+ function init() {
844
+ refreshEls();
845
+ on("load-btn", "click", async function () {
846
+ busy(true, els.loadBtn);
847
+ try {
848
+ var sel = els.modelSelect;
849
+ var url = sel && sel.value;
850
+ var label = url ? url.split("/").pop() : "model";
851
+ await loadFromUrl(url, label);
852
+ } catch (e) {
853
+ say(els.loadStatus, "refused: " + e.message, "bad");
854
+ log("load failed: " + e.message, "bad");
855
+ } finally { busy(false, els.loadBtn); }
856
+ });
857
+ on("run-btn", "click", async function () {
858
+ busy(true, els.runBtn);
859
+ try { await runInference(); } finally { busy(false, els.runBtn); }
860
+ });
861
+ on("ladder-btn", "click", async function () {
862
+ readPositions();
863
+ busy(true, els.ladderBtn);
864
+ try { await runLadder(); } finally { busy(false, els.ladderBtn); }
865
+ });
866
+ on("zero-btn", "click", async function () {
867
+ readPositions();
868
+ busy(true, els.zeroBtn);
869
+ try { await runZeroTest(); } finally { busy(false, els.zeroBtn); }
870
+ });
871
+ on("plan-btn", "click", async function () {
872
+ readPositions();
873
+ busy(true, els.planBtn);
874
+ try { await runPlan(); } finally { busy(false, els.planBtn); }
875
+ });
876
+ on("positions", "input", readPositions);
877
+ on("clear-btn", "click", function () {
878
+ clearTable(els.ladderBody); clearTable(els.zeroBody); clearTable(els.planBody);
879
+ clearTable(els.topkBody);
880
+ if (els.log) els.log.innerHTML = "";
881
+ if (els.terminal) {
882
+ els.terminal.innerHTML = "";
883
+ if (els.cursor) els.terminal.appendChild(els.cursor);
884
+ }
885
+ log("cleared", null);
886
+ });
887
+
888
+ readPositions();
889
+ if (els.prompt && (!els.prompt.value || !els.prompt.value.length)) els.prompt.value = DEFAULT_TEXT;
890
+ term("DMCRA Lab — ready. Load a GGUF; the exact pass is measured first, because every figure " +
891
+ "afterwards is expressed against it.");
892
+ log("ready: " + LADDER.length + " level sets available, " + int(Object.keys(Q.GRIDS).length) +
893
+ " grids in the quantiser", "ok");
894
+ return true;
895
+ }
896
+
897
+ var api = {
898
+ els: els,
899
+ refreshEls: refreshEls,
900
+ log: log,
901
+ status: status,
902
+ state: state,
903
+ init: init,
904
+ loadFromBuffer: loadFromBuffer,
905
+ loadFromUrl: loadFromUrl,
906
+ runInference: runInference,
907
+ runLadder: runLadder,
908
+ runZeroTest: runZeroTest,
909
+ runPlan: runPlan,
910
+ elasticPlan: elasticPlan,
911
+ gridQuantiser: gridQuantiser,
912
+ planQuantiser: planQuantiser,
913
+ evaluate: evaluate,
914
+ ensureExact: ensureExact,
915
+ setText: setText,
916
+ meanRMSE: meanRMSE,
917
+ pairedRank: pairedRank,
918
+ stats: { avgRanks: avgRanks, spearman: spearman, pearson: pearson, rankOfTrue: rankOfTrue, median: median },
919
+ config: { BLOCK: BLOCK, LADDER: LADDER, MAX_BYTES: MAX_BYTES, DEFAULT_TEXT: DEFAULT_TEXT }
920
+ };
921
+ return api;
922
+ });