Queue ONNX Runtime calls, PE-G head in JS, example loader
Browse files172 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021193 unmodified lines30530630730830931031131231319 unmodified lines33333433530033633733833934034134234334434534634734834935035135231435335435535631835735835936058 unmodified lines4194204213834224234244259 unmodified lines4354364373994384394014404414424434044054064074444454464474094104484494504514525 unmodified lines458459460461462463464465466467468469470471172 unmodified lines };}
// Round a float32 value to the nearest binary16 value (ties to even), as torch's .half() does.function f16round(x) { if (!Number.isFinite(x) || x === 0) return x; const a = Math.abs(x); if (a >= 65520) return Math.sign(x) * Infinity; let e = Math.floor(Math.log2(a)); if (2 ** e > a) e--; else if (2 ** (e + 1) <= a) e++; const q = 2 ** (Math.max(e, -14) - 10); // spacing of binary16 values near a (subnormals below 2^-14) const v = a / q, f = Math.floor(v), d = v - f; const r = (d > 0.5 || (d === 0.5 && f % 2 === 1) ? f + 1 : f) * q; return x < 0 ? -r : r;}
// Detector.score_peg's head: [mean, std] of blocks 25 / 38 / 50 + the pooled output, each clamped to// +-65000 and rounded to fp16, NaN -> 0, L2-normalised per block, standardised, then a dot product.// head: Float32Array mu | sd | w (n each) | b, dims: block widths summing to n.function pegLogit(s25, s38, s50, pooled, head, dims) { const h = (s) => [s.subarray(0, s.length / 2), s.subarray(s.length / 2)]; const blocks = [...h(s25), ...h(s38), ...h(s50), pooled]; const n = dims.reduce((a, b) => a + b, 0), mu = head.subarray(0, n), sd = head.subarray(n, 2 * n), w = head.subarray(2 * n, 3 * n); let logit = head[3 * n], o = 0; blocks.forEach((blk, i) => { if (blk.length !== dims[i]) throw new Error(`PE-G block ${i}: ${blk.length} values, expected ${dims[i]}`); const x = Array.from(blk, (v) => { const r = f16round(Math.min(65000, Math.max(-65000, v))); return Number.isNaN(r) ? 0 : r; }); const norm = Math.max(Math.fround(Math.sqrt(x.reduce((a, v) => a + v * v, 0))), 1e-12); for (let k = 0; k < x.length; k++, o++) { const z = Math.fround(Math.fround(Math.fround(x[k] / norm) - mu[o]) / sd[o]); logit += z * w[o]; } }); return logit;}
function mesmerVerdict(pelLogit, pegLogit, fusion) { const zp = fusion.rank.pel(pelLogit), zg = fusion.rank.peg(pegLogit), w = fusion.weights; const z = (w.pel * zp + w.peg * zg) / (w.pel + w.peg);93 unmodified lines ort.env.logLevel = 'error'; return ort;})());// One ONNX Runtime call at a time: creating one session while another runs corrupts its memory.let gpuQ = Promise.resolve();const gpu = (fn) => { const p = gpuQ.then(fn); gpuQ = p.catch(() => {}); return p; };
async function download(name, files, total) { // files: [[url, bytes]], sequential, progress in the row let done = 0;19 unmodified lines const ort = await getOrt(); const [bytes] = await download('smaug', [[SMAUG, 181210404]], 181210404); show('smaug', 'busy', 1, 'starting on your GPU…'); return ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 }); return gpu(() => ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 }));})());
const getMesmer = () => (mesmerP ||= (async () => { const ort = await getOrt(); await getSmaug().catch(() => {}); // Smaug's download first, so its answer comes quickly const man = await getManifest(); const parts = ['pel', ...man.peg]; const files = parts.map((p) => [`${MESMER}/${man.files[p].path}`, man.files[p].bytes]); const total = files.reduce((a, [, b]) => a + b, 0); const [fusion, policy] = await Promise.all(['fusion.json', 'policy.json'].map((f) => fetchBytes(`${MESMER}/${f}`).then((b) => JSON.parse(new TextDecoder().decode(b))))); const hb = await fetchBytes(`${MESMER}/${man.peg_head.path}`); const head = new Float32Array(hb.buffer, hb.byteOffset, hb.byteLength / 4); const bytes = await download('mesmer', files, total); const sessions = {}; for (const [i, p] of parts.entries()) { show('mesmer', 'busy', 1, `starting on your GPU (${i + 1} of ${parts.length})…`); sessions[p] = await ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 }); sessions[p] = await gpu(() => ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 })); bytes[i] = null; } const th = policy.thresholds; return { ort, man, sessions, fusion: { weights: fusion.weights, thresholds: { ai: th.likely_ai_at_or_above, unc: th.uncertain_at_or_above }, return { ort, man, sessions, head, fusion: { weights: fusion.weights, thresholds: { ai: th.likely_ai_at_or_above, unc: th.uncertain_at_or_above }, rank: { pel: makeRanker(fusion.reference.pel), peg: makeRanker(fusion.reference.peg) } } };})());
58 unmodified lines if (stale()) return; show('smaug', 'busy', 0, 'scanning…'); const t0 = performance.now(), { ort } = { ort: await getOrt() }; const r = await s.run({ pixels: new ort.Tensor('float32', smaugIn.tensor, [3, 3, 528, 528]) }); const r = await gpu(() => s.run({ pixels: new ort.Tensor('float32', smaugIn.tensor, [3, 3, 528, 528]) })); const lg = Array.from(r.logits.data), p = sigmoid(lg.reduce((a, b) => a + b, 0) / lg.length); Object.values(r).forEach((t) => t.dispose?.()); if (!stale()) {9 unmodified lines if (stale()) return; show('mesmer', 'busy', 0, 'scanning…'); const { ort, sessions: S, fusion } = m, t0 = performance.now(); const pr = await S.pel.run({ pixels: new ort.Tensor('float32', mesmerIn.pel, [5, 3, 336, 336]) }); const pr = await gpu(() => S.pel.run({ pixels: new ort.Tensor('float32', mesmerIn.pel, [5, 3, 336, 336]) })); const pv = Array.from(pr.logit.data), pel = pv.reduce((a, b) => a + b, 0) / pv.length; let x = new ort.Tensor('float32', mesmerIn.peg, [1, 3, 448, 448]), s25 = null, s38 = null, peg = null; let x = new ort.Tensor('float32', mesmerIn.peg, [1, 3, 448, 448]); const st = {}; for (const [i, part] of m.man.peg.entries()) { show('mesmer', 'busy', (i + 1) / (m.man.peg.length + 1), 'scanning…'); const sess = S[part], feed = {}; for (const n of sess.inputNames) feed[n] = n === 's25' ? s25 : n === 's38' ? s38 : x; const o = await sess.run(feed); if (o.logit) { peg = o.logit.data[0]; break; } const sess = S[part]; const o = await gpu(() => sess.run({ [sess.inputNames[0]]: x })); for (const k of ['s25', 's38', 's50', 'pooled']) if (o[k]) st[k] = o[k].data; x = o.y || o.x; if (o.s25) s25 = o.s25; if (o.s38) s38 = o.s38; } const peg = pegLogit(st.s25, st.s38, st.s50, st.pooled, m.head, m.man.peg_head.dims); const v = mesmerVerdict(pel, peg, fusion); if (!stale()) { const label = { likely_ai: ['ai', 'Likely AI'], uncertain: ['unsure', 'Uncertain'], likely_real: ['real', 'Likely real'] }[v.verdict];5 unmodified lines}
// ---------------------------------------------------------------- input// An error thrown inside ONNX Runtime can escape its promise; say so instead of spinning forever.const fail = (e) => { const msg = (e?.reason ?? e?.error ?? e)?.message || String(e?.reason ?? e?.message ?? e); for (const n of Object.keys(rows)) if (rows[n].classList.contains('busy')) show(n, 'bad', 0, `stopped: ${msg}. Reload the page to try again.`);};addEventListener('error', fail);addEventListener('unhandledrejection', fail);
ui.file.addEventListener('change', () => { onImage(ui.file.files[0]); ui.file.value = ''; });addEventListener('paste', (e) => { const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith('image/'));app.js+58-12