Spaces:
Running
Running
MiniGPT-4 WebGPU
Browse filesFiles changed (12)
- .gitattributes+1
- README.md+25-5
- examples/cats.jpgAdded
- index.html+45-17
- llm.jsAdded+61
- main.jsAdded+109
- pilresize.jsAdded+85
- store.jsAdded+23
- style.css+30-28
- vendor/wllama/index.jsAdded
- vendor/wllama/wllama.wasmAdded+3
- vision.jsAdded+34
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/cats.jpg filter=lfs diff=lfs merge=lfs -text
12345678910---title: MiniGPT4 WebGPUemoji: 🐠colorFrom: yellowcolorTo: yellowsdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930---title: MiniGPT-4 WebGPUemoji: 🖼️colorFrom: purplecolorTo: graysdk: staticapp_file: index.htmlpinned: falselicense: othershort_description: The original 2023 MiniGPT-4, on your GPU in the browsercustom_headers:cross-origin-embedder-policy: credentiallesscross-origin-opener-policy: same-origincross-origin-resource-policy: cross-originmodels:- WeReCooking/MiniGPT4-7B-WebGPU- Vision-CAIR/vicuna-7btags:- webgpu- wllama- onnxruntime-web- minigpt4- image-captioning---The original April 2023 [MiniGPT-4](https://github.com/Vision-CAIR/MiniGPT-4) (EVA ViT-G, Q-Former, one linear projection, Vicuna-7B v0) running in your browser, with nothing uploaded: the vision side as an 8-bit ONNX graph on ONNX Runtime Web, the language model as a 4-bit GGUF on wllama (llama.cpp WebAssembly + WebGPU). A browser port of [Luminia/MiniGPT-4](https://huggingface.co/spaces/Luminia/MiniGPT-4); weights in [WeReCooking/MiniGPT4-7B-WebGPU](https://huggingface.co/WeReCooking/MiniGPT4-7B-WebGPU).llama.cpp cannot take raw embeddings, so the 32 image vectors are written into 32 reserved rows (`<0x80>`..`<0x9F>`) of the F16 token-embedding table before the model is loaded; the prompt carries those 32 token ids. A new image reloads the model from the browser cache; more questions about the same image do not.Checked in headless Chromium: image preprocessing is bit-exact with torchvision; the ONNX vision graph matches PyTorch (cosine 0.99996); the 8-bit WebGPU kernel matches the CPU one to 2.5e-7; native llama.cpp with the patched table captions the example correctly, and so does the full page on CPU. **Not measured:** speed and memory on a real GPU (this sandbox has none). Vicuna v0 derives from LLaMA-1 (non-commercial research licence).
12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>MiniGPT-4 WebGPU</title><meta name="description" content="The original 2023 MiniGPT-4 (EVA ViT-G, Q-Former, Vicuna-7B v0) running on your own GPU in the browser. Nothing is uploaded."><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"></head><body><main><p id="line"><b><a href="https://github.com/Vision-CAIR/MiniGPT-4" target="_blank" rel="noopener">MiniGPT-4</a></b>, the original April 2023 model, running on <b>your GPU</b>:a vision encoder and a 4-bit Vicuna-7B, nothing uploaded. First use downloads about 5 GB, kept in your browser.</p><label id="drop" for="file"><input id="file" type="file" accept="image/*"><span>Drop an image here, or choose one</span></label><p id="examples-row">Or try: <span id="examples"></span></p><img id="preview" alt="" hidden><p id="status" role="status" aria-live="polite">Pick an image to begin.</p><div id="bar"><i></i></div><form id="ask" autocomplete="off"><label for="q" class="sr">Question about the image</label><input id="q" type="text" maxlength="400" value="Describe this image in detail." disabled><button id="go" type="submit" disabled>Ask</button><button id="stop" type="button" hidden>Stop</button></form><p id="prompts"></p><section id="log" aria-live="polite"></section><details id="more"><summary>How it works, limits and credits</summary><p><b>Model.</b> The original MiniGPT-4 (Vision-CAIR, KAUST): a frozen EVA ViT-G, a frozen BLIP-2 Q-Former and one trained linear projection feed 32 image tokens to Vicuna-7B v0. The vision part runs as an 8-bit ONNX graph on<a href="https://onnxruntime.ai/" target="_blank" rel="noopener">ONNX Runtime Web</a> (1.2 GB); the language model is a 4-bit GGUF (3.8 GB) on <a href="https://github.com/ngxson/wllama" target="_blank" rel="noopener">wllama</a> (llama.cpp WebAssembly + WebGPU).Weights: <a id="repo" target="_blank" rel="noopener">the model repo</a>. Sources: <a href="https://huggingface.co/spaces/Luminia/MiniGPT-4" target="_blank" rel="noopener">Luminia/MiniGPT-4</a>, whose CPU/GPU version this mirrors, <a href="https://huggingface.co/Vision-CAIR/vicuna-7b" target="_blank" rel="noopener">Vision-CAIR/vicuna-7b</a>.</p><p><b>How the image gets in.</b> llama.cpp (and so wllama) cannot take raw embeddings, so the 32 image vectors are written into 32 reserved rows of the model's token-embedding table (the byte tokens <0x80>…<0x9F>) before the model is loaded, and the prompt carries those 32 token ids.A new image therefore reloads the language model from your browser's cache (some seconds); more questions about the same image do not. Text containing those rare byte tokens is not supported.</p><p><b>Limits.</b> About 6 GB of free memory and a GPU with 4 GB+ of video memory are needed; without WebGPU it runs on the CPU, at under one word a second. This is a 2023 model: captions are often wrong in details, and it is uncensored, so it describes whatever you give it.Vicuna v0 is derived from LLaMA-1 (non-commercial research licence).</p><p id="store"></p><button id="wipe" type="button">Delete downloaded models</button></details></main><script type="module" src="main.js"></script></body></html>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// Vicuna-7B v0 (Q4_0 GGUF) on wllama, with the 32 image embeddings written into 32 rows of the F16 token-embedding table.// wllama cannot take raw embeddings, so the image rides in as 32 reserved token ids whose embedding rows are replaced// before the model is loaded (a lazily-composed Blob: slice of the cached file + the new rows + the rest of the file).import { Wllama } from './vendor/wllama/index.js';
export const SYSTEM = 'Give the following image: <Img>ImageContent</Img>. You will be able to see the image once I provide it to you. Please answer my questions.';export const SAMPLING = { temperature: 0.7, top_p: 0.9, repeat_penalty: 1.05 }; // the original demo's defaults
// float32 -> float16 bits (round to nearest), exact for the normal range the embeddings live inexport function f32ToF16(src) { const f = new Float32Array(1), i = new Int32Array(f.buffer), out = new Uint16Array(src.length); for (let k = 0; k < src.length; k++) { f[0] = src[k]; const x = i[0], e = (x >> 23) & 0xff; let bits = (x >> 16) & 0x8000, m = (x >> 12) & 0x07ff; if (e < 103) { out[k] = bits; continue; } if (e > 142) { out[k] = bits | 0x7c00 | (e === 255 && (x & 0x007fffff) ? 1 : 0); continue; } if (e < 113) { m |= 0x0800; bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1); out[k] = bits; continue; } bits |= ((e - 112) << 10) | (m >> 1); bits += m & 1; out[k] = bits; } return out;}
export function composeModel(file, cfg, embeds) { const rowBytes = cfg.dim * 2, start = cfg.embd_offset + cfg.first_id * rowBytes, end = start + cfg.n_image * rowBytes; if (embeds.length !== cfg.n_image * cfg.dim) throw new Error('unexpected embedding size'); return new Blob([file.slice(0, start), f32ToF16(embeds), file.slice(end)]);}
export async function loadModel(blob, { nCtx, gpu, onStatus }) { let n = nCtx; for (;;) { const w = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href }); try { await w.loadModel([blob], { n_ctx: n, n_gpu_layers: gpu ? 999 : 0 }); return { w, nCtx: n }; } catch (e) { console.warn('load failed', e); await w.exit().catch(() => {}); if (n <= 1024) throw e; n = Math.max(1024, n >> 1); onStatus?.(`Not enough memory for a ${nCtx}-token context, retrying with ${n}…`); } }}
// One conversation about one image. The prompt is rebuilt from text each turn; llama.cpp reuses the shared prefix.export class Chat { constructor(w, cfg) { this.w = w; this.cfg = cfg; this.turns = []; this.ids = Array.from({ length: cfg.n_image }, (_, i) => cfg.first_id + i); } async promptTokens(question) { const turns = [...this.turns, { q: question, a: null }]; // no trailing space after the last role: with a Q4_0 model it makes the answer open with a stray character let rest = '</Img> '; turns.forEach((t, i) => { rest += (i ? '###Human: ' : '') + t.q + '###Assistant:' + (t.a !== null ? ' ' + t.a : ''); }); const head = await this.w.tokenize(`${SYSTEM}###Human: <Img>`, { addSpecial: true }); const tail = await this.w.tokenize(rest, { addSpecial: false }); return [...head, ...this.ids, ...tail]; } async *ask(question, { maxTokens = 300, signal } = {}) { const prompt = await this.promptTokens(question); let text = ''; const stream = await this.w.createCompletion({ prompt, stream: true, max_tokens: maxTokens, stop: ['###'], abortSignal: signal, ...SAMPLING }); for await (const chunk of stream) { const t = chunk.choices?.[0]?.text ?? ''; text += t; yield { text, tokens: prompt.length }; } this.turns.push({ q: question, a: text.split('###')[0].replace(/^\s*Assistant:/, '').trim() }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import { 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 onlyconst 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;const USE_GPU = q.get('gpu') !== '0', LLM_GPU = q.get('llmgpu') !== '0'; // llmgpu=0: test hook (vision on WebGPU, language model on CPU)
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; };
// ---------------------------------------------------------------- weightslet 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 -> chatlet 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 embeds = await encodeImage(ort, files.vision, bitmap, gpu ? 'webgpu' : 'wasm', () => status('The GPU could not run the vision model: using the CPU instead (slower)…', 0)); 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); } catch (e) { console.error(e); if (my === generation) status(e?.message || String(e), 0, true); }}
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());
// ---------------------------------------------------------------- inputsasync 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 hook12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485// Port of Pillow's 8-bit resampling (libImaging/Resample.c) for RGB images, as used by torchvision's Resize(BICUBIC) on a PIL image,// so the browser feeds the vision tower the same pixels as the Python original. img: { w, h, data: Uint8Array RGB }.const PRECISION_BITS = 22;const ONE = 1 << PRECISION_BITS;
const FILTERS = { bicubic: { support: 2.0, f: (x) => { const a = -0.5; if (x < 0) x = -x; if (x < 1) return ((a + 2) * x - (a + 3)) * x * x + 1; if (x < 2) return (((x - 5) * x + 8) * x - 4) * a; return 0; } }, lanczos: { support: 3.0, f: (x) => { const sinc = (v) => { if (v === 0) return 1; v *= Math.PI; return Math.sin(v) / v; }; return (x >= -3 && x < 3) ? sinc(x) * sinc(x / 3) : 0; } },};
function coeffs(inSize, outSize, filter) { const scale = inSize / outSize; const filterscale = scale < 1 ? 1 : scale; const support = filter.support * filterscale; const ksize = Math.ceil(support) * 2 + 1; const kk = new Int32Array(outSize * ksize), bounds = new Int32Array(outSize * 2); const pre = new Float64Array(ksize); for (let xx = 0; xx < outSize; xx++) { const center = (xx + 0.5) * scale, ss = 1 / filterscale; let xmin = Math.trunc(center - support + 0.5); if (xmin < 0) xmin = 0; let xmax = Math.trunc(center + support + 0.5); if (xmax > inSize) xmax = inSize; xmax -= xmin; let ww = 0; for (let x = 0; x < xmax; x++) { const w = filter.f((x + xmin - center + 0.5) * ss); pre[x] = w; ww += w; } for (let x = 0; x < xmax; x++) { const v = ww !== 0 ? pre[x] / ww : pre[x]; kk[xx * ksize + x] = v < 0 ? Math.trunc(-0.5 + v * ONE) : Math.trunc(0.5 + v * ONE); } bounds[xx * 2] = xmin; bounds[xx * 2 + 1] = xmax; } return { kk, bounds, ksize };}
const clip8 = (v) => (v >= (ONE * 256) ? 255 : v <= 0 ? 0 : Math.floor(v / ONE));
// img: { w, h, data: Uint8Array RGB } -> { w, h, data }export function resize(img, outW, outH, kind) { if (outW === img.w && outH === img.h) return { w: img.w, h: img.h, data: img.data.slice() }; const filter = FILTERS[kind]; const H = coeffs(img.w, outW, filter), V = coeffs(img.h, outH, filter); const needH = outW !== img.w, needV = outH !== img.h; const yFirst = V.bounds[0], yLast = V.bounds[(outH - 1) * 2] + V.bounds[(outH - 1) * 2 + 1]; let src = img; if (needH) { const rows = yLast - yFirst, out = new Uint8Array(outW * rows * 3), d = img.data, W = img.w; for (let yy = 0; yy < rows; yy++) { const rowOff = (yy + yFirst) * W * 3; for (let xx = 0; xx < outW; xx++) { const xmin = H.bounds[xx * 2], xmax = H.bounds[xx * 2 + 1], k = xx * H.ksize; let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2; for (let x = 0; x < xmax; x++) { const c = H.kk[k + x], p = rowOff + (x + xmin) * 3; s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c; } const o = (yy * outW + xx) * 3; out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2); } } src = { w: outW, h: rows, data: out }; } if (!needV) return src; const shift = needH ? yFirst : 0, W = src.w, d = src.data, out = new Uint8Array(W * outH * 3); for (let yy = 0; yy < outH; yy++) { const ymin = V.bounds[yy * 2] - shift, ymax = V.bounds[yy * 2 + 1], k = yy * V.ksize; for (let xx = 0; xx < W; xx++) { let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2; for (let y = 0; y < ymax; y++) { const c = V.kk[k + y], p = ((y + ymin) * W + xx) * 3; s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c; } const o = (yy * W + xx) * 3; out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2); } } return { w: W, h: outH, data: out };}1234567891011121314151617181920212223// Downloads big files once into the browser's origin-private file system (OPFS) and hands them back as lazily-read File objects.const root = () => navigator.storage.getDirectory();const exists = async (dir, name) => { try { return await dir.getFileHandle(name); } catch { return null; } };
export async function cachedFile(name, url, bytes, onProgress) { const dir = await root(); const ok = await exists(dir, name + '.ok'), fh = await exists(dir, name); if (ok && fh) { const f = await fh.getFile(); if (f.size === bytes) return f; } await dir.removeEntry(name + '.ok').catch(() => {}); const r = await fetch(url); if (!r.ok) throw new Error(`download of ${name} failed (HTTP ${r.status})`); let got = 0; const counter = new TransformStream({ transform(chunk, ctl) { got += chunk.length; onProgress?.(got, bytes); ctl.enqueue(chunk); } }); const handle = await dir.getFileHandle(name, { create: true }); try { await r.body.pipeThrough(counter).pipeTo(await handle.createWritable()); } catch (e) { await dir.removeEntry(name).catch(() => {}); throw /quota/i.test(`${e?.name} ${e?.message}`) ? new Error('Not enough free disk space in this browser for the model (about 5 GB).') : e; } const f = await handle.getFile(); if (f.size !== bytes) { await dir.removeEntry(name).catch(() => {}); throw new Error(`${name}: expected ${bytes} bytes, got ${f.size}`); } await (await dir.getFileHandle(name + '.ok', { create: true })).createWritable().then((w) => w.close()); return f;}export async function wipe() { const dir = await root(); for await (const [n] of dir.entries()) await dir.removeEntry(n, { recursive: true }); }export async function usage() { try { const e = await navigator.storage.estimate(); return e.usage || 0; } catch { return 0; } }12345678910111213141516171819202122232425262728body {padding: 2rem;font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;}h1 {font-size: 16px;margin-top: 0;}p {color: rgb(107, 114, 128);font-size: 15px;margin-bottom: 10px;margin-top: 5px;}.card {max-width: 620px;margin: 0 auto;padding: 16px;border: 1px solid lightgray;border-radius: 16px;}.card p:last-child {margin-bottom: 0;}123456789101112131415161718192021222324252627282930:root { --bg:#f2f3f5; --panel:#fff; --ink:#1b1d21; --muted:#686d76; --line:#d5d8de; --accent:#4a5bb8; --accent-ink:#fff; --bad:#a3261b; color-scheme: light dark; }@media (prefers-color-scheme: dark) { :root { --bg:#141518; --panel:#1e2024; --ink:#e8eaee; --muted:#9ea3ac; --line:#363a41; --accent:#8d9cf0; --accent-ink:#141518; --bad:#ff8a7a; } }* { box-sizing: border-box; }[hidden] { display: none !important; }html, body { margin:0; background:var(--bg); color:var(--ink); font:15px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; }main { display:grid; gap:10px; padding:10px 12px 24px; max-width:760px; margin:0 auto; }#line { margin:0; font-size:14px; color:var(--muted); } #line b { color:var(--ink); }a { color:var(--accent); }#drop { display:grid; place-items:center; min-height:90px; border:2px dashed var(--line); border-radius:8px; background:var(--panel); cursor:pointer; color:var(--muted); text-align:center; padding:12px; }#drop.over, #drop:hover { border-color:var(--accent); color:var(--ink); }#drop input { position:absolute; width:1px; height:1px; opacity:0; }#drop:focus-within { outline:2px solid var(--accent); outline-offset:2px; }#examples-row, #prompts { margin:0; font-size:13px; color:var(--muted); display:flex; flex-wrap:wrap; gap:6px; align-items:center; }#preview { max-width:100%; max-height:46vh; justify-self:start; border-radius:6px; border:1px solid var(--line); }button { font:inherit; font-weight:600; min-height:38px; padding:0 16px; cursor:pointer; color:var(--accent-ink); background:var(--accent); border:0; border-radius:5px; }button:disabled { opacity:.5; cursor:default; }#examples button, #prompts button { min-height:28px; padding:0 10px; font-size:13px; font-weight:400; color:var(--muted); background:transparent; border:1px solid var(--line); border-radius:14px; }#examples button:hover, #prompts button:hover { color:var(--accent); border-color:var(--accent); }#stop, #wipe { background:transparent; color:var(--ink); border:1px solid var(--line); font-weight:500; }#wipe { min-height:30px; }#status { margin:0; min-height:1.4em; font-size:13px; color:var(--muted); font-variant-numeric:tabular-nums; } #status.bad { color:var(--bad); }#bar { height:4px; background:var(--line); border-radius:2px; overflow:hidden; margin-top:-4px; } #bar i { display:block; height:100%; width:0; background:var(--accent); transition:width .2s; }#ask { display:flex; gap:8px; } #q { flex:1; min-width:0; font:inherit; padding:8px 10px; color:var(--ink); background:var(--panel); border:1px solid var(--line); border-radius:6px; min-height:38px; }#log { display:grid; gap:8px; }.turn { background:var(--panel); border:1px solid var(--line); border-radius:6px; padding:8px 12px; }.turn .q { color:var(--muted); font-size:13px; margin:0 0 4px; } .turn .a { margin:0; white-space:pre-wrap; overflow-wrap:anywhere; } .turn .note { margin:6px 0 0; font-size:12px; color:var(--muted); }#more { color:var(--muted); font-size:13px; } #more p { margin:6px 0; } summary { cursor:pointer; }.sr { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0 0 0 0); }:where(button,input,summary,a,[tabindex]):focus-visible { outline:2px solid var(--accent) !important; outline-offset:2px; }@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration:.01ms !important; } }
123version https://git-lfs.github.com/spec/v1oid sha256:b012436a101ede8c877f2d26644c3181429d4fb8da4fd90c356110d86bfd74a6size 1083865212345678910111213141516171819202122232425262728293031323334// MiniGPT-4's vision side in the browser: EVA ViT-g -> Q-Former -> linear projection, as one ONNX graph (8-bit weights) on ONNX Runtime Web.import { resize } from './pilresize.js';const MEAN = [0.48145466, 0.4578275, 0.40821073], STD = [0.26862954, 0.26130258, 0.27577711];
// bitmap -> Float32 [1,3,224,224]: PIL-exact bicubic squash to 224x224 (no crop), then normalise, like blip2_image_eval.export function preprocess(bitmap) { const c = new OffscreenCanvas(bitmap.width, bitmap.height), g = c.getContext('2d', { willReadFrequently: true }); g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, c.height); g.drawImage(bitmap, 0, 0); // flatten transparency like PIL's convert('RGB') on white-less data const px = g.getImageData(0, 0, c.width, c.height).data, rgb = new Uint8Array(c.width * c.height * 3); for (let i = 0, j = 0; i < px.length; i += 4, j += 3) { rgb[j] = px[i]; rgb[j + 1] = px[i + 1]; rgb[j + 2] = px[i + 2]; } const r = resize({ w: c.width, h: c.height, data: rgb }, 224, 224, 'bicubic'), out = new Float32Array(3 * 224 * 224); for (let i = 0; i < 224 * 224; i++) for (let k = 0; k < 3; k++) out[k * 224 * 224 + i] = (r.data[i * 3 + k] / 255 - MEAN[k]) / STD[k]; return out;}
async function runOnce(ort, files, input, ep) { const [model, data] = await Promise.all([files.model.arrayBuffer(), files.data.arrayBuffer()]); const sess = await ort.InferenceSession.create(new Uint8Array(model), { executionProviders: [ep], logSeverityLevel: 3, externalData: [{ path: files.dataName, data: new Uint8Array(data) }] }); try { return Float32Array.from((await sess.run({ image: new ort.Tensor('float32', input, [1, 3, 224, 224]) })).embeds.data); } // copied out before release finally { await sess.release(); }}const sane = (e) => { let s = 0, s2 = 0; for (const v of e) { if (!Number.isFinite(v)) return false; s += v; s2 += v * v; } const n = e.length; return Math.sqrt(s2 / n - (s / n) ** 2) > 0.05; };
// 32 x 4096 image embeddings. If the GPU run fails or returns junk (a driver or kernel problem), redo it on the CPU provider.export async function encodeImage(ort, files, bitmap, ep, onFallback) { const input = preprocess(bitmap); if (ep === 'webgpu') { try { const e = await runOnce(ort, files, input, 'webgpu'); if (sane(e)) return e; console.warn('WebGPU vision output looks wrong'); } catch (err) { console.warn('WebGPU vision run failed', err); } onFallback?.(); } return runOnce(ort, files, input, 'wasm');}.gitattributes+1
README.md+25-5
examples/cats.jpgAdded

Large File Pointer Details
- SHA256: dea9e7ef97386345f7cff32f9055da4982da5471c48d575146c796ab4563b04e
- Pointer size: 131 Bytes
- Size of remote file: 173 kB
index.html+45-17
llm.jsAdded+61
main.jsAdded+109
pilresize.jsAdded+85
store.jsAdded+23
style.css+30-28
vendor/wllama/index.jsAdded
vendor/wllama/wllama.wasmAdded+3
vision.jsAdded+34