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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* quant.js — the DMCRA level-set quantiser: a codebook chosen per block, from an elastic family.
|
| 2 |
+
*
|
| 3 |
+
* WHAT THIS IS, AND WHAT IT IS NOT
|
| 4 |
+
* The DMCRA document proposes replacing fixed ternary `{-1,0,+1}` with an elastic family of grids
|
| 5 |
+
* that "unclamps" as pressure demands. Stripped of the hardware vocabulary that a static page
|
| 6 |
+
* cannot implement, that is one concrete, decidable mechanism: a weight matrix is cut into blocks,
|
| 7 |
+
* each block is assigned a LEVEL SET from a nested family, and the assignment is chosen by a
|
| 8 |
+
* measured criterion under a bit budget. This file is that mechanism and nothing else. There is no
|
| 9 |
+
* routing fabric here, and no zero-bus: `0/0/0` is three zeros and this module reports, by exact
|
| 10 |
+
* arithmetic, that it reconstructs identically to `{0}`.
|
| 11 |
+
*
|
| 12 |
+
* Two scale rules, on purpose:
|
| 13 |
+
* rule "meanabs" — scale = mean(|w|) per block, the convention this repo's weights.js already
|
| 14 |
+
* uses for ternary. Reproduced here so a test can assert that this quantiser's
|
| 15 |
+
* ternary is IDENTICAL to the already-verified `toTernary`/`fromTernary`. That
|
| 16 |
+
* assertion is what stops this file from drifting away from the project.
|
| 17 |
+
* rule "lsq" — least-squares optimal step per block (the classic LSQ iteration, Esser et al.
|
| 18 |
+
* 2020): s <- sum(w*q)/sum(q*q) with q = nearest level of w/s. Default for the
|
| 19 |
+
* level-set ladder, because it gives EVERY grid its own optimal scale, so the
|
| 20 |
+
* ladder compares codebooks rather than comparing one grid's scale artefact
|
| 21 |
+
* against another's.
|
| 22 |
+
*
|
| 23 |
+
* Bit accounting is explicit and separated, because the interesting honest wrinkle is that they
|
| 24 |
+
* disagree: `indexBits` is what an encoder must carry per weight, `effBits` adds the per-block scale
|
| 25 |
+
* overhead (which is what makes small blocks expensive), and `entropyBits` is the measured Shannon
|
| 26 |
+
* entropy of the level histogram. A grid that claims five channels but decodes to three distinct
|
| 27 |
+
* values is reported as exactly that: `distinctLevels` < `levels.length`, `wastedChannels` > 0.
|
| 28 |
+
*/
|
| 29 |
+
(function (root, factory) {
|
| 30 |
+
var Q = factory();
|
| 31 |
+
if (typeof module !== "undefined" && module.exports) module.exports = Q;
|
| 32 |
+
root.DMCRAQUANT = Q;
|
| 33 |
+
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
|
| 34 |
+
"use strict";
|
| 35 |
+
|
| 36 |
+
/* ---------------------------------------------------------------- the elastic family
|
| 37 |
+
* The document's family is nested: {+-1} -> {0,+-1} -> {0,+-1,+-2} -> ... . Two extra grids are
|
| 38 |
+
* included because they are what an equal-bits contest actually needs: `quad` spends the SAME two
|
| 39 |
+
* index bits as ternary but on two magnitudes instead of a zero, and `oct` spends the same three
|
| 40 |
+
* bits as penta on four magnitudes instead of a zero. Without those two, "unclamping ternary"
|
| 41 |
+
* would only ever be compared against a cheaper code, which would decide nothing.
|
| 42 |
+
* `ternaryDup` is not a proposal; it is the document's `0/0/0` written down so it can be measured.
|
| 43 |
+
*/
|
| 44 |
+
var GRIDS = {
|
| 45 |
+
binary: { levels: [0, 1], note: "sign only, 1 index bit" },
|
| 46 |
+
binaryPN: { levels: [-1, 1], note: "bipolar sign only, 1 index bit" },
|
| 47 |
+
ternary: { levels: [-1, 0, 1], note: "BitNet b1.58, 2 index bits" },
|
| 48 |
+
quad: { levels: [-2, -1, 1, 2], note: "2 magnitudes, no zero, 2 index bits" },
|
| 49 |
+
ternaryDup:{ levels: [-1, 0, 0, 0, 1], note: "the document's {0/0/0}: 5 channels, 3 distinct values" },
|
| 50 |
+
penta: { levels: [-2, -1, 0, 1, 2], note: "3 index bits" },
|
| 51 |
+
hepta: { levels: [-3, -2, -1, 0, 1, 2, 3], note: "3 index bits, same cost as penta" },
|
| 52 |
+
oct: { levels: [-4, -3, -2, -1, 1, 2, 3, 4], note: "4 magnitudes, no zero, 3 index bits" },
|
| 53 |
+
nona: { levels: [-4, -3, -2, -1, 0, 1, 2, 3, 4], note: "4 index bits" }
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
var SCALE_BYTES = 4;
|
| 57 |
+
|
| 58 |
+
function gridOf(grid) {
|
| 59 |
+
if (typeof grid === "string") {
|
| 60 |
+
if (!GRIDS[grid]) throw new Error("unknown grid: " + grid);
|
| 61 |
+
return GRIDS[grid].levels.slice();
|
| 62 |
+
}
|
| 63 |
+
if (Object.prototype.toString.call(grid) === "[object Array]") {
|
| 64 |
+
if (!grid.length) throw new Error("empty level set");
|
| 65 |
+
return grid.slice();
|
| 66 |
+
}
|
| 67 |
+
throw new Error("grid must be a known name or an array of levels");
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
function indexBitsFor(k) { return Math.max(1, Math.ceil(Math.log2(k))); }
|
| 71 |
+
|
| 72 |
+
/* Distinct DECODED values. This is what makes `ternaryDup` measurable rather than rhetorical:
|
| 73 |
+
* three zero channels decode to one value, so the encoding is wider than the codebook. */
|
| 74 |
+
function distinctValues(levels) {
|
| 75 |
+
var seen = Object.create(null), n = 0, i, v;
|
| 76 |
+
for (i = 0; i < levels.length; i++) { v = levels[i]; if (seen[v] !== 1) { seen[v] = 1; n++; } }
|
| 77 |
+
return n;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
function gridInfo(grid) {
|
| 81 |
+
var levels = gridOf(grid);
|
| 82 |
+
var maxLevel = 0, i;
|
| 83 |
+
for (i = 0; i < levels.length; i++) if (Math.abs(levels[i]) > maxLevel) maxLevel = Math.abs(levels[i]);
|
| 84 |
+
var d = distinctValues(levels);
|
| 85 |
+
var idx = indexBitsFor(levels.length);
|
| 86 |
+
var dec = indexBitsFor(d);
|
| 87 |
+
return {
|
| 88 |
+
levels: levels, count: levels.length, maxLevel: maxLevel,
|
| 89 |
+
distinctLevels: d, distinctBits: dec,
|
| 90 |
+
indexBits: idx, decodeBits: dec,
|
| 91 |
+
wastedChannels: levels.length - d,
|
| 92 |
+
/* Channels paid for that the decoder cannot distinguish. Zero for every honest grid. */
|
| 93 |
+
wastedBits: idx - dec
|
| 94 |
+
};
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
/* ---------------------------------------------------------------- nearest level */
|
| 98 |
+
|
| 99 |
+
function isContiguousIntegers(levels) {
|
| 100 |
+
for (var i = 1; i < levels.length; i++) if (levels[i] !== levels[i - 1] + 1) return false;
|
| 101 |
+
return true;
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
/* Nearest level to x, given that the levels were built by scaling integers. Ties resolve to the
|
| 105 |
+
* first (lowest) candidate, which is why three zero channels can never disagree: every one of
|
| 106 |
+
* them is 0, so the reconstructed value is 0 whichever way the tie falls. */
|
| 107 |
+
function nearestIndex(levels, x, contiguous, lo, hi) {
|
| 108 |
+
if (contiguous) {
|
| 109 |
+
var r = Math.round(x);
|
| 110 |
+
if (r < lo) r = lo; else if (r > hi) r = hi;
|
| 111 |
+
return r - lo;
|
| 112 |
+
}
|
| 113 |
+
var best = 0, bestD = Infinity, i, d;
|
| 114 |
+
for (i = 0; i < levels.length; i++) {
|
| 115 |
+
d = Math.abs(x - levels[i]);
|
| 116 |
+
if (d < bestD) { bestD = d; best = i; }
|
| 117 |
+
}
|
| 118 |
+
return best;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/* ---------------------------------------------------------------- block statistics */
|
| 122 |
+
|
| 123 |
+
/* Per-block moments. `variance` is the document's stated pressure; it is computed here so the
|
| 124 |
+
* allocation experiment can test whether it is the RIGHT pressure, and `mse` per grid is kept so
|
| 125 |
+
* the benefit-driven allocator can allocate by measured error reduction instead. */
|
| 126 |
+
function blockStats(values, blockSize, gridNames, rule) {
|
| 127 |
+
var n = values.length;
|
| 128 |
+
var bs = blockSize > 0 ? blockSize : n;
|
| 129 |
+
var out = [], off;
|
| 130 |
+
for (off = 0; off < n; off += bs) {
|
| 131 |
+
var len = Math.min(bs, n - off);
|
| 132 |
+
var sum = 0, absSum = 0, sq = 0, i, v;
|
| 133 |
+
for (i = 0; i < len; i++) { v = values[off + i]; sum += v; absSum += Math.abs(v); sq += v * v; }
|
| 134 |
+
var mean = sum / len;
|
| 135 |
+
var variance = Math.max(0, sq / len - mean * mean);
|
| 136 |
+
var rec = { offset: off, len: len, mean: mean, meanAbs: absSum / len,
|
| 137 |
+
variance: variance, sd: Math.sqrt(variance), rms: Math.sqrt(sq / len), mse: {} };
|
| 138 |
+
if (gridNames) {
|
| 139 |
+
for (i = 0; i < gridNames.length; i++) {
|
| 140 |
+
var q = quantiseBlock(values, off, len, gridNames[i], rule);
|
| 141 |
+
rec.mse[gridNames[i]] = q.mse;
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
out.push(rec);
|
| 145 |
+
}
|
| 146 |
+
return out;
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
/* ---------------------------------------------------------------- the scale step */
|
| 150 |
+
|
| 151 |
+
function meanAbsOf(values, off, len) {
|
| 152 |
+
var s = 0, i;
|
| 153 |
+
for (i = 0; i < len; i++) s += Math.abs(values[off + i]);
|
| 154 |
+
return s / len;
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
/* LSQ step: iterate s <- sum(w*q)/sum(q*q) until it stops moving. This is the same update used in
|
| 158 |
+
* learned step-size quantization, run here as a few fixed-point iterations per block. */
|
| 159 |
+
function lsqScale(values, off, len, levels, contiguous, lo, hi, seed) {
|
| 160 |
+
var s = seed > 0 ? seed : meanAbsOf(values, off, len);
|
| 161 |
+
if (!(s > 0)) {
|
| 162 |
+
/* An all-zero block: any scale reconstructs it exactly. */
|
| 163 |
+
return 0;
|
| 164 |
+
}
|
| 165 |
+
var it, i, num, den, q, w, s2;
|
| 166 |
+
for (it = 0; it < 6; it++) {
|
| 167 |
+
num = 0; den = 0;
|
| 168 |
+
for (i = 0; i < len; i++) {
|
| 169 |
+
w = values[off + i];
|
| 170 |
+
q = levels[nearestIndex(levels, w / s, contiguous, lo, hi)];
|
| 171 |
+
num += w * q; den += q * q;
|
| 172 |
+
}
|
| 173 |
+
if (den <= 0) break;
|
| 174 |
+
s2 = num / den;
|
| 175 |
+
if (!(s2 > 0)) break;
|
| 176 |
+
if (Math.abs(s2 - s) <= 1e-12 * s) { s = s2; break; }
|
| 177 |
+
s = s2;
|
| 178 |
+
}
|
| 179 |
+
return s;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
/* ---------------------------------------------------------------- one block */
|
| 183 |
+
|
| 184 |
+
/* Quantise one block under one grid. Returns the reconstruction, the scale, and both error and
|
| 185 |
+
* bit accounts. `rule` is "lsq" (default) or "meanabs" (the weights.js ternary convention). */
|
| 186 |
+
function quantiseBlock(values, off, len, grid, rule) {
|
| 187 |
+
var info = gridInfo(grid);
|
| 188 |
+
var levels = info.levels;
|
| 189 |
+
var contiguous = isContiguousIntegers(levels);
|
| 190 |
+
var lo = contiguous ? levels[0] : 0, hi = contiguous ? levels[levels.length - 1] : 0;
|
| 191 |
+
var s;
|
| 192 |
+
if (rule === "meanabs") s = meanAbsOf(values, off, len);
|
| 193 |
+
else s = lsqScale(values, off, len, levels, contiguous, lo, hi, meanAbsOf(values, off, len));
|
| 194 |
+
var rec = new Float32Array(len);
|
| 195 |
+
var counts = new Array(levels.length);
|
| 196 |
+
for (var c = 0; c < counts.length; c++) counts[c] = 0;
|
| 197 |
+
var sse = 0, sae = 0, maxAbs = 0, i, w, qi, r, d;
|
| 198 |
+
for (i = 0; i < len; i++) {
|
| 199 |
+
w = values[off + i];
|
| 200 |
+
qi = s > 0 ? nearestIndex(levels, w / s, contiguous, lo, hi) : 0;
|
| 201 |
+
counts[qi]++;
|
| 202 |
+
r = s > 0 ? levels[qi] * s : 0;
|
| 203 |
+
rec[i] = r;
|
| 204 |
+
d = w - r; sse += d * d; sae += Math.abs(d);
|
| 205 |
+
if (Math.abs(d) > maxAbs) maxAbs = Math.abs(d);
|
| 206 |
+
}
|
| 207 |
+
return {
|
| 208 |
+
grid: typeof grid === "string" ? grid : "custom", levels: levels, scale: s,
|
| 209 |
+
values: rec, counts: counts,
|
| 210 |
+
mse: len ? sse / len : 0, mae: len ? sae / len : 0, maxAbs: maxAbs,
|
| 211 |
+
bits: blockBits(len, s, info, counts)
|
| 212 |
+
};
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
/* Bit account for one block. `indexBits` travels per weight; the scale is one 4-byte float per
|
| 216 |
+
* block, so its share is 32/len bits per weight — the term that punishes small blocks. */
|
| 217 |
+
function blockBits(len, scale, info, counts) {
|
| 218 |
+
var indexBits = info.indexBits;
|
| 219 |
+
var scaleBits = len ? (SCALE_BYTES * 8) / len : 0;
|
| 220 |
+
var entropy = 0, total = len || 1, j, p;
|
| 221 |
+
if (counts) {
|
| 222 |
+
for (j = 0; j < counts.length; j++) {
|
| 223 |
+
if (!counts[j]) continue;
|
| 224 |
+
p = counts[j] / total;
|
| 225 |
+
entropy -= p * Math.log2(p);
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
return {
|
| 229 |
+
indexBits: indexBits, scaleBits: scaleBits, effBits: indexBits + scaleBits,
|
| 230 |
+
entropyBits: entropy + (scale ? scaleBits : 0),
|
| 231 |
+
decodeBits: info.decodeBits, wastedBits: info.wastedBits,
|
| 232 |
+
wastedChannels: info.wastedChannels, distinctLevels: info.distinctLevels,
|
| 233 |
+
channels: info.count, scaleZero: !(scale > 0)
|
| 234 |
+
};
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
/* ---------------------------------------------------------------- whole tensor */
|
| 238 |
+
|
| 239 |
+
/* Quantise a whole array under one grid. Returns the reconstruction plus an aggregate bit account
|
| 240 |
+
* that is the length-weighted mean of the per-block accounts, so a caller can compare two grids
|
| 241 |
+
* at equal bits rather than at equal nominal precision. */
|
| 242 |
+
function quantise(values, opts) {
|
| 243 |
+
opts = opts || {};
|
| 244 |
+
var grid = opts.grid === undefined ? "ternary" : opts.grid;
|
| 245 |
+
var rule = opts.rule === "meanabs" ? "meanabs" : "lsq";
|
| 246 |
+
var bs = opts.blockSize | 0;
|
| 247 |
+
var n = values.length;
|
| 248 |
+
var size = bs > 0 ? bs : n;
|
| 249 |
+
var out = new Float32Array(n);
|
| 250 |
+
var blocks = [], off, acc = null;
|
| 251 |
+
for (off = 0; off < n; off += size) {
|
| 252 |
+
var len = Math.min(size, n - off);
|
| 253 |
+
var q = quantiseBlock(values, off, len, grid, rule);
|
| 254 |
+
out.set(q.values, off);
|
| 255 |
+
blocks.push({ offset: off, len: len, scale: q.scale, mse: q.mse, bits: q.bits,
|
| 256 |
+
counts: q.counts, levels: q.levels });
|
| 257 |
+
acc = acc ? acc : {
|
| 258 |
+
indexBits: 0, scaleBits: 0, effBits: 0, entropyBits: 0, decodeBits: 0,
|
| 259 |
+
wastedBits: 0, wastedChannels: q.bits.wastedChannels, distinctLevels: q.bits.distinctLevels,
|
| 260 |
+
channels: q.bits.channels, grid: q.grid, name: typeof grid === "string" ? grid : "custom"
|
| 261 |
+
};
|
| 262 |
+
acc.indexBits += q.bits.indexBits * len / n;
|
| 263 |
+
acc.scaleBits += q.bits.scaleBits * len / n;
|
| 264 |
+
acc.effBits += q.bits.effBits * len / n;
|
| 265 |
+
acc.entropyBits += q.bits.entropyBits * len / n;
|
| 266 |
+
acc.decodeBits += q.bits.decodeBits * len / n;
|
| 267 |
+
acc.wastedBits += q.bits.wastedBits * len / n;
|
| 268 |
+
}
|
| 269 |
+
if (!acc) {
|
| 270 |
+
acc = { indexBits: 0, scaleBits: 0, effBits: 0, entropyBits: 0, decodeBits: 0,
|
| 271 |
+
wastedBits: 0, wastedChannels: 0, distinctLevels: 0, channels: 0,
|
| 272 |
+
grid: String(grid), name: typeof grid === "string" ? grid : "custom" };
|
| 273 |
+
}
|
| 274 |
+
acc.blockSize = bs; acc.rule = rule; acc.count = n;
|
| 275 |
+
acc.storedBytes = Math.ceil(n * acc.indexBits / 8) + blocks.length * SCALE_BYTES;
|
| 276 |
+
acc.floatBytes = n * 4;
|
| 277 |
+
acc.ratio = acc.storedBytes ? acc.floatBytes / acc.storedBytes : 0;
|
| 278 |
+
var err = measure(values, out);
|
| 279 |
+
acc.mse = err.mse; acc.rmse = err.rmse; acc.mae = err.mae; acc.maxAbs = err.maxAbs;
|
| 280 |
+
return { values: out, blocks: blocks, bits: acc, error: err };
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
/* ---------------------------------------------------------------- error */
|
| 284 |
+
|
| 285 |
+
function measure(orig, rec) {
|
| 286 |
+
var n = Math.min(orig.length, rec.length), i, d, sse = 0, sae = 0, maxAbs = 0, e0 = 0;
|
| 287 |
+
for (i = 0; i < n; i++) {
|
| 288 |
+
d = orig[i] - rec[i];
|
| 289 |
+
sse += d * d; sae += Math.abs(d);
|
| 290 |
+
if (Math.abs(d) > maxAbs) maxAbs = Math.abs(d);
|
| 291 |
+
e0 += orig[i] * orig[i];
|
| 292 |
+
}
|
| 293 |
+
return {
|
| 294 |
+
count: n, mse: n ? sse / n : 0, rmse: n ? Math.sqrt(sse / n) : 0,
|
| 295 |
+
mae: n ? sae / n : 0, maxAbs: maxAbs,
|
| 296 |
+
/* Fraction of the original energy the reconstruction retains; 1 means nothing was lost. */
|
| 297 |
+
energyRetained: e0 > 0 ? 1 - sse / e0 : 1
|
| 298 |
+
};
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
/* Exact equality of two reconstructions, used by the {0/0/0} identity test. Compares bit patterns
|
| 302 |
+
* rather than a tolerance, because the claim under test is identity, not closeness. */
|
| 303 |
+
function identical(a, b) {
|
| 304 |
+
if (a.length !== b.length) return false;
|
| 305 |
+
for (var i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
| 306 |
+
return true;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
/* ---------------------------------------------------------------- elastic allocation */
|
| 310 |
+
|
| 311 |
+
/* The allocator. This is the DMCRA mechanism made decidable: given a bit budget, assign each block
|
| 312 |
+
* a grid so that measured reconstruction error is as low as possible.
|
| 313 |
+
*
|
| 314 |
+
* key "benefit" (default) — greedy by MEASURED error reduction per extra bit, using each
|
| 315 |
+
* block's per-grid MSE. The "pressure" is benefit/cost, not variance.
|
| 316 |
+
* key "variance" — the document's stated rule: rank blocks by variance and unclamp the most
|
| 317 |
+
* dispersed ones first, ignoring how much each block's error would actually
|
| 318 |
+
* improve. Implemented faithfully so it can be compared, not assumed inferior.
|
| 319 |
+
*
|
| 320 |
+
* Budget is an average of `indexBits` per weight. The greedy walks upgrades from the cheapest
|
| 321 |
+
* candidate upward and stops when the next cheapest upgrade no longer fits, so the realised
|
| 322 |
+
* average is <= budget and, when the budget happens to be reachable exactly, equals it.
|
| 323 |
+
*/
|
| 324 |
+
function allocate(values, opts) {
|
| 325 |
+
opts = opts || {};
|
| 326 |
+
var candidates = (opts.candidates || ["binary", "ternary", "penta", "hepta"]).slice();
|
| 327 |
+
var rule = opts.rule === "meanabs" ? "meanabs" : "lsq";
|
| 328 |
+
var budget = opts.budget === undefined ? 2 : opts.budget;
|
| 329 |
+
var key = opts.key === "variance" ? "variance" : "benefit";
|
| 330 |
+
var bs = opts.blockSize | 0;
|
| 331 |
+
var n = values.length;
|
| 332 |
+
var size = bs > 0 ? bs : n;
|
| 333 |
+
|
| 334 |
+
candidates.sort(function (a, b) { return gridInfo(a).indexBits - gridInfo(b).indexBits; });
|
| 335 |
+
var stats = blockStats(values, size, candidates, rule);
|
| 336 |
+
var nBlocks = stats.length;
|
| 337 |
+
if (!nBlocks) {
|
| 338 |
+
return { grids: [], stats: [], avgBits: 0, bits: null, values: new Float32Array(0),
|
| 339 |
+
error: measure(values, new Float32Array(0)), key: key, candidates: candidates };
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
/* Costs, and the exact error reduction each single-step upgrade would buy. */
|
| 343 |
+
var cost = candidates.map(function (c) { return gridInfo(c).indexBits; });
|
| 344 |
+
var level = stats.map(function () { return 0; }); // index into candidates
|
| 345 |
+
var totalWeight = 0;
|
| 346 |
+
stats.forEach(function (s) { totalWeight += s.len; });
|
| 347 |
+
|
| 348 |
+
function currentBits() {
|
| 349 |
+
var b = 0;
|
| 350 |
+
for (var i = 0; i < nBlocks; i++) b += cost[level[i]] * stats[i].len / totalWeight;
|
| 351 |
+
return b;
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
/* A plain greedy on single-step upgrades. Unclamping is monotone: a block only moves to a
|
| 355 |
+
* costlier grid, and only when that grid actually reduces its measured error, so a grid that
|
| 356 |
+
* costs more without helping is never selected. Each pass takes the single best-scoring upgrade
|
| 357 |
+
* that still fits the budget, which is the standard greedy for this separable problem. The two
|
| 358 |
+
* keys differ only in the score: benefit uses measured error reduction per extra bit, variance
|
| 359 |
+
* uses the block's own dispersion, which is the rule the document names. */
|
| 360 |
+
var guard = 0;
|
| 361 |
+
while (guard++ < nBlocks * candidates.length + 10) {
|
| 362 |
+
var best = -1, bestScore = -Infinity, i, next, gain, dCost, score;
|
| 363 |
+
for (i = 0; i < nBlocks; i++) {
|
| 364 |
+
next = level[i] + 1;
|
| 365 |
+
if (next >= candidates.length) continue;
|
| 366 |
+
gain = (stats[i].mse[candidates[level[i]]] - stats[i].mse[candidates[next]]) * stats[i].len;
|
| 367 |
+
if (gain <= 0) continue;
|
| 368 |
+
dCost = (cost[next] - cost[level[i]]) * stats[i].len / totalWeight;
|
| 369 |
+
if (dCost > 0 && currentBits() + dCost > budget + 1e-9) continue;
|
| 370 |
+
if (key === "variance") score = stats[i].variance + gain * 1e-18;
|
| 371 |
+
else score = dCost > 0 ? gain / dCost : gain;
|
| 372 |
+
if (score > bestScore) { bestScore = score; best = i; }
|
| 373 |
+
}
|
| 374 |
+
if (best < 0) break;
|
| 375 |
+
level[best]++;
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
/* Realise the assignment. */
|
| 379 |
+
var out = new Float32Array(n);
|
| 380 |
+
var grids = [], off = 0, i2;
|
| 381 |
+
var accBits = { indexBits: 0, scaleBits: 0, effBits: 0, entropyBits: 0, storedBytes: 0 };
|
| 382 |
+
for (i2 = 0; i2 < nBlocks; i2++) {
|
| 383 |
+
var st = stats[i2];
|
| 384 |
+
var name = candidates[level[i2]];
|
| 385 |
+
var q = quantiseBlock(values, st.offset, st.len, name, rule);
|
| 386 |
+
out.set(q.values, st.offset);
|
| 387 |
+
grids.push(name);
|
| 388 |
+
accBits.indexBits += q.bits.indexBits * st.len / n;
|
| 389 |
+
accBits.scaleBits += q.bits.scaleBits * st.len / n;
|
| 390 |
+
accBits.effBits += q.bits.effBits * st.len / n;
|
| 391 |
+
accBits.entropyBits += q.bits.entropyBits * st.len / n;
|
| 392 |
+
accBits.storedBytes += Math.ceil(st.len * q.bits.indexBits / 8) + SCALE_BYTES;
|
| 393 |
+
}
|
| 394 |
+
accBits.count = n; accBits.blockSize = bs; accBits.rule = rule;
|
| 395 |
+
accBits.mode = "elastic"; accBits.key = key; accBits.budget = budget;
|
| 396 |
+
accBits.storedBytes = Math.ceil(accBits.storedBytes);
|
| 397 |
+
accBits.floatBytes = n * 4;
|
| 398 |
+
accBits.ratio = accBits.storedBytes ? accBits.floatBytes / accBits.storedBytes : 0;
|
| 399 |
+
var err2 = measure(values, out);
|
| 400 |
+
accBits.mse = err2.mse; accBits.rmse = err2.rmse; accBits.mae = err2.mae;
|
| 401 |
+
accBits.maxAbs = err2.maxAbs;
|
| 402 |
+
var hist = Object.create(null);
|
| 403 |
+
grids.forEach(function (g) { hist[g] = (hist[g] || 0) + 1; });
|
| 404 |
+
accBits.gridHistogram = hist;
|
| 405 |
+
return { values: out, grids: grids, stats: stats, bits: accBits, error: err2,
|
| 406 |
+
avgBits: accBits.indexBits, key: key, candidates: candidates,
|
| 407 |
+
/* The ladder the allocator was allowed to climb, for reporting. */
|
| 408 |
+
costs: candidates.map(function (c) { return { grid: c, indexBits: gridInfo(c).indexBits }; }) };
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
/* ---------------------------------------------------------------- the {0/0/0} experiment */
|
| 412 |
+
|
| 413 |
+
/* Everything needed to settle the document's multi-channel-centroid claim numerically: the same
|
| 414 |
+
* weights quantised with one zero channel and with three, the reconstruction compared for exact
|
| 415 |
+
* inequality, and the channel accounting of each. A three-channel zero that decodes identically
|
| 416 |
+
* is not an information channel; the caller can print both rows and see that. */
|
| 417 |
+
function zeroChannelTest(values, opts) {
|
| 418 |
+
opts = opts || {};
|
| 419 |
+
var bs = opts.blockSize | 0;
|
| 420 |
+
var one = quantise(values, { grid: "ternary", blockSize: bs, rule: opts.rule });
|
| 421 |
+
var three = quantise(values, { grid: "ternaryDup", blockSize: bs, rule: opts.rule });
|
| 422 |
+
return {
|
| 423 |
+
one: one, three: three,
|
| 424 |
+
identical: identical(one.values, three.values),
|
| 425 |
+
info: { ternary: gridInfo("ternary"), ternaryDup: gridInfo("ternaryDup") }
|
| 426 |
+
};
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
/* ---------------------------------------------------------------- HDC-side helpers */
|
| 430 |
+
|
| 431 |
+
/* Shannon entropy in bits of a categorical histogram, used by the bundling experiment to compare
|
| 432 |
+
* multi-channel codes at equal information content rather than equal channel count. */
|
| 433 |
+
function entropy(counts) {
|
| 434 |
+
var total = 0, i;
|
| 435 |
+
for (i = 0; i < counts.length; i++) total += counts[i];
|
| 436 |
+
if (!total) return 0;
|
| 437 |
+
var h = 0, p;
|
| 438 |
+
for (i = 0; i < counts.length; i++) {
|
| 439 |
+
if (!counts[i]) continue;
|
| 440 |
+
p = counts[i] / total;
|
| 441 |
+
h -= p * Math.log2(p);
|
| 442 |
+
}
|
| 443 |
+
return h;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
return {
|
| 447 |
+
GRIDS: GRIDS, gridInfo: gridInfo, gridOf: gridOf,
|
| 448 |
+
quantise: quantise, quantiseBlock: quantiseBlock, blockStats: blockStats,
|
| 449 |
+
allocate: allocate, zeroChannelTest: zeroChannelTest,
|
| 450 |
+
measure: measure, identical: identical, entropy: entropy,
|
| 451 |
+
indexBitsFor: indexBitsFor, SCALE_BYTES: SCALE_BYTES
|
| 452 |
+
};
|
| 453 |
+
});
|