Spaces:
Running
Running
Update Space
Browse files
README.md
CHANGED
|
@@ -1,10 +1,28 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: static
|
|
|
|
| 7 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: loopmm playground
|
| 3 |
+
emoji: 🔁
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: static
|
| 7 |
+
app_file: index.html
|
| 8 |
pinned: false
|
| 9 |
+
license: apache-2.0
|
| 10 |
+
short_description: Chat with a small looped multimodal model in your browser
|
| 11 |
+
models:
|
| 12 |
+
- MostLime/loopmm-chat
|
| 13 |
+
- MostLime/loopmm-base
|
| 14 |
+
custom_headers:
|
| 15 |
+
cross-origin-embedder-policy: credentialless
|
| 16 |
+
cross-origin-opener-policy: same-origin
|
| 17 |
+
cross-origin-resource-policy: cross-origin
|
| 18 |
---
|
| 19 |
|
| 20 |
+
# loopmm playground
|
| 21 |
+
|
| 22 |
+
Chat with loopmm, a small model that reads images and text. Add an image with the + button, by pasting it or by dropping it on the page.
|
| 23 |
+
|
| 24 |
+
The page downloads the model once (about 240 MB, int8 ONNX) and keeps it in your browser's cache. It runs on your computer with onnxruntime-web. Your messages and images do not leave your computer.
|
| 25 |
+
|
| 26 |
+
The "Loops" slider sets how many times the model runs its 12 middle layers. The model was trained with 3. Fewer loops make it faster and worse.
|
| 27 |
+
|
| 28 |
+
There is also a Mac app that works offline: [Mostlime12195/loopmm-app](https://github.com/Mostlime12195/loopmm-app/releases/latest).
|
app.js
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// loopmm chat UI. Same code in the Hugging Face Space and in the desktop app; config.js says where files live.
|
| 2 |
+
import { Engine, Tok, sample, preprocessImage } from './engine.js';
|
| 3 |
+
|
| 4 |
+
const C = window.LOOPMM;
|
| 5 |
+
const $ = (id) => document.getElementById(id);
|
| 6 |
+
const CHUNK = 512, MAX_CTX = 8192;
|
| 7 |
+
const IMG_TOKENS = [395, 396, 498, 499];
|
| 8 |
+
const store = { get(k) { try { return localStorage.getItem(k); } catch { return null; } },
|
| 9 |
+
set(k, v) { try { localStorage.setItem(k, v); } catch {} } };
|
| 10 |
+
const setStatus = (t) => { $('status').textContent = t; };
|
| 11 |
+
const setBar = (f) => { $('bar').hidden = f == null; if (f != null) $('bar').firstElementChild.style.width = `${Math.round(f * 100)}%`; };
|
| 12 |
+
|
| 13 |
+
// ---------------------------------------------------------------- settings
|
| 14 |
+
const S = {};
|
| 15 |
+
for (const [id, key, fmt] of [['loops', 'loops', (v) => v], ['temp', 'temperature', (v) => v], ['topp', 'topP', (v) => v],
|
| 16 |
+
['rep', 'repPenalty', (v) => v], ['max', 'maxNew', (v) => v]]) {
|
| 17 |
+
const el = $(id), out = $(id + 'v');
|
| 18 |
+
const saved = store.get('loopmm.' + id); if (saved != null) el.value = saved;
|
| 19 |
+
const upd = () => { S[key] = +el.value; out.textContent = fmt(el.value); store.set('loopmm.' + id, el.value); };
|
| 20 |
+
el.addEventListener('input', upd); upd();
|
| 21 |
+
}
|
| 22 |
+
$('detail').value = store.get('loopmm.detail') || '256';
|
| 23 |
+
$('detail').addEventListener('change', () => store.set('loopmm.detail', $('detail').value));
|
| 24 |
+
$('menu').onclick = () => $('app').classList.toggle('open');
|
| 25 |
+
$('log').addEventListener('click', () => $('app').classList.remove('open'));
|
| 26 |
+
|
| 27 |
+
// ---------------------------------------------------------------- downloads (Cache API when available)
|
| 28 |
+
async function fetchBytes(url, onProgress) {
|
| 29 |
+
let cache = null;
|
| 30 |
+
try { cache = await caches.open('loopmm-v1'); const hit = await cache.match(url); if (hit) return new Uint8Array(await hit.arrayBuffer()); } catch {}
|
| 31 |
+
const r = await fetch(url);
|
| 32 |
+
if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`);
|
| 33 |
+
const total = +r.headers.get('content-length') || 0, reader = r.body.getReader(), parts = [];
|
| 34 |
+
let got = 0;
|
| 35 |
+
for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); got += value.length; onProgress?.(got, total); }
|
| 36 |
+
const buf = new Uint8Array(got); let o = 0;
|
| 37 |
+
for (const p of parts) { buf.set(p, o); o += p.length; }
|
| 38 |
+
try { if (cache && /^https?:/.test(url)) await cache.put(url, new Response(buf)); } catch {}
|
| 39 |
+
return buf;
|
| 40 |
+
}
|
| 41 |
+
const fetchJson = async (url) => JSON.parse(new TextDecoder().decode(await fetchBytes(url)));
|
| 42 |
+
|
| 43 |
+
// ---------------------------------------------------------------- model loading
|
| 44 |
+
let ort, TokenizerCls, engine = null, tok = null, model = null, chatCfg = null;
|
| 45 |
+
let fed = { keys: [] }; // what the engine holds: one key per token (image tokens keyed by image uid)
|
| 46 |
+
|
| 47 |
+
async function loadLibs() {
|
| 48 |
+
await new Promise((ok, bad) => { const s = document.createElement('script'); s.src = C.ortBase + 'ort.wasm.min.js'; s.onload = ok; s.onerror = () => bad(new Error('could not load onnxruntime-web')); document.head.appendChild(s); });
|
| 49 |
+
ort = window.ort;
|
| 50 |
+
ort.env.wasm.wasmPaths = C.ortBase;
|
| 51 |
+
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(C.maxThreads || 8, navigator.hardwareConcurrency || 1) : 1;
|
| 52 |
+
TokenizerCls = (await import(C.tokenizersUrl)).Tokenizer;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
async function loadModel(m) {
|
| 56 |
+
$('send').disabled = true;
|
| 57 |
+
if (engine) { for (const s of Object.values(engine.s)) try { await s.release(); } catch {} engine = null; }
|
| 58 |
+
model = m; fed = { keys: [] };
|
| 59 |
+
$('model').value = m.id;
|
| 60 |
+
const url = (f) => C.fileUrl(m, f);
|
| 61 |
+
setStatus(`Loading ${m.label}…`);
|
| 62 |
+
const meta = await fetchJson(url('onnx/meta.json'));
|
| 63 |
+
const tj = await fetchJson(url('tokenizer.json')), tc = await fetchJson(url('tokenizer_config.json'));
|
| 64 |
+
tok = new Tok(TokenizerCls, tj, tc);
|
| 65 |
+
chatCfg = m.mode === 'chat' ? await fetchJson(url('chat.json')) : null;
|
| 66 |
+
const names = ['stem', 'prelude', 'core', 'coda'], sizes = meta.file_bytes || {}, got = {}, bufs = {};
|
| 67 |
+
const total = names.reduce((s, n) => s + (sizes[n] || 0), 0);
|
| 68 |
+
for (const n of names) {
|
| 69 |
+
bufs[n] = await fetchBytes(url(`onnx/${n}.onnx`), (g, t) => {
|
| 70 |
+
got[n] = g; const all = Object.values(got).reduce((a, b) => a + b, 0);
|
| 71 |
+
setBar(total ? all / total : g / (t || 1));
|
| 72 |
+
setStatus(`Downloading ${m.label}: ${(all / 1e6).toFixed(0)}${total ? ` of ${(total / 1e6).toFixed(0)}` : ''} MB (once)`);
|
| 73 |
+
});
|
| 74 |
+
}
|
| 75 |
+
setBar(null); setStatus('Starting…');
|
| 76 |
+
engine = await Engine.load(ort, bufs, meta);
|
| 77 |
+
// thinking modes
|
| 78 |
+
const modes = chatCfg?.thinking_modes || [];
|
| 79 |
+
$('thinkfield').hidden = !modes.length;
|
| 80 |
+
$('thinking').innerHTML = modes.map((x) => `<option value="${x.id}">${x.label}</option>`).join('');
|
| 81 |
+
const sv = store.get('loopmm.thinking'); if (sv && modes.some((x) => x.id === sv)) $('thinking').value = sv;
|
| 82 |
+
$('input').placeholder = m.mode === 'chat' ? 'Message loopmm' : 'Start a text; the base model continues it';
|
| 83 |
+
renderEmpty();
|
| 84 |
+
setStatus(`Ready · ${m.label} · ${ort.env.wasm.numThreads} thread${ort.env.wasm.numThreads > 1 ? 's' : ''}`);
|
| 85 |
+
updateSend();
|
| 86 |
+
}
|
| 87 |
+
$('thinking').addEventListener('change', () => store.set('loopmm.thinking', $('thinking').value));
|
| 88 |
+
|
| 89 |
+
// ---------------------------------------------------------------- conversation -> tokens
|
| 90 |
+
let messages = [], uid = 0;
|
| 91 |
+
|
| 92 |
+
function thinkMode() { return (chatCfg?.thinking_modes || []).find((x) => x.id === $('thinking').value) || null; }
|
| 93 |
+
|
| 94 |
+
// units: {ids: number[]} or {image: imageObj}
|
| 95 |
+
function buildUnits(forGen) {
|
| 96 |
+
const U = [], T = (s) => U.push({ ids: tok.encode(s) });
|
| 97 |
+
U.push({ ids: [1] });
|
| 98 |
+
if (model.mode !== 'chat') {
|
| 99 |
+
for (const m of messages) {
|
| 100 |
+
if (m.role === 'user') { for (const im of m.images) U.push({ image: im }); T(m.text); }
|
| 101 |
+
else U.push({ ids: m.ids });
|
| 102 |
+
}
|
| 103 |
+
return U;
|
| 104 |
+
}
|
| 105 |
+
const c = chatCfg, mode = thinkMode();
|
| 106 |
+
const turn = (role) => c.turn_start.replace('{role}', role);
|
| 107 |
+
const sys = [c.system, mode?.system].filter(Boolean).join('\n');
|
| 108 |
+
if (sys) T(turn('system') + sys + c.turn_end);
|
| 109 |
+
const lastA = messages.map((m) => m.role).lastIndexOf('assistant');
|
| 110 |
+
messages.forEach((m, i) => {
|
| 111 |
+
if (m.role === 'user') {
|
| 112 |
+
T(turn('user'));
|
| 113 |
+
if (c.image_placement === 'after_text') { T(m.text); for (const im of m.images) U.push({ image: im }); T(c.turn_end); }
|
| 114 |
+
else { for (const im of m.images) U.push({ image: im }); T(m.text + c.turn_end); }
|
| 115 |
+
} else {
|
| 116 |
+
T(turn('assistant'));
|
| 117 |
+
if (c.think?.history === 'strip' && (forGen || i < lastA)) U.push({ ids: tok.encode(m.answer) });
|
| 118 |
+
else U.push({ ids: m.ids });
|
| 119 |
+
T(c.turn_end);
|
| 120 |
+
}
|
| 121 |
+
});
|
| 122 |
+
if (forGen) { T(c.generation_prompt); if (mode?.prefill) T(mode.prefill); }
|
| 123 |
+
return U;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
function flatten(U) {
|
| 127 |
+
const ids = [], keys = [], spans = [];
|
| 128 |
+
for (const u of U) {
|
| 129 |
+
if (u.ids) { for (const t of u.ids) { ids.push(t); keys.push(t); } continue; }
|
| 130 |
+
const p = u.image.prep, s = ids.length;
|
| 131 |
+
const span = [498]; for (let r = 0; r < p.gh; r++) { for (let c = 0; c < p.gw; c++) span.push(396); span.push(395); } span.push(499);
|
| 132 |
+
span.forEach((t, k) => { ids.push(t); keys.push(`i${u.image.uid}:${k}`); });
|
| 133 |
+
spans.push({ s, e: s + span.length, p });
|
| 134 |
+
}
|
| 135 |
+
return { ids, keys, spans };
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
async function feedFlat(F, from, onProgress) {
|
| 139 |
+
let a = from, imgId = 0;
|
| 140 |
+
let logits = null;
|
| 141 |
+
while (a < F.ids.length) {
|
| 142 |
+
let b = Math.min(F.ids.length, a + CHUNK);
|
| 143 |
+
for (const sp of F.spans) if (sp.s < b && sp.e > b) b = sp.s > a ? sp.s : sp.e; // never split an image
|
| 144 |
+
const img = new Array(b - a).fill(0), images = [];
|
| 145 |
+
for (const sp of F.spans) {
|
| 146 |
+
if (sp.s < a || sp.e > b) continue;
|
| 147 |
+
imgId++;
|
| 148 |
+
for (let k = sp.s + 1; k < sp.e; k++) img[k - a] = imgId;
|
| 149 |
+
const slot = [];
|
| 150 |
+
for (let r = 0; r < sp.p.gh; r++) for (let c = 0; c < sp.p.gw; c++) slot.push(sp.s + 1 + r * (sp.p.gw + 1) + c - a);
|
| 151 |
+
images.push({ pix: sp.p.pix, rc: sp.p.rc, slot });
|
| 152 |
+
}
|
| 153 |
+
logits = await engine.feed(F.ids.slice(a, b), img, images);
|
| 154 |
+
fed.keys.push(...F.keys.slice(a, b));
|
| 155 |
+
a = b;
|
| 156 |
+
onProgress?.(a);
|
| 157 |
+
}
|
| 158 |
+
return logits;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
// ---------------------------------------------------------------- rendering
|
| 162 |
+
const esc = (s) => s.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));
|
| 163 |
+
function renderEmpty() {
|
| 164 |
+
const e = $('empty'); if (!e) return;
|
| 165 |
+
e.innerHTML = model?.mode === 'chat'
|
| 166 |
+
? '<b>loopmm</b>Ask something, or add an image and ask about it.<br>It is a small model, so expect mistakes.'
|
| 167 |
+
: '<b>loopmm base</b>This is the pretrained model before chat tuning. Type the start of a text<br>(or add an image and write "A photo of") and it continues.';
|
| 168 |
+
}
|
| 169 |
+
function addMsgEl(m) {
|
| 170 |
+
$('empty')?.remove();
|
| 171 |
+
const el = document.createElement('div');
|
| 172 |
+
el.className = 'msg ' + m.role;
|
| 173 |
+
$('log').appendChild(el);
|
| 174 |
+
m.el = el;
|
| 175 |
+
renderMsg(m);
|
| 176 |
+
return el;
|
| 177 |
+
}
|
| 178 |
+
function splitThink(text) {
|
| 179 |
+
const c = chatCfg?.think;
|
| 180 |
+
if (!c) return { think: null, answer: text, open: false };
|
| 181 |
+
const i = text.indexOf(c.open);
|
| 182 |
+
if (i < 0) return { think: null, answer: text, open: false };
|
| 183 |
+
const j = text.indexOf(c.close, i);
|
| 184 |
+
if (j < 0) return { think: text.slice(i + c.open.length).trim(), answer: '', open: true };
|
| 185 |
+
return { think: text.slice(i + c.open.length, j).trim(), answer: (text.slice(0, i) + text.slice(j + c.close.length)).trim(), open: false };
|
| 186 |
+
}
|
| 187 |
+
function renderMsg(m, live = false) {
|
| 188 |
+
const el = m.el;
|
| 189 |
+
if (m.role === 'user') {
|
| 190 |
+
el.innerHTML = (m.images.length ? `<div class="imgs">${m.images.map((im) => `<img src="${im.url}" alt="">`).join('')}</div>` : '') + esc(m.text);
|
| 191 |
+
return;
|
| 192 |
+
}
|
| 193 |
+
if (m.error) { el.className = 'msg assistant err'; el.textContent = m.error; return; }
|
| 194 |
+
const keep = chatCfg?.think ? new Set([tok.id(chatCfg.think.open), tok.id(chatCfg.think.close)].filter((x) => x >= 0)) : null;
|
| 195 |
+
const text = tok.decode(m.ids, keep);
|
| 196 |
+
const { think, answer, open } = splitThink(text);
|
| 197 |
+
m.answer = answer;
|
| 198 |
+
let h = '';
|
| 199 |
+
if (think != null && think.length) {
|
| 200 |
+
const wasOpen = el.querySelector('details')?.open;
|
| 201 |
+
h += `<details${open || wasOpen ? ' open' : ''}><summary>${open ? 'Thinking…' : 'Thinking'}</summary>${esc(think)}</details>`;
|
| 202 |
+
}
|
| 203 |
+
h += `<span class="${live && !open ? 'cursor' : ''}">${esc(answer)}</span>`;
|
| 204 |
+
if (m.stats) h += `<div class="stats">${m.stats}</div>`;
|
| 205 |
+
el.innerHTML = h;
|
| 206 |
+
}
|
| 207 |
+
const scrollDown = () => { const l = $('log'); if (l.scrollHeight - l.scrollTop - l.clientHeight < 120) l.scrollTop = l.scrollHeight; };
|
| 208 |
+
|
| 209 |
+
// ---------------------------------------------------------------- generation
|
| 210 |
+
let busy = false, stopFlag = false;
|
| 211 |
+
function updateSend() {
|
| 212 |
+
const b = $('send');
|
| 213 |
+
b.textContent = busy ? 'Stop' : 'Send';
|
| 214 |
+
b.disabled = !engine || (!busy && !$('input').value.trim() && !pending.length);
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
async function generate() {
|
| 218 |
+
busy = true; stopFlag = false; updateSend();
|
| 219 |
+
const a = { role: 'assistant', ids: [], answer: '' };
|
| 220 |
+
addMsgEl(a);
|
| 221 |
+
try {
|
| 222 |
+
const mode = model.mode === 'chat' ? thinkMode() : null;
|
| 223 |
+
const prefill = mode?.prefill ? tok.encode(mode.prefill) : [];
|
| 224 |
+
let F = flatten(buildUnits(true));
|
| 225 |
+
while (F.ids.length + S.maxNew > MAX_CTX && messages.length > 2) { // drop the oldest exchange
|
| 226 |
+
for (const x of messages.splice(0, 2)) x.el?.remove();
|
| 227 |
+
F = flatten(buildUnits(true));
|
| 228 |
+
}
|
| 229 |
+
let L = 0;
|
| 230 |
+
if (engine.nLoops === S.loops) while (L < fed.keys.length && L < F.keys.length && fed.keys[L] === F.keys[L]) L++;
|
| 231 |
+
if (engine.nLoops !== S.loops || L < fed.keys.length || L === F.ids.length) { engine.reset(S.loops); fed = { keys: [] }; L = 0; }
|
| 232 |
+
const t0 = performance.now(), nPrompt = F.ids.length - L;
|
| 233 |
+
let logits = await feedFlat(F, L, (k) => setStatus(`Reading ${k - L} of ${nPrompt} tokens…`));
|
| 234 |
+
const tPrompt = performance.now();
|
| 235 |
+
a.ids = prefill.slice();
|
| 236 |
+
const stop = new Set(model.mode === 'chat' ? [2, ...(chatCfg.stop || []).map((s) => tok.id(s)).filter((x) => x >= 0)] : [1, 2]);
|
| 237 |
+
const banned = [...IMG_TOKENS, ...(model.mode === 'chat' ? [1] : [])];
|
| 238 |
+
const seen = new Set();
|
| 239 |
+
let n = 0;
|
| 240 |
+
setStatus(`Writing… · ${S.loops} loop${S.loops > 1 ? 's' : ''}`);
|
| 241 |
+
while (n < S.maxNew && !stopFlag) {
|
| 242 |
+
const t = sample(logits, { temperature: S.temperature, topP: S.topP, repPenalty: S.repPenalty, seen, banned });
|
| 243 |
+
if (stop.has(t)) break;
|
| 244 |
+
a.ids.push(t); seen.add(t); n++;
|
| 245 |
+
renderMsg(a, true); scrollDown();
|
| 246 |
+
logits = await engine.feed([t]);
|
| 247 |
+
fed.keys.push(t);
|
| 248 |
+
}
|
| 249 |
+
const dt = (performance.now() - tPrompt) / 1000;
|
| 250 |
+
a.stats = `${n} tokens · ${(n / Math.max(dt, 1e-3)).toFixed(1)} tok/s · ${S.loops} loop${S.loops > 1 ? 's' : ''}` +
|
| 251 |
+
(nPrompt > 1 ? ` · read ${nPrompt} in ${((tPrompt - t0) / 1000).toFixed(1)} s` : '');
|
| 252 |
+
messages.push(a);
|
| 253 |
+
renderMsg(a);
|
| 254 |
+
setStatus(`Ready · ${model.label}`);
|
| 255 |
+
} catch (e) {
|
| 256 |
+
console.error(e);
|
| 257 |
+
a.error = `Error: ${e.message || e}`; renderMsg(a);
|
| 258 |
+
engine.reset(S.loops); fed = { keys: [] };
|
| 259 |
+
setStatus('Error (see the message)');
|
| 260 |
+
}
|
| 261 |
+
busy = false; updateSend(); scrollDown();
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// ---------------------------------------------------------------- composer
|
| 265 |
+
let pending = [];
|
| 266 |
+
async function addImage(file) {
|
| 267 |
+
if (!file?.type?.startsWith('image/')) return;
|
| 268 |
+
const url = URL.createObjectURL(file);
|
| 269 |
+
const bmp = await createImageBitmap(file);
|
| 270 |
+
const im = { uid: ++uid, url, prep: preprocessImage(bmp, +$('detail').value, 32) };
|
| 271 |
+
pending.push(im);
|
| 272 |
+
renderAttach(); updateSend();
|
| 273 |
+
}
|
| 274 |
+
function renderAttach() {
|
| 275 |
+
$('attach').innerHTML = '';
|
| 276 |
+
pending.forEach((im, i) => {
|
| 277 |
+
const d = document.createElement('div'); d.className = 'thumb';
|
| 278 |
+
d.innerHTML = `<img src="${im.url}" alt=""><button type="button" aria-label="Remove">×</button>`;
|
| 279 |
+
d.querySelector('button').onclick = () => { pending.splice(i, 1); renderAttach(); updateSend(); };
|
| 280 |
+
$('attach').appendChild(d);
|
| 281 |
+
});
|
| 282 |
+
}
|
| 283 |
+
$('file').addEventListener('change', async (e) => { for (const f of e.target.files) await addImage(f); e.target.value = ''; });
|
| 284 |
+
document.addEventListener('paste', async (e) => { for (const it of e.clipboardData?.items || []) if (it.type.startsWith('image/')) await addImage(it.getAsFile()); });
|
| 285 |
+
document.addEventListener('dragover', (e) => { e.preventDefault(); document.body.classList.add('drag'); });
|
| 286 |
+
document.addEventListener('dragleave', () => document.body.classList.remove('drag'));
|
| 287 |
+
document.addEventListener('drop', async (e) => { e.preventDefault(); document.body.classList.remove('drag'); for (const f of e.dataTransfer.files) await addImage(f); });
|
| 288 |
+
const input = $('input');
|
| 289 |
+
input.addEventListener('input', () => { input.style.height = 'auto'; input.style.height = Math.min(200, input.scrollHeight) + 'px'; updateSend(); });
|
| 290 |
+
input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); $('composer').requestSubmit(); } });
|
| 291 |
+
$('composer').addEventListener('submit', (e) => {
|
| 292 |
+
e.preventDefault();
|
| 293 |
+
if (busy) { stopFlag = true; return; }
|
| 294 |
+
const text = input.value;
|
| 295 |
+
if (!engine || (!text.trim() && !pending.length)) return;
|
| 296 |
+
const m = { role: 'user', text, images: pending };
|
| 297 |
+
pending = []; renderAttach();
|
| 298 |
+
input.value = ''; input.style.height = 'auto';
|
| 299 |
+
messages.push(m); addMsgEl(m); scrollDown();
|
| 300 |
+
generate();
|
| 301 |
+
});
|
| 302 |
+
$('newchat').onclick = () => {
|
| 303 |
+
if (busy) stopFlag = true;
|
| 304 |
+
messages = []; $('log').innerHTML = '<div id="empty"></div>'; renderEmpty();
|
| 305 |
+
$('app').classList.remove('open');
|
| 306 |
+
};
|
| 307 |
+
|
| 308 |
+
// ---------------------------------------------------------------- start
|
| 309 |
+
(async () => {
|
| 310 |
+
try {
|
| 311 |
+
$('about').innerHTML = C.about || '';
|
| 312 |
+
const models = C.models.filter((m) => !m.hidden);
|
| 313 |
+
$('model').innerHTML = models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');
|
| 314 |
+
const sv = store.get('loopmm.model'); if (sv && models.some((m) => m.id === sv)) $('model').value = sv;
|
| 315 |
+
$('model').addEventListener('change', async () => {
|
| 316 |
+
store.set('loopmm.model', $('model').value);
|
| 317 |
+
$('newchat').onclick();
|
| 318 |
+
try { await loadModel(models.find((m) => m.id === $('model').value)); } catch (e) { setStatus(`Could not load: ${e.message}`); }
|
| 319 |
+
});
|
| 320 |
+
await loadLibs();
|
| 321 |
+
await loadModel(models.find((m) => m.id === $('model').value));
|
| 322 |
+
if (new URLSearchParams(location.search).has('smoke')) await smoke(models);
|
| 323 |
+
} catch (e) {
|
| 324 |
+
console.error(e); setStatus(`Could not start: ${e.message || e}`);
|
| 325 |
+
if (new URLSearchParams(location.search).has('smoke')) document.title = 'SMOKE:' + JSON.stringify({ ok: false, threads: window.ort?.env?.wasm?.numThreads, isolated: !!self.crossOriginIsolated, error: String(e && e.stack || e) });
|
| 326 |
+
}
|
| 327 |
+
})();
|
| 328 |
+
// Scripted run for automated tests (?smoke=1): every model, a two-turn chat with an image, greedy. The result goes
|
| 329 |
+
// into document.title as 'SMOKE:{json}' (the desktop app writes it to a file; the Space test reads the title).
|
| 330 |
+
async function testImage() {
|
| 331 |
+
const cv = document.createElement('canvas'); cv.width = 320; cv.height = 240;
|
| 332 |
+
const g = cv.getContext('2d');
|
| 333 |
+
g.fillStyle = '#3b6fd1'; g.fillRect(0, 0, 320, 240);
|
| 334 |
+
g.fillStyle = '#e53935'; g.beginPath(); g.arc(160, 120, 70, 0, 2 * Math.PI); g.fill();
|
| 335 |
+
return new File([await new Promise((ok) => cv.toBlob(ok, 'image/png'))], 'test.png', { type: 'image/png' });
|
| 336 |
+
}
|
| 337 |
+
async function smoke(models) {
|
| 338 |
+
const out = { ok: true, threads: ort.env.wasm.numThreads, isolated: !!self.crossOriginIsolated, results: [] };
|
| 339 |
+
const saved = { ...S };
|
| 340 |
+
try {
|
| 341 |
+
for (const m of models) {
|
| 342 |
+
if (m !== model) await loadModel(m);
|
| 343 |
+
$('newchat').onclick();
|
| 344 |
+
Object.assign(S, { temperature: 0, maxNew: 24, loops: 3 });
|
| 345 |
+
const turns = m.mode === 'chat' ? ['What is in this image?', 'What color is the circle?'] : ['A photo of', ' The'];
|
| 346 |
+
const r = { model: m.id, turns: [] };
|
| 347 |
+
for (let i = 0; i < turns.length; i++) {
|
| 348 |
+
if (i === 0) await addImage(await testImage());
|
| 349 |
+
const u = { role: 'user', text: turns[i], images: pending }; pending = []; renderAttach();
|
| 350 |
+
messages.push(u); addMsgEl(u);
|
| 351 |
+
await generate();
|
| 352 |
+
const a = messages[messages.length - 1];
|
| 353 |
+
r.turns.push({ user: turns[i], reply: a.role === 'assistant' ? tok.decode(a.ids) : null, stats: a.stats, error: a.error || null });
|
| 354 |
+
if (a.role !== 'assistant' || !a.ids.length) out.ok = false;
|
| 355 |
+
}
|
| 356 |
+
S.loops = 1; $('newchat').onclick();
|
| 357 |
+
const u = { role: 'user', text: m.mode === 'chat' ? 'Name a fruit.' : 'The capital of France is', images: [] };
|
| 358 |
+
messages.push(u); addMsgEl(u); await generate();
|
| 359 |
+
const a = messages[messages.length - 1];
|
| 360 |
+
r.loops1 = { reply: a.role === 'assistant' ? tok.decode(a.ids) : null, stats: a.stats };
|
| 361 |
+
out.results.push(r);
|
| 362 |
+
}
|
| 363 |
+
} catch (e) { out.ok = false; out.error = String(e && e.stack || e); }
|
| 364 |
+
Object.assign(S, saved);
|
| 365 |
+
document.title = 'SMOKE:' + JSON.stringify(out);
|
| 366 |
+
}
|
| 367 |
+
window.loopmm = { get engine() { return engine; }, get messages() { return messages; }, S };
|
config.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
window.LOOPMM = {
|
| 2 |
+
ortBase: 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.30.0/dist/',
|
| 3 |
+
tokenizersUrl: 'https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@0.1.3/dist/tokenizers.mjs',
|
| 4 |
+
models: [
|
| 5 |
+
{
|
| 6 |
+
"id": "base",
|
| 7 |
+
"label": "Base (pretrained only)",
|
| 8 |
+
"repo": "MostLime/loopmm-base",
|
| 9 |
+
"rev": "029807d250f7d4458ab4d9d7fb22baaa92ceaffd",
|
| 10 |
+
"mode": "complete"
|
| 11 |
+
}
|
| 12 |
+
],
|
| 13 |
+
fileUrl: (m, f) => `https://huggingface.co/${m.repo}/resolve/${m.rev}/${f}`,
|
| 14 |
+
about: "A 189M-parameter looped multimodal model. <a href=\"https://huggingface.co/MostLime/loopmm-base\" target=\"_blank\">Base</a> \u00b7 <a href=\"https://github.com/Mostlime12195/loopmm-app/releases/latest\" target=\"_blank\">Mac app</a>",
|
| 15 |
+
};
|
engine.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// loopmm inference engine for onnxruntime-web (browser and the desktop app).
|
| 2 |
+
// Four ONNX graphs: stem (pixels -> patch embeddings), prelude (layers 0-5), core (layers 6-17, run once per loop,
|
| 3 |
+
// with its own cache per loop) and coda (layers 18-23 + LM head). Python twin: export_hf.py OnnxRunner.
|
| 4 |
+
|
| 5 |
+
export class Engine {
|
| 6 |
+
constructor(ort, sessions, meta) {
|
| 7 |
+
this.ort = ort; this.s = sessions; this.meta = meta;
|
| 8 |
+
this.reset(meta.num_loops || 3);
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
static async load(ort, buffers, meta, opts = {}) {
|
| 12 |
+
const so = { executionProviders: ['wasm'], graphOptimizationLevel: 'all', ...opts };
|
| 13 |
+
const s = {};
|
| 14 |
+
for (const k of ['stem', 'prelude', 'core', 'coda']) s[k] = await ort.InferenceSession.create(buffers[k], so);
|
| 15 |
+
return new Engine(ort, s, meta);
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// ---- state
|
| 19 |
+
reset(nLoops) {
|
| 20 |
+
const T = this.ort.Tensor, m = this.meta;
|
| 21 |
+
this.nLoops = nLoops ?? this.nLoops;
|
| 22 |
+
this.n = 0; // tokens fed so far
|
| 23 |
+
this.pastPos = new T('int64', BigInt64Array.from([-1n]), [1]);
|
| 24 |
+
this.st = {};
|
| 25 |
+
const parts = ['pre', ...Array.from({ length: this.nLoops }, (_, r) => `core${r}`), 'coda'];
|
| 26 |
+
for (const part of parts) {
|
| 27 |
+
const key = part.startsWith('core') ? 'core' : part, d = {};
|
| 28 |
+
for (const j of m.parts[key].attn) {
|
| 29 |
+
d[`past_k${j}`] = new T('float32', new Float32Array(m.n_kv * m.head_dim), [1, m.n_kv, 1, m.head_dim]);
|
| 30 |
+
d[`past_v${j}`] = new T('float32', new Float32Array(m.n_kv * m.head_dim), [1, m.n_kv, 1, m.head_dim]);
|
| 31 |
+
}
|
| 32 |
+
for (const j of m.parts[key].conv)
|
| 33 |
+
d[`past_c${j}`] = new T('float32', new Float32Array((m.conv_kernel - 1) * m.hidden_size), [1, m.conv_kernel - 1, m.hidden_size]);
|
| 34 |
+
this.st[part] = d;
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
async _run(name, part, feeds) {
|
| 39 |
+
const o = await this.s[name].run({ ...feeds, ...this.st[part] });
|
| 40 |
+
const next = {};
|
| 41 |
+
for (const k in o) if (k.startsWith('present_')) next['past_' + k.slice(8)] = o[k];
|
| 42 |
+
this.st[part] = next;
|
| 43 |
+
return o;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
// Feed N new tokens. ids: number[]; img: number[] image id per token (0 = text); images: [{pix Float32Array
|
| 47 |
+
// [M*p*p*3] (0..255), rc Int32Array [M*2], slot number[] (index into ids)}]. Returns logits Float32Array [V].
|
| 48 |
+
async feed(ids, img = null, images = []) {
|
| 49 |
+
const T = this.ort.Tensor, m = this.meta, N = ids.length, d = m.hidden_size, p = m.patch_size;
|
| 50 |
+
const big = (a) => BigInt64Array.from(a, (x) => BigInt(x));
|
| 51 |
+
const pos = new T('int64', big(ids.map((_, j) => this.n + j)), [N]);
|
| 52 |
+
const imgT = new T('int64', big(img || ids.map(() => 0)), [N]);
|
| 53 |
+
const emb = new Float32Array(N * d), isImg = new Float32Array(N);
|
| 54 |
+
for (const im of images) {
|
| 55 |
+
const M = im.slot.length;
|
| 56 |
+
const o = await this.s.stem.run({ pix: new T('float32', im.pix, [M, p, p, 3]),
|
| 57 |
+
rc: new T('int64', big(im.rc), [M, 2]) });
|
| 58 |
+
const e = o.emb.data;
|
| 59 |
+
for (let i = 0; i < M; i++) { emb.set(e.subarray(i * d, (i + 1) * d), im.slot[i] * d); isImg[im.slot[i]] = 1; }
|
| 60 |
+
}
|
| 61 |
+
const com = { pos, img: imgT, past_pos: this.pastPos };
|
| 62 |
+
let o = await this._run('prelude', 'pre', { ids: new T('int64', big(ids), [1, N]),
|
| 63 |
+
img_emb: new T('float32', emb, [1, N, d]), is_img: new T('float32', isImg, [1, N]), ...com });
|
| 64 |
+
const base = [o.base0, o.base1, o.base2];
|
| 65 |
+
const zero = new T('float32', new Float32Array(N * d), [1, N, d]);
|
| 66 |
+
let bank = [zero, zero, zero, zero];
|
| 67 |
+
for (let r = 0; r < this.nLoops; r++) {
|
| 68 |
+
o = await this._run('core', `core${r}`, { base0: base[0], base1: base[1], base2: base[2], bank0: bank[0],
|
| 69 |
+
bank1: bank[1], bank2: bank[2], bank3: bank[3], use_msg: new T('float32', Float32Array.from([r ? 1 : 0]), [1]), ...com });
|
| 70 |
+
bank = [o.core0, o.core1, o.core2, o.core3];
|
| 71 |
+
}
|
| 72 |
+
o = await this._run('coda', 'coda', { base0: base[0], base1: base[1], base2: base[2], core0: bank[0],
|
| 73 |
+
core1: bank[1], core2: bank[2], core3: bank[3], ...com });
|
| 74 |
+
const pp = new BigInt64Array(this.pastPos.data.length + N);
|
| 75 |
+
pp.set(this.pastPos.data); pp.set(pos.data, this.pastPos.data.length);
|
| 76 |
+
this.pastPos = new T('int64', pp, [pp.length]);
|
| 77 |
+
this.n += N;
|
| 78 |
+
return o.logits.data;
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// ---------------------------------------------------------------- images
|
| 83 |
+
export function imageGrid(h, w, maxTokens = 256, p = 32, minTokens = 16, maxSide = 64) {
|
| 84 |
+
const native = (h / p) * (w / p);
|
| 85 |
+
const target = Math.min(maxTokens, Math.max(native, minTokens));
|
| 86 |
+
const s = Math.sqrt(target / native);
|
| 87 |
+
let gh = Math.max(1, Math.round(h / p * s)), gw = Math.max(1, Math.round(w / p * s));
|
| 88 |
+
gh = Math.min(gh, maxSide); gw = Math.min(gw, maxSide);
|
| 89 |
+
while (gh * gw > maxTokens) { if (gh >= gw) gh--; else gw--; }
|
| 90 |
+
return [gh, gw];
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
// ImageBitmap/HTMLImageElement -> {gh, gw, pix Float32Array [gh*gw, p, p, 3], rc Int32Array}
|
| 94 |
+
export function preprocessImage(bitmap, maxTokens = 256, p = 32) {
|
| 95 |
+
const [gh, gw] = imageGrid(bitmap.height, bitmap.width, maxTokens, p);
|
| 96 |
+
const W = gw * p, H = gh * p;
|
| 97 |
+
const cv = (typeof OffscreenCanvas !== 'undefined') ? new OffscreenCanvas(W, H)
|
| 98 |
+
: Object.assign(document.createElement('canvas'), { width: W, height: H });
|
| 99 |
+
const ctx = cv.getContext('2d');
|
| 100 |
+
ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high';
|
| 101 |
+
ctx.drawImage(bitmap, 0, 0, W, H);
|
| 102 |
+
const px = ctx.getImageData(0, 0, W, H).data;
|
| 103 |
+
const M = gh * gw, pix = new Float32Array(M * p * p * 3), rc = new Int32Array(M * 2);
|
| 104 |
+
for (let r = 0; r < gh; r++) for (let c = 0; c < gw; c++) {
|
| 105 |
+
const t = r * gw + c; rc[2 * t] = r; rc[2 * t + 1] = c;
|
| 106 |
+
for (let i = 0; i < p; i++) for (let j = 0; j < p; j++) {
|
| 107 |
+
const src = ((r * p + i) * W + (c * p + j)) * 4, dst = ((t * p + i) * p + j) * 3;
|
| 108 |
+
pix[dst] = px[src]; pix[dst + 1] = px[src + 1]; pix[dst + 2] = px[src + 2];
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
return { gh, gw, pix, rc };
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
// ---------------------------------------------------------------- tokens: byte-level BPE pieces
|
| 115 |
+
export class Tok {
|
| 116 |
+
constructor(TokenizerCls, tokJson, tokCfg) {
|
| 117 |
+
this.t = new TokenizerCls(tokJson, tokCfg);
|
| 118 |
+
const V = 65536;
|
| 119 |
+
this.pieces = new Array(V); this.special = new Uint8Array(V); this.specialIds = new Map();
|
| 120 |
+
for (const [p, id] of Object.entries(tokJson.model.vocab)) this.pieces[id] = p;
|
| 121 |
+
for (const a of tokJson.added_tokens || []) {
|
| 122 |
+
this.pieces[a.id] = a.content;
|
| 123 |
+
if (a.special) { this.special[a.id] = 1; this.specialIds.set(a.content, a.id); }
|
| 124 |
+
}
|
| 125 |
+
const bs = []; for (let i = 33; i <= 126; i++) bs.push(i); for (let i = 161; i <= 172; i++) bs.push(i); for (let i = 174; i <= 255; i++) bs.push(i);
|
| 126 |
+
const cs = bs.slice(); let n = 0;
|
| 127 |
+
for (let b = 0; b < 256; b++) if (!bs.includes(b)) { bs.push(b); cs.push(256 + n++); }
|
| 128 |
+
this.BYTE = new Map(); bs.forEach((b, i) => this.BYTE.set(String.fromCharCode(cs[i]), b));
|
| 129 |
+
const esc = [...this.specialIds.keys()].sort((a, b) => b.length - a.length).map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
| 130 |
+
this.splitRe = esc.length ? new RegExp(`(${esc.join('|')})`) : null;
|
| 131 |
+
this.utf8 = new TextDecoder('utf-8');
|
| 132 |
+
}
|
| 133 |
+
// text with special tokens written out (e.g. "<|im_start|>user\n") -> ids
|
| 134 |
+
encode(text) {
|
| 135 |
+
if (!text) return [];
|
| 136 |
+
const out = [];
|
| 137 |
+
for (const part of this.splitRe ? text.split(this.splitRe) : [text]) {
|
| 138 |
+
if (!part) continue;
|
| 139 |
+
if (this.specialIds.has(part)) out.push(this.specialIds.get(part));
|
| 140 |
+
else out.push(...this.t.encode(part, { add_special_tokens: false }).ids);
|
| 141 |
+
}
|
| 142 |
+
return out;
|
| 143 |
+
}
|
| 144 |
+
id(s) { return this.specialIds.has(s) ? this.specialIds.get(s) : (this.encode(s).length === 1 ? this.encode(s)[0] : -1); }
|
| 145 |
+
// ids -> text. keepSpecial: show special tokens that are not plain control tokens (e.g. <think>)
|
| 146 |
+
decode(ids, keep = null) {
|
| 147 |
+
const bytes = [];
|
| 148 |
+
for (const id of ids) {
|
| 149 |
+
const p = this.pieces[id];
|
| 150 |
+
if (p == null) continue;
|
| 151 |
+
if (this.special[id]) { if (keep && keep.has(id)) bytes.push(...new TextEncoder().encode(p)); continue; }
|
| 152 |
+
for (const ch of p) { const b = this.BYTE.get(ch); if (b !== undefined) bytes.push(b); }
|
| 153 |
+
}
|
| 154 |
+
return this.utf8.decode(new Uint8Array(bytes)).replace(/�+$/, '');
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
// ---------------------------------------------------------------- sampling
|
| 159 |
+
export function sample(logits, { temperature = 0.7, topP = 0.9, topK = 0, repPenalty = 1.0, seen = null, banned = null }) {
|
| 160 |
+
const V = logits.length, l = new Float32Array(logits);
|
| 161 |
+
if (banned) for (const i of banned) l[i] = -Infinity;
|
| 162 |
+
if (repPenalty !== 1 && seen) for (const i of seen) l[i] = l[i] > 0 ? l[i] / repPenalty : l[i] * repPenalty;
|
| 163 |
+
let best = 0; for (let i = 1; i < V; i++) if (l[i] > l[best]) best = i;
|
| 164 |
+
if (temperature <= 0) return best;
|
| 165 |
+
const mx = l[best], cand = [];
|
| 166 |
+
for (let i = 0; i < V; i++) { const z = (l[i] - mx) / temperature; if (z > -30) cand.push([i, Math.exp(z)]); }
|
| 167 |
+
cand.sort((a, b) => b[1] - a[1]);
|
| 168 |
+
let c = topK > 0 ? cand.slice(0, topK) : cand;
|
| 169 |
+
let tot = c.reduce((s, x) => s + x[1], 0);
|
| 170 |
+
if (topP < 1) { let acc = 0, k = 0; while (k < c.length && acc < topP * tot) acc += c[k++][1]; c = c.slice(0, Math.max(1, k)); tot = acc; }
|
| 171 |
+
let r = Math.random() * tot;
|
| 172 |
+
for (const [i, w] of c) { r -= w; if (r <= 0) return i; }
|
| 173 |
+
return c[c.length - 1][0];
|
| 174 |
+
}
|
index.html
CHANGED
|
@@ -1,19 +1,58 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<title>loopmm</title>
|
| 7 |
+
<meta name="description" content="Chat with loopmm, a small looped multimodal model, on your own computer.">
|
| 8 |
+
<link rel="stylesheet" href="style.css">
|
| 9 |
+
<script src="config.js"></script>
|
| 10 |
+
</head>
|
| 11 |
+
<body>
|
| 12 |
+
<div id="app">
|
| 13 |
+
<aside id="side">
|
| 14 |
+
<div class="brand"><b>loopmm</b><span class="sub">looped multimodal · runs on your computer</span></div>
|
| 15 |
+
<button id="newchat" class="btn wide">New chat</button>
|
| 16 |
+
<label class="field">Model
|
| 17 |
+
<select id="model"></select>
|
| 18 |
+
</label>
|
| 19 |
+
<label class="field" id="thinkfield">Thinking
|
| 20 |
+
<select id="thinking"></select>
|
| 21 |
+
</label>
|
| 22 |
+
<label class="field">Loops <output id="loopsv">3</output>
|
| 23 |
+
<input id="loops" type="range" min="1" max="8" step="1" value="3">
|
| 24 |
+
<small>How many times the middle 12 layers run. Trained at 3.</small>
|
| 25 |
+
</label>
|
| 26 |
+
<label class="field">Temperature <output id="tempv">0.7</output>
|
| 27 |
+
<input id="temp" type="range" min="0" max="1.5" step="0.05" value="0.7">
|
| 28 |
+
</label>
|
| 29 |
+
<label class="field">Top-p <output id="toppv">0.9</output>
|
| 30 |
+
<input id="topp" type="range" min="0.1" max="1" step="0.05" value="0.9">
|
| 31 |
+
</label>
|
| 32 |
+
<label class="field">Repetition penalty <output id="repv">1.1</output>
|
| 33 |
+
<input id="rep" type="range" min="1" max="1.5" step="0.05" value="1.1">
|
| 34 |
+
</label>
|
| 35 |
+
<label class="field">Max new tokens <output id="maxv">512</output>
|
| 36 |
+
<input id="max" type="range" min="32" max="2048" step="32" value="512">
|
| 37 |
+
</label>
|
| 38 |
+
<label class="field">Image detail
|
| 39 |
+
<select id="detail"><option value="64">Low (64 tokens)</option><option value="144">Medium (144)</option><option value="256" selected>High (256)</option></select>
|
| 40 |
+
</label>
|
| 41 |
+
<div id="about"></div>
|
| 42 |
+
</aside>
|
| 43 |
+
<main>
|
| 44 |
+
<header><button id="menu" class="btn icon" aria-label="Settings">☰</button><span id="status">Loading…</span><div id="bar" hidden><div></div></div></header>
|
| 45 |
+
<div id="log"><div id="empty"></div></div>
|
| 46 |
+
<form id="composer">
|
| 47 |
+
<div id="attach"></div>
|
| 48 |
+
<div class="row">
|
| 49 |
+
<label class="btn icon" title="Add an image" aria-label="Add an image">+<input id="file" type="file" accept="image/*" multiple hidden></label>
|
| 50 |
+
<textarea id="input" rows="1" placeholder="Message loopmm" autocomplete="off"></textarea>
|
| 51 |
+
<button id="send" class="btn primary" type="submit" disabled>Send</button>
|
| 52 |
+
</div>
|
| 53 |
+
</form>
|
| 54 |
+
</main>
|
| 55 |
+
</div>
|
| 56 |
+
<script type="module" src="app.js"></script>
|
| 57 |
+
</body>
|
| 58 |
</html>
|
style.css
CHANGED
|
@@ -1,28 +1,73 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
| 4 |
}
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
margin-top: 0;
|
| 9 |
}
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
}
|
| 17 |
-
|
| 18 |
-
.
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
}
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
}
|
|
|
|
| 1 |
+
:root {
|
| 2 |
+
--bg: #fbfbf9; --panel: #f3f2ee; --fg: #1d1d1b; --muted: #6b6a65; --line: #e2e0da; --accent: #2f6f4f;
|
| 3 |
+
--accent-fg: #fff; --user: #ebe9e3; --think: #f6f5f1; --err: #a33;
|
| 4 |
+
font: 15px/1.55 ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
| 5 |
}
|
| 6 |
+
@media (prefers-color-scheme: dark) {
|
| 7 |
+
:root { --bg: #161615; --panel: #1e1e1c; --fg: #e8e6e1; --muted: #9a988f; --line: #2f2e2b; --accent: #5fae86;
|
| 8 |
+
--accent-fg: #0d1a13; --user: #262624; --think: #1b1b19; --err: #e07a7a; }
|
|
|
|
| 9 |
}
|
| 10 |
+
* { box-sizing: border-box; }
|
| 11 |
+
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); }
|
| 12 |
+
#app { display: flex; height: 100%; }
|
| 13 |
+
#side { width: 270px; flex: none; background: var(--panel); border-right: 1px solid var(--line); padding: 16px;
|
| 14 |
+
overflow-y: auto; display: flex; flex-direction: column; gap: 14px; }
|
| 15 |
+
.brand b { font-size: 18px; display: block; }
|
| 16 |
+
.brand .sub { color: var(--muted); font-size: 12.5px; }
|
| 17 |
+
.field { display: grid; grid-template-columns: 1fr auto; gap: 4px; font-size: 13px; color: var(--muted); }
|
| 18 |
+
.field > input, .field > select, .field > small { grid-column: 1 / -1; }
|
| 19 |
+
.field output { color: var(--fg); font-variant-numeric: tabular-nums; }
|
| 20 |
+
[hidden] { display: none !important; }
|
| 21 |
+
.field small { font-size: 11.5px; }
|
| 22 |
+
select, textarea { font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--line); border-radius: 8px; }
|
| 23 |
+
select { padding: 6px 8px; }
|
| 24 |
+
input[type=range] { accent-color: var(--accent); width: 100%; }
|
| 25 |
+
#about { margin-top: auto; font-size: 12px; color: var(--muted); }
|
| 26 |
+
#about a { color: inherit; }
|
| 27 |
+
main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
| 28 |
+
header { display: flex; align-items: center; gap: 10px; padding: 10px 16px; border-bottom: 1px solid var(--line);
|
| 29 |
+
font-size: 13px; color: var(--muted); position: relative; min-height: 45px; }
|
| 30 |
+
#bar { position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; background: var(--line); }
|
| 31 |
+
#bar > div { height: 100%; width: 0; background: var(--accent); transition: width .2s; }
|
| 32 |
+
#menu { display: none; }
|
| 33 |
+
#log { flex: 1; overflow-y: auto; padding: 20px 16px 8px; }
|
| 34 |
+
#log > * { max-width: 760px; margin-left: auto; margin-right: auto; }
|
| 35 |
+
#empty { color: var(--muted); text-align: center; margin-top: 15vh; }
|
| 36 |
+
#empty b { color: var(--fg); font-size: 20px; display: block; margin-bottom: 6px; }
|
| 37 |
+
.msg { margin-bottom: 18px; white-space: pre-wrap; word-wrap: break-word; }
|
| 38 |
+
.msg.user { background: var(--user); border-radius: 14px; padding: 10px 14px; width: fit-content;
|
| 39 |
+
max-width: 85%; margin-left: auto; margin-right: 0; }
|
| 40 |
+
.msg .imgs { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 6px; }
|
| 41 |
+
.msg .imgs img { max-height: 160px; max-width: 100%; border-radius: 8px; display: block; }
|
| 42 |
+
.msg details { background: var(--think); border: 1px solid var(--line); border-radius: 10px; padding: 6px 12px;
|
| 43 |
+
margin-bottom: 8px; color: var(--muted); font-size: 13.5px; }
|
| 44 |
+
.msg summary { cursor: pointer; user-select: none; }
|
| 45 |
+
.msg .stats { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
| 46 |
+
.msg.err { color: var(--err); }
|
| 47 |
+
.msg .base-prompt { color: var(--muted); }
|
| 48 |
+
.cursor::after { content: "▍"; color: var(--accent); }
|
| 49 |
+
#composer { padding: 10px 16px 16px; }
|
| 50 |
+
#composer > * { max-width: 760px; margin: 0 auto; }
|
| 51 |
+
#composer .row { display: flex; gap: 8px; align-items: flex-end; background: var(--panel); border: 1px solid var(--line);
|
| 52 |
+
border-radius: 14px; padding: 6px; }
|
| 53 |
+
#input { flex: 1; border: 0; background: transparent; resize: none; padding: 8px 6px; max-height: 200px; outline: none; }
|
| 54 |
+
#attach { display: flex; gap: 8px; flex-wrap: wrap; }
|
| 55 |
+
#attach:not(:empty) { margin-bottom: 8px; }
|
| 56 |
+
#attach .thumb { position: relative; }
|
| 57 |
+
#attach img { height: 64px; border-radius: 8px; display: block; }
|
| 58 |
+
#attach button { position: absolute; top: -6px; right: -6px; border: 0; border-radius: 50%; width: 20px; height: 20px;
|
| 59 |
+
background: var(--fg); color: var(--bg); cursor: pointer; font-size: 12px; line-height: 20px; padding: 0; }
|
| 60 |
+
.btn { font: inherit; border: 1px solid var(--line); background: var(--bg); color: var(--fg); border-radius: 10px;
|
| 61 |
+
padding: 7px 14px; cursor: pointer; }
|
| 62 |
+
.btn.wide { width: 100%; }
|
| 63 |
+
.btn.icon { padding: 6px 10px; font-size: 17px; line-height: 1; border: 0; background: transparent; }
|
| 64 |
+
.btn.primary { background: var(--accent); color: var(--accent-fg); border-color: var(--accent); }
|
| 65 |
+
.btn:disabled { opacity: .45; cursor: default; }
|
| 66 |
+
body.drag #composer .row { border-color: var(--accent); }
|
| 67 |
+
@media (max-width: 760px) {
|
| 68 |
+
#side { position: fixed; inset: 0 auto 0 0; z-index: 5; transform: translateX(-100%); transition: transform .2s;
|
| 69 |
+
box-shadow: 0 0 30px rgba(0,0,0,.2); }
|
| 70 |
+
#app.open #side { transform: none; }
|
| 71 |
+
#menu { display: inline-block; }
|
| 72 |
+
.msg.user { max-width: 92%; }
|
| 73 |
}
|