import { cachedFile, wipe, usage } from './store.js'; import { encodeImage } from './vision.js'; import { composeModel, loadModel, Chat } from './llm.js'; const q = new URLSearchParams(location.search); const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks: same-origin paths only const REPO = 'WeReCooking/MiniGPT4-7B-WebGPU'; const BASE = local(q.get('model')) || `https://huggingface.co/${REPO}/resolve/main`; const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs'; const N_CTX = Number(q.get('ctx')) || 2048; // Switches for telling a GPU problem from a model problem: ?gpu=0 everything on CPU, ?vgpu=0 vision on CPU, ?llmgpu=0 language model on CPU, ?check=1 compare GPU and CPU image embeddings. const USE_GPU = q.get('gpu') !== '0', VISION_GPU = q.get('vgpu') !== '0', LLM_GPU = q.get('llmgpu') !== '0', CHECK = q.get('check') === '1'; const EXAMPLES = [{ label: 'two cats', image: 'examples/cats.jpg', q: 'Describe this image in detail.', a: 'This image shows two cats lying on a pink blanket. One cat is sleeping with its eyes closed, while the other is lying on its side with its eyes open. There are two remote controls on the blanket next to the cats. The image appears to be taken in a living room or other indoor space.' }]; const PROMPTS = ['Describe this image in detail.', 'Write a short caption for this image.', 'What is unusual about this image?', 'What is the mood of this image?']; const $ = (id) => document.getElementById(id); const ui = { drop: $('drop'), file: $('file'), preview: $('preview'), status: $('status'), bar: $('bar').firstElementChild, ask: $('ask'), q: $('q'), go: $('go'), stop: $('stop'), log: $('log'), examples: $('examples'), prompts: $('prompts'), store: $('store'), wipe: $('wipe') }; const mb = (b) => `${Math.round(b / 1e6)} MB`; const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }; function status(text, frac = null, bad = false) { ui.status.textContent = text; ui.status.classList.toggle('bad', bad); if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`; } const setReady = (on) => { ui.q.disabled = !on; ui.go.disabled = !on; }; // ---------------------------------------------------------------- weights let cfgP = null, ortP = null, filesP = null; const getCfg = () => (cfgP ||= fetch(`${BASE}/config.json`).then((r) => { if (!r.ok) throw new Error(`model repo not reachable (HTTP ${r.status})`); return r.json(); })); const getOrt = () => (ortP ||= import(ORT_URL).then((o) => { o.env.logLevel = 'error'; return o; })); const getFiles = () => (filesP ||= (async () => { const cfg = await getCfg(), total = cfg.gguf.bytes + cfg.vision.model_bytes + cfg.vision.data_bytes; let done = 0; const get = async (label, f) => { const file = await cachedFile(f.name, `${BASE}/${f.path}`, f.bytes, (got) => status(`Downloading ${label}: ${mb(done + got)} of ${mb(total)}, first time only`, (done + got) / total)); done += f.bytes; return file; }; const vm = await get('the vision model', { name: 'vision.onnx', path: cfg.vision.model, bytes: cfg.vision.model_bytes }); const vd = await get('the vision weights', { name: 'vision.onnx.data', path: cfg.vision.data, bytes: cfg.vision.data_bytes }); const gguf = await get('the language model', { name: 'vicuna.gguf', path: cfg.gguf.path, bytes: cfg.gguf.bytes }); return { cfg, vision: { model: vm, data: vd, dataName: cfg.vision.data_name }, gguf }; })().catch((e) => { filesP = null; throw e; })); // ---------------------------------------------------------------- one image = embeddings -> patched model -> chat let current = null, generation = 0, abort = null; async function useImage(bitmap, cached = null) { const my = ++generation; abort?.abort(); setReady(false); ui.log.replaceChildren(); ui.stop.hidden = true; try { const [ort, files] = await Promise.all([getOrt(), getFiles()]); const gpu = USE_GPU && !!navigator.gpu && !!(await navigator.gpu.requestAdapter().catch(() => null)); if (!gpu) status('No WebGPU in this browser: running on the CPU (very slow).', 0); status('Looking at the image (vision model)…', 0); const vgpu = gpu && VISION_GPU; const embeds = await encodeImage(ort, files.vision, bitmap, vgpu ? 'webgpu' : 'wasm', () => status('The GPU could not run the vision model: using the CPU instead (slower)…', 0)); let check = ''; if (CHECK && vgpu) { status('Checking the GPU result against the CPU (slow)…', 0); check = `GPU vs CPU image embeddings: cosine ${cosine(embeds, await encodeImage(ort, files.vision, bitmap, 'wasm')).toFixed(5)} (1.0 = identical; below 0.99 means the GPU computes the image wrongly)`; } if (my !== generation) return; if (current) { await current.w.exit().catch(() => {}); current = null; } status('Loading the language model with the image (a few seconds from the cache)…', 0); const blob = composeModel(files.gguf, files.cfg.gguf, embeds); const { w, nCtx } = await loadModel(blob, { nCtx: N_CTX, gpu: gpu && LLM_GPU, onStatus: (t) => status(t) }); if (my !== generation) { await w.exit().catch(() => {}); return; } current = { w, chat: new Chat(w, files.cfg.gguf), nCtx }; setReady(true); if (cached) { addTurn(cached.q, cached.a, 'Precomputed answer (greedy decoding). Ask again to run it on your GPU.'); status('Ready. Ask anything about the image.', 1); } else status('Ready. Ask anything about the image.', 1); if (check) addTurn('Diagnostics', check); else if (CHECK) addTurn('Diagnostics', 'Vision ran on the CPU, so there is nothing to compare.'); } catch (e) { console.error(e); if (my === generation) status(e?.message || String(e), 0, true); } } const cosine = (a, b) => { let d = 0, x = 0, y = 0; for (let i = 0; i < a.length; i++) { d += a[i] * b[i]; x += a[i] * a[i]; y += b[i] * b[i]; } return d / Math.sqrt(x * y); }; function addTurn(question, answer, note) { const t = el('div', 'turn'); t.append(el('p', 'q', question)); const a = el('p', 'a', answer); t.append(a); const n = el('p', 'note', note || ''); if (note) t.append(n); ui.log.prepend(t); return { set(text) { a.textContent = text; }, note(text) { n.textContent = text; if (!n.isConnected) t.append(n); } }; } ui.ask.addEventListener('submit', async (e) => { e.preventDefault(); const question = ui.q.value.trim(); if (!question || !current) return; const { chat, nCtx } = current, my = generation; setReady(false); ui.stop.hidden = false; status('Reading the image and your question…', 0); abort = new AbortController(); const card = addTurn(question, '…'); const t0 = performance.now(); let n = 0, tokens = 0; try { for await (const part of chat.ask(question, { maxTokens: 300, signal: abort.signal })) { n++; tokens = part.tokens; card.set(part.text.split('###')[0].replace(/^\s*Assistant:/, '').trim() || '…'); status(`Answering… ${n} tokens · ${(n / ((performance.now() - t0) / 1000)).toFixed(1)} tokens/s · context ${(tokens + n).toLocaleString()} of ${nCtx}`); } card.note(`${n} tokens in ${((performance.now() - t0) / 1000).toFixed(1)} s`); status('Ready. Ask anything about the image.', 1); } catch (err) { if (abort.signal.aborted) { card.note('Stopped.'); status('Stopped.', 1); } else { console.error(err); card.note(err?.message || String(err)); status(err?.message || String(err), 1, true); } } ui.stop.hidden = true; if (my === generation) setReady(true); }); ui.stop.addEventListener('click', () => abort?.abort()); // ---------------------------------------------------------------- inputs async function openImage(file, cached) { try { const bitmap = await createImageBitmap(file); ui.preview.src = URL.createObjectURL(file); ui.preview.hidden = false; await useImage(bitmap, cached); } catch (e) { status(`Cannot read this image: ${e.message}`, 0, true); } } ui.file.addEventListener('change', () => ui.file.files[0] && openImage(ui.file.files[0], null)); ui.drop.addEventListener('dragover', (e) => { e.preventDefault(); ui.drop.classList.add('over'); }); ui.drop.addEventListener('dragleave', () => ui.drop.classList.remove('over')); ui.drop.addEventListener('drop', (e) => { e.preventDefault(); ui.drop.classList.remove('over'); const f = e.dataTransfer.files[0]; if (f) openImage(f, null); }); for (const ex of EXAMPLES) { const b = el('button', '', ex.label); b.type = 'button'; b.addEventListener('click', async () => { ui.q.value = ex.q; openImage(await (await fetch(ex.image)).blob(), ex); }); ui.examples.append(b); } for (const p of PROMPTS) { const b = el('button', '', p); b.type = 'button'; b.addEventListener('click', () => { ui.q.value = p; ui.q.focus(); }); ui.prompts.append(b); } $('repo').href = `https://huggingface.co/${REPO}`; $('repo').textContent = REPO; const showStore = async () => { ui.store.textContent = `This site stores ${mb(await usage())} in this browser.`; }; ui.wipe.addEventListener('click', async () => { await wipe(); filesP = null; ui.store.textContent = 'Deleted. The models download again next time.'; }); showStore(); window.__m4 = { useImage, getFiles, getOrt, get current() { return current; }, openImage }; // test hook