eee-score-prediction / predict.js
evijit's picture
evijit HF Staff
Ability term as the default bias (our addition), paper's exact model behind a checkbox; validation for both
e7e6604 verified
Raw History Blame Contribute Delete
10.2 kB
/* Client-side predictor for the whole EEE store.
*
* pipeline/store.py fits the paper's model (LRMC, PKPS, ensemble; see its docstring) and exports
* its parameters; this file reproduces store.Completion.lrmc, store.Perspective.predict and the
* ensemble exactly, so that any unmeasured (model, metric) cell can be estimated on demand in the
* browser. It has no DOM dependencies (tests/parity.mjs runs it under Node against the Python output).
*/
(function (root) {
'use strict';
const LINEAR = 0, LOGIT = 1;
function createStore(store, models, metrics, cellsBuf, factorsBuf, heldoutBuf, eligBuf) {
const meta = store.meta, nM = models.id.length, nT = metrics.c.length, n = store.layout.cells.n;
const R = store.layout.factors.R, EPS = meta.eps, K = meta.k, MIN_TRAIN = meta.pkps_min_train ?? 3, alpha = meta.alpha_pkps;
const cm = new Uint32Array(cellsBuf, 0, n), ct = new Uint32Array(cellsBuf, 4 * n, n);
const cy = new Float64Array(cellsBuf.slice(8 * n, 16 * n));
const a = new Float32Array(factorsBuf, 0, nM);
const U = new Float32Array(factorsBuf, 4 * nM, nM * R), V = new Float32Array(factorsBuf, 4 * (nM + nM * R), nT * R);
// cells are sorted by (model, metric): CSR by model is a scan; CSR by metric is a counting sort
const mStart = new Uint32Array(nM + 1), tStart = new Uint32Array(nT + 1), tIdx = new Uint32Array(n);
for (let i = 0; i < n; i++) { mStart[cm[i] + 1]++; tStart[ct[i] + 1]++; }
for (let i = 0; i < nM; i++) mStart[i + 1] += mStart[i];
for (let i = 0; i < nT; i++) tStart[i + 1] += tStart[i];
const fill = tStart.slice(0, nT);
for (let i = 0; i < n; i++) tIdx[fill[ct[i]]++] = i;
const M = metrics, sign = t => (M.lower[t] ? -1 : 1), cb = M.cb || new Array(nT).fill(0), al = M.al || null;
function raw(t, y) { // logit on bounded metrics (mapped to [0, 1], clipped at EPS), else identity
if (M.kind[t] === LOGIT) {
const p = Math.min(1 - EPS, Math.max(EPS, (y - M.lo[t]) / (M.hi[t] - M.lo[t])));
return Math.log(p / (1 - p));
}
return y;
}
const forward = (t, y) => (sign(t) * raw(t, y) - M.mu[t]) / M.sd[t];
function inverse(t, x) {
const r = sign(t) * (M.mu[t] + M.sd[t] * x);
return M.kind[t] === LOGIT ? M.lo[t] + (M.hi[t] - M.lo[t]) / (1 + Math.exp(-r)) : r;
}
const clip = (t, y) => (M.kind[t] === LOGIT ? Math.min(M.hi[t], Math.max(M.lo[t], y)) : y);
function measured(m, t) { // binary search within the model's row
let lo = mStart[m], hi = mStart[m + 1] - 1;
while (lo <= hi) { const mid = (lo + hi) >> 1; if (ct[mid] === t) return cy[mid]; if (ct[mid] < t) lo = mid + 1; else hi = mid - 1; }
return null;
}
// bias: per-metric intercept + slope x model term (the paper's two-way bias when every slope is 1)
const bias = (m, t) => cb[t] + (al ? al[t] : 1) * a[m];
function lrmc(m, t) {
let s = bias(m, t); const u = m * R, v = t * R;
for (let k = 0; k < R; k++) s += U[u + k] * V[v + k];
return s;
}
// PKPS: inverse-distance k-NN of the whitened residual over models with response coordinates
const coordOf = models.coord, cModels = store.coords.models, Z = store.coords.z, nc = cModels.length;
const dist = new Float64Array(nc * nc);
for (let i = 0; i < nc; i++) for (let j = 0; j < nc; j++) {
let d = 0; for (let k = 0; k < Z[i].length; k++) d += (Z[i][k] - Z[j][k]) ** 2;
dist[i * nc + j] = Math.sqrt(d);
}
function pkps(m, t, biasOf = bias) {
const q = coordOf[m];
if (q < 0) return null;
const cand = [];
for (let p = tStart[t]; p < tStart[t + 1]; p++) {
const i = tIdx[p], dm = cm[i], dl = coordOf[dm];
if (dl < 0 || dm === m) continue;
const bd = biasOf(dm, t);
if (bd === null) continue;
cand.push([dist[q * nc + dl], dm, forward(t, cy[i]) - bd, cy[i]]);
}
// the code's support counts the task's observed models with coordinates, the target included
if (cand.length < 1 || cand.length + (measured(m, t) !== null ? 1 : 0) < MIN_TRAIN) return null;
cand.sort((x, y) => x[0] - y[0] || coordOf[x[1]] - coordOf[y[1]]);
const kk = Math.min(K, cand.length), near = cand.slice(0, kk), zero = near.some(c => c[0] === 0);
let sw = 0, sx = 0; const donors = [];
for (const c of near) {
const w = zero ? (c[0] === 0 ? 1 : 0) : 1 / c[0];
sw += w; sx += w * c[2]; donors.push({ m: c[1], w, y: c[3], d: c[0] });
}
donors.forEach(d => { d.w /= sw; });
return { x: biasOf(m, t) + sx / sw, donors };
}
// scores of this model on the same benchmark from other sources (shown, not used in the estimate)
const B = M.b || [], sib = new Map(), nC = store.collections.length;
for (let t = 0; t < nT; t++) if (B[t] >= 0) { if (!sib.has(B[t])) sib.set(B[t], []); sib.get(B[t]).push(t); }
const siblings = t => (B[t] >= 0 ? sib.get(B[t]).filter(s => s !== t && M.c[s] !== M.c[t] && M.lo[s] === M.lo[t] && M.hi[s] === M.hi[t]) : []);
function elsewhere(m, t) {
const out = [];
for (const s of siblings(t)) { const y = measured(m, s); if (y !== null) out.push({ t: s, y }); }
return out;
}
const member = new Set(); // (model, source) pairs with a modelled measured score
for (let i = 0; i < n; i++) if (M.valid[ct[i]]) member.add(cm[i] * nC + M.c[ct[i]]);
// what an estimate rests on: 'within' (other scores of the model from this source) or 'cross'
const evidence = (m, t) => (member.has(m * nC + M.c[t]) ? 'within' : 'cross');
// held-out estimates from the cross-validation (score scale), sorted by (model, metric)
const nh = heldoutBuf && store.layout.heldout ? store.layout.heldout.n : 0;
const hm = nh ? new Uint32Array(heldoutBuf, 0, nh) : null, ht = nh ? new Uint32Array(heldoutBuf, 4 * nh, nh) : null;
const hy = nh ? new Float32Array(heldoutBuf, 8 * nh, nh) : null, hStart = new Uint32Array(nM + 1);
for (let i = 0; i < nh; i++) hStart[hm[i] + 1]++;
for (let i = 0; i < nM; i++) hStart[i + 1] += hStart[i];
function heldout(m, t) { // held-out estimate for a measured cell, or null
let lo = hStart[m], hi = hStart[m + 1] - 1;
while (lo <= hi) { const mid = (lo + hi) >> 1; if (ht[mid] === t) return hy[mid]; if (ht[mid] < t) lo = mid + 1; else hi = mid - 1; }
return null;
}
// an estimate needs models on the metric that share a metric with this model (store.py: eligibility)
const EL = eligBuf && store.layout.eligible ? new Uint8Array(eligBuf) : null, bpr = EL ? store.layout.eligible.bytes_per_row : 0;
const eligible = (m, t) => { if (!EL) return true; const r = models.e[m]; return r >= 0 && ((EL[r * bpr + (t >> 3)] >> (t & 7)) & 1) === 1; };
const canPredict = (m, t) => M.valid[t] === 1 && models.support[m] > 0 && eligible(m, t);
const mean = t => (M.mean ? M.mean[t] : inverse(t, 0)); // mean of the measured scores
function predict(m, t, withDonors) {
if (!canPredict(m, t)) return null;
const xl = lrmc(m, t), p = pkps(m, t), yl = inverse(t, xl), yp = p ? inverse(t, p.x) : null;
// the paper's ensemble: blend in score space, clip to the score range; LRMC alone without PKPS
const y = p ? clip(t, alpha * yp + (1 - alpha) * yl) : yl;
const x = forward(t, y), q = (store.groups && store.groups.q90[M.g[t]]) ?? meta.q90_global;
const y0 = inverse(t, x - q), y1 = inverse(t, x + q);
return { x, y, lo: Math.min(y0, y1), hi: Math.max(y0, y1), q, lrmc: yl, xl, pkps: yp, xp: p ? p.x : null,
donors: p && withDonors ? p.donors : null, evidence: evidence(m, t) };
}
function cell(m, t) {
const y = measured(m, t);
if (y !== null) { const h = nh ? heldout(m, t) : null; return { kind: 'obs', y, oof: h, xoof: h === null ? null : forward(t, h) }; }
const p = predict(m, t, false);
return p ? { kind: 'pred', y: p.y, lo: p.lo, hi: p.hi, evidence: p.evidence } : null;
}
return { meta, nM, nT, n, R, cm, ct, cy, mStart, tStart, tIdx, a, forward, inverse, measured, heldout, lrmc, pkps, predict, cell,
elsewhere, siblings, evidence, eligible, mean, canPredict, coordOf, cModels, clip, LINEAR, LOGIT };
}
/* Same-setup estimates: the same estimators fitted within one recorded evaluation setup
* (store.same_setup; data/store/setup.json). A metric without a recorded setup has none. */
function createSame(ST, D, metrics) {
const M = metrics, nT = ST.nT;
const parts = D.parts.map(P => {
const loc = new Map(P.models.map((m, i) => [m, i])), tl = new Map(P.metrics.map((t, i) => [t, i])), ho = new Map();
P.ho.m.forEach((m, i) => ho.set(m * nT + P.ho.t[i], P.ho.y[i]));
return Object.assign({}, P, { loc, tl, ho });
});
const part = t => (M.sp && M.sp[t] >= 0 ? parts[M.sp[t]] : null);
function predict(m, t) {
const P = part(t);
if (!P || M.valid[t] !== 1) return null;
const l = P.loc.get(m), k = P.tl.get(t);
if (l === undefined || k === undefined || P.n[l] < D.min_record) return null;
const slope = P.al ? P.al[k] : 1;
const R = P.R, bias = (mm, tt) => { const j = P.loc.get(mm); return j === undefined ? null : P.cb[k] + slope * P.a[j]; };
let xl = P.cb[k] + slope * P.a[l];
for (let r = 0; r < R; r++) xl += P.U[l * R + r] * P.V[k * R + r];
const p = ST.pkps(m, t, bias), yl = ST.inverse(t, xl), yp = p ? ST.inverse(t, p.x) : null;
const y = p ? ST.clip(t, D.alpha * yp + (1 - D.alpha) * yl) : yl;
const x = ST.forward(t, y), q = P.q90 ?? D.q90_global, y0 = ST.inverse(t, x - q), y1 = ST.inverse(t, x + q);
return { x, y, lo: Math.min(y0, y1), hi: Math.max(y0, y1), q, lrmc: yl, pkps: yp, evidence: 'within', part: P };
}
function cell(m, t) {
const y = ST.measured(m, t);
if (y !== null) { const P = part(t), h = P ? P.ho.get(m * nT + t) : undefined; return { kind: 'obs', y, oof: h ?? null, xoof: h === undefined ? null : ST.forward(t, h) }; }
const p = predict(m, t);
return p ? { kind: 'pred', y: p.y, lo: p.lo, hi: p.hi, evidence: 'within' } : null;
}
return { predict, cell, part, summary: D.summary, parts };
}
if (typeof module !== 'undefined' && module.exports) module.exports = { createStore, createSame };
else { root.createStore = createStore; root.createSame = createSame; }
})(typeof self !== 'undefined' ? self : globalThis);