Spaces:
Running
Running
Load the decision fine-tune (ONNX served from the Space), trained prompt format and scale, Egg check tab
Browse files- .gitattributes +2 -0
- CREDITS.md +26 -22
- README.md +65 -59
- app.js +977 -844
- examples/egg-candling-bad-1.jpg +0 -0
- examples/egg-candling-bad-104.jpg +0 -0
- examples/egg-candling-good-1.jpg +0 -0
- examples/egg-candling-good-10.jpg +0 -0
- examples/egg-test/egg-test-bad-107.jpg +0 -0
- examples/egg-test/egg-test-bad-295.jpg +0 -0
- examples/egg-test/egg-test-bad-397.jpg +0 -0
- examples/egg-test/egg-test-bad-78.jpg +0 -0
- examples/egg-test/egg-test-good-125.jpg +0 -0
- examples/egg-test/egg-test-good-235.jpg +0 -0
- examples/egg-test/egg-test-good-409.jpg +0 -0
- examples/egg-test/egg-test-good-81.jpg +0 -0
- examples/samples.json +4 -4
- index.html +45 -13
- models/egemma2-decide/chat_template.jinja +1 -0
- models/egemma2-decide/config.json +193 -0
- models/egemma2-decide/decision.json +10 -0
- models/egemma2-decide/onnx/audio_encoder_q4.onnx +3 -0
- models/egemma2-decide/onnx/audio_encoder_q4.onnx_data +3 -0
- models/egemma2-decide/onnx/audio_encoder_q4f16.onnx +3 -0
- models/egemma2-decide/onnx/audio_encoder_q4f16.onnx_data +3 -0
.gitattributes
CHANGED
|
@@ -40,3 +40,5 @@ examples/coco-relation.jpg filter=lfs diff=lfs merge=lfs -text
|
|
| 40 |
examples/rico-sca.jpg filter=lfs diff=lfs merge=lfs -text
|
| 41 |
examples/textvqa-mc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 42 |
examples/vqav2-yesno.jpg filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 40 |
examples/rico-sca.jpg filter=lfs diff=lfs merge=lfs -text
|
| 41 |
examples/textvqa-mc.jpg filter=lfs diff=lfs merge=lfs -text
|
| 42 |
examples/vqav2-yesno.jpg filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
models/egemma2-decide/onnx/audio_encoder_q4.onnx_data filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
models/egemma2-decide/onnx/audio_encoder_q4f16.onnx_data filter=lfs diff=lfs merge=lfs -text
|
CREDITS.md
CHANGED
|
@@ -1,22 +1,26 @@
|
|
| 1 |
-
# Credits for example images
|
| 2 |
-
|
| 3 |
-
- `examples/coco-count.jpg`: COCO instances_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm1.staticflickr.com/36/87658925_8500121897_z.jpg
|
| 4 |
-
- `examples/vqav2-yesno.jpg`: VQAv2 (visualqa.org) (CC BY 4.0 (annotations, VQA Consortium); image per-image Flickr license) http://farm1.staticflickr.com/36/87658925_8500121897_z.jpg
|
| 5 |
-
- `examples/coco-relation.jpg`: COCO instances_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm1.staticflickr.com/64/173587843_a38f86076d_z.jpg
|
| 6 |
-
- `examples/clevr-depth.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 7 |
-
- `examples/clevr-count.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 8 |
-
- `examples/synth-chart-reason.png`: synthetic chart generated in-house (Apache-2.0, no third-party data)
|
| 9 |
-
- `examples/cord-kie.jpg`: naver-clova-ix/cord-v2 (CC BY 4.0)
|
| 10 |
-
- `examples/rico-sca.jpg`: RICO-SCA (seq2act) re-host bevaya/RICO-SCA (Apache-2.0 (dataset card); RICO screenshots CC BY 4.0)
|
| 11 |
-
- `examples/rico-screenqa.jpg`: ScreenQA (google-research-datasets/screen_qa) on RICO, re-host bevaya/RICO-ScreenQA (CC BY 4.0 (ScreenQA annotations; RICO screenshots CC BY 4.0))
|
| 12 |
-
- `examples/textvqa-mc.jpg`: TextVQA 0.5.1 (parquet re-host lmms-lab/textvqa) (CC BY 4.0 (TextVQA annotations, per facebook/textvqa card); images Open Images (listed CC BY 2.0))
|
| 13 |
-
- `examples/aokvqa-mc.jpg`: allenai/aokvqa (Apache-2.0 (annotations); image per-image Flickr license) http://farm9.staticflickr.com/8063/8230694437_9da6316b25_z.jpg
|
| 14 |
-
- `examples/coco-capmatch.jpg`: COCO captions_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm9.staticflickr.com/8532/8562810747_4a9b068aaa_z.jpg
|
| 15 |
-
- `examples/vsr-spatial.jpg`: cambridgeltl/vsr_random (CC BY 4.0 (dataset card; code Apache-2.0); image per-image Flickr license) http://farm1.staticflickr.com/114/312142651_5b20f24075_z.jpg
|
| 16 |
-
- `examples/clevr-attr.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 17 |
-
- `examples/egg-
|
| 18 |
-
- `examples/egg-
|
| 19 |
-
- `examples/egg-
|
| 20 |
-
- `examples/egg-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Credits for example images
|
| 2 |
+
|
| 3 |
+
- `examples/coco-count.jpg`: COCO instances_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm1.staticflickr.com/36/87658925_8500121897_z.jpg
|
| 4 |
+
- `examples/vqav2-yesno.jpg`: VQAv2 (visualqa.org) (CC BY 4.0 (annotations, VQA Consortium); image per-image Flickr license) http://farm1.staticflickr.com/36/87658925_8500121897_z.jpg
|
| 5 |
+
- `examples/coco-relation.jpg`: COCO instances_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm1.staticflickr.com/64/173587843_a38f86076d_z.jpg
|
| 6 |
+
- `examples/clevr-depth.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 7 |
+
- `examples/clevr-count.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 8 |
+
- `examples/synth-chart-reason.png`: synthetic chart generated in-house (Apache-2.0, no third-party data)
|
| 9 |
+
- `examples/cord-kie.jpg`: naver-clova-ix/cord-v2 (CC BY 4.0)
|
| 10 |
+
- `examples/rico-sca.jpg`: RICO-SCA (seq2act) re-host bevaya/RICO-SCA (Apache-2.0 (dataset card); RICO screenshots CC BY 4.0)
|
| 11 |
+
- `examples/rico-screenqa.jpg`: ScreenQA (google-research-datasets/screen_qa) on RICO, re-host bevaya/RICO-ScreenQA (CC BY 4.0 (ScreenQA annotations; RICO screenshots CC BY 4.0))
|
| 12 |
+
- `examples/textvqa-mc.jpg`: TextVQA 0.5.1 (parquet re-host lmms-lab/textvqa) (CC BY 4.0 (TextVQA annotations, per facebook/textvqa card); images Open Images (listed CC BY 2.0))
|
| 13 |
+
- `examples/aokvqa-mc.jpg`: allenai/aokvqa (Apache-2.0 (annotations); image per-image Flickr license) http://farm9.staticflickr.com/8063/8230694437_9da6316b25_z.jpg
|
| 14 |
+
- `examples/coco-capmatch.jpg`: COCO captions_train2017 (CC BY 4.0 (COCO annotations); image per-image Flickr license) http://farm9.staticflickr.com/8532/8562810747_4a9b068aaa_z.jpg
|
| 15 |
+
- `examples/vsr-spatial.jpg`: cambridgeltl/vsr_random (CC BY 4.0 (dataset card; code Apache-2.0); image per-image Flickr license) http://farm1.staticflickr.com/114/312142651_5b20f24075_z.jpg
|
| 16 |
+
- `examples/clevr-attr.jpg`: CLEVR v1.0 (via allenai/Molmo2-ER-CLEVR CLEVR_v1.0.zip) (CC BY 4.0)
|
| 17 |
+
- `examples/egg-test/egg-test-good-81.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Good_Egg (81).jpg, 512 x 512 copy. Held out from training (test split).
|
| 18 |
+
- `examples/egg-test/egg-test-good-125.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Good_Egg (125).jpg, 512 x 512 copy. Held out from training (test split).
|
| 19 |
+
- `examples/egg-test/egg-test-good-409.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Good_Egg (409).jpg, 512 x 512 copy. Held out from training (test split).
|
| 20 |
+
- `examples/egg-test/egg-test-good-235.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Good_Egg (235).jpg, 512 x 512 copy. Held out from training (test split).
|
| 21 |
+
- `examples/egg-test/egg-test-bad-78.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Bad_Egg (78).jpg, 512 x 512 copy. Held out from training (test split).
|
| 22 |
+
- `examples/egg-test/egg-test-bad-107.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Bad_Egg (107).jpg, 512 x 512 copy. Held out from training (test split).
|
| 23 |
+
- `examples/egg-test/egg-test-bad-295.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Bad_Egg (295).jpg, 512 x 512 copy. Held out from training (test split).
|
| 24 |
+
- `examples/egg-test/egg-test-bad-397.jpg`: Good and Bad Eggs Identification Image Dataset, Md Mafiul Hasan Matin, Marium Jahan, Md. Saroar Jahan, Mendeley Data, doi:10.17632/mdty358x8m.1 (CC BY 4.0), file Bad_Egg (397).jpg, 512 x 512 copy. Held out from training (test split).
|
| 25 |
+
|
| 26 |
+
COCO and VQA images keep their per-image Flickr licenses (CC BY 2.0, CC BY-SA 2.0 or no known copyright restrictions only).
|
README.md
CHANGED
|
@@ -1,59 +1,65 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: Decide Live
|
| 3 |
-
emoji: 🎯
|
| 4 |
-
colorFrom: green
|
| 5 |
-
colorTo: gray
|
| 6 |
-
sdk: static
|
| 7 |
-
pinned: false
|
| 8 |
-
license: apache-2.0
|
| 9 |
-
short_description: On-device decisions from camera and microphone
|
| 10 |
-
models:
|
| 11 |
-
- google/embeddinggemma-2
|
| 12 |
-
-
|
| 13 |
-
---
|
| 14 |
-
|
| 15 |
-
# Decide Live: on-device decisions from camera and microphone
|
| 16 |
-
|
| 17 |
-
A static page that makes zero-token decisions in the browser. A multimodal embedding model,
|
| 18 |
-
[EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2) (
|
| 19 |
-
[
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
`
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Decide Live
|
| 3 |
+
emoji: 🎯
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: gray
|
| 6 |
+
sdk: static
|
| 7 |
+
pinned: false
|
| 8 |
+
license: apache-2.0
|
| 9 |
+
short_description: On-device decisions from camera and microphone
|
| 10 |
+
models:
|
| 11 |
+
- google/embeddinggemma-2
|
| 12 |
+
- FINAL-Bench/EmbeddingGemma2-ZTC-ONNX
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Decide Live: on-device decisions from camera and microphone
|
| 16 |
+
|
| 17 |
+
A static page that makes zero-token decisions in the browser. A multimodal embedding model,
|
| 18 |
+
[EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2) (Apache-2.0) fine-tuned for decisions,
|
| 19 |
+
runs locally with [transformers.js](https://github.com/huggingface/transformers.js) 4.3.1 on WebGPU,
|
| 20 |
+
or on the CPU (WASM) when WebGPU is not available (slower, and it uses the larger fp16 files).
|
| 21 |
+
|
| 22 |
+
The ONNX files (from the private model repo `FINAL-Bench/EmbeddingGemma2-ZTC-ONNX`, same file layout as
|
| 23 |
+
[onnx-community/embeddinggemma-2-ONNX](https://huggingface.co/onnx-community/embeddinggemma-2-ONNX)) are served
|
| 24 |
+
from this Space under `models/egemma2-decide/`, so the page needs no access to any other repository.
|
| 25 |
+
There is no server and no API call per decision. The weights are downloaded once and cached by the browser.
|
| 26 |
+
Camera frames, microphone audio, images and text are processed on the device and are never uploaded.
|
| 27 |
+
|
| 28 |
+
## What it does
|
| 29 |
+
|
| 30 |
+
- **Live**: embeds camera frames (or a demo feed made from the sample images) and scores up to 4 decision
|
| 31 |
+
cards. By default each card embeds the frame together with its own question, in the trained format
|
| 32 |
+
(one pass per card). The "frame alone" setting embeds the frame once for all cards (faster, not the
|
| 33 |
+
trained format). Each card shows probability bars, the current decision, and a confidence gate.
|
| 34 |
+
- **Microphone / sound file**: the same cards for 2 second sound windows (16 kHz mono). Windows
|
| 35 |
+
quieter than -55 dBFS are not sent to the model. The audio encoder is the unchanged base one.
|
| 36 |
+
- **Single input**: one image, text, audio clip or short video, a question, an optional context,
|
| 37 |
+
and 2 to 8 options written as `key: description` (or a yes / no question).
|
| 38 |
+
- **Egg check**: 8 held-out candling photos (not used in training) and your own photo, decided with
|
| 39 |
+
the trained egg prompt.
|
| 40 |
+
- **Sample tests**: 18 image tests with gold answers, run in the browser with an accuracy report,
|
| 41 |
+
plus a comparison of prompt formats.
|
| 42 |
+
|
| 43 |
+
## How a decision is computed (trained format)
|
| 44 |
+
|
| 45 |
+
1. Query: the media placeholders first, then `task: classification | query: {question}`, then
|
| 46 |
+
`\nContext: {context}` when a context is given. The model embeds media and text together.
|
| 47 |
+
2. Each option: `title: none | text: {description}`, embedded once and cached.
|
| 48 |
+
3. Embedding: mean pooling over the attention mask, then L2 normalization (768 numbers).
|
| 49 |
+
4. P(option) = softmax(scale * cosine). The scale was learned in training: 19.96
|
| 50 |
+
(temperature 1 / scale, about 0.0501), stored in `models/egemma2-decide/decision.json`.
|
| 51 |
+
|
| 52 |
+
Yes / no questions keep the question in the query and score the options `Yes` and `No`.
|
| 53 |
+
The older prompt formats of the first version of this page remain selectable for comparison.
|
| 54 |
+
|
| 55 |
+
## Files
|
| 56 |
+
|
| 57 |
+
- `index.html`, `style.css`, `app.js`: the page.
|
| 58 |
+
- `worker.js`: loads the model in a Web Worker and returns embeddings.
|
| 59 |
+
- `models/egemma2-decide/`: ONNX model (q4, q4f16 and fp16 text and vision graphs, 4-bit audio graphs),
|
| 60 |
+
config, processor and tokenizer files, and `decision.json` (scale and prompt formats).
|
| 61 |
+
- `examples/`: sample images and `samples.json` (name, files, state, type, question, options, gold);
|
| 62 |
+
`examples/egg-test/`: held-out egg candling photos.
|
| 63 |
+
- `CREDITS.md`: sources and licenses of the sample images.
|
| 64 |
+
|
| 65 |
+
Code: Apache-2.0. Model: derived from google/embeddinggemma-2 (Apache-2.0).
|
app.js
CHANGED
|
@@ -1,844 +1,977 @@
|
|
| 1 |
-
// SPDX-License-Identifier: Apache-2.0
|
| 2 |
-
// Decide Live: zero-token decisions with a multimodal embedding model running in the browser.
|
| 3 |
-
const $ = (id) => document.getElementById(id);
|
| 4 |
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
| 5 |
-
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
| 6 |
-
const params = new URLSearchParams(location.search);
|
| 7 |
-
|
| 8 |
-
/* ------------------------------------------------------------------ worker */
|
| 9 |
-
const worker = new Worker(new URL("./worker.js?v=
|
| 10 |
-
let reqId = 0;
|
| 11 |
-
const pending = new Map();
|
| 12 |
-
worker.onmessage = ({ data }) => {
|
| 13 |
-
if (data.type === "state") return onState(data);
|
| 14 |
-
const p = pending.get(data.id);
|
| 15 |
-
if (!p) return;
|
| 16 |
-
pending.delete(data.id);
|
| 17 |
-
if (data.type === "result") p.resolve(data.result);
|
| 18 |
-
else p.reject(new Error(data.message));
|
| 19 |
-
};
|
| 20 |
-
worker.onerror = (e) => setStatus("error", `Worker error: ${e.message || e}`);
|
| 21 |
-
function rpc(op, payload = {}, transfer = []) {
|
| 22 |
-
const id = ++reqId;
|
| 23 |
-
return new Promise((resolve, reject) => {
|
| 24 |
-
pending.set(id, { resolve, reject });
|
| 25 |
-
worker.postMessage({ id, op, ...payload }, transfer);
|
| 26 |
-
});
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
/* ------------------------------------------------------------------ model */
|
| 30 |
-
let model = null; // {device, dtype, audio, loadMs}
|
| 31 |
-
let loadPromise = null;
|
| 32 |
-
if (params.get("device")) $("device").value = params.get("device");
|
| 33 |
-
if (params.get("dtype")) $("dtype").value = params.get("dtype");
|
| 34 |
-
|
| 35 |
-
function setStatus(phase, text) {
|
| 36 |
-
$("status").className = `status ${phase}`;
|
| 37 |
-
$("statusText").textContent = text;
|
| 38 |
-
}
|
| 39 |
-
function onState(s) {
|
| 40 |
-
setStatus(s.phase, s.label + (s.totalBytes ? ` (${(s.loadedBytes / 1e6).toFixed(0)} / ${(s.totalBytes / 1e6).toFixed(0)} MB)` : ""));
|
| 41 |
-
if (s.phase === "loading" && typeof s.progress === "number") {
|
| 42 |
-
$("progressWrap").hidden = false;
|
| 43 |
-
$("progressBar").style.width = `${Math.max(2, Math.min(100, s.progress))}%`;
|
| 44 |
-
}
|
| 45 |
-
if (s.phase === "ready" || s.phase === "error") $("progressWrap").hidden = true;
|
| 46 |
-
}
|
| 47 |
-
async function ensureModel(audio = false) {
|
| 48 |
-
const want = { device: $("device").value, dtype: $("dtype").value, audio: audio || !!model?.audio };
|
| 49 |
-
if (model && model.requested === want.dtype && (want.device === "auto" || want.device === model.device) && (!audio || model.audio)) return model;
|
| 50 |
-
if (loadPromise) {
|
| 51 |
-
await loadPromise.catch(() => {});
|
| 52 |
-
return ensureModel(audio);
|
| 53 |
-
}
|
| 54 |
-
loadPromise = rpc("load", { options: want })
|
| 55 |
-
.then((info) => {
|
| 56 |
-
if (model && model.dtype !== info.dtype) textCache.clear();
|
| 57 |
-
model = info;
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
const
|
| 88 |
-
const
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
/
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
//
|
| 102 |
-
const
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
const
|
| 149 |
-
const
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
const
|
| 154 |
-
const
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
);
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
const
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
document.querySelectorAll(".
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
const
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
}
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
const
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
const
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
$("
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
}
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
const
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
}
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
const
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
const
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
const
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
$("
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
);
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
const
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
const
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
const
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
}
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
}
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
const
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
}
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
const
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
}
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
}
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
const
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
}
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
const
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
}
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
);
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
// Decide Live: zero-token decisions with a multimodal embedding model running in the browser.
|
| 3 |
+
const $ = (id) => document.getElementById(id);
|
| 4 |
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
| 5 |
+
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
| 6 |
+
const params = new URLSearchParams(location.search);
|
| 7 |
+
|
| 8 |
+
/* ------------------------------------------------------------------ worker */
|
| 9 |
+
const worker = new Worker(new URL("./worker.js?v=5", import.meta.url), { type: "module" });
|
| 10 |
+
let reqId = 0;
|
| 11 |
+
const pending = new Map();
|
| 12 |
+
worker.onmessage = ({ data }) => {
|
| 13 |
+
if (data.type === "state") return onState(data);
|
| 14 |
+
const p = pending.get(data.id);
|
| 15 |
+
if (!p) return;
|
| 16 |
+
pending.delete(data.id);
|
| 17 |
+
if (data.type === "result") p.resolve(data.result);
|
| 18 |
+
else p.reject(new Error(data.message));
|
| 19 |
+
};
|
| 20 |
+
worker.onerror = (e) => setStatus("error", `Worker error: ${e.message || e}`);
|
| 21 |
+
function rpc(op, payload = {}, transfer = []) {
|
| 22 |
+
const id = ++reqId;
|
| 23 |
+
return new Promise((resolve, reject) => {
|
| 24 |
+
pending.set(id, { resolve, reject });
|
| 25 |
+
worker.postMessage({ id, op, ...payload }, transfer);
|
| 26 |
+
});
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
/* ------------------------------------------------------------------ model */
|
| 30 |
+
let model = null; // {device, dtype, audio, loadMs}
|
| 31 |
+
let loadPromise = null;
|
| 32 |
+
if (params.get("device")) $("device").value = params.get("device");
|
| 33 |
+
if (params.get("dtype")) $("dtype").value = params.get("dtype");
|
| 34 |
+
|
| 35 |
+
function setStatus(phase, text) {
|
| 36 |
+
$("status").className = `status ${phase}`;
|
| 37 |
+
$("statusText").textContent = text;
|
| 38 |
+
}
|
| 39 |
+
function onState(s) {
|
| 40 |
+
setStatus(s.phase, s.label + (s.totalBytes ? ` (${(s.loadedBytes / 1e6).toFixed(0)} / ${(s.totalBytes / 1e6).toFixed(0)} MB)` : ""));
|
| 41 |
+
if (s.phase === "loading" && typeof s.progress === "number") {
|
| 42 |
+
$("progressWrap").hidden = false;
|
| 43 |
+
$("progressBar").style.width = `${Math.max(2, Math.min(100, s.progress))}%`;
|
| 44 |
+
}
|
| 45 |
+
if (s.phase === "ready" || s.phase === "error") $("progressWrap").hidden = true;
|
| 46 |
+
}
|
| 47 |
+
async function ensureModel(audio = false) {
|
| 48 |
+
const want = { device: $("device").value, dtype: $("dtype").value, audio: audio || !!model?.audio };
|
| 49 |
+
if (model && model.requested === want.dtype && (want.device === "auto" || want.device === model.device) && (!audio || model.audio)) return model;
|
| 50 |
+
if (loadPromise) {
|
| 51 |
+
await loadPromise.catch(() => {});
|
| 52 |
+
return ensureModel(audio);
|
| 53 |
+
}
|
| 54 |
+
loadPromise = rpc("load", { options: want })
|
| 55 |
+
.then((info) => {
|
| 56 |
+
if (model && model.dtype !== info.dtype) textCache.clear();
|
| 57 |
+
model = info;
|
| 58 |
+
if (info.scale) {
|
| 59 |
+
trainedScale = info.scale;
|
| 60 |
+
if (!tempTouched) setTemp(1 / trainedScale);
|
| 61 |
+
}
|
| 62 |
+
$("backend").textContent = info.device === "webgpu" ? "WebGPU" : "WASM (CPU)";
|
| 63 |
+
$("wasmNote").hidden = info.device !== "wasm";
|
| 64 |
+
return info;
|
| 65 |
+
})
|
| 66 |
+
.catch((e) => { setStatus("error", `Could not load the model: ${e.message}`); throw e; })
|
| 67 |
+
.finally(() => (loadPromise = null));
|
| 68 |
+
return loadPromise;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/* ------------------------------------------------------------------ embeddings and scoring */
|
| 72 |
+
const textCache = new Map();
|
| 73 |
+
async function embedTexts(texts) {
|
| 74 |
+
const missing = [...new Set(texts.filter((t) => !textCache.has(t)))];
|
| 75 |
+
let ms = 0;
|
| 76 |
+
if (missing.length) {
|
| 77 |
+
const r = await rpc("embedTexts", { texts: missing });
|
| 78 |
+
r.embeddings.forEach((e, i) => textCache.set(missing[i], e));
|
| 79 |
+
ms = r.ms;
|
| 80 |
+
}
|
| 81 |
+
return { embeddings: texts.map((t) => textCache.get(t)), ms, fresh: missing.length };
|
| 82 |
+
}
|
| 83 |
+
const dot = (a, b) => { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; };
|
| 84 |
+
function softmax(xs, T) {
|
| 85 |
+
const z = xs.map((x) => x / T);
|
| 86 |
+
const m = Math.max(...z);
|
| 87 |
+
const e = z.map((x) => Math.exp(x - m));
|
| 88 |
+
const s = e.reduce((a, b) => a + b, 0);
|
| 89 |
+
return e.map((x) => x / s);
|
| 90 |
+
}
|
| 91 |
+
const argmax = (xs) => xs.reduce((bi, x, i) => (x > xs[bi] ? i : bi), 0);
|
| 92 |
+
// The model was trained with P(option) = softmax(scale * cos); the learned scale ships with the model
|
| 93 |
+
// (decision.json). The default temperature is 1 / scale.
|
| 94 |
+
let trainedScale = 19.9607;
|
| 95 |
+
let tempTouched = false;
|
| 96 |
+
function setTemp(t) {
|
| 97 |
+
$("temp").value = t.toFixed(4);
|
| 98 |
+
$("tempVal").textContent = `${(+$("temp").value).toFixed(4)}${Math.abs(t - 1 / trainedScale) < 5e-5 ? ` (trained: 1 / ${trainedScale.toFixed(2)})` : ""}`;
|
| 99 |
+
}
|
| 100 |
+
const temperature = () => parseFloat($("temp").value);
|
| 101 |
+
// Image tokens for single inputs and sample tests: model default 280 on WebGPU, 70 on the much slower CPU path.
|
| 102 |
+
const imageBudget = () => ($("budgetSingle").value === "auto" ? (model?.device === "wasm" ? 70 : 280) : +$("budgetSingle").value);
|
| 103 |
+
|
| 104 |
+
/* ------------------------------------------------------------------ prompts */
|
| 105 |
+
const DOC = (d) => `title: none | text: ${d}`;
|
| 106 |
+
const PH = { image: "<|image|>", rgba: "<|image|>", audio: "<|audio|>", video: "<|video|>" };
|
| 107 |
+
// Trained format: media placeholders first, then "task: classification | query: {question}" and
|
| 108 |
+
// "\nContext: {context}" when there is one (a context of exactly "See the image." is left out, as in training).
|
| 109 |
+
function trainedQuery(kind, question, context, extraText = "") {
|
| 110 |
+
const ctx = [context === "See the image." ? "" : context, extraText].filter(Boolean).join("\n");
|
| 111 |
+
return (PH[kind] || "") + `task: classification | query: ${question}` + (ctx ? `\nContext: ${ctx}` : "");
|
| 112 |
+
}
|
| 113 |
+
const PRESETS = {
|
| 114 |
+
trained: { label: "Trained decision format (default)", trained: true, opt: DOC },
|
| 115 |
+
cls: { label: "Classification query (input + question) and document options", interleave: true, q: "task: classification | query: ", opt: DOC },
|
| 116 |
+
qa: { label: "Question answering query (input + question) and document options", interleave: true, q: "task: question answering | query: ", opt: DOC },
|
| 117 |
+
sym: { label: "Classification prefix on both sides (symmetric)", interleave: true, q: "task: classification | query: ", opt: (d) => `task: classification | query: ${d}` },
|
| 118 |
+
xsearch: { label: "Media alone; question + option as a search query", interleave: false, q: "task: classification | query: ", opt: (d) => `task: search result | query: ${d}` },
|
| 119 |
+
xdoc: { label: "Media alone; question + option as a document", interleave: false, q: "task: classification | query: ", opt: DOC },
|
| 120 |
+
};
|
| 121 |
+
// Live cards: the frame is embedded once with no text (media takes no prefix), options are self-describing.
|
| 122 |
+
const LIVE_OPT = (d) => `task: search result | query: ${d}`;
|
| 123 |
+
for (const [k, p] of Object.entries(PRESETS)) $("preset").insertAdjacentHTML("beforeend", `<option value="${k}">${esc(p.label)}</option>`);
|
| 124 |
+
$("promptDoc").innerHTML =
|
| 125 |
+
`<p>Single input, sample tests and the egg check (the format is selectable under Single input > Settings):</p><ul>` +
|
| 126 |
+
Object.values(PRESETS)
|
| 127 |
+
.map((p) => `<li>${esc(p.label)}: input <code>${p.trained ? esc("<media>task: classification | query: {question}") + "<br>" + esc("Context: {context}") : p.interleave ? esc(p.q) + "{context} {question} <media>" : "<media> (no text)"}</code>, option <code>${esc(p.opt(p.interleave || p.trained ? "{description}" : "{question} {description}"))}</code>${p.trained ? ". Yes / no questions use the options <code>Yes</code> and <code>No</code>." : ""}</li>`)
|
| 128 |
+
.join("") +
|
| 129 |
+
`</ul><p>Live cards: by default each card embeds the frame with its own question in the trained format (one pass per card). The alternative embeds the frame or sound window alone, once for all cards, and each option as <code>${esc(LIVE_OPT("{description}"))}</code>.</p>`;
|
| 130 |
+
|
| 131 |
+
function parseOptions(text) {
|
| 132 |
+
return text
|
| 133 |
+
.split(/\r?\n/)
|
| 134 |
+
.map((l) => l.trim())
|
| 135 |
+
.filter(Boolean)
|
| 136 |
+
.map((l) => {
|
| 137 |
+
const i = l.indexOf(":");
|
| 138 |
+
let key = i > 0 ? l.slice(0, i).trim() : l;
|
| 139 |
+
let desc = i > 0 ? l.slice(i + 1).trim() : l;
|
| 140 |
+
if (!desc || desc.toLowerCase() === "null") desc = key.replace(/_/g, " ");
|
| 141 |
+
return { key, desc };
|
| 142 |
+
});
|
| 143 |
+
}
|
| 144 |
+
// Trained format for yes / no questions: the question stays in the query, the options are just "Yes" and "No".
|
| 145 |
+
const TRAINED_YES_NO = [{ key: "yes", desc: "Yes" }, { key: "no", desc: "No" }];
|
| 146 |
+
function yesNoOptions(statement) {
|
| 147 |
+
const s = statement.trim();
|
| 148 |
+
const quoted = s.match(/["“]([^"”]+)["”]/);
|
| 149 |
+
const base = quoted ? quoted[1].trim() : s;
|
| 150 |
+
if (!quoted && /\?\s*$/.test(base)) {
|
| 151 |
+
return [{ key: "yes", desc: `${base} Yes.`, full: true }, { key: "no", desc: `${base} No.`, full: true }];
|
| 152 |
+
}
|
| 153 |
+
const stmt = base.replace(/[.!]\s*$/, "");
|
| 154 |
+
const lower = stmt.charAt(0).toLowerCase() + stmt.slice(1);
|
| 155 |
+
return [{ key: "yes", desc: `${stmt}.`, full: true }, { key: "no", desc: `It is not true that ${lower}.`, full: true }];
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
// input: {kind:'image'|'text'|'audio'|'video', blob?, text?, audio?, frames?, duration?}
|
| 159 |
+
async function decideCore(input, context, question, options, presetKey, T) {
|
| 160 |
+
const P = PRESETS[presetKey] || PRESETS.trained;
|
| 161 |
+
const qctx = [context, question].filter(Boolean).join(" ");
|
| 162 |
+
let queryText, optTexts;
|
| 163 |
+
if (P.trained) {
|
| 164 |
+
queryText = trainedQuery(input.kind, question, context, input.kind === "text" ? input.text : "");
|
| 165 |
+
optTexts = options.map((o) => P.opt(o.desc));
|
| 166 |
+
} else if (P.interleave) {
|
| 167 |
+
queryText = P.q + qctx + (input.kind === "text" ? `\n${input.text}` : "") + (PH[input.kind] ? ` ${PH[input.kind]}` : "");
|
| 168 |
+
optTexts = options.map((o) => P.opt(o.desc));
|
| 169 |
+
} else {
|
| 170 |
+
queryText = input.kind === "text" ? P.q + input.text : "";
|
| 171 |
+
optTexts = options.map((o) => P.opt(o.full || !question ? o.desc : `${question} ${o.desc}`));
|
| 172 |
+
}
|
| 173 |
+
const t0 = performance.now();
|
| 174 |
+
const opt = await embedTexts(optTexts);
|
| 175 |
+
const transfer = [];
|
| 176 |
+
const payload = { ...input, text: queryText, budget: imageBudget() };
|
| 177 |
+
if (input.kind === "audio") { payload.audio = input.audio.slice(); transfer.push(payload.audio.buffer); }
|
| 178 |
+
const r = await rpc("embedInput", { input: payload }, transfer);
|
| 179 |
+
const cos = opt.embeddings.map((e) => dot(r.embedding, e));
|
| 180 |
+
const probs = softmax(cos, T);
|
| 181 |
+
return { cos, probs, top: argmax(probs), inputMs: r.ms, optMs: opt.ms, totalMs: performance.now() - t0, queryText, optTexts };
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
/* ------------------------------------------------------------------ tabs */
|
| 185 |
+
document.querySelectorAll(".tab").forEach((b) =>
|
| 186 |
+
b.addEventListener("click", () => {
|
| 187 |
+
document.querySelectorAll(".tab").forEach((x) => x.classList.toggle("active", x === b));
|
| 188 |
+
document.querySelectorAll(".view").forEach((v) => (v.hidden = v.dataset.view !== b.dataset.tab));
|
| 189 |
+
})
|
| 190 |
+
);
|
| 191 |
+
|
| 192 |
+
/* ------------------------------------------------------------------ samples */
|
| 193 |
+
let SAMPLES = [];
|
| 194 |
+
let demoFiles = [];
|
| 195 |
+
const blobCache = new Map();
|
| 196 |
+
async function fetchBlob(path) {
|
| 197 |
+
if (!blobCache.has(path)) blobCache.set(path, fetch(path).then((r) => { if (!r.ok) throw new Error(`${path}: ${r.status}`); return r.blob(); }));
|
| 198 |
+
return blobCache.get(path);
|
| 199 |
+
}
|
| 200 |
+
const samplesReady = fetch("examples/samples.json")
|
| 201 |
+
.then((r) => r.json())
|
| 202 |
+
.then((list) => {
|
| 203 |
+
SAMPLES = list;
|
| 204 |
+
list.forEach((s, i) => $("sampleSelect").insertAdjacentHTML("beforeend", `<option value="${i}">${i + 1}. ${esc(s.name)}</option>`));
|
| 205 |
+
demoFiles = [...new Set(list.flatMap((s) => s.files))];
|
| 206 |
+
return list;
|
| 207 |
+
})
|
| 208 |
+
.catch((e) => console.warn("samples.json", e));
|
| 209 |
+
|
| 210 |
+
/* ------------------------------------------------------------------ single input */
|
| 211 |
+
let kind = "image";
|
| 212 |
+
let imageBlob = null, audioData = null, videoData = null;
|
| 213 |
+
document.querySelectorAll(".subtab").forEach((b) =>
|
| 214 |
+
b.addEventListener("click", () => {
|
| 215 |
+
kind = b.dataset.kind;
|
| 216 |
+
document.querySelectorAll(".subtab").forEach((x) => x.classList.toggle("active", x === b));
|
| 217 |
+
document.querySelectorAll(".pane").forEach((p) => (p.hidden = p.dataset.pane !== kind));
|
| 218 |
+
})
|
| 219 |
+
);
|
| 220 |
+
const modeVal = () => document.querySelector('input[name="mode"]:checked').value;
|
| 221 |
+
document.querySelectorAll('input[name="mode"]').forEach((r) =>
|
| 222 |
+
r.addEventListener("change", () => {
|
| 223 |
+
const yn = modeVal() === "yesno";
|
| 224 |
+
$("optionsWrap").hidden = yn;
|
| 225 |
+
$("yesnoNote").hidden = !yn;
|
| 226 |
+
$("questionLabel").textContent = yn ? "Statement (or a yes / no question)" : "Question";
|
| 227 |
+
})
|
| 228 |
+
);
|
| 229 |
+
$("temp").addEventListener("input", () => { tempTouched = true; setTemp(+$("temp").value); });
|
| 230 |
+
$("resetTemp").addEventListener("click", () => { tempTouched = false; setTemp(1 / trainedScale); });
|
| 231 |
+
setTemp(1 / trainedScale);
|
| 232 |
+
function showImage(blob) {
|
| 233 |
+
imageBlob = blob;
|
| 234 |
+
const img = $("imagePreview");
|
| 235 |
+
if (img.src) URL.revokeObjectURL(img.src);
|
| 236 |
+
img.src = URL.createObjectURL(blob);
|
| 237 |
+
img.hidden = false;
|
| 238 |
+
}
|
| 239 |
+
$("imageFile").addEventListener("change", (e) => { const f = e.target.files[0]; if (f) { showImage(f); $("sampleSelect").value = ""; } });
|
| 240 |
+
$("sampleSelect").addEventListener("change", async (e) => {
|
| 241 |
+
const s = SAMPLES[+e.target.value];
|
| 242 |
+
if (!s) return;
|
| 243 |
+
showImage(await fetchBlob(s.files[0]));
|
| 244 |
+
$("contextInput").value = s.state || "";
|
| 245 |
+
$("questionInput").value = s.question;
|
| 246 |
+
const yn = s.type === "noul";
|
| 247 |
+
document.querySelector(`input[name="mode"][value="${yn ? "yesno" : "choice"}"]`).checked = true;
|
| 248 |
+
document.querySelector('input[name="mode"]:checked').dispatchEvent(new Event("change"));
|
| 249 |
+
$("optionsInput").value = s.options;
|
| 250 |
+
});
|
| 251 |
+
|
| 252 |
+
async function decodeAudio(blob, maxSec = 60) {
|
| 253 |
+
const buf = await new OfflineAudioContext(1, 1, 16000).decodeAudioData(await blob.arrayBuffer());
|
| 254 |
+
if (buf.duration > maxSec) throw new Error(`Audio is longer than ${maxSec} s.`);
|
| 255 |
+
const out = new Float32Array(buf.length);
|
| 256 |
+
for (let c = 0; c < buf.numberOfChannels; c++) { const d = buf.getChannelData(c); for (let i = 0; i < out.length; i++) out[i] += d[i] / buf.numberOfChannels; }
|
| 257 |
+
return out;
|
| 258 |
+
}
|
| 259 |
+
$("audioFile").addEventListener("change", async (e) => {
|
| 260 |
+
const f = e.target.files[0];
|
| 261 |
+
if (!f) return;
|
| 262 |
+
$("audioPreview").src = URL.createObjectURL(f);
|
| 263 |
+
$("audioPreview").hidden = false;
|
| 264 |
+
try { audioData = await decodeAudio(f); } catch (err) { alert(err.message); }
|
| 265 |
+
});
|
| 266 |
+
async function sampleVideoFrames(blob, maxFrames = 16, maxSide = 448) {
|
| 267 |
+
const v = document.createElement("video");
|
| 268 |
+
v.muted = true; v.preload = "auto"; v.playsInline = true;
|
| 269 |
+
v.src = URL.createObjectURL(blob);
|
| 270 |
+
const wait = (ev) => new Promise((res, rej) => { v.addEventListener(ev, res, { once: true }); v.addEventListener("error", () => rej(new Error("Could not decode this video.")), { once: true }); });
|
| 271 |
+
await wait("loadeddata");
|
| 272 |
+
const dur = v.duration;
|
| 273 |
+
const n = Math.min(maxFrames, Math.max(1, Math.ceil(dur)));
|
| 274 |
+
const sc = Math.min(1, maxSide / Math.max(v.videoWidth, v.videoHeight));
|
| 275 |
+
const cv = document.createElement("canvas");
|
| 276 |
+
cv.width = Math.round(v.videoWidth * sc); cv.height = Math.round(v.videoHeight * sc);
|
| 277 |
+
const g = cv.getContext("2d", { willReadFrequently: true });
|
| 278 |
+
const frames = [];
|
| 279 |
+
for (let i = 0; i < n; i++) {
|
| 280 |
+
const t = n === 1 ? dur / 2 : (i / (n - 1)) * Math.max(0, dur - 0.05);
|
| 281 |
+
v.currentTime = t; await wait("seeked");
|
| 282 |
+
g.drawImage(v, 0, 0, cv.width, cv.height);
|
| 283 |
+
frames.push({ data: g.getImageData(0, 0, cv.width, cv.height).data.buffer, width: cv.width, height: cv.height, timestamp: t });
|
| 284 |
+
}
|
| 285 |
+
URL.revokeObjectURL(v.src);
|
| 286 |
+
return { frames, duration: dur };
|
| 287 |
+
}
|
| 288 |
+
$("videoFile").addEventListener("change", async (e) => {
|
| 289 |
+
const f = e.target.files[0];
|
| 290 |
+
if (!f) return;
|
| 291 |
+
$("videoPreview").src = URL.createObjectURL(f);
|
| 292 |
+
$("videoPreview").hidden = false;
|
| 293 |
+
try { videoData = await sampleVideoFrames(f); } catch (err) { alert(err.message); }
|
| 294 |
+
});
|
| 295 |
+
|
| 296 |
+
function renderResult(r, options, extra = "") {
|
| 297 |
+
const top = options[r.top];
|
| 298 |
+
const bars = options
|
| 299 |
+
.map((o, i) => `<div class="obar ${i === r.top ? "top" : ""}"><span class="k" title="${esc(o.desc)}">${esc(o.key)}</span><span class="track"><span class="fill" style="width:${(r.probs[i] * 100).toFixed(1)}%"></span></span><span class="p">${(r.probs[i] * 100).toFixed(1)}%</span></div>`)
|
| 300 |
+
.join("");
|
| 301 |
+
$("result").innerHTML =
|
| 302 |
+
`<p class="decision">Decision: <b>${esc(top.key)}</b> <span class="note">(${(r.probs[r.top] * 100).toFixed(1)}%)</span></p>` +
|
| 303 |
+
`<div class="bars">${bars}</div>` +
|
| 304 |
+
`<p class="meta">Total ${r.totalMs.toFixed(0)} ms: input embedding ${r.inputMs.toFixed(0)} ms, option embeddings ${r.optMs ? r.optMs.toFixed(0) + " ms" : "cached"}. Backend ${esc(model?.device || "?")}, ${esc(model?.dtype || "")}, temperature ${temperature()}. ${extra}</p>` +
|
| 305 |
+
`<details class="prompts"><summary>Prompts sent to the model</summary><pre>input: ${esc(r.queryText || "(media only, no text)")}${["image", "audio", "video"].includes(r.kind) ? " + " + r.kind : ""}\n${r.optTexts.map((t, i) => `option ${options[i].key}: ${esc(t)} (cos ${r.cos[i].toFixed(4)})`).join("\n")}</pre></details>`;
|
| 306 |
+
$("resultCard").hidden = false;
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
$("decideBtn").addEventListener("click", async () => {
|
| 310 |
+
const btn = $("decideBtn");
|
| 311 |
+
btn.disabled = true;
|
| 312 |
+
try {
|
| 313 |
+
const question = $("questionInput").value.trim();
|
| 314 |
+
const context = $("contextInput").value.trim();
|
| 315 |
+
const trained = !!PRESETS[$("preset").value]?.trained;
|
| 316 |
+
let options = modeVal() === "yesno" ? (trained ? TRAINED_YES_NO : yesNoOptions(question)) : parseOptions($("optionsInput").value);
|
| 317 |
+
if (modeVal() === "yesno" && !question) throw new Error("Write a statement or a yes / no question.");
|
| 318 |
+
if (options.length < 2 || options.length > 8) throw new Error("Write 2 to 8 options, one per line.");
|
| 319 |
+
let input;
|
| 320 |
+
if (kind === "image") { if (!imageBlob) throw new Error("Choose a sample or upload an image."); input = { kind, blob: imageBlob }; }
|
| 321 |
+
else if (kind === "text") { const t = $("textInput").value.trim(); if (!t) throw new Error("Enter some text."); input = { kind, text: t }; }
|
| 322 |
+
else if (kind === "audio") { if (!audioData) throw new Error("Upload an audio clip."); input = { kind, audio: audioData }; }
|
| 323 |
+
else { if (!videoData) throw new Error("Upload a video."); input = { kind, frames: videoData.frames.map((f) => ({ ...f, data: f.data.slice(0) })), duration: videoData.duration }; }
|
| 324 |
+
btn.textContent = "Loading model...";
|
| 325 |
+
await ensureModel(kind === "audio");
|
| 326 |
+
btn.textContent = "Deciding...";
|
| 327 |
+
const r = await decideCore(input, context, question, options, $("preset").value, temperature());
|
| 328 |
+
r.kind = kind;
|
| 329 |
+
renderResult(r, options);
|
| 330 |
+
} catch (e) {
|
| 331 |
+
$("result").innerHTML = `<p class="warn">${esc(e.message)}</p>`;
|
| 332 |
+
$("resultCard").hidden = false;
|
| 333 |
+
} finally {
|
| 334 |
+
btn.disabled = false;
|
| 335 |
+
btn.textContent = "Decide";
|
| 336 |
+
}
|
| 337 |
+
});
|
| 338 |
+
|
| 339 |
+
/* ------------------------------------------------------------------ run all samples */
|
| 340 |
+
async function runSample(s, presetKey, T) {
|
| 341 |
+
const blob = await fetchBlob(s.files[0]);
|
| 342 |
+
const yn = s.type === "noul";
|
| 343 |
+
const trained = !!PRESETS[presetKey]?.trained;
|
| 344 |
+
const options = yn ? (trained ? TRAINED_YES_NO : yesNoOptions(s.question)) : parseOptions(s.options);
|
| 345 |
+
let gold = s.gold;
|
| 346 |
+
if (yn) gold = { true: "yes", false: "no" }[String(s.gold).toLowerCase()] ?? s.gold;
|
| 347 |
+
// in the older formats the yes / no options already contain the question
|
| 348 |
+
const r = await decideCore({ kind: "image", blob }, s.state || "", yn && !trained ? "" : s.question, options, presetKey, T);
|
| 349 |
+
return { pred: options[r.top].key, p: r.probs[r.top], gold, ok: options[r.top].key === gold, ms: r.totalMs, r };
|
| 350 |
+
}
|
| 351 |
+
async function runAll(presetKey, { table = true } = {}) {
|
| 352 |
+
await samplesReady;
|
| 353 |
+
await ensureModel(false);
|
| 354 |
+
const T = temperature();
|
| 355 |
+
const tbody = $("runAllTable").querySelector("tbody");
|
| 356 |
+
if (table) { tbody.innerHTML = ""; $("runAllTable").hidden = false; }
|
| 357 |
+
let correct = 0, msSum = 0;
|
| 358 |
+
const rows = [];
|
| 359 |
+
const t0 = performance.now();
|
| 360 |
+
for (let i = 0; i < SAMPLES.length; i++) {
|
| 361 |
+
const s = SAMPLES[i];
|
| 362 |
+
$("runAllSummary").innerHTML = `Running ${i + 1} / ${SAMPLES.length} (${esc(PRESETS[presetKey].label)})...`;
|
| 363 |
+
const x = await runSample(s, presetKey, T);
|
| 364 |
+
correct += x.ok ? 1 : 0;
|
| 365 |
+
msSum += x.ms;
|
| 366 |
+
rows.push({ name: s.name, type: s.type, ...x, r: undefined });
|
| 367 |
+
if (table) tbody.insertAdjacentHTML("beforeend", `<tr><td>${i + 1}</td><td>${esc(s.name)}</td><td>${esc(s.type)}</td><td>${esc(x.gold)}</td><td>${esc(x.pred)}</td><td>${(x.p * 100).toFixed(1)}%</td><td class="${x.ok ? "ok" : "no"}">${x.ok ? "yes" : "no"}</td><td>${x.ms.toFixed(0)}</td></tr>`);
|
| 368 |
+
}
|
| 369 |
+
const wall = performance.now() - t0;
|
| 370 |
+
return { presetKey, correct, n: SAMPLES.length, meanMs: msSum / SAMPLES.length, wallMs: wall, rows, device: model.device, dtype: model.dtype, T, budget: imageBudget() };
|
| 371 |
+
}
|
| 372 |
+
const summaryHtml = (res) =>
|
| 373 |
+
`Accuracy <b>${res.correct} / ${res.n}</b> (${((100 * res.correct) / res.n).toFixed(1)}%). Mean ${res.meanMs.toFixed(0)} ms per test, ${(res.wallMs / 1000).toFixed(1)} s in total, on ${res.device === "webgpu" ? "WebGPU" : "WASM (CPU)"} (${res.dtype}), ${res.budget} image tokens, temperature ${res.T}, prompt format: ${esc(PRESETS[res.presetKey].label)}. Chance level is about ${(SAMPLES.reduce((a, s) => a + 1 / (s.type === "noul" ? 2 : parseOptions(s.options).length), 0)).toFixed(1)} / ${res.n}.`;
|
| 374 |
+
window.lastRuns = [];
|
| 375 |
+
$("runAllBtn").addEventListener("click", async () => {
|
| 376 |
+
$("runAllBtn").disabled = $("compareBtn").disabled = true;
|
| 377 |
+
try {
|
| 378 |
+
const res = await runAll($("preset").value);
|
| 379 |
+
window.lastRuns.push(res);
|
| 380 |
+
$("runAllSummary").innerHTML = summaryHtml(res);
|
| 381 |
+
} catch (e) {
|
| 382 |
+
$("runAllSummary").innerHTML = `<span class="warn">${esc(e.message)}</span>`;
|
| 383 |
+
} finally {
|
| 384 |
+
$("runAllBtn").disabled = $("compareBtn").disabled = false;
|
| 385 |
+
}
|
| 386 |
+
});
|
| 387 |
+
$("compareBtn").addEventListener("click", async () => {
|
| 388 |
+
$("runAllBtn").disabled = $("compareBtn").disabled = true;
|
| 389 |
+
const tb = $("compareTable").querySelector("tbody");
|
| 390 |
+
tb.innerHTML = "";
|
| 391 |
+
$("compareTable").hidden = false;
|
| 392 |
+
try {
|
| 393 |
+
for (const k of Object.keys(PRESETS)) {
|
| 394 |
+
const res = await runAll(k, { table: false });
|
| 395 |
+
window.lastRuns.push(res);
|
| 396 |
+
tb.insertAdjacentHTML("beforeend", `<tr><td>${esc(PRESETS[k].label)}</td><td>${res.correct} / ${res.n}</td><td>${res.meanMs.toFixed(0)}</td></tr>`);
|
| 397 |
+
}
|
| 398 |
+
$("runAllSummary").innerHTML = `Compared ${Object.keys(PRESETS).length} prompt formats on ${model.device === "webgpu" ? "WebGPU" : "WASM (CPU)"}, temperature ${temperature()}.`;
|
| 399 |
+
} catch (e) {
|
| 400 |
+
$("runAllSummary").innerHTML = `<span class="warn">${esc(e.message)}</span>`;
|
| 401 |
+
} finally {
|
| 402 |
+
$("runAllBtn").disabled = $("compareBtn").disabled = false;
|
| 403 |
+
}
|
| 404 |
+
});
|
| 405 |
+
|
| 406 |
+
/* ------------------------------------------------------------------ egg check */
|
| 407 |
+
const EGG = {
|
| 408 |
+
question: "Is this egg good or bad?",
|
| 409 |
+
context: "Candling photo: a light is shone through the egg in a dark room.",
|
| 410 |
+
options: [{ key: "good", desc: "Normal, healthy egg" }, { key: "bad", desc: "Defective, spoiled or damaged egg" }],
|
| 411 |
+
};
|
| 412 |
+
// Held-out photos (egg test split, first 4 good and first 4 bad in file order; not picked by result)
|
| 413 |
+
const EGG_PHOTOS = ["good-81", "good-125", "good-409", "good-235", "bad-78", "bad-107", "bad-295", "bad-397"].map((n) => ({
|
| 414 |
+
file: `examples/egg-test/egg-test-${n}.jpg`, gold: n.split("-")[0], label: `${n.split("-")[0]} egg #${n.split("-")[1]}`,
|
| 415 |
+
}));
|
| 416 |
+
$("eggGrid").innerHTML = EGG_PHOTOS.map((p, i) => `<button class="eggthumb" data-i="${i}" title="Decide on this photo"><img src="${p.file}" alt="${esc(p.label)}" loading="lazy" /><span>gold: ${esc(p.gold)}</span></button>`).join("");
|
| 417 |
+
async function eggDecide(blob) {
|
| 418 |
+
await ensureModel(false);
|
| 419 |
+
const presetKey = PRESETS[$("preset").value] ? $("preset").value : "trained";
|
| 420 |
+
return decideCore({ kind: "image", blob }, EGG.context, EGG.question, EGG.options, presetKey, temperature());
|
| 421 |
+
}
|
| 422 |
+
function eggShow(blob, r, gold) {
|
| 423 |
+
const img = $("eggPreview");
|
| 424 |
+
if (img.src) URL.revokeObjectURL(img.src);
|
| 425 |
+
img.src = URL.createObjectURL(blob);
|
| 426 |
+
const pred = EGG.options[r.top].key;
|
| 427 |
+
const bars = EGG.options
|
| 428 |
+
.map((o, i) => `<div class="obar ${i === r.top ? "top" : ""}"><span class="k" title="${esc(o.desc)}">${esc(o.key)}</span><span class="track"><span class="fill" style="width:${(r.probs[i] * 100).toFixed(1)}%"></span></span><span class="p">${(r.probs[i] * 100).toFixed(1)}%</span></div>`)
|
| 429 |
+
.join("");
|
| 430 |
+
$("eggOut").innerHTML =
|
| 431 |
+
`<p class="decision">Decision: <b>${esc(pred)}</b> <span class="note">(${(r.probs[r.top] * 100).toFixed(1)}%)</span>${gold ? ` <span class="${pred === gold ? "okc" : "noc"}">gold: ${esc(gold)}, ${pred === gold ? "correct" : "wrong"}</span>` : ""}</p>` +
|
| 432 |
+
`<div class="bars">${bars}</div>` +
|
| 433 |
+
`<p class="meta">${r.totalMs.toFixed(0)} ms (input ${r.inputMs.toFixed(0)} ms, options ${r.optMs ? r.optMs.toFixed(0) + " ms" : "cached"}). ${esc(model?.device || "?")}, ${esc(model?.dtype || "")}, ${imageBudget()} image tokens, temperature ${temperature().toFixed(4)}.</p>` +
|
| 434 |
+
`<details class="prompts"><summary>Prompts sent to the model</summary><pre>input: ${esc(r.queryText)} + image\n${r.optTexts.map((t, i) => `option ${EGG.options[i].key}: ${esc(t)} (cos ${r.cos[i].toFixed(4)})`).join("\n")}</pre></details>`;
|
| 435 |
+
$("eggResult").hidden = false;
|
| 436 |
+
}
|
| 437 |
+
async function eggBusy(fn) {
|
| 438 |
+
const btns = [$("eggRunAll"), ...document.querySelectorAll(".eggthumb")];
|
| 439 |
+
btns.forEach((b) => (b.disabled = true));
|
| 440 |
+
try { await fn(); } catch (e) { $("eggSummary").innerHTML = `<span class="warn">${esc(e.message)}</span>`; }
|
| 441 |
+
finally { btns.forEach((b) => (b.disabled = false)); }
|
| 442 |
+
}
|
| 443 |
+
$("eggGrid").querySelectorAll(".eggthumb").forEach((b) =>
|
| 444 |
+
b.addEventListener("click", () => eggBusy(async () => {
|
| 445 |
+
const p = EGG_PHOTOS[+b.dataset.i];
|
| 446 |
+
$("eggSummary").textContent = model ? "Deciding..." : "Loading the model...";
|
| 447 |
+
const blob = await fetchBlob(p.file);
|
| 448 |
+
const r = await eggDecide(blob);
|
| 449 |
+
eggShow(blob, r, p.gold);
|
| 450 |
+
$("eggSummary").textContent = "";
|
| 451 |
+
}))
|
| 452 |
+
);
|
| 453 |
+
$("eggFile").addEventListener("change", (e) => eggBusy(async () => {
|
| 454 |
+
const f = e.target.files[0];
|
| 455 |
+
if (!f) return;
|
| 456 |
+
$("eggSummary").textContent = model ? "Deciding..." : "Loading the model...";
|
| 457 |
+
const r = await eggDecide(f);
|
| 458 |
+
eggShow(f, r, null);
|
| 459 |
+
$("eggSummary").textContent = "";
|
| 460 |
+
}));
|
| 461 |
+
async function eggRunAll() {
|
| 462 |
+
const tb = $("eggTable").querySelector("tbody");
|
| 463 |
+
tb.innerHTML = "";
|
| 464 |
+
$("eggTable").hidden = false;
|
| 465 |
+
let ok = 0, ms = 0;
|
| 466 |
+
const rows = [];
|
| 467 |
+
for (let i = 0; i < EGG_PHOTOS.length; i++) {
|
| 468 |
+
const p = EGG_PHOTOS[i];
|
| 469 |
+
$("eggSummary").textContent = model ? `Checking ${i + 1} / ${EGG_PHOTOS.length}...` : "Loading the model...";
|
| 470 |
+
const blob = await fetchBlob(p.file);
|
| 471 |
+
const r = await eggDecide(blob);
|
| 472 |
+
const pred = EGG.options[r.top].key;
|
| 473 |
+
ok += pred === p.gold ? 1 : 0;
|
| 474 |
+
ms += r.totalMs;
|
| 475 |
+
rows.push({ file: p.file, gold: p.gold, pred, probs: r.probs, cos: r.cos, ms: r.totalMs });
|
| 476 |
+
tb.insertAdjacentHTML("beforeend", `<tr><td><img class="mini" src="${p.file}" alt="" /> ${esc(p.label)}</td><td>${esc(p.gold)}</td><td>${esc(pred)}</td><td>${(r.probs[0] * 100).toFixed(1)}%</td><td>${(r.probs[1] * 100).toFixed(1)}%</td><td class="${pred === p.gold ? "ok" : "no"}">${pred === p.gold ? "yes" : "no"}</td><td>${r.totalMs.toFixed(0)}</td></tr>`);
|
| 477 |
+
}
|
| 478 |
+
$("eggSummary").innerHTML = `Accuracy <b>${ok} / ${EGG_PHOTOS.length}</b>. Mean ${(ms / EGG_PHOTOS.length).toFixed(0)} ms per photo on ${model.device === "webgpu" ? "WebGPU" : "WASM (CPU)"} (${esc(model.dtype)}), ${imageBudget()} image tokens.`;
|
| 479 |
+
const res = { ok, n: EGG_PHOTOS.length, meanMs: ms / EGG_PHOTOS.length, device: model.device, dtype: model.dtype, budget: imageBudget(), rows };
|
| 480 |
+
window.lastEgg = res;
|
| 481 |
+
return res;
|
| 482 |
+
}
|
| 483 |
+
$("eggRunAll").addEventListener("click", () => eggBusy(eggRunAll));
|
| 484 |
+
|
| 485 |
+
/* ------------------------------------------------------------------ live decision cards */
|
| 486 |
+
const VISION_TEMPLATES = [
|
| 487 |
+
{ title: "What kind of scene is this?", options: "animals: wild animals such as giraffes or elephants\nstreet: a city street with vehicles and buildings\npeople: people outdoors, walking or playing\nreceipt: a paper receipt or printed document\napp: a screenshot of a mobile phone app\nchart: a chart or data plot\nshapes: a 3D render of simple geometric objects\negg: an egg lit from behind in the dark" },
|
| 488 |
+
{ title: "Is a person in view?", options: "yes: a photo with a person or people in it\nno: a photo with no people, only objects, animals or graphics" },
|
| 489 |
+
{ title: "Is this egg good or bad?", context: "Candling photo: a light is shone through the egg in a dark room.", options: "good: Normal, healthy egg\nbad: Defective, spoiled or damaged egg" },
|
| 490 |
+
{ title: "What is the person holding?", options: "phone: a person holding a mobile phone\ncup: a person holding a cup or mug\nbook: a person holding a book or paper\nnothing: a person with empty hands" },
|
| 491 |
+
{ title: "Which hand gesture is shown?", options: "thumbs_up: a hand giving a thumbs up\nopen_palm: an open palm facing the camera\npeace: a hand making a peace sign\nno_hand: no hand visible" },
|
| 492 |
+
{ title: "What is the facial expression?", options: "smiling: a smiling face\nneutral: a neutral, calm face\nsurprised: a surprised face with open mouth" },
|
| 493 |
+
{ title: "Is the person wearing a safety helmet?", options: "helmet: a worker wearing a hard hat\nno_helmet: a person without a hard hat on their head" },
|
| 494 |
+
{ title: "Indoor or outdoor?", options: "indoor: an indoor scene inside a room\noutdoor: an outdoor scene under the open sky" },
|
| 495 |
+
{ title: "How bright is the scene?", options: "bright: a bright, well lit scene\ndim: a dim scene with low light\ndark: a very dark scene" },
|
| 496 |
+
];
|
| 497 |
+
const AUDIO_TEMPLATES = [
|
| 498 |
+
{ title: "What sound is this?", options: "dog: a dog barking\nspeech: a person speaking\nmusic: music playing\nmachine: machine noise, an engine or a motor\nbirds: birds chirping\nwater: running water, rain or waves" },
|
| 499 |
+
{ title: "Is someone speaking?", options: "yes: a person speaking words\nno: no speech, only other sounds or silence" },
|
| 500 |
+
{ title: "Is there an alarm or siren?", options: "alarm: an alarm, siren or beeping warning sound\nnormal: ordinary background sound" },
|
| 501 |
+
{ title: "Are hands clapping or knocking?", options: "clapping: hands clapping\nknocking: knocking on a door or table\nnone: no clapping or knocking" },
|
| 502 |
+
];
|
| 503 |
+
const MAX_CARDS = 4;
|
| 504 |
+
let cardSeq = 0;
|
| 505 |
+
const decks = { vision: [], audio: [] };
|
| 506 |
+
function makeCard(t, threshold) {
|
| 507 |
+
const n = parseOptions(t.options).length;
|
| 508 |
+
threshold = threshold ?? (n <= 2 ? 0.6 : 0.5);
|
| 509 |
+
return { id: ++cardSeq, title: t.title, context: t.context || "", optionsText: t.options, options: parseOptions(t.options), threshold, probs: null, n: 0, onDevice: 0, escalate: 0, editing: false };
|
| 510 |
+
}
|
| 511 |
+
decks.vision = [VISION_TEMPLATES[0], VISION_TEMPLATES[1], VISION_TEMPLATES[2]].map((t) => makeCard(t));
|
| 512 |
+
decks.audio = [AUDIO_TEMPLATES[0], AUDIO_TEMPLATES[1]].map((t) => makeCard(t));
|
| 513 |
+
let primaryId = { vision: decks.vision[0].id, audio: decks.audio[0].id };
|
| 514 |
+
|
| 515 |
+
const live = { running: false, token: 0, src: "demo", facing: "user", stream: null, fps: 0, lat: 0, lastDone: 0, audioCtx: null, analyser: null, ring: null, ringPos: 0, ringFilled: 0, fileEl: null };
|
| 516 |
+
const deckName = () => (live.src === "mic" || live.src === "sound" ? "audio" : "vision");
|
| 517 |
+
const deck = () => decks[deckName()];
|
| 518 |
+
|
| 519 |
+
function renderTemplates() {
|
| 520 |
+
const list = deckName() === "audio" ? AUDIO_TEMPLATES : VISION_TEMPLATES;
|
| 521 |
+
$("templates").innerHTML = list.map((t, i) => `<button data-t="${i}">${esc(t.title)}</button>`).join("");
|
| 522 |
+
$("templates").querySelectorAll("button").forEach((b) =>
|
| 523 |
+
b.addEventListener("click", () => {
|
| 524 |
+
if (deck().length >= MAX_CARDS) return flash(`At most ${MAX_CARDS} decisions at once. Remove one first.`);
|
| 525 |
+
deck().push(makeCard(list[+b.dataset.t]));
|
| 526 |
+
renderCards();
|
| 527 |
+
})
|
| 528 |
+
);
|
| 529 |
+
$("cardsTitle").textContent = deckName() === "audio" ? "Decisions on every sound window" : "Decisions on every frame";
|
| 530 |
+
}
|
| 531 |
+
function flash(msg) { $("cardsCount").textContent = msg; setTimeout(updateCount, 2500); }
|
| 532 |
+
function updateCount() { $("cardsCount").textContent = `${deck().length} / ${MAX_CARDS}, ${liveTrained() ? "one pass per card" : "one embedding scores all"}`; }
|
| 533 |
+
|
| 534 |
+
function renderCards() {
|
| 535 |
+
const d = deck();
|
| 536 |
+
if (!d.find((c) => c.id === primaryId[deckName()]) && d.length) primaryId[deckName()] = d[0].id;
|
| 537 |
+
$("cards").innerHTML = d
|
| 538 |
+
.map((c) => {
|
| 539 |
+
const prim = c.id === primaryId[deckName()];
|
| 540 |
+
return `<div class="dcard ${prim ? "primary" : ""}" data-id="${c.id}">
|
| 541 |
+
<div class="dtop"><div class="dtitle">${esc(c.title)}${c.context ? `<span class="dctx">${esc(c.context)}</span>` : ""}</div>
|
| 542 |
+
<div class="dact">
|
| 543 |
+
<button data-act="pin" title="Show this decision on the video">${prim ? "On video" : "Show on video"}</button>
|
| 544 |
+
<button data-act="edit">Edit</button>
|
| 545 |
+
<button data-act="del" title="Remove">Remove</button>
|
| 546 |
+
</div></div>
|
| 547 |
+
<div class="dverdict">waiting for the first ${deckName() === "audio" ? "sound window" : "frame"}</div>
|
| 548 |
+
<div class="dbars">${c.options.map((o) => `<div class="obar"><span class="k" title="${esc(o.desc)}">${esc(o.key.replace(/_/g, " "))}</span><span class="track"><span class="fill"></span></span><span class="p">-</span></div>`).join("")}</div>
|
| 549 |
+
<div class="thr">Confidence gate <input type="range" min="0.3" max="0.99" step="0.01" value="${c.threshold}" data-act="thr" /><span class="tv">${Math.round(c.threshold * 100)}%</span></div>
|
| 550 |
+
<div class="dstats"></div>
|
| 551 |
+
${c.editing ? `<div class="dedit"><input type="text" data-f="title" value="${esc(c.title)}" placeholder="Question" /><input type="text" data-f="ctx" value="${esc(c.context || "")}" placeholder="Context (optional)" /><textarea rows="5" data-f="opts">${esc(c.optionsText)}</textarea><button data-act="save">Save</button></div>` : ""}
|
| 552 |
+
</div>`;
|
| 553 |
+
})
|
| 554 |
+
.join("");
|
| 555 |
+
$("cards").querySelectorAll(".dcard").forEach((el) => {
|
| 556 |
+
const c = d.find((x) => x.id === +el.dataset.id);
|
| 557 |
+
el.querySelector('[data-act="pin"]').onclick = () => { primaryId[deckName()] = c.id; renderCards(); };
|
| 558 |
+
el.querySelector('[data-act="edit"]').onclick = () => { c.editing = !c.editing; renderCards(); };
|
| 559 |
+
el.querySelector('[data-act="del"]').onclick = () => { decks[deckName()] = d.filter((x) => x !== c); renderCards(); };
|
| 560 |
+
el.querySelector('[data-act="thr"]').oninput = (e) => { c.threshold = +e.target.value; el.querySelector(".tv").textContent = `${Math.round(c.threshold * 100)}%`; paintCard(c); };
|
| 561 |
+
const save = el.querySelector('[data-act="save"]');
|
| 562 |
+
if (save) save.onclick = () => {
|
| 563 |
+
const opts = parseOptions(el.querySelector('[data-f="opts"]').value);
|
| 564 |
+
if (opts.length < 2 || opts.length > 8) return alert("Write 2 to 8 options, one per line as key: description.");
|
| 565 |
+
c.title = el.querySelector('[data-f="title"]').value.trim() || "Decision";
|
| 566 |
+
c.context = el.querySelector('[data-f="ctx"]').value.trim();
|
| 567 |
+
c.optionsText = el.querySelector('[data-f="opts"]').value;
|
| 568 |
+
c.options = opts; c.probs = null; c.n = c.onDevice = c.escalate = 0; c.editing = false;
|
| 569 |
+
renderCards();
|
| 570 |
+
};
|
| 571 |
+
paintCard(c);
|
| 572 |
+
});
|
| 573 |
+
updateCount();
|
| 574 |
+
paintOverlay();
|
| 575 |
+
}
|
| 576 |
+
$("customBtn").addEventListener("click", () => {
|
| 577 |
+
if (deck().length >= MAX_CARDS) return flash(`At most ${MAX_CARDS} decisions at once. Remove one first.`);
|
| 578 |
+
const c = makeCard({ title: "What is happening?", options: deckName() === "audio" ? "a: describe the first sound\nb: describe the second sound" : "a: describe the first situation\nb: describe the second situation" });
|
| 579 |
+
c.editing = true;
|
| 580 |
+
deck().push(c);
|
| 581 |
+
renderCards();
|
| 582 |
+
});
|
| 583 |
+
|
| 584 |
+
function paintCard(c) {
|
| 585 |
+
const el = $("cards").querySelector(`.dcard[data-id="${c.id}"]`);
|
| 586 |
+
if (!el || !c.probs) return;
|
| 587 |
+
const top = argmax(c.probs);
|
| 588 |
+
const conf = c.probs[top];
|
| 589 |
+
const sure = conf >= c.threshold;
|
| 590 |
+
el.classList.toggle("uncertain", !sure);
|
| 591 |
+
el.querySelectorAll(".obar").forEach((row, i) => {
|
| 592 |
+
row.classList.toggle("top", i === top);
|
| 593 |
+
row.querySelector(".fill").style.width = `${(c.probs[i] * 100).toFixed(1)}%`;
|
| 594 |
+
row.querySelector(".p").textContent = `${Math.round(c.probs[i] * 100)}%`;
|
| 595 |
+
});
|
| 596 |
+
el.querySelector(".dverdict").innerHTML = sure
|
| 597 |
+
? `<b>${esc(c.options[top].key.replace(/_/g, " "))}</b> ${Math.round(conf * 100)}%, decided on device`
|
| 598 |
+
: `<b>uncertain</b> (${esc(c.options[top].key.replace(/_/g, " "))} ${Math.round(conf * 100)}%): would escalate to a larger model`;
|
| 599 |
+
el.querySelector(".dstats").textContent = `${c.n} ${deckName() === "audio" ? "windows" : "frames"}: ${c.onDevice} on device, ${c.escalate} would escalate`;
|
| 600 |
+
}
|
| 601 |
+
const RING_LEN = 2 * Math.PI * 52;
|
| 602 |
+
function paintOverlay() {
|
| 603 |
+
const c = deck().find((x) => x.id === primaryId[deckName()]);
|
| 604 |
+
const ov = $("overlay");
|
| 605 |
+
if (!c || !c.probs) { ov.hidden = !live.running || !c; if (c) { $("ovQuestion").textContent = c.title; $("ovLabel").textContent = "..."; $("ovPct").textContent = ""; $("ringFg").style.strokeDashoffset = RING_LEN; } return; }
|
| 606 |
+
ov.hidden = false;
|
| 607 |
+
const top = argmax(c.probs);
|
| 608 |
+
const conf = c.probs[top];
|
| 609 |
+
const sure = conf >= c.threshold;
|
| 610 |
+
ov.classList.toggle("uncertain", !sure);
|
| 611 |
+
$("ovQuestion").textContent = c.title;
|
| 612 |
+
$("ovLabel").textContent = sure ? c.options[top].key.replace(/_/g, " ") : `uncertain`;
|
| 613 |
+
$("ovPct").textContent = sure ? `${(conf * 100).toFixed(0)}% confidence` : `best guess ${c.options[top].key.replace(/_/g, " ")} at ${(conf * 100).toFixed(0)}%, below the ${Math.round(c.threshold * 100)}% gate: would escalate`;
|
| 614 |
+
$("ringFg").style.strokeDashoffset = RING_LEN * (1 - conf);
|
| 615 |
+
}
|
| 616 |
+
function paintGate() {
|
| 617 |
+
let on = 0, esc_ = 0;
|
| 618 |
+
for (const d of Object.values(decks)) for (const c of d) { on += c.onDevice; esc_ += c.escalate; }
|
| 619 |
+
$("gOnDevice").textContent = on;
|
| 620 |
+
$("gEscalate").textContent = esc_;
|
| 621 |
+
$("gRate").textContent = on + esc_ ? `${((100 * on) / (on + esc_)).toFixed(1)}%` : "-";
|
| 622 |
+
}
|
| 623 |
+
$("resetGate").addEventListener("click", () => { for (const d of Object.values(decks)) for (const c of d) { c.n = c.onDevice = c.escalate = 0; } paintGate(); deck().forEach(paintCard); });
|
| 624 |
+
|
| 625 |
+
// Live prompt: "trained" embeds the frame once per card with the card's question (trained format);
|
| 626 |
+
// "alone" embeds the frame once, with no text, and scores every card from that one vector.
|
| 627 |
+
const liveTrained = () => $("livePrompt").value === "trained";
|
| 628 |
+
// embs: one embedding per card (trained) or a single shared embedding (alone)
|
| 629 |
+
async function scoreDeck(embs) {
|
| 630 |
+
const d = deck();
|
| 631 |
+
const trained = Array.isArray(embs);
|
| 632 |
+
const texts = d.flatMap((c) => c.options.map((o) => (trained ? DOC(o.desc) : LIVE_OPT(o.desc))));
|
| 633 |
+
const { embeddings } = await embedTexts(texts);
|
| 634 |
+
const T = temperature();
|
| 635 |
+
const alpha = parseFloat($("smoothSel").value);
|
| 636 |
+
let k = 0;
|
| 637 |
+
for (const [ci, c] of d.entries()) {
|
| 638 |
+
const emb = trained ? embs[ci] : embs;
|
| 639 |
+
const cos = c.options.map(() => dot(emb, embeddings[k++]));
|
| 640 |
+
const p = softmax(cos, T);
|
| 641 |
+
c.probs = c.probs && c.probs.length === p.length && alpha > 0 ? c.probs.map((x, i) => alpha * x + (1 - alpha) * p[i]) : p;
|
| 642 |
+
const conf = Math.max(...c.probs);
|
| 643 |
+
c.n++;
|
| 644 |
+
if (conf >= c.threshold) c.onDevice++; else c.escalate++;
|
| 645 |
+
paintCard(c);
|
| 646 |
+
}
|
| 647 |
+
paintOverlay();
|
| 648 |
+
paintGate();
|
| 649 |
+
}
|
| 650 |
+
function hud(ms) {
|
| 651 |
+
const now = performance.now();
|
| 652 |
+
if (live.lastDone) {
|
| 653 |
+
const inst = 1000 / (now - live.lastDone);
|
| 654 |
+
live.fps = live.fps ? 0.7 * live.fps + 0.3 * inst : inst;
|
| 655 |
+
}
|
| 656 |
+
live.lastDone = now;
|
| 657 |
+
live.lat = live.lat ? 0.7 * live.lat + 0.3 * ms : ms;
|
| 658 |
+
$("fpsVal").textContent = live.fps.toFixed(1);
|
| 659 |
+
$("latVal").textContent = live.lat.toFixed(0);
|
| 660 |
+
$("latUnit").textContent = deckName() === "audio" ? "ms / window" : "ms / frame";
|
| 661 |
+
}
|
| 662 |
+
function targetGap() {
|
| 663 |
+
const v = $("rateSel").value;
|
| 664 |
+
if (v === "auto") return model?.device === "wasm" ? 1000 : 200;
|
| 665 |
+
return 1000 / +v;
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
/* sources */
|
| 669 |
+
const demoImgs = [];
|
| 670 |
+
const feed = $("feed");
|
| 671 |
+
const feedCtx = feed.getContext("2d");
|
| 672 |
+
const grab = document.createElement("canvas");
|
| 673 |
+
const grabCtx = grab.getContext("2d", { willReadFrequently: true });
|
| 674 |
+
let demoIdx = 0, demoStart = 0, rafId = 0;
|
| 675 |
+
async function loadDemoImages() {
|
| 676 |
+
await samplesReady;
|
| 677 |
+
if (demoImgs.length) return;
|
| 678 |
+
for (const f of demoFiles) {
|
| 679 |
+
try { demoImgs.push(await createImageBitmap(await fetchBlob(f))); } catch (e) { console.warn(f, e); }
|
| 680 |
+
}
|
| 681 |
+
}
|
| 682 |
+
function fitCanvas() {
|
| 683 |
+
const r = feed.getBoundingClientRect();
|
| 684 |
+
const w = Math.max(320, Math.round(r.width * Math.min(2, devicePixelRatio || 1)));
|
| 685 |
+
const h = Math.max(240, Math.round(r.height * Math.min(2, devicePixelRatio || 1)));
|
| 686 |
+
if (feed.width !== w || feed.height !== h) { feed.width = w; feed.height = h; }
|
| 687 |
+
}
|
| 688 |
+
const DEMO_MS = 3200;
|
| 689 |
+
function drawDemo(now) {
|
| 690 |
+
renderDemo(now);
|
| 691 |
+
rafId = requestAnimationFrame(drawDemo);
|
| 692 |
+
}
|
| 693 |
+
function renderDemo(now) {
|
| 694 |
+
fitCanvas();
|
| 695 |
+
if (!demoStart) demoStart = now;
|
| 696 |
+
// keep each picture up long enough for at least two decisions, even on the slow CPU path
|
| 697 |
+
const dur = Math.max(DEMO_MS, (live.lat || 0) * 2.2);
|
| 698 |
+
let t = (now - demoStart) / dur;
|
| 699 |
+
if (t >= 1) { demoIdx = (demoIdx + 1) % demoImgs.length; demoStart = now; t = 0; }
|
| 700 |
+
const img = demoImgs[demoIdx];
|
| 701 |
+
feedCtx.fillStyle = "#05070a";
|
| 702 |
+
feedCtx.fillRect(0, 0, feed.width, feed.height);
|
| 703 |
+
if (img && img.width) {
|
| 704 |
+
// slow zoom, like a handheld camera; the whole image stays visible
|
| 705 |
+
const zoom = 1 + 0.06 * t;
|
| 706 |
+
const s = Math.min(feed.width / img.width, feed.height / img.height) * zoom;
|
| 707 |
+
const w = img.width * s, h = img.height * s;
|
| 708 |
+
feedCtx.globalAlpha = Math.min(1, t * 6);
|
| 709 |
+
feedCtx.drawImage(img, (feed.width - w) / 2, (feed.height - h) / 2, w, h);
|
| 710 |
+
feedCtx.globalAlpha = 1;
|
| 711 |
+
}
|
| 712 |
+
}
|
| 713 |
+
function drawAudio() {
|
| 714 |
+
fitCanvas();
|
| 715 |
+
const a = live.analyser;
|
| 716 |
+
feedCtx.fillStyle = "#05070a";
|
| 717 |
+
feedCtx.fillRect(0, 0, feed.width, feed.height);
|
| 718 |
+
if (a) {
|
| 719 |
+
const buf = new Float32Array(a.fftSize);
|
| 720 |
+
a.getFloatTimeDomainData(buf);
|
| 721 |
+
let rms = 0; for (const x of buf) rms += x * x; rms = Math.sqrt(rms / buf.length);
|
| 722 |
+
feedCtx.strokeStyle = "#2dd4bf";
|
| 723 |
+
feedCtx.lineWidth = Math.max(2, feed.height / 200);
|
| 724 |
+
feedCtx.beginPath();
|
| 725 |
+
for (let i = 0; i < buf.length; i++) {
|
| 726 |
+
const x = (i / buf.length) * feed.width;
|
| 727 |
+
const y = feed.height * 0.45 + Math.max(-1, Math.min(1, buf[i] * 0.8)) * feed.height * 0.3;
|
| 728 |
+
i ? feedCtx.lineTo(x, y) : feedCtx.moveTo(x, y);
|
| 729 |
+
}
|
| 730 |
+
feedCtx.stroke();
|
| 731 |
+
const lvl = Math.min(1, rms * 8);
|
| 732 |
+
feedCtx.fillStyle = "rgba(45,212,191,.25)";
|
| 733 |
+
feedCtx.fillRect(14, feed.height * 0.2, 10, feed.height * 0.5);
|
| 734 |
+
feedCtx.fillStyle = "#2dd4bf";
|
| 735 |
+
feedCtx.fillRect(14, feed.height * 0.2 + feed.height * 0.5 * (1 - lvl), 10, feed.height * 0.5 * lvl);
|
| 736 |
+
feedCtx.fillStyle = "rgba(255,255,255,.55)";
|
| 737 |
+
feedCtx.font = `${Math.round(feed.height / 34)}px system-ui`;
|
| 738 |
+
feedCtx.fillText(`Listening in 2 s windows (${live.src === "sound" ? "sound file" : "microphone"}), 16 kHz mono`, 34, feed.height * 0.16);
|
| 739 |
+
}
|
| 740 |
+
rafId = requestAnimationFrame(drawAudio);
|
| 741 |
+
}
|
| 742 |
+
function grabFrame(budget) {
|
| 743 |
+
let srcEl, sw, sh;
|
| 744 |
+
if (live.src === "camera") { srcEl = $("cam"); sw = srcEl.videoWidth; sh = srcEl.videoHeight; }
|
| 745 |
+
else {
|
| 746 |
+
// Demo feed: embed the picture itself (not the letterboxed canvas with its caption)
|
| 747 |
+
renderDemo(performance.now()); // also keeps the slideshow moving if the tab is in the background
|
| 748 |
+
srcEl = demoImgs[demoIdx]; sw = srcEl?.width; sh = srcEl?.height;
|
| 749 |
+
}
|
| 750 |
+
if (!sw || !sh) return null;
|
| 751 |
+
const maxSide = budget >= 280 ? 640 : 448;
|
| 752 |
+
const sc = Math.min(1, maxSide / Math.max(sw, sh));
|
| 753 |
+
grab.width = Math.round(sw * sc); grab.height = Math.round(sh * sc);
|
| 754 |
+
grabCtx.drawImage(srcEl, 0, 0, grab.width, grab.height);
|
| 755 |
+
return grabCtx.getImageData(0, 0, grab.width, grab.height);
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
async function visionLoop(token) {
|
| 759 |
+
while (live.running && token === live.token) {
|
| 760 |
+
const t0 = performance.now();
|
| 761 |
+
const budget = +$("budgetSel").value;
|
| 762 |
+
const f = grabFrame(budget);
|
| 763 |
+
if (f) {
|
| 764 |
+
try {
|
| 765 |
+
const base = { kind: "rgba", data: f.data.buffer, width: f.width, height: f.height, budget };
|
| 766 |
+
let embs;
|
| 767 |
+
if (liveTrained()) {
|
| 768 |
+
const inputs = deck().map((c) => ({ ...base, text: trainedQuery("rgba", c.title, c.context) }));
|
| 769 |
+
embs = (await rpc("embedInputs", { inputs }, [f.data.buffer])).embeddings;
|
| 770 |
+
} else {
|
| 771 |
+
embs = (await rpc("embedInput", { input: base }, [f.data.buffer])).embedding;
|
| 772 |
+
}
|
| 773 |
+
if (token !== live.token) break;
|
| 774 |
+
await scoreDeck(embs);
|
| 775 |
+
hud(performance.now() - t0);
|
| 776 |
+
} catch (e) { console.error(e); setStatus("error", e.message); await sleep(1000); }
|
| 777 |
+
}
|
| 778 |
+
const gap = targetGap() - (performance.now() - t0);
|
| 779 |
+
await sleep(Math.max(gap, 16));
|
| 780 |
+
}
|
| 781 |
+
}
|
| 782 |
+
const SR = 16000, WIN = 2 * SR;
|
| 783 |
+
// The embedding of near-silence is not meaningful (tested: silence scores as speech),
|
| 784 |
+
// so quiet windows are not sent to the model at all.
|
| 785 |
+
const QUIET_DB = -55;
|
| 786 |
+
function showQuiet(db) {
|
| 787 |
+
for (const c of deck()) {
|
| 788 |
+
const el = $("cards").querySelector(`.dcard[data-id="${c.id}"]`);
|
| 789 |
+
if (el) el.querySelector(".dverdict").innerHTML = `<b>quiet</b> input level ${db.toFixed(0)} dBFS is below the ${QUIET_DB} dBFS level gate: model not run`;
|
| 790 |
+
}
|
| 791 |
+
const ov = $("overlay");
|
| 792 |
+
ov.hidden = false;
|
| 793 |
+
ov.classList.add("uncertain");
|
| 794 |
+
$("ovLabel").textContent = "quiet";
|
| 795 |
+
$("ovPct").textContent = `level ${db.toFixed(0)} dBFS, below the ${QUIET_DB} dBFS gate: model not run`;
|
| 796 |
+
$("ringFg").style.strokeDashoffset = RING_LEN;
|
| 797 |
+
}
|
| 798 |
+
async function audioLoop(token) {
|
| 799 |
+
while (live.running && token === live.token) {
|
| 800 |
+
const t0 = performance.now();
|
| 801 |
+
if (live.ringFilled >= WIN) {
|
| 802 |
+
const win = new Float32Array(WIN);
|
| 803 |
+
const p = live.ringPos;
|
| 804 |
+
win.set(live.ring.subarray(p));
|
| 805 |
+
win.set(live.ring.subarray(0, p), WIN - p);
|
| 806 |
+
let e2 = 0;
|
| 807 |
+
for (let i = 0; i < win.length; i++) e2 += win[i] * win[i];
|
| 808 |
+
const db = 10 * Math.log10(e2 / win.length + 1e-12);
|
| 809 |
+
if (db < QUIET_DB) {
|
| 810 |
+
showQuiet(db);
|
| 811 |
+
await sleep(500);
|
| 812 |
+
continue;
|
| 813 |
+
}
|
| 814 |
+
try {
|
| 815 |
+
let embs;
|
| 816 |
+
if (liveTrained()) {
|
| 817 |
+
const inputs = deck().map((c) => ({ kind: "audio", audio: win, text: trainedQuery("audio", c.title, c.context) }));
|
| 818 |
+
embs = (await rpc("embedInputs", { inputs }, [win.buffer])).embeddings;
|
| 819 |
+
} else {
|
| 820 |
+
embs = (await rpc("embedInput", { input: { kind: "audio", audio: win } }, [win.buffer])).embedding;
|
| 821 |
+
}
|
| 822 |
+
if (token !== live.token) break;
|
| 823 |
+
await scoreDeck(embs);
|
| 824 |
+
hud(performance.now() - t0);
|
| 825 |
+
} catch (e) { console.error(e); setStatus("error", e.message); await sleep(1000); }
|
| 826 |
+
}
|
| 827 |
+
const gap = Math.max(model?.device === "wasm" ? 2000 : 1000, 0) - (performance.now() - t0);
|
| 828 |
+
await sleep(Math.max(gap, 50));
|
| 829 |
+
}
|
| 830 |
+
}
|
| 831 |
+
function setupAudioGraph(sourceNodeFactory) {
|
| 832 |
+
const ctx = new AudioContext({ sampleRate: SR });
|
| 833 |
+
live.audioCtx = ctx;
|
| 834 |
+
const src = sourceNodeFactory(ctx);
|
| 835 |
+
const an = ctx.createAnalyser();
|
| 836 |
+
an.fftSize = 2048;
|
| 837 |
+
live.analyser = an;
|
| 838 |
+
live.ring = new Float32Array(WIN); live.ringPos = 0; live.ringFilled = 0;
|
| 839 |
+
const proc = ctx.createScriptProcessor(4096, 1, 1);
|
| 840 |
+
const ratio = ctx.sampleRate / SR;
|
| 841 |
+
proc.onaudioprocess = (e) => {
|
| 842 |
+
const x = e.inputBuffer.getChannelData(0);
|
| 843 |
+
const n = Math.floor(x.length / ratio);
|
| 844 |
+
for (let i = 0; i < n; i++) {
|
| 845 |
+
live.ring[live.ringPos] = x[Math.floor(i * ratio)];
|
| 846 |
+
live.ringPos = (live.ringPos + 1) % WIN;
|
| 847 |
+
}
|
| 848 |
+
live.ringFilled += n;
|
| 849 |
+
};
|
| 850 |
+
src.connect(an);
|
| 851 |
+
src.connect(proc);
|
| 852 |
+
const mute = ctx.createGain(); mute.gain.value = 0;
|
| 853 |
+
proc.connect(mute); mute.connect(ctx.destination);
|
| 854 |
+
return src;
|
| 855 |
+
}
|
| 856 |
+
|
| 857 |
+
async function startLive(opts = {}) {
|
| 858 |
+
if (opts instanceof Event) opts = {};
|
| 859 |
+
stopLive(false);
|
| 860 |
+
const token = ++live.token;
|
| 861 |
+
const btn = $("startBtn");
|
| 862 |
+
btn.disabled = true;
|
| 863 |
+
const isAudio = deckName() === "audio";
|
| 864 |
+
try {
|
| 865 |
+
btn.textContent = "Loading model...";
|
| 866 |
+
await ensureModel(isAudio);
|
| 867 |
+
btn.textContent = "Starting...";
|
| 868 |
+
const stage = $("stage");
|
| 869 |
+
stage.classList.remove("camera", "mirror");
|
| 870 |
+
if (live.src === "camera") {
|
| 871 |
+
if (!navigator.mediaDevices?.getUserMedia) throw new Error("This browser cannot open a camera here. Try the Demo feed.");
|
| 872 |
+
live.stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: live.facing, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false });
|
| 873 |
+
const v = $("cam");
|
| 874 |
+
v.srcObject = live.stream;
|
| 875 |
+
await v.play();
|
| 876 |
+
stage.classList.add("camera");
|
| 877 |
+
if (live.facing === "user") stage.classList.add("mirror");
|
| 878 |
+
$("flipBtn").hidden = false;
|
| 879 |
+
} else if (live.src === "demo") {
|
| 880 |
+
await loadDemoImages();
|
| 881 |
+
demoStart = 0;
|
| 882 |
+
rafId = requestAnimationFrame(drawDemo);
|
| 883 |
+
} else if (live.src === "mic") {
|
| 884 |
+
if (!navigator.mediaDevices?.getUserMedia) throw new Error("This browser cannot open a microphone here. Try a sound file.");
|
| 885 |
+
live.stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
|
| 886 |
+
setupAudioGraph((ctx) => ctx.createMediaStreamSource(live.stream));
|
| 887 |
+
rafId = requestAnimationFrame(drawAudio);
|
| 888 |
+
} else if (live.src === "sound") {
|
| 889 |
+
const f = opts.file || (await pickFile("audio/*"));
|
| 890 |
+
const el = new Audio(URL.createObjectURL(f));
|
| 891 |
+
el.loop = true;
|
| 892 |
+
live.fileEl = el;
|
| 893 |
+
setupAudioGraph((ctx) => { const s = ctx.createMediaElementSource(el); s.connect(ctx.destination); return s; });
|
| 894 |
+
await el.play();
|
| 895 |
+
rafId = requestAnimationFrame(drawAudio);
|
| 896 |
+
}
|
| 897 |
+
live.running = true;
|
| 898 |
+
live.fps = live.lat = live.lastDone = 0;
|
| 899 |
+
$("idle").hidden = true;
|
| 900 |
+
$("stopBtn").disabled = false;
|
| 901 |
+
renderCards();
|
| 902 |
+
if (isAudio) audioLoop(token); else visionLoop(token);
|
| 903 |
+
} catch (e) {
|
| 904 |
+
console.error(e);
|
| 905 |
+
stopLive();
|
| 906 |
+
$("idle").querySelector("p").textContent = e.message;
|
| 907 |
+
} finally {
|
| 908 |
+
btn.disabled = false;
|
| 909 |
+
btn.textContent = "Start live decisions";
|
| 910 |
+
}
|
| 911 |
+
}
|
| 912 |
+
function pickFile(accept) {
|
| 913 |
+
return new Promise((res, rej) => {
|
| 914 |
+
const i = document.createElement("input");
|
| 915 |
+
i.type = "file"; i.accept = accept;
|
| 916 |
+
i.onchange = () => (i.files[0] ? res(i.files[0]) : rej(new Error("No file chosen.")));
|
| 917 |
+
i.click();
|
| 918 |
+
});
|
| 919 |
+
}
|
| 920 |
+
function stopLive(showIdle = true) {
|
| 921 |
+
live.running = false;
|
| 922 |
+
live.token++;
|
| 923 |
+
cancelAnimationFrame(rafId);
|
| 924 |
+
if (live.stream) { live.stream.getTracks().forEach((t) => t.stop()); live.stream = null; }
|
| 925 |
+
if (live.audioCtx) { live.audioCtx.close().catch(() => {}); live.audioCtx = null; live.analyser = null; }
|
| 926 |
+
if (live.fileEl) { live.fileEl.pause(); live.fileEl = null; }
|
| 927 |
+
$("cam").srcObject = null;
|
| 928 |
+
$("stopBtn").disabled = true;
|
| 929 |
+
$("flipBtn").hidden = live.src !== "camera";
|
| 930 |
+
if (showIdle) { $("idle").hidden = false; $("overlay").hidden = true; }
|
| 931 |
+
}
|
| 932 |
+
$("startBtn").addEventListener("click", () => startLive());
|
| 933 |
+
$("stopBtn").addEventListener("click", () => stopLive());
|
| 934 |
+
$("flipBtn").addEventListener("click", () => { live.facing = live.facing === "user" ? "environment" : "user"; if (live.running) startLive(); });
|
| 935 |
+
document.querySelectorAll(".src").forEach((b) =>
|
| 936 |
+
b.addEventListener("click", () => {
|
| 937 |
+
const wasRunning = live.running;
|
| 938 |
+
stopLive();
|
| 939 |
+
live.src = b.dataset.src;
|
| 940 |
+
document.querySelectorAll(".src").forEach((x) => x.classList.toggle("active", x === b));
|
| 941 |
+
$("flipBtn").hidden = live.src !== "camera";
|
| 942 |
+
$("idle").querySelector("p").textContent =
|
| 943 |
+
live.src === "camera" ? "Your camera stays on this device. Frames are embedded in the browser and dropped."
|
| 944 |
+
: live.src === "mic" ? "Listens in 2 second windows. Loads the audio encoder too (about 190 MB more at q4)."
|
| 945 |
+
: live.src === "sound" ? "Plays a sound file of your choice through the same 2 second windows."
|
| 946 |
+
: "Cycles through the sample images as if they were a camera feed.";
|
| 947 |
+
renderTemplates();
|
| 948 |
+
renderCards();
|
| 949 |
+
if (wasRunning && live.src === "demo") startLive();
|
| 950 |
+
})
|
| 951 |
+
);
|
| 952 |
+
// The sound-file source shares the microphone deck; expose it as a fourth button.
|
| 953 |
+
$("flipBtn").insertAdjacentHTML("beforebegin", `<button class="src" data-src="sound">Sound file</button>`);
|
| 954 |
+
const soundBtn = document.querySelector('.src[data-src="sound"]');
|
| 955 |
+
soundBtn.addEventListener("click", () => {
|
| 956 |
+
stopLive();
|
| 957 |
+
live.src = "sound";
|
| 958 |
+
document.querySelectorAll(".src").forEach((x) => x.classList.toggle("active", x === soundBtn));
|
| 959 |
+
$("flipBtn").hidden = true;
|
| 960 |
+
$("idle").querySelector("p").textContent = "Plays a sound file of your choice through the same 2 second windows. The file stays on this device.";
|
| 961 |
+
renderTemplates();
|
| 962 |
+
renderCards();
|
| 963 |
+
});
|
| 964 |
+
document.addEventListener("visibilitychange", () => { if (document.hidden && live.running && live.src === "camera") stopLive(); });
|
| 965 |
+
|
| 966 |
+
renderTemplates();
|
| 967 |
+
renderCards();
|
| 968 |
+
paintGate();
|
| 969 |
+
$("idle").querySelector("p").textContent = "Cycles through the sample images as if they were a camera feed. Loads the model on first start (about 260 to 290 MB at 4 bits, cached afterwards).";
|
| 970 |
+
|
| 971 |
+
// Expose a small hook for automated checks in the page.
|
| 972 |
+
$("livePrompt").addEventListener("change", () => {
|
| 973 |
+
for (const d of Object.values(decks)) for (const c of d) { c.probs = null; c.n = c.onDevice = c.escalate = 0; }
|
| 974 |
+
renderCards();
|
| 975 |
+
paintGate();
|
| 976 |
+
});
|
| 977 |
+
window.decideApp = { ensureModel, runAll, decideCore, eggDecide, eggRunAll, EGG, trainedQuery, PRESETS, live, decks, startLive, stopLive, yesNoOptions, parseOptions, embedTexts, rpc, get model() { return model; } };
|
examples/egg-candling-bad-1.jpg
DELETED
|
Binary file (12.3 kB)
|
|
|
examples/egg-candling-bad-104.jpg
DELETED
|
Binary file (7.59 kB)
|
|
|
examples/egg-candling-good-1.jpg
DELETED
|
Binary file (18.2 kB)
|
|
|
examples/egg-candling-good-10.jpg
DELETED
|
Binary file (19.6 kB)
|
|
|
examples/egg-test/egg-test-bad-107.jpg
ADDED
|
examples/egg-test/egg-test-bad-295.jpg
ADDED
|
examples/egg-test/egg-test-bad-397.jpg
ADDED
|
examples/egg-test/egg-test-bad-78.jpg
ADDED
|
examples/egg-test/egg-test-good-125.jpg
ADDED
|
examples/egg-test/egg-test-good-235.jpg
ADDED
|
examples/egg-test/egg-test-good-409.jpg
ADDED
|
examples/egg-test/egg-test-good-81.jpg
ADDED
|
examples/samples.json
CHANGED
|
@@ -156,7 +156,7 @@
|
|
| 156 |
{
|
| 157 |
"name": "Egg candling (good)",
|
| 158 |
"files": [
|
| 159 |
-
"examples/egg-
|
| 160 |
],
|
| 161 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 162 |
"type": "choice",
|
|
@@ -167,7 +167,7 @@
|
|
| 167 |
{
|
| 168 |
"name": "Egg candling (good)",
|
| 169 |
"files": [
|
| 170 |
-
"examples/egg-
|
| 171 |
],
|
| 172 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 173 |
"type": "choice",
|
|
@@ -178,7 +178,7 @@
|
|
| 178 |
{
|
| 179 |
"name": "Egg candling (bad)",
|
| 180 |
"files": [
|
| 181 |
-
"examples/egg-
|
| 182 |
],
|
| 183 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 184 |
"type": "choice",
|
|
@@ -189,7 +189,7 @@
|
|
| 189 |
{
|
| 190 |
"name": "Egg candling (bad)",
|
| 191 |
"files": [
|
| 192 |
-
"examples/egg-
|
| 193 |
],
|
| 194 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 195 |
"type": "choice",
|
|
|
|
| 156 |
{
|
| 157 |
"name": "Egg candling (good)",
|
| 158 |
"files": [
|
| 159 |
+
"examples/egg-test/egg-test-good-81.jpg"
|
| 160 |
],
|
| 161 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 162 |
"type": "choice",
|
|
|
|
| 167 |
{
|
| 168 |
"name": "Egg candling (good)",
|
| 169 |
"files": [
|
| 170 |
+
"examples/egg-test/egg-test-good-125.jpg"
|
| 171 |
],
|
| 172 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 173 |
"type": "choice",
|
|
|
|
| 178 |
{
|
| 179 |
"name": "Egg candling (bad)",
|
| 180 |
"files": [
|
| 181 |
+
"examples/egg-test/egg-test-bad-78.jpg"
|
| 182 |
],
|
| 183 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 184 |
"type": "choice",
|
|
|
|
| 189 |
{
|
| 190 |
"name": "Egg candling (bad)",
|
| 191 |
"files": [
|
| 192 |
+
"examples/egg-test/egg-test-bad-107.jpg"
|
| 193 |
],
|
| 194 |
"state": "Candling photo: a light is shone through the egg in a dark room.",
|
| 195 |
"type": "choice",
|
index.html
CHANGED
|
@@ -7,14 +7,14 @@
|
|
| 7 |
<meta name="theme-color" content="#0b0d12" />
|
| 8 |
<title>Decide Live</title>
|
| 9 |
<meta name="description" content="Decide Live: on-device decisions from camera and microphone. A multimodal embedding model runs in your browser and turns every frame into calibrated probabilities." />
|
| 10 |
-
<link rel="stylesheet" href="./style.css?v=
|
| 11 |
</head>
|
| 12 |
<body>
|
| 13 |
<header class="top">
|
| 14 |
<div class="wrap topbar">
|
| 15 |
<div class="brand">
|
| 16 |
<h1>Decide Live</h1>
|
| 17 |
-
<p class="sub">On-device decisions from camera and microphone. Every frame is embedded in your browser by EmbeddingGemma 2 and scored against the options you write. No text generation, no tokens, no server.</p>
|
| 18 |
</div>
|
| 19 |
<div class="statusbox">
|
| 20 |
<div class="status" id="status"><span class="dot"></span><span id="statusText">Model not loaded</span></div>
|
|
@@ -26,6 +26,7 @@
|
|
| 26 |
<nav class="wrap tabs" role="tablist">
|
| 27 |
<button class="tab active" data-tab="live" role="tab">Live</button>
|
| 28 |
<button class="tab" data-tab="single" role="tab">Single input</button>
|
|
|
|
| 29 |
<button class="tab" data-tab="samples" role="tab">Sample tests</button>
|
| 30 |
<button class="tab" data-tab="about" role="tab">How it works</button>
|
| 31 |
</nav>
|
|
@@ -59,7 +60,7 @@
|
|
| 59 |
</div>
|
| 60 |
<div class="idle" id="idle">
|
| 61 |
<button class="big" id="startBtn">Start live decisions</button>
|
| 62 |
-
<p>Loads the model on first start (about 290 MB at
|
| 63 |
</div>
|
| 64 |
</div>
|
| 65 |
<div class="controls">
|
|
@@ -79,6 +80,12 @@
|
|
| 79 |
<option value="280">fine (280)</option>
|
| 80 |
</select>
|
| 81 |
</label>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
<label>Smoothing
|
| 83 |
<select id="smoothSel">
|
| 84 |
<option value="0">off</option>
|
|
@@ -157,11 +164,11 @@
|
|
| 157 |
<label class="col" id="optionsWrap">Options, 2 to 8, one per line as <code>key: description</code>
|
| 158 |
<textarea id="optionsInput" rows="6" placeholder="good: Normal, healthy egg bad: Defective, spoiled or damaged egg"></textarea>
|
| 159 |
</label>
|
| 160 |
-
<p class="note" id="yesnoNote" hidden>Yes
|
| 161 |
<details class="adv">
|
| 162 |
<summary>Settings</summary>
|
| 163 |
-
<label class="col">Temperature <span id="tempVal">0.
|
| 164 |
-
<input type="range" id="temp" min="0.005" max="0.5" step="0.
|
| 165 |
</label>
|
| 166 |
<label class="col">Prompt format
|
| 167 |
<select id="preset"></select>
|
|
@@ -179,7 +186,6 @@
|
|
| 179 |
<option value="auto">Auto: 4-bit (q4f16 on WebGPU with fp16 support, else q4)</option>
|
| 180 |
<option value="q4">q4 (4-bit, works everywhere)</option>
|
| 181 |
<option value="q4f16">q4f16 (4-bit weights, fp16 math; WebGPU with fp16 only)</option>
|
| 182 |
-
<option value="q8">q8 (larger, closer to full precision)</option>
|
| 183 |
<option value="fp16">fp16 (largest; WebGPU only)</option>
|
| 184 |
</select>
|
| 185 |
</label>
|
|
@@ -200,11 +206,36 @@
|
|
| 200 |
</section>
|
| 201 |
</main>
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
<!-- SAMPLES -->
|
| 204 |
<main class="wrap view" data-view="samples" hidden>
|
| 205 |
<section class="panel">
|
| 206 |
<h2>Sample tests (18)</h2>
|
| 207 |
-
<p class="note">Counting, yes / no, spatial relations, a chart, a receipt, app screens, scene text, common sense and egg candling. Each test runs in this browser with the prompt format, image detail and temperature chosen under Single input > Settings.
|
| 208 |
<div class="btnrow">
|
| 209 |
<button id="runAllBtn" class="primary inline">Run all samples</button>
|
| 210 |
<button id="compareBtn" class="ghost">Compare all prompt formats</button>
|
|
@@ -225,10 +256,10 @@
|
|
| 225 |
<section class="panel prose">
|
| 226 |
<h2>How it works</h2>
|
| 227 |
<ol>
|
| 228 |
-
<li>The input (a camera frame, an image, a text, a 2 second sound window or a short video)
|
| 229 |
<li>Each option description is embedded once and cached.</li>
|
| 230 |
-
<li>The
|
| 231 |
-
<li>In Live mode the frame
|
| 232 |
<li>A card whose top probability is below its threshold is marked uncertain. That is where a larger model would take over; this page only counts it.</li>
|
| 233 |
</ol>
|
| 234 |
<h3>Privacy</h3>
|
|
@@ -240,14 +271,15 @@
|
|
| 240 |
<li>An embedding model compares meanings; it does not read, count or reason step by step. Questions about exact counts, small text or negation are hard for it.</li>
|
| 241 |
<li>Probabilities depend on the temperature. They are comparable between options of one card, not calibrated against ground truth.</li>
|
| 242 |
<li>WebGPU needs a recent Chrome, Edge or Safari. Without it the page falls back to the CPU (WASM): it works, but it downloads a larger fp16 model (about 880 MB, because the 4-bit graphs need an operator the CPU runtime lacks) and takes several seconds per image, so the live rate drops to a frame every few seconds.</li>
|
|
|
|
| 243 |
</ul>
|
| 244 |
<p class="note">Sample image credits: <a href="./CREDITS.md" target="_blank">CREDITS.md</a>. Code: Apache-2.0.</p>
|
| 245 |
</section>
|
| 246 |
</main>
|
| 247 |
|
| 248 |
<footer class="wrap foot">
|
| 249 |
-
<p>EmbeddingGemma 2 by Google DeepMind (Apache-2.0), run with transformers.js. This page sends no data anywhere.</p>
|
| 250 |
</footer>
|
| 251 |
-
<script type="module" src="./app.js?v=
|
| 252 |
</body>
|
| 253 |
</html>
|
|
|
|
| 7 |
<meta name="theme-color" content="#0b0d12" />
|
| 8 |
<title>Decide Live</title>
|
| 9 |
<meta name="description" content="Decide Live: on-device decisions from camera and microphone. A multimodal embedding model runs in your browser and turns every frame into calibrated probabilities." />
|
| 10 |
+
<link rel="stylesheet" href="./style.css?v=5" />
|
| 11 |
</head>
|
| 12 |
<body>
|
| 13 |
<header class="top">
|
| 14 |
<div class="wrap topbar">
|
| 15 |
<div class="brand">
|
| 16 |
<h1>Decide Live</h1>
|
| 17 |
+
<p class="sub">On-device decisions from camera and microphone. Every frame is embedded in your browser by EmbeddingGemma 2, fine-tuned for decisions, and scored against the options you write. No text generation, no tokens, no server.</p>
|
| 18 |
</div>
|
| 19 |
<div class="statusbox">
|
| 20 |
<div class="status" id="status"><span class="dot"></span><span id="statusText">Model not loaded</span></div>
|
|
|
|
| 26 |
<nav class="wrap tabs" role="tablist">
|
| 27 |
<button class="tab active" data-tab="live" role="tab">Live</button>
|
| 28 |
<button class="tab" data-tab="single" role="tab">Single input</button>
|
| 29 |
+
<button class="tab" data-tab="egg" role="tab">Egg check</button>
|
| 30 |
<button class="tab" data-tab="samples" role="tab">Sample tests</button>
|
| 31 |
<button class="tab" data-tab="about" role="tab">How it works</button>
|
| 32 |
</nav>
|
|
|
|
| 60 |
</div>
|
| 61 |
<div class="idle" id="idle">
|
| 62 |
<button class="big" id="startBtn">Start live decisions</button>
|
| 63 |
+
<p>Loads the model on first start (about 260 to 290 MB at 4 bits, cached afterwards).</p>
|
| 64 |
</div>
|
| 65 |
</div>
|
| 66 |
<div class="controls">
|
|
|
|
| 80 |
<option value="280">fine (280)</option>
|
| 81 |
</select>
|
| 82 |
</label>
|
| 83 |
+
<label>Prompt
|
| 84 |
+
<select id="livePrompt">
|
| 85 |
+
<option value="trained" selected>question + frame, as trained (one pass per card)</option>
|
| 86 |
+
<option value="alone">frame alone (one pass for all cards)</option>
|
| 87 |
+
</select>
|
| 88 |
+
</label>
|
| 89 |
<label>Smoothing
|
| 90 |
<select id="smoothSel">
|
| 91 |
<option value="0">off</option>
|
|
|
|
| 164 |
<label class="col" id="optionsWrap">Options, 2 to 8, one per line as <code>key: description</code>
|
| 165 |
<textarea id="optionsInput" rows="6" placeholder="good: Normal, healthy egg bad: Defective, spoiled or damaged egg"></textarea>
|
| 166 |
</label>
|
| 167 |
+
<p class="note" id="yesnoNote" hidden>In the trained format (default), the question stays in the query and the two options are "Yes" and "No". The older formats build two options from the statement: the statement and its negation, or for a question, the question followed by "Yes." and by "No.".</p>
|
| 168 |
<details class="adv">
|
| 169 |
<summary>Settings</summary>
|
| 170 |
+
<label class="col">Temperature <span id="tempVal">0.0501</span> <button type="button" class="ghost small" id="resetTemp">Use trained value</button>
|
| 171 |
+
<input type="range" id="temp" min="0.005" max="0.5" step="0.0001" value="0.0501" />
|
| 172 |
</label>
|
| 173 |
<label class="col">Prompt format
|
| 174 |
<select id="preset"></select>
|
|
|
|
| 186 |
<option value="auto">Auto: 4-bit (q4f16 on WebGPU with fp16 support, else q4)</option>
|
| 187 |
<option value="q4">q4 (4-bit, works everywhere)</option>
|
| 188 |
<option value="q4f16">q4f16 (4-bit weights, fp16 math; WebGPU with fp16 only)</option>
|
|
|
|
| 189 |
<option value="fp16">fp16 (largest; WebGPU only)</option>
|
| 190 |
</select>
|
| 191 |
</label>
|
|
|
|
| 206 |
</section>
|
| 207 |
</main>
|
| 208 |
|
| 209 |
+
<!-- EGG CHECK -->
|
| 210 |
+
<main class="wrap view" data-view="egg" hidden>
|
| 211 |
+
<section class="panel">
|
| 212 |
+
<h2>Egg check</h2>
|
| 213 |
+
<p class="note">Candling photos (a light shone through the egg in a dark room). The decision uses the format the model was trained with:
|
| 214 |
+
the photo with <code>Is this egg good or bad?</code> and the candling context, scored against <code>Normal, healthy egg</code> and
|
| 215 |
+
<code>Defective, spoiled or damaged egg</code>. The 8 photos below are held out: they were not used in training. Pick one, run all 8, or use your own photo.</p>
|
| 216 |
+
<div class="egggrid" id="eggGrid"></div>
|
| 217 |
+
<div class="btnrow">
|
| 218 |
+
<button id="eggRunAll" class="primary inline">Check all 8</button>
|
| 219 |
+
<label class="drop inline"><input type="file" id="eggFile" accept="image/*" /><span>Use your own candling photo (stays on this device)</span></label>
|
| 220 |
+
</div>
|
| 221 |
+
<div id="eggSummary" class="summary"></div>
|
| 222 |
+
<div class="eggresult" id="eggResult" hidden>
|
| 223 |
+
<img id="eggPreview" alt="Selected egg photo" />
|
| 224 |
+
<div id="eggOut"></div>
|
| 225 |
+
</div>
|
| 226 |
+
<div class="tablewrap"><table id="eggTable" hidden>
|
| 227 |
+
<thead><tr><th>Photo</th><th>Gold</th><th>Decision</th><th>p(good)</th><th>p(bad)</th><th>OK</th><th>ms</th></tr></thead>
|
| 228 |
+
<tbody></tbody>
|
| 229 |
+
</table></div>
|
| 230 |
+
<p class="note">Photos: Good and Bad Eggs Identification Image Dataset (Mendeley Data, doi:10.17632/mdty358x8m.1), CC BY 4.0. See <a href="./CREDITS.md" target="_blank">CREDITS.md</a>.</p>
|
| 231 |
+
</section>
|
| 232 |
+
</main>
|
| 233 |
+
|
| 234 |
<!-- SAMPLES -->
|
| 235 |
<main class="wrap view" data-view="samples" hidden>
|
| 236 |
<section class="panel">
|
| 237 |
<h2>Sample tests (18)</h2>
|
| 238 |
+
<p class="note">Counting, yes / no, spatial relations, a chart, a receipt, app screens, scene text, common sense and egg candling (the egg photos are held out from training; the other images may come from datasets the training mix drew on). Each test runs in this browser with the prompt format, image detail and temperature chosen under Single input > Settings. In the trained format, yes / no tests keep the question in the query and score the options "Yes" and "No"; the older formats use the yes / no mode (the question followed by "Yes." or "No.").</p>
|
| 239 |
<div class="btnrow">
|
| 240 |
<button id="runAllBtn" class="primary inline">Run all samples</button>
|
| 241 |
<button id="compareBtn" class="ghost">Compare all prompt formats</button>
|
|
|
|
| 256 |
<section class="panel prose">
|
| 257 |
<h2>How it works</h2>
|
| 258 |
<ol>
|
| 259 |
+
<li>The input (a camera frame, an image, a text, a 2 second sound window or a short video) and the question are turned into one 768-number vector (mean pooling, then L2 normalization) by <a href="https://huggingface.co/google/embeddinggemma-2" target="_blank" rel="noopener">EmbeddingGemma 2</a> (Apache-2.0), fine-tuned for decisions: the question and the media go into one embedding and each option into another, and training pushes the right option closest. It runs as ONNX (same file layout as <a href="https://huggingface.co/onnx-community/embeddinggemma-2-ONNX" target="_blank" rel="noopener">onnx-community/embeddinggemma-2-ONNX</a>, with the fine-tuned weights) with <a href="https://github.com/huggingface/transformers.js" target="_blank" rel="noopener">transformers.js</a> 4.3.1 on WebGPU (or WASM on the CPU). The model files are served with this page.</li>
|
| 260 |
<li>Each option description is embedded once and cached.</li>
|
| 261 |
+
<li>The probabilities are softmax(scale × cosine) over the options. The scale was learned in training (about 19.96), so the default temperature is 1 / scale, about 0.050.</li>
|
| 262 |
+
<li>In Live mode each card embeds the frame together with its own question (one pass per card). The alternative "frame alone" setting embeds the frame once and scores all cards from that vector, which is faster but is not the format the model was trained with.</li>
|
| 263 |
<li>A card whose top probability is below its threshold is marked uncertain. That is where a larger model would take over; this page only counts it.</li>
|
| 264 |
</ol>
|
| 265 |
<h3>Privacy</h3>
|
|
|
|
| 271 |
<li>An embedding model compares meanings; it does not read, count or reason step by step. Questions about exact counts, small text or negation are hard for it.</li>
|
| 272 |
<li>Probabilities depend on the temperature. They are comparable between options of one card, not calibrated against ground truth.</li>
|
| 273 |
<li>WebGPU needs a recent Chrome, Edge or Safari. Without it the page falls back to the CPU (WASM): it works, but it downloads a larger fp16 model (about 880 MB, because the 4-bit graphs need an operator the CPU runtime lacks) and takes several seconds per image, so the live rate drops to a frame every few seconds.</li>
|
| 274 |
+
<li>The fine-tuning targeted image decisions (including egg candling). The audio encoder is the unchanged base one, so sound decisions are not tuned.</li>
|
| 275 |
</ul>
|
| 276 |
<p class="note">Sample image credits: <a href="./CREDITS.md" target="_blank">CREDITS.md</a>. Code: Apache-2.0.</p>
|
| 277 |
</section>
|
| 278 |
</main>
|
| 279 |
|
| 280 |
<footer class="wrap foot">
|
| 281 |
+
<p>Based on EmbeddingGemma 2 by Google DeepMind (Apache-2.0), fine-tuned for decisions, run with transformers.js. This page sends no data anywhere.</p>
|
| 282 |
</footer>
|
| 283 |
+
<script type="module" src="./app.js?v=5"></script>
|
| 284 |
</body>
|
| 285 |
</html>
|
models/egemma2-decide/chat_template.jinja
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{%- for msg in messages if msg.get('role') == 'system' -%}{%- if msg.get('content') is string -%}{{ msg['content'] }}{%- else -%}{%- for item in msg['content'] if item.get('type') == 'text' -%}{{ item['text'] }}{%- endfor -%}{%- endif -%}{%- endfor -%}{%- for msg in messages if msg.get('role') != 'system' -%}{%- if msg.get('content') is string -%}{{ msg['content'] }}{%- else -%}{%- set existing_text = msg['content'] | selectattr('type', 'equalto', 'text') | map(attribute='text') | join -%}{%- set has_manual_placeholders = ('<|image|>' in existing_text) or ('<|video|>' in existing_text) or ('<|audio|>' in existing_text) -%}{%- for item in msg['content'] -%}{%- if item.get('type') == 'text' -%}{{ item['text'] }}{%- elif not has_manual_placeholders and item.get('type') == 'image' -%}<|image|>{%- elif not has_manual_placeholders and item.get('type') == 'video' -%}<|video|>{%- elif not has_manual_placeholders and item.get('type') == 'audio' -%}<|audio|>{%- endif -%}{%- endfor -%}{%- endif -%}{%- endfor -%}
|
models/egemma2-decide/config.json
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"EmbeddingGemma2Model"
|
| 4 |
+
],
|
| 5 |
+
"audio_config": {
|
| 6 |
+
"_name_or_path": "",
|
| 7 |
+
"architectures": null,
|
| 8 |
+
"attention_chunk_size": 12,
|
| 9 |
+
"attention_context_left": 13,
|
| 10 |
+
"attention_context_right": 0,
|
| 11 |
+
"attention_invalid_logits_value": -1000000000.0,
|
| 12 |
+
"attention_logit_cap": 50.0,
|
| 13 |
+
"chunk_size_feed_forward": 0,
|
| 14 |
+
"conv_kernel_size": 5,
|
| 15 |
+
"dtype": "bfloat16",
|
| 16 |
+
"gradient_clipping": 10000000000.0,
|
| 17 |
+
"hidden_act": "silu",
|
| 18 |
+
"hidden_size": 1024,
|
| 19 |
+
"id2label": {
|
| 20 |
+
"0": "LABEL_0",
|
| 21 |
+
"1": "LABEL_1"
|
| 22 |
+
},
|
| 23 |
+
"initializer_range": 0.02,
|
| 24 |
+
"is_encoder_decoder": false,
|
| 25 |
+
"label2id": {
|
| 26 |
+
"LABEL_0": 0,
|
| 27 |
+
"LABEL_1": 1
|
| 28 |
+
},
|
| 29 |
+
"model_type": "gemma4_audio",
|
| 30 |
+
"num_attention_heads": 8,
|
| 31 |
+
"num_hidden_layers": 12,
|
| 32 |
+
"output_attentions": false,
|
| 33 |
+
"output_hidden_states": false,
|
| 34 |
+
"output_proj_dims": 1536,
|
| 35 |
+
"problem_type": null,
|
| 36 |
+
"residual_weight": 0.5,
|
| 37 |
+
"return_dict": true,
|
| 38 |
+
"rms_norm_eps": 1e-06,
|
| 39 |
+
"subsampling_conv_channels": [
|
| 40 |
+
128,
|
| 41 |
+
32
|
| 42 |
+
],
|
| 43 |
+
"use_clipped_linears": true
|
| 44 |
+
},
|
| 45 |
+
"audio_token_id": 258881,
|
| 46 |
+
"boa_token_id": 256000,
|
| 47 |
+
"boi_token_id": 255999,
|
| 48 |
+
"dtype": "bfloat16",
|
| 49 |
+
"eoa_token_index": 258883,
|
| 50 |
+
"eoi_token_id": 258882,
|
| 51 |
+
"image_token_id": 258880,
|
| 52 |
+
"initializer_range": 0.02,
|
| 53 |
+
"model_type": "embedding_gemma2",
|
| 54 |
+
"text_config": {
|
| 55 |
+
"attention_bias": false,
|
| 56 |
+
"attention_dropout": 0.0,
|
| 57 |
+
"bos_token_id": 2,
|
| 58 |
+
"dtype": "bfloat16",
|
| 59 |
+
"embedding_dim": 768,
|
| 60 |
+
"eos_token_id": 1,
|
| 61 |
+
"head_dim": 256,
|
| 62 |
+
"hidden_activation": "gelu_pytorch_tanh",
|
| 63 |
+
"hidden_size": 512,
|
| 64 |
+
"hidden_size_per_layer_input": 512,
|
| 65 |
+
"initializer_range": 0.02,
|
| 66 |
+
"intermediate_size": 2048,
|
| 67 |
+
"layer_types": [
|
| 68 |
+
"sliding_attention",
|
| 69 |
+
"sliding_attention",
|
| 70 |
+
"sliding_attention",
|
| 71 |
+
"sliding_attention",
|
| 72 |
+
"sliding_attention",
|
| 73 |
+
"full_attention",
|
| 74 |
+
"sliding_attention",
|
| 75 |
+
"sliding_attention",
|
| 76 |
+
"sliding_attention",
|
| 77 |
+
"sliding_attention",
|
| 78 |
+
"sliding_attention",
|
| 79 |
+
"full_attention",
|
| 80 |
+
"sliding_attention",
|
| 81 |
+
"sliding_attention",
|
| 82 |
+
"sliding_attention",
|
| 83 |
+
"sliding_attention",
|
| 84 |
+
"sliding_attention",
|
| 85 |
+
"full_attention",
|
| 86 |
+
"sliding_attention",
|
| 87 |
+
"sliding_attention",
|
| 88 |
+
"sliding_attention",
|
| 89 |
+
"sliding_attention",
|
| 90 |
+
"sliding_attention",
|
| 91 |
+
"full_attention"
|
| 92 |
+
],
|
| 93 |
+
"max_position_embeddings": 262144,
|
| 94 |
+
"model_type": "embedding_gemma2_text",
|
| 95 |
+
"num_attention_heads": 4,
|
| 96 |
+
"num_hidden_layers": 24,
|
| 97 |
+
"num_key_value_heads": 2,
|
| 98 |
+
"pad_token_id": 0,
|
| 99 |
+
"per_layer_config": {
|
| 100 |
+
"05": {
|
| 101 |
+
"head_dim": 512,
|
| 102 |
+
"num_key_value_heads": 1
|
| 103 |
+
},
|
| 104 |
+
"11": {
|
| 105 |
+
"head_dim": 512,
|
| 106 |
+
"num_key_value_heads": 1
|
| 107 |
+
},
|
| 108 |
+
"17": {
|
| 109 |
+
"head_dim": 512,
|
| 110 |
+
"num_key_value_heads": 1
|
| 111 |
+
},
|
| 112 |
+
"23": {
|
| 113 |
+
"head_dim": 512,
|
| 114 |
+
"num_key_value_heads": 1
|
| 115 |
+
}
|
| 116 |
+
},
|
| 117 |
+
"rms_norm_eps": 1e-06,
|
| 118 |
+
"rope_parameters": {
|
| 119 |
+
"full_attention": {
|
| 120 |
+
"rope_theta": 1000000.0,
|
| 121 |
+
"rope_type": "default"
|
| 122 |
+
},
|
| 123 |
+
"sliding_attention": {
|
| 124 |
+
"rope_theta": 10000.0,
|
| 125 |
+
"rope_type": "default"
|
| 126 |
+
}
|
| 127 |
+
},
|
| 128 |
+
"sliding_window": 512,
|
| 129 |
+
"vocab_size": 262144
|
| 130 |
+
},
|
| 131 |
+
"transformers_version": "5.18.0.dev0",
|
| 132 |
+
"video_token_id": 258884,
|
| 133 |
+
"vision_config": {
|
| 134 |
+
"_name_or_path": "",
|
| 135 |
+
"architectures": null,
|
| 136 |
+
"attention_bias": false,
|
| 137 |
+
"attention_dropout": 0.0,
|
| 138 |
+
"chunk_size_feed_forward": 0,
|
| 139 |
+
"default_output_length": 280,
|
| 140 |
+
"dtype": "bfloat16",
|
| 141 |
+
"global_head_dim": 64,
|
| 142 |
+
"head_dim": 64,
|
| 143 |
+
"hidden_activation": "gelu_pytorch_tanh",
|
| 144 |
+
"hidden_size": 768,
|
| 145 |
+
"id2label": {
|
| 146 |
+
"0": "LABEL_0",
|
| 147 |
+
"1": "LABEL_1"
|
| 148 |
+
},
|
| 149 |
+
"initializer_range": 0.02,
|
| 150 |
+
"intermediate_size": 3072,
|
| 151 |
+
"is_encoder_decoder": false,
|
| 152 |
+
"label2id": {
|
| 153 |
+
"LABEL_0": 0,
|
| 154 |
+
"LABEL_1": 1
|
| 155 |
+
},
|
| 156 |
+
"max_position_embeddings": 131072,
|
| 157 |
+
"model_type": "gemma4_vision",
|
| 158 |
+
"num_attention_heads": 12,
|
| 159 |
+
"num_hidden_layers": 16,
|
| 160 |
+
"num_key_value_heads": 12,
|
| 161 |
+
"output_attentions": false,
|
| 162 |
+
"output_hidden_states": false,
|
| 163 |
+
"patch_size": 16,
|
| 164 |
+
"pooling_kernel_size": 3,
|
| 165 |
+
"position_embedding_size": 10240,
|
| 166 |
+
"problem_type": null,
|
| 167 |
+
"return_dict": true,
|
| 168 |
+
"rms_norm_eps": 1e-06,
|
| 169 |
+
"rope_parameters": {
|
| 170 |
+
"rope_theta": 100.0,
|
| 171 |
+
"rope_type": "axial"
|
| 172 |
+
},
|
| 173 |
+
"standardize": false,
|
| 174 |
+
"use_clipped_linears": false
|
| 175 |
+
},
|
| 176 |
+
"vision_soft_tokens_per_image": 280,
|
| 177 |
+
"transformers.js_config": {
|
| 178 |
+
"use_external_data_format": {
|
| 179 |
+
"audio_encoder.onnx": 1,
|
| 180 |
+
"audio_encoder_fp16.onnx": 1,
|
| 181 |
+
"audio_encoder_q4.onnx": 1,
|
| 182 |
+
"audio_encoder_q4f16.onnx": 1,
|
| 183 |
+
"model.onnx": 1,
|
| 184 |
+
"model_fp16.onnx": 1,
|
| 185 |
+
"model_q4.onnx": 1,
|
| 186 |
+
"model_q4f16.onnx": 1,
|
| 187 |
+
"vision_encoder.onnx": 1,
|
| 188 |
+
"vision_encoder_fp16.onnx": 1,
|
| 189 |
+
"vision_encoder_q4.onnx": 1,
|
| 190 |
+
"vision_encoder_q4f16.onnx": 1
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
}
|
models/egemma2-decide/decision.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"scale": 19.96074676513672,
|
| 3 |
+
"log_scale": 2.993767738342285,
|
| 4 |
+
"base_model": "google/embeddinggemma-2",
|
| 5 |
+
"source_checkpoint": "runs/eg_v1/final",
|
| 6 |
+
"probability": "softmax(scale * cos(query_embedding, option_embedding)) over the options",
|
| 7 |
+
"embedding": "mean of last_hidden_state over the attention mask, then L2 normalisation (ONNX output sentence_embedding)",
|
| 8 |
+
"query_format": "<|image|> (one per image, first) + \"task: classification | query: {question}\" + \"\nContext: {context}\" when a context is given",
|
| 9 |
+
"option_format": "title: none | text: {option description}"
|
| 10 |
+
}
|
models/egemma2-decide/onnx/audio_encoder_q4.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c4cce3370e72262280d00293cac038896050a03a8e9a27e10b061ca97510296e
|
| 3 |
+
size 245543
|
models/egemma2-decide/onnx/audio_encoder_q4.onnx_data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ba9328e6341360974083085b44b2bba265003bda564740f7c4c23ed9928f17e2
|
| 3 |
+
size 189075968
|
models/egemma2-decide/onnx/audio_encoder_q4f16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e61ee0d27a4ee2b13cfa4f6492d6bc9e18d23f998992b31e9c7355be6c028d58
|
| 3 |
+
size 252538
|
models/egemma2-decide/onnx/audio_encoder_q4f16.onnx_data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:356991f24ed4daee4728997a71fe11b72ebf5c053410ac29c7ce27d0f3fc7655
|
| 3 |
+
size 170348800
|