Nekochu commited on
Commit
658106a
·
verified ·
1 Parent(s): 4221512

Queue ONNX Runtime calls, PE-G head in JS, example loader

Browse files
Files changed (1) hide show
  1. app.js +58 -12
app.js CHANGED
@@ -173,6 +173,39 @@ function makeRanker(ref) {
173
  };
174
  }
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  function mesmerVerdict(pelLogit, pegLogit, fusion) {
177
  const zp = fusion.rank.pel(pelLogit), zg = fusion.rank.peg(pegLogit), w = fusion.weights;
178
  const z = (w.pel * zp + w.peg * zg) / (w.pel + w.peg);
@@ -272,6 +305,9 @@ const getOrt = () => (ortP ||= (async () => {
272
  ort.env.logLevel = 'error';
273
  return ort;
274
  })());
 
 
 
275
 
276
  async function download(name, files, total) { // files: [[url, bytes]], sequential, progress in the row
277
  let done = 0;
@@ -297,25 +333,28 @@ const getSmaug = () => (smaugP ||= (async () => {
297
  const ort = await getOrt();
298
  const [bytes] = await download('smaug', [[SMAUG, 181210404]], 181210404);
299
  show('smaug', 'busy', 1, 'starting on your GPU…');
300
- return ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 });
301
  })());
302
 
303
  const getMesmer = () => (mesmerP ||= (async () => {
304
  const ort = await getOrt();
 
305
  const man = await getManifest();
306
  const parts = ['pel', ...man.peg];
307
  const files = parts.map((p) => [`${MESMER}/${man.files[p].path}`, man.files[p].bytes]);
308
  const total = files.reduce((a, [, b]) => a + b, 0);
309
  const [fusion, policy] = await Promise.all(['fusion.json', 'policy.json'].map((f) => fetchBytes(`${MESMER}/${f}`).then((b) => JSON.parse(new TextDecoder().decode(b)))));
 
 
310
  const bytes = await download('mesmer', files, total);
311
  const sessions = {};
312
  for (const [i, p] of parts.entries()) {
313
  show('mesmer', 'busy', 1, `starting on your GPU (${i + 1} of ${parts.length})…`);
314
- sessions[p] = await ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 });
315
  bytes[i] = null;
316
  }
317
  const th = policy.thresholds;
318
- return { ort, man, sessions, fusion: { weights: fusion.weights, thresholds: { ai: th.likely_ai_at_or_above, unc: th.uncertain_at_or_above },
319
  rank: { pel: makeRanker(fusion.reference.pel), peg: makeRanker(fusion.reference.peg) } } };
320
  })());
321
 
@@ -380,7 +419,7 @@ async function scan(blob, id) {
380
  if (stale()) return;
381
  show('smaug', 'busy', 0, 'scanning…');
382
  const t0 = performance.now(), { ort } = { ort: await getOrt() };
383
- const r = await s.run({ pixels: new ort.Tensor('float32', smaugIn.tensor, [3, 3, 528, 528]) });
384
  const lg = Array.from(r.logits.data), p = sigmoid(lg.reduce((a, b) => a + b, 0) / lg.length);
385
  Object.values(r).forEach((t) => t.dispose?.());
386
  if (!stale()) {
@@ -396,19 +435,18 @@ async function scan(blob, id) {
396
  if (stale()) return;
397
  show('mesmer', 'busy', 0, 'scanning…');
398
  const { ort, sessions: S, fusion } = m, t0 = performance.now();
399
- const pr = await S.pel.run({ pixels: new ort.Tensor('float32', mesmerIn.pel, [5, 3, 336, 336]) });
400
  const pv = Array.from(pr.logit.data), pel = pv.reduce((a, b) => a + b, 0) / pv.length;
401
- let x = new ort.Tensor('float32', mesmerIn.peg, [1, 3, 448, 448]), s25 = null, s38 = null, peg = null;
 
402
  for (const [i, part] of m.man.peg.entries()) {
403
  show('mesmer', 'busy', (i + 1) / (m.man.peg.length + 1), 'scanning…');
404
- const sess = S[part], feed = {};
405
- for (const n of sess.inputNames) feed[n] = n === 's25' ? s25 : n === 's38' ? s38 : x;
406
- const o = await sess.run(feed);
407
- if (o.logit) { peg = o.logit.data[0]; break; }
408
  x = o.y || o.x;
409
- if (o.s25) s25 = o.s25;
410
- if (o.s38) s38 = o.s38;
411
  }
 
412
  const v = mesmerVerdict(pel, peg, fusion);
413
  if (!stale()) {
414
  const label = { likely_ai: ['ai', 'Likely AI'], uncertain: ['unsure', 'Uncertain'], likely_real: ['real', 'Likely real'] }[v.verdict];
@@ -420,6 +458,14 @@ async function scan(blob, id) {
420
  }
421
 
422
  // ---------------------------------------------------------------- input
 
 
 
 
 
 
 
 
423
  ui.file.addEventListener('change', () => { onImage(ui.file.files[0]); ui.file.value = ''; });
424
  addEventListener('paste', (e) => {
425
  const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith('image/'));
 
173
  };
174
  }
175
 
176
+ // Round a float32 value to the nearest binary16 value (ties to even), as torch's .half() does.
177
+ function f16round(x) {
178
+ if (!Number.isFinite(x) || x === 0) return x;
179
+ const a = Math.abs(x);
180
+ if (a >= 65520) return Math.sign(x) * Infinity;
181
+ let e = Math.floor(Math.log2(a));
182
+ if (2 ** e > a) e--; else if (2 ** (e + 1) <= a) e++;
183
+ const q = 2 ** (Math.max(e, -14) - 10); // spacing of binary16 values near a (subnormals below 2^-14)
184
+ const v = a / q, f = Math.floor(v), d = v - f;
185
+ const r = (d > 0.5 || (d === 0.5 && f % 2 === 1) ? f + 1 : f) * q;
186
+ return x < 0 ? -r : r;
187
+ }
188
+
189
+ // Detector.score_peg's head: [mean, std] of blocks 25 / 38 / 50 + the pooled output, each clamped to
190
+ // +-65000 and rounded to fp16, NaN -> 0, L2-normalised per block, standardised, then a dot product.
191
+ // head: Float32Array mu | sd | w (n each) | b, dims: block widths summing to n.
192
+ function pegLogit(s25, s38, s50, pooled, head, dims) {
193
+ const h = (s) => [s.subarray(0, s.length / 2), s.subarray(s.length / 2)];
194
+ const blocks = [...h(s25), ...h(s38), ...h(s50), pooled];
195
+ 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);
196
+ let logit = head[3 * n], o = 0;
197
+ blocks.forEach((blk, i) => {
198
+ if (blk.length !== dims[i]) throw new Error(`PE-G block ${i}: ${blk.length} values, expected ${dims[i]}`);
199
+ const x = Array.from(blk, (v) => { const r = f16round(Math.min(65000, Math.max(-65000, v))); return Number.isNaN(r) ? 0 : r; });
200
+ const norm = Math.max(Math.fround(Math.sqrt(x.reduce((a, v) => a + v * v, 0))), 1e-12);
201
+ for (let k = 0; k < x.length; k++, o++) {
202
+ const z = Math.fround(Math.fround(Math.fround(x[k] / norm) - mu[o]) / sd[o]);
203
+ logit += z * w[o];
204
+ }
205
+ });
206
+ return logit;
207
+ }
208
+
209
  function mesmerVerdict(pelLogit, pegLogit, fusion) {
210
  const zp = fusion.rank.pel(pelLogit), zg = fusion.rank.peg(pegLogit), w = fusion.weights;
211
  const z = (w.pel * zp + w.peg * zg) / (w.pel + w.peg);
 
305
  ort.env.logLevel = 'error';
306
  return ort;
307
  })());
308
+ // One ONNX Runtime call at a time: creating one session while another runs corrupts its memory.
309
+ let gpuQ = Promise.resolve();
310
+ const gpu = (fn) => { const p = gpuQ.then(fn); gpuQ = p.catch(() => {}); return p; };
311
 
312
  async function download(name, files, total) { // files: [[url, bytes]], sequential, progress in the row
313
  let done = 0;
 
333
  const ort = await getOrt();
334
  const [bytes] = await download('smaug', [[SMAUG, 181210404]], 181210404);
335
  show('smaug', 'busy', 1, 'starting on your GPU…');
336
+ return gpu(() => ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 }));
337
  })());
338
 
339
  const getMesmer = () => (mesmerP ||= (async () => {
340
  const ort = await getOrt();
341
+ await getSmaug().catch(() => {}); // Smaug's download first, so its answer comes quickly
342
  const man = await getManifest();
343
  const parts = ['pel', ...man.peg];
344
  const files = parts.map((p) => [`${MESMER}/${man.files[p].path}`, man.files[p].bytes]);
345
  const total = files.reduce((a, [, b]) => a + b, 0);
346
  const [fusion, policy] = await Promise.all(['fusion.json', 'policy.json'].map((f) => fetchBytes(`${MESMER}/${f}`).then((b) => JSON.parse(new TextDecoder().decode(b)))));
347
+ const hb = await fetchBytes(`${MESMER}/${man.peg_head.path}`);
348
+ const head = new Float32Array(hb.buffer, hb.byteOffset, hb.byteLength / 4);
349
  const bytes = await download('mesmer', files, total);
350
  const sessions = {};
351
  for (const [i, p] of parts.entries()) {
352
  show('mesmer', 'busy', 1, `starting on your GPU (${i + 1} of ${parts.length})…`);
353
+ sessions[p] = await gpu(() => ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 }));
354
  bytes[i] = null;
355
  }
356
  const th = policy.thresholds;
357
+ return { ort, man, sessions, head, fusion: { weights: fusion.weights, thresholds: { ai: th.likely_ai_at_or_above, unc: th.uncertain_at_or_above },
358
  rank: { pel: makeRanker(fusion.reference.pel), peg: makeRanker(fusion.reference.peg) } } };
359
  })());
360
 
 
419
  if (stale()) return;
420
  show('smaug', 'busy', 0, 'scanning…');
421
  const t0 = performance.now(), { ort } = { ort: await getOrt() };
422
+ const r = await gpu(() => s.run({ pixels: new ort.Tensor('float32', smaugIn.tensor, [3, 3, 528, 528]) }));
423
  const lg = Array.from(r.logits.data), p = sigmoid(lg.reduce((a, b) => a + b, 0) / lg.length);
424
  Object.values(r).forEach((t) => t.dispose?.());
425
  if (!stale()) {
 
435
  if (stale()) return;
436
  show('mesmer', 'busy', 0, 'scanning…');
437
  const { ort, sessions: S, fusion } = m, t0 = performance.now();
438
+ const pr = await gpu(() => S.pel.run({ pixels: new ort.Tensor('float32', mesmerIn.pel, [5, 3, 336, 336]) }));
439
  const pv = Array.from(pr.logit.data), pel = pv.reduce((a, b) => a + b, 0) / pv.length;
440
+ let x = new ort.Tensor('float32', mesmerIn.peg, [1, 3, 448, 448]);
441
+ const st = {};
442
  for (const [i, part] of m.man.peg.entries()) {
443
  show('mesmer', 'busy', (i + 1) / (m.man.peg.length + 1), 'scanning…');
444
+ const sess = S[part];
445
+ const o = await gpu(() => sess.run({ [sess.inputNames[0]]: x }));
446
+ for (const k of ['s25', 's38', 's50', 'pooled']) if (o[k]) st[k] = o[k].data;
 
447
  x = o.y || o.x;
 
 
448
  }
449
+ const peg = pegLogit(st.s25, st.s38, st.s50, st.pooled, m.head, m.man.peg_head.dims);
450
  const v = mesmerVerdict(pel, peg, fusion);
451
  if (!stale()) {
452
  const label = { likely_ai: ['ai', 'Likely AI'], uncertain: ['unsure', 'Uncertain'], likely_real: ['real', 'Likely real'] }[v.verdict];
 
458
  }
459
 
460
  // ---------------------------------------------------------------- input
461
+ // An error thrown inside ONNX Runtime can escape its promise; say so instead of spinning forever.
462
+ const fail = (e) => {
463
+ const msg = (e?.reason ?? e?.error ?? e)?.message || String(e?.reason ?? e?.message ?? e);
464
+ 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.`);
465
+ };
466
+ addEventListener('error', fail);
467
+ addEventListener('unhandledrejection', fail);
468
+
469
  ui.file.addEventListener('change', () => { onImage(ui.file.files[0]); ui.file.value = ''; });
470
  addEventListener('paste', (e) => {
471
  const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith('image/'));