Spaces:
Running
Running
thalismind
Claude Opus 5.5
feat: Solstice 80M and Nyx 36M in the browser with prompt sweeps, embedding arithmetic and runtime LoRAs
48441eb Download js/app.js from ThalisAI/solstice-80m-webgpu: direct link, hf CLI and curl.
- Browser
- Download file 30.9 kB
-
https://huggingface.co/spaces/ThalisAI/solstice-80m-webgpu/resolve/main/js/app.js
- Command line
-
hf download hf://spaces/ThalisAI/solstice-80m-webgpu/js/app.js
-
curl -L -o app.js https://huggingface.co/spaces/ThalisAI/solstice-80m-webgpu/resolve/main/js/app.js
30.9 kB
| // Solstice 80M / Nyx 36M WebGPU space: model loading, prompt resolution, and the generate / sweep / arithmetic modes. | |
| import { MODELS, VARIANTS, LORAS, R80_LORA_SPEC, NYX_SIGLIP, modelById } from './models.js'; | |
| import { ort, fetchBytes, createSession, hasWebGPU, constTensor, HttpError } from './runtime.js'; | |
| import { addLoraInputs } from './onnxlora.js'; | |
| import { EmbeddingStore } from './embeddings.js'; | |
| import { mix, wordArith, averagedDirection, applyDirection, linspace } from './embedmath.js'; | |
| import { Runner, sampleMany, toRGBA } from './sampler.js'; | |
| import { parseSafetensors, describeLora, loraFeeds } from './lora.js'; | |
| const $ = (id) => document.getElementById(id); | |
| const state = { | |
| library: null, | |
| stores: {}, | |
| runner: null, | |
| runnerKey: null, | |
| model: MODELS[0], | |
| batch: 4, | |
| busy: false, | |
| abort: null, | |
| loras: LORAS.map((l) => ({ ...l, on: false, strength: 1, parsed: null, custom: false })), | |
| loraMode: {}, // model id -> true once a LoRA was enabled (the session then keeps its LoRA inputs) | |
| loraDirty: true, | |
| siglip: null, | |
| sheet: null, | |
| }; | |
| // ---------------------------------------------------------------- progress / status | |
| function setEngine(text, cls) { | |
| $('engine-text').textContent = text; | |
| $('engine-dot').className = `dot ${cls || ''}`; | |
| } | |
| function progress(text, frac = null, error = false) { | |
| $('progress-text').textContent = text; | |
| $('progress').classList.toggle('error', error); | |
| if (frac !== null) { | |
| const pct = Math.round(Math.max(0, Math.min(1, frac)) * 100); | |
| $('progress-fill').style.width = `${pct}%`; | |
| $('progress-pct').textContent = `${pct}%`; | |
| } | |
| } | |
| function mb(n) { | |
| return (n / 1048576).toFixed(1); | |
| } | |
| function downloadProgress(label) { | |
| return (got, total, cached) => { | |
| if (cached) progress(`${label}: from browser cache`, 1); | |
| else if (total) progress(`${label}: ${mb(got)} / ${mb(total)} MB`, got / total); | |
| else progress(`${label}: ${mb(got)} MB`, null); | |
| }; | |
| } | |
| // ---------------------------------------------------------------- model + embeddings | |
| async function ensureStore(family) { | |
| if (!state.stores[family]) { | |
| progress(`Loading precomputed ${family === 'nyx' ? 'SigLIP' : 'T5Gemma'} embeddings…`, 0); | |
| state.stores[family] = await EmbeddingStore.load(family); | |
| } | |
| return state.stores[family]; | |
| } | |
| function anyLoraOn() { | |
| return state.loras.some((l) => l.on && l.strength !== 0); | |
| } | |
| // LoRA inputs are added to the fp32 export once the first LoRA is switched on, and kept for that model, so later | |
| // LoRA and strength changes only change the inputs. | |
| function wantLoraInputs(model, variant) { | |
| if (!model.lora || variant !== 'fp32') return false; | |
| if (anyLoraOn()) state.loraMode[model.id] = true; | |
| return !!state.loraMode[model.id]; | |
| } | |
| async function ensureModel() { | |
| const model = state.model; | |
| const variant = $('variant-select').value; | |
| const pref = $('backend-select').value; | |
| const useLora = wantLoraInputs(model, variant); | |
| const url = model.url(variant); | |
| const key = `${url}|${pref}|${useLora ? 'lora' : 'plain'}`; | |
| const store = await ensureStore(model.family); | |
| if (state.runner && state.runnerKey === key) return { runner: state.runner, store }; | |
| if (state.runner) { | |
| try { | |
| await state.runner.session.release(); | |
| } catch { | |
| // already released | |
| } | |
| state.runner = null; | |
| } | |
| setEngine('Loading model…', 'loading'); | |
| const label = `${model.group} · ${model.label}${useLora ? ' (LoRA inputs)' : ''}`; | |
| let bytes = await fetchBytes(url, downloadProgress(label)); | |
| let loraSpec = null; | |
| if (useLora) { | |
| progress(`Adding LoRA inputs to ${model.label}…`, 1); | |
| await new Promise((r) => setTimeout(r, 0)); | |
| const rewritten = addLoraInputs(bytes); | |
| bytes = rewritten.bytes; | |
| loraSpec = rewritten.spec; | |
| } | |
| progress(`Compiling ${label}…`, 1); | |
| const { session, backend } = await createSession(bytes, { | |
| wasmOnly: VARIANTS[variant]?.wasmOnly, preferWebGPU: pref === 'webgpu', | |
| }); | |
| bytes = null; | |
| const runner = new Runner(ort, session, model, backend, { constTensor, L: store.L, D: store.D }); | |
| runner.loraSpec = loraSpec; | |
| state.runner = runner; | |
| state.runnerKey = key; | |
| state.loraDirty = true; | |
| setEngine(`${model.label} · ${backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, backend === 'webgpu' ? 'ok' : 'wasm'); | |
| progress(`Ready: ${label} on ${backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, 1); | |
| updateLoraStatus(); | |
| return { runner, store }; | |
| } | |
| async function syncLoras(runner) { | |
| if (!runner.loraSpec || !state.loraDirty) return; | |
| const active = []; | |
| for (const l of state.loras) { | |
| if (!l.on || l.strength === 0) continue; | |
| if (!l.parsed) { | |
| const bytes = await fetchBytes(l.url, downloadProgress(`LoRA ${l.label}`)); | |
| l.parsed = parseSafetensors(bytes); | |
| } | |
| active.push({ lora: l.parsed, strength: l.strength }); | |
| } | |
| progress(active.length ? `Applying ${active.length} LoRA${active.length > 1 ? 's' : ''}…` : 'No LoRA active', null); | |
| runner.setExtraFeeds(await loraFeeds(runner.loraSpec, active, runner.backend)); | |
| state.loraDirty = false; | |
| } | |
| // ---------------------------------------------------------------- prompts | |
| async function ensureSiglip() { | |
| if (state.siglip) return state.siglip; | |
| const { AutoTokenizer } = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.1.2'); | |
| progress('Loading SigLIP tokenizer…', 0); | |
| const tokenizer = await AutoTokenizer.from_pretrained(NYX_SIGLIP.tokenizer); | |
| const bytes = await fetchBytes(NYX_SIGLIP.url, downloadProgress('SigLIP text encoder')); | |
| progress('Compiling SigLIP text encoder…', 1); | |
| const { session } = await createSession(bytes, { preferWebGPU: $('backend-select').value === 'webgpu' }); | |
| state.siglip = { tokenizer, session }; | |
| return state.siglip; | |
| } | |
| async function encodeNyxLive(store, text) { | |
| const { tokenizer, session } = await ensureSiglip(); | |
| const wrapped = text.toLowerCase().includes('pixel art icon of ') ? text : `pixel art icon of a ${text}`; | |
| const enc = await tokenizer(wrapped, { padding: 'max_length', max_length: 64, truncation: true }); | |
| const ids = new BigInt64Array(64); | |
| for (let i = 0; i < 64; i++) ids[i] = BigInt(enc.input_ids.data[i]); | |
| const out = await session.run({ input_ids: new ort.Tensor('int64', ids, [1, 64]) }); | |
| return store.fromArrays(out.text_tokens.data.subarray(0, 32 * 768), out.text_pool.data.subarray(0, 768)); | |
| } | |
| function normalise(text) { | |
| let t = (text || '').trim().toLowerCase().replace(/\s+/g, ' '); | |
| t = t.replace(/^pixel art, 32px, /, ''); | |
| if (t.startsWith('a ') || t.startsWith('an ')) { | |
| const rest = t.replace(/^an? /, ''); | |
| return [t, rest]; | |
| } | |
| return [t]; | |
| } | |
| function lookupKey(store, text) { | |
| for (const k of normalise(text)) if (store.has(k)) return k; | |
| return null; | |
| } | |
| function suggestions(store, text, n = 6) { | |
| const words = normalise(text).pop().split(' ').filter((w) => w.length > 2); | |
| if (!words.length) return []; | |
| const scored = store.keys.map((k) => [k, words.filter((w) => k.includes(w)).length]).filter(([, s]) => s > 0); | |
| scored.sort((a, b) => b[1] - a[1] || a[0].length - b[0].length); | |
| return scored.slice(0, n).map(([k]) => k); | |
| } | |
| async function resolve(store, text) { | |
| const key = lookupKey(store, text); | |
| if (key !== null) return store.get(key); | |
| if (state.model.family === 'nyx' && $('live-encoder').checked) return encodeNyxLive(store, text.trim()); | |
| const near = suggestions(store, text); | |
| const extra = state.model.family === 'nyx' ? ' Or enable live SigLIP encoding below.' : ''; | |
| throw new Error(`"${text}" is not precomputed.${near.length ? ` Try: ${near.join(', ')}.` : ''}${extra}`); | |
| } | |
| function checkPromptHint() { | |
| const store = state.stores[state.model.family]; | |
| const text = $('prompt-input').value; | |
| const hint = $('prompt-hint'); | |
| if (!store || !text.trim()) { | |
| hint.textContent = ''; | |
| return; | |
| } | |
| if (lookupKey(store, text) !== null) { | |
| hint.textContent = `Precomputed: "${store.meta.entries[store.byKey.get(lookupKey(store, text))].text}"`; | |
| hint.classList.remove('err'); | |
| } else if (state.model.family === 'nyx' && $('live-encoder').checked) { | |
| hint.textContent = 'Not precomputed; will be encoded live with SigLIP.'; | |
| hint.classList.remove('err'); | |
| } else { | |
| const near = suggestions(store, text); | |
| hint.textContent = `Not precomputed.${near.length ? ` Closest: ${near.join(' · ')}` : ''}`; | |
| hint.classList.add('err'); | |
| } | |
| } | |
| // ---------------------------------------------------------------- rendering | |
| function drawSprite(canvas, x, final = true) { | |
| const ctx = canvas.getContext('2d'); | |
| const img = ctx.createImageData(32, 32); | |
| img.data.set(toRGBA(x, final)); | |
| ctx.putImageData(img, 0, 0); | |
| } | |
| function makeSprite(caption, filename) { | |
| const wrap = document.createElement('div'); | |
| wrap.className = 'sprite'; | |
| const canvas = document.createElement('canvas'); | |
| canvas.width = 32; | |
| canvas.height = 32; | |
| canvas.title = 'Click to download PNG (8×)'; | |
| canvas.addEventListener('click', () => downloadCanvas(canvas, filename || 'sprite.png', 8)); | |
| wrap.appendChild(canvas); | |
| if (caption) { | |
| const cap = document.createElement('div'); | |
| cap.className = 'cap'; | |
| cap.textContent = caption; | |
| wrap.appendChild(cap); | |
| } | |
| return { wrap, canvas }; | |
| } | |
| function downloadCanvas(canvas, filename, scale) { | |
| const big = document.createElement('canvas'); | |
| big.width = canvas.width * scale; | |
| big.height = canvas.height * scale; | |
| const ctx = big.getContext('2d'); | |
| ctx.imageSmoothingEnabled = false; | |
| ctx.drawImage(canvas, 0, 0, big.width, big.height); | |
| const a = document.createElement('a'); | |
| a.download = filename; | |
| a.href = big.toDataURL('image/png'); | |
| a.click(); | |
| } | |
| function slug(s) { | |
| return s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'sprite'; | |
| } | |
| // A sheet: { title, cols: [label], rows: [{ label, cells: [canvas] }] }. Renders a table and remembers it. | |
| function renderSheet(title, cols, rows) { | |
| const out = $('output'); | |
| out.innerHTML = ''; | |
| const box = document.createElement('div'); | |
| box.className = 'sheet'; | |
| const table = document.createElement('table'); | |
| const head = document.createElement('tr'); | |
| head.appendChild(document.createElement('th')); | |
| for (const c of cols) { | |
| const th = document.createElement('th'); | |
| th.textContent = c; | |
| head.appendChild(th); | |
| } | |
| table.appendChild(head); | |
| const sheetRows = rows.map((r) => { | |
| const tr = document.createElement('tr'); | |
| const th = document.createElement('th'); | |
| th.className = 'rowhead'; | |
| th.textContent = r.label; | |
| tr.appendChild(th); | |
| const cells = r.cells.map((c) => { | |
| const td = document.createElement('td'); | |
| const s = makeSprite(null, `${slug(`${r.label}-${c}`)}.png`); | |
| td.appendChild(s.wrap); | |
| tr.appendChild(td); | |
| return s.canvas; | |
| }); | |
| table.appendChild(tr); | |
| return { label: r.label, cells }; | |
| }); | |
| box.appendChild(table); | |
| out.appendChild(box); | |
| $('output-title').textContent = title; | |
| state.sheet = { title, cols, rows: sheetRows }; | |
| $('btn-sheet').disabled = false; | |
| return sheetRows; | |
| } | |
| function renderGrid(title, captions, prompt) { | |
| const out = $('output'); | |
| out.innerHTML = ''; | |
| const grid = document.createElement('div'); | |
| grid.className = 'grid'; | |
| const canvases = captions.map((cap) => { | |
| const s = makeSprite(cap, `${slug(prompt)}-${cap.replace(/\D+/g, '')}.png`); | |
| grid.appendChild(s.wrap); | |
| return s.canvas; | |
| }); | |
| out.appendChild(grid); | |
| $('output-title').textContent = title; | |
| state.sheet = { title, cols: captions, rows: [{ label: '', cells: canvases }] }; | |
| $('btn-sheet').disabled = false; | |
| return canvases; | |
| } | |
| function downloadSheet() { | |
| const sh = state.sheet; | |
| if (!sh) return; | |
| const S = 96; | |
| const gap = 6; | |
| const left = sh.rows.some((r) => r.label) ? 170 : 8; | |
| const top = 46; | |
| const ncols = Math.max(...sh.rows.map((r) => r.cells.length)); | |
| const c = document.createElement('canvas'); | |
| c.width = left + ncols * (S + gap) + 8; | |
| c.height = top + sh.rows.length * (S + gap) + 8; | |
| const ctx = c.getContext('2d'); | |
| ctx.fillStyle = '#2d2d2d'; | |
| ctx.fillRect(0, 0, c.width, c.height); | |
| ctx.fillStyle = '#ffffff'; | |
| ctx.font = '13px sans-serif'; | |
| ctx.fillText(sh.title, 8, 18); | |
| ctx.fillStyle = '#c8c8c8'; | |
| ctx.font = '11px sans-serif'; | |
| sh.cols.forEach((label, i) => ctx.fillText(String(label).slice(0, 16), left + i * (S + gap), top - 8)); | |
| ctx.imageSmoothingEnabled = false; | |
| sh.rows.forEach((r, ri) => { | |
| const y = top + ri * (S + gap); | |
| ctx.fillStyle = '#e6e6e6'; | |
| ctx.fillText(r.label.slice(0, 26), 8, y + S / 2); | |
| r.cells.forEach((cv, ci) => { | |
| ctx.fillStyle = '#969696'; | |
| ctx.fillRect(left + ci * (S + gap), y, S, S); | |
| ctx.drawImage(cv, left + ci * (S + gap), y, S, S); | |
| }); | |
| }); | |
| const a = document.createElement('a'); | |
| a.download = `${slug(sh.title)}.png`; | |
| a.href = c.toDataURL('image/png'); | |
| a.click(); | |
| } | |
| // ---------------------------------------------------------------- running | |
| function settings() { | |
| return { | |
| steps: parseInt($('slider-steps').value, 10), | |
| guidance: parseFloat($('slider-guidance').value), | |
| sampler: $('sampler-select').value, | |
| seed: parseInt($('seed-input').value, 10) || 0, | |
| }; | |
| } | |
| // items: [{ cond, seed, canvas }] | |
| async function runItems(runner, store, items, label) { | |
| const { steps, guidance, sampler } = settings(); | |
| const maxBatch = runner.backend === 'webgpu' ? 8 : 4; | |
| const evals = sampler === 'heun' ? 2 * steps - 1 : steps; | |
| const t0 = performance.now(); | |
| const results = await sampleMany(runner, items, { | |
| uncond: store.uncond(), steps, sampler, guidance, maxBatch, signal: state.abort.signal, | |
| onStep: async (start, n, i, total, xs) => { | |
| for (let k = 0; k < n; k++) drawSprite(items[start + k].canvas, xs.subarray(k * 4096, (k + 1) * 4096), true); | |
| const done = (start + (n * i) / total) / items.length; | |
| progress(`${label}: ${Math.min(items.length, start + n)}/${items.length} sprites, step ${i}/${total} (${evals} evaluations each)`, done); | |
| await new Promise((r) => requestAnimationFrame(r)); | |
| }, | |
| }); | |
| results.forEach((x, k) => drawSprite(items[k].canvas, x, true)); | |
| const secs = (performance.now() - t0) / 1000; | |
| progress(`${label}: ${items.length} sprite${items.length > 1 ? 's' : ''} in ${secs.toFixed(1)}s on ${runner.backend === 'webgpu' ? 'WebGPU' : 'WASM'}`, 1); | |
| } | |
| async function guarded(fn) { | |
| if (state.busy) { | |
| state.abort?.abort(); | |
| return; | |
| } | |
| state.busy = true; | |
| state.abort = new AbortController(); | |
| document.querySelectorAll('[data-run]').forEach((b) => { | |
| b.dataset.label = b.textContent; | |
| b.textContent = 'Cancel'; | |
| }); | |
| try { | |
| await fn(); | |
| } catch (err) { | |
| if (err.name === 'AbortError') progress('Cancelled', null); | |
| else { | |
| console.error(err); | |
| progress(err instanceof HttpError && err.status === 404 | |
| ? `This checkpoint is not on the Hub yet (${err.message.split(': ').pop()})` | |
| : `Error: ${err.message}`, null, true); | |
| if (!state.runner) setEngine('Model not loaded', 'err'); | |
| } | |
| } finally { | |
| state.busy = false; | |
| document.querySelectorAll('[data-run]').forEach((b) => { | |
| b.textContent = b.dataset.label; | |
| }); | |
| } | |
| } | |
| async function runGenerate() { | |
| const text = $('prompt-input').value.trim(); | |
| const { runner, store } = await ensureModel(); | |
| await syncLoras(runner); | |
| const cond = await resolve(store, text); | |
| const { seed } = settings(); | |
| const n = state.batch; | |
| const canvases = renderGrid(`“${text}”`, Array.from({ length: n }, (_, i) => `seed ${seed + i}`), text); | |
| await runItems(runner, store, canvases.map((canvas, i) => ({ cond, seed: seed + i, canvas })), 'Generating'); | |
| } | |
| async function runSweep() { | |
| const a = $('sweep-a').value.trim(); | |
| const b = $('sweep-b').value.trim(); | |
| const { runner, store } = await ensureModel(); | |
| await syncLoras(runner); | |
| const [A, B] = [await resolve(store, a), await resolve(store, b)]; | |
| const frames = parseInt($('sweep-frames').value, 10); | |
| const nSeeds = parseInt($('sweep-seeds').value, 10); | |
| const ts = linspace(parseFloat($('sweep-t0').value), parseFloat($('sweep-t1').value), frames); | |
| const { seed } = settings(); | |
| const conds = ts.map((t) => mix(A, B, t)); | |
| const rows = renderSheet(`${a} → ${b}`, ts.map((t) => `t=${t.toFixed(2)}`), | |
| Array.from({ length: nSeeds }, (_, s) => ({ label: `seed ${seed + s}`, cells: ts.map((t) => t.toFixed(2)) }))); | |
| const items = rows.flatMap((r, s) => r.cells.map((canvas, i) => ({ cond: conds[i], seed: seed + s, canvas }))); | |
| await runItems(runner, store, items, 'Sweep'); | |
| } | |
| function directionPairs(store, groupName, from, to, exclude) { | |
| const g = state.library.directions.find((d) => d.name === groupName); | |
| if (!g) throw new Error(`unknown direction group ${groupName}`); | |
| const objects = g.objects.filter((o) => !exclude.some((w) => w.split(' ').includes(o))); | |
| if (!objects.length) throw new Error('every object of the group appears in A; pick another group'); | |
| return objects.map((o) => [store.get(`${from} ${o}`), store.get(`${to} ${o}`)]); | |
| } | |
| async function runArith() { | |
| const [a, b, c, d] = ['arith-a', 'arith-b', 'arith-c', 'arith-d'].map((id) => $(id).value.trim()); | |
| const group = $('arith-group').value; | |
| const from = $('arith-from').value; | |
| const to = $('arith-to').value; | |
| const strength = parseFloat($('arith-strength').value); | |
| const nSeeds = parseInt($('arith-seeds').value, 10); | |
| const { runner, store } = await ensureModel(); | |
| await syncLoras(runner); | |
| const A = await resolve(store, a); | |
| const cols = []; | |
| const conds = []; | |
| const push = (label, cond) => { | |
| cols.push(label); | |
| conds.push(cond); | |
| }; | |
| push(`A: ${a}`, A); | |
| let B = null; | |
| let C = null; | |
| if (b && c) { | |
| B = await resolve(store, b); | |
| C = await resolve(store, c); | |
| push(`B: ${b}`, B); | |
| push(`C: ${c}`, C); | |
| push(`A − B + C${strength !== 1 ? ` ×${strength}` : ''}`, wordArith(A, B, C, strength)); | |
| } | |
| let dir = null; | |
| if (group && from && to && from !== to) { | |
| dir = averagedDirection(directionPairs(store, group, from, to, [a])); | |
| push(`A + (${to} − ${from})${strength !== 1 ? ` ×${strength}` : ''}`, applyDirection(A, dir, strength)); | |
| } | |
| if (d) push(`direct: ${d}`, await resolve(store, d)); | |
| if (conds.length < 2) throw new Error('Give B and C, or pick a direction group with two different attributes'); | |
| const { seed } = settings(); | |
| const rowsSpec = Array.from({ length: nSeeds }, (_, s) => ({ label: `seed ${seed + s}`, cells: cols })); | |
| let ladder = null; | |
| if (dir && $('arith-ladder').checked) { | |
| ladder = linspace(0, 2, cols.length > 4 ? cols.length : 9); | |
| rowsSpec.push({ label: `strength 0→2 (seed ${seed})`, cells: ladder.map((s) => `s=${s.toFixed(2)}`) }); | |
| } | |
| const rows = renderSheet(`${a} · arithmetic`, ladder && ladder.length > cols.length ? ladder.map((_, i) => cols[i] || '') : cols, rowsSpec); | |
| const items = rows.slice(0, nSeeds).flatMap((r, s) => r.cells.map((canvas, i) => ({ cond: conds[i], seed: seed + s, canvas }))); | |
| if (ladder) { | |
| rows[nSeeds].cells.forEach((canvas, i) => items.push({ cond: applyDirection(A, dir, ladder[i]), seed, canvas })); | |
| } | |
| await runItems(runner, store, items, 'Arithmetic'); | |
| } | |
| // ---------------------------------------------------------------- LoRA UI | |
| function updateLoraStatus() { | |
| const m = state.model; | |
| const card = $('lora-card'); | |
| card.hidden = !m.lora; | |
| if (!m.lora) return; | |
| const variant = $('variant-select').value; | |
| const status = $('lora-status'); | |
| const active = state.runner?.loraSpec && state.runner.model === m; | |
| if (variant !== 'fp32') status.textContent = 'LoRAs need the fp32 weights'; | |
| else if (active) status.textContent = m.id === 'r80-teacher' ? 'LoRA inputs active' : 'LoRA inputs active (LoRAs were trained on the teacher)'; | |
| else status.textContent = 'applied at run time: the first LoRA recompiles the model once'; | |
| const usable = variant === 'fp32'; | |
| card.querySelectorAll('input, button').forEach((el) => { | |
| el.disabled = !usable; | |
| }); | |
| } | |
| function renderLoras() { | |
| const list = $('lora-list'); | |
| list.innerHTML = ''; | |
| for (const l of state.loras) { | |
| const el = document.createElement('div'); | |
| el.className = `lora${l.on ? ' on' : ''}`; | |
| el.innerHTML = ` | |
| <input type="checkbox" ${l.on ? 'checked' : ''} aria-label="Enable ${l.label}"> | |
| <span class="name">${l.label}</span> | |
| ${l.custom ? '<button class="remove" title="Remove">✕</button>' : '<span></span>'} | |
| <span class="trigger" title="Use the trigger in the prompt">${l.trigger ? `trigger: ${l.trigger}` : 'no trigger in metadata'}</span> | |
| <input type="range" min="0" max="1.5" step="0.05" value="${l.strength}" aria-label="${l.label} strength"> | |
| <span class="val">${l.strength.toFixed(2)}</span>`; | |
| const [check, range] = el.querySelectorAll('input'); | |
| check.addEventListener('change', () => { | |
| l.on = check.checked; | |
| el.classList.toggle('on', l.on); | |
| state.loraDirty = true; | |
| }); | |
| range.addEventListener('input', () => { | |
| l.strength = parseFloat(range.value); | |
| el.querySelector('.val').textContent = l.strength.toFixed(2); | |
| state.loraDirty = true; | |
| }); | |
| el.querySelector('.trigger').addEventListener('click', () => { | |
| if (!l.trigger) return; | |
| const subject = $('prompt-input').value.replace(/^.*?,\s*/, '') || 'red apple'; | |
| $('prompt-input').value = `${l.trigger}, ${subject}`; | |
| if (!l.on) check.click(); | |
| checkPromptHint(); | |
| }); | |
| el.querySelector('.remove')?.addEventListener('click', () => { | |
| state.loras = state.loras.filter((x) => x !== l); | |
| state.loraDirty = true; | |
| renderLoras(); | |
| }); | |
| list.appendChild(el); | |
| } | |
| updateLoraStatus(); | |
| } | |
| async function addLoraFile(file) { | |
| const parsed = parseSafetensors(new Uint8Array(await file.arrayBuffer())); | |
| const info = describeLora(parsed, R80_LORA_SPEC); | |
| if (!info.covered) throw new Error(`${file.name} has no tensors for this model's linears`); | |
| state.loras.push({ | |
| id: `file-${state.loras.length}`, label: file.name.replace(/\.safetensors$/, ''), trigger: info.trigger, | |
| url: null, on: true, strength: 1, parsed, custom: true, | |
| }); | |
| state.loraDirty = true; | |
| renderLoras(); | |
| progress(`Added ${file.name}: rank ${info.rank}, alpha ${info.alpha}, ${info.covered}/${info.total} linears`, null); | |
| } | |
| // ---------------------------------------------------------------- setup | |
| function fillSelect(sel, options, value) { | |
| sel.innerHTML = ''; | |
| for (const o of options) { | |
| const opt = document.createElement('option'); | |
| opt.value = o.value; | |
| opt.textContent = o.label; | |
| sel.appendChild(opt); | |
| } | |
| if (value !== undefined) sel.value = value; | |
| } | |
| function onModelChange() { | |
| const m = modelById($('model-select').value); | |
| state.model = m; | |
| fillSelect($('variant-select'), m.variants.map((v) => ({ value: v, label: `${VARIANTS[v].label} · ${VARIANTS[v].note}` })), 'fp32'); | |
| const steps = $('slider-steps'); | |
| steps.max = m.maxSteps; | |
| steps.value = m.steps; | |
| $('val-steps').textContent = m.steps; | |
| $('slider-guidance').value = m.guidance; | |
| $('val-guidance').textContent = m.guidance.toFixed(1); | |
| $('sampler-select').value = m.sampler; | |
| const kind = m.guided ? 'distilled: guidance is a model input, 1 forward per step' | |
| : m.selfCond ? 'teacher: CFG on t ≤ 0.75 + self-conditioning' : 'CFG on t ≤ 0.75'; | |
| $('model-info').textContent = `${kind}`; | |
| $('live-encoder-wrap').hidden = m.family !== 'nyx'; | |
| updateLoraStatus(); | |
| ensureStore(m.family).then(() => { | |
| if (!state.busy) progress('Model loads on first run (downloaded once, then cached by the browser)', 0); | |
| checkPromptHint(); | |
| }).catch((err) => progress(`Error loading embeddings: ${err.message}`, null, true)); | |
| } | |
| function setupPresets() { | |
| const lib = state.library; | |
| fillSelect($('sweep-preset'), lib.sweeps.map((s, i) => ({ value: i, label: `${s.a} → ${s.b}` })), 0); | |
| const applySweep = () => { | |
| const s = lib.sweeps[$('sweep-preset').value]; | |
| $('sweep-a').value = s.a; | |
| $('sweep-b').value = s.b; | |
| }; | |
| $('sweep-preset').addEventListener('change', applySweep); | |
| applySweep(); | |
| fillSelect($('arith-group'), [{ value: '', label: '(none)' }, ...lib.directions.map((d) => ({ value: d.name, label: `${d.name} (${d.objects.join(', ')})` }))]); | |
| const fillAttrs = () => { | |
| const g = lib.directions.find((d) => d.name === $('arith-group').value); | |
| const opts = g ? g.attributes.map((a) => ({ value: a, label: a })) : []; | |
| fillSelect($('arith-from'), opts); | |
| fillSelect($('arith-to'), opts); | |
| }; | |
| $('arith-group').addEventListener('change', fillAttrs); | |
| fillSelect($('arith-preset'), lib.arithmetic.map((r, i) => ({ value: i, label: `${r.a} − ${r.b} + ${r.c} ≈ ${r.direct}` })), 0); | |
| const applyArith = () => { | |
| const r = lib.arithmetic[$('arith-preset').value]; | |
| $('arith-a').value = r.a; | |
| $('arith-b').value = r.b; | |
| $('arith-c').value = r.c; | |
| $('arith-d').value = r.direct; | |
| $('arith-group').value = r.group; | |
| fillAttrs(); | |
| $('arith-from').value = r.from; | |
| $('arith-to').value = r.to; | |
| }; | |
| $('arith-preset').addEventListener('change', applyArith); | |
| applyArith(); | |
| } | |
| function setupLibrary() { | |
| const lib = state.library; | |
| const dl = $('library-list'); | |
| dl.innerHTML = ''; | |
| for (const e of lib.entries) { | |
| const o = document.createElement('option'); | |
| o.value = e.key; | |
| dl.appendChild(o); | |
| } | |
| const chips = $('chips'); | |
| for (const e of lib.entries.filter((x) => x.groups.includes('showcase'))) { | |
| const b = document.createElement('button'); | |
| b.className = 'chip'; | |
| b.textContent = e.label; | |
| b.title = e.key; | |
| b.addEventListener('click', () => { | |
| $('prompt-input').value = e.key; | |
| checkPromptHint(); | |
| guarded(runGenerate); | |
| }); | |
| chips.appendChild(b); | |
| } | |
| const order = ['showcase', 'subjects', 'attributes', 'combos', 'arithmetic', 'sweeps', 'directions', 'lora']; | |
| const titles = { | |
| showcase: 'Showcase prompts', subjects: 'Subjects', attributes: 'Attributes', combos: 'Attribute + subject', | |
| arithmetic: 'Arithmetic terms', sweeps: 'Sweep terms', directions: 'Direction phrase pairs', lora: 'LoRA trigger prompts', | |
| }; | |
| const render = () => { | |
| const q = $('library-search').value.trim().toLowerCase(); | |
| const box = $('library'); | |
| box.innerHTML = ''; | |
| let count = 0; | |
| for (const g of order) { | |
| const items = lib.entries.filter((e) => e.groups[0] === g && (!q || e.key.includes(q))); | |
| if (!items.length) continue; | |
| count += items.length; | |
| const sec = document.createElement('div'); | |
| sec.innerHTML = `<h3>${titles[g]} · ${items.length}</h3>`; | |
| const row = document.createElement('div'); | |
| row.className = 'chips'; | |
| for (const e of items) { | |
| const b = document.createElement('button'); | |
| b.className = 'chip'; | |
| b.textContent = e.key; | |
| b.addEventListener('click', () => { | |
| $('prompt-input').value = e.key; | |
| document.querySelector('.tab[data-tab="generate"]').click(); | |
| checkPromptHint(); | |
| }); | |
| row.appendChild(b); | |
| } | |
| sec.appendChild(row); | |
| box.appendChild(sec); | |
| } | |
| $('library-count').textContent = `${count} of ${lib.entries.length} precomputed prompts`; | |
| }; | |
| $('library-search').addEventListener('input', render); | |
| render(); | |
| } | |
| function bindControls() { | |
| const groups = [...new Set(MODELS.map((m) => m.group))]; | |
| const sel = $('model-select'); | |
| for (const g of groups) { | |
| const og = document.createElement('optgroup'); | |
| og.label = g; | |
| for (const m of MODELS.filter((x) => x.group === g)) { | |
| const o = document.createElement('option'); | |
| o.value = m.id; | |
| o.textContent = m.label; | |
| og.appendChild(o); | |
| } | |
| sel.appendChild(og); | |
| } | |
| sel.value = 'r80-s20'; | |
| sel.addEventListener('change', onModelChange); | |
| $('variant-select').addEventListener('change', updateLoraStatus); | |
| $('btn-load').addEventListener('click', () => guarded(async () => { | |
| const { runner } = await ensureModel(); | |
| await syncLoras(runner); | |
| })); | |
| const bindRange = (id, valId, fmt) => $(id).addEventListener('input', (e) => { | |
| $(valId).textContent = fmt(parseFloat(e.target.value)); | |
| }); | |
| bindRange('slider-steps', 'val-steps', (v) => v); | |
| bindRange('slider-guidance', 'val-guidance', (v) => v.toFixed(1)); | |
| bindRange('sweep-frames', 'val-frames', (v) => v); | |
| bindRange('sweep-seeds', 'val-sweep-seeds', (v) => v); | |
| bindRange('arith-seeds', 'val-arith-seeds', (v) => v); | |
| bindRange('arith-strength', 'val-strength', (v) => v.toFixed(2)); | |
| const trange = () => { | |
| $('val-trange').textContent = `${$('sweep-t0').value} – ${$('sweep-t1').value}`; | |
| }; | |
| $('sweep-t0').addEventListener('input', trange); | |
| $('sweep-t1').addEventListener('input', trange); | |
| $('btn-random-seed').addEventListener('click', () => { | |
| $('seed-input').value = Math.floor(Math.random() * 1e6); | |
| }); | |
| document.querySelectorAll('#batch-pills .pill').forEach((p) => p.addEventListener('click', () => { | |
| document.querySelectorAll('#batch-pills .pill').forEach((x) => x.classList.remove('active')); | |
| p.classList.add('active'); | |
| state.batch = parseInt(p.dataset.batch, 10); | |
| })); | |
| document.querySelectorAll('.tab').forEach((t) => t.addEventListener('click', () => { | |
| document.querySelectorAll('.tab').forEach((x) => x.classList.toggle('active', x === t)); | |
| document.querySelectorAll('.panel').forEach((p) => p.classList.toggle('active', p.id === `panel-${t.dataset.tab}`)); | |
| })); | |
| for (const [id, fn] of [['btn-generate', runGenerate], ['btn-sweep', runSweep], ['btn-arith', runArith]]) { | |
| $(id).dataset.run = '1'; | |
| $(id).addEventListener('click', () => guarded(fn)); | |
| } | |
| $('prompt-input').addEventListener('keydown', (e) => { | |
| if (e.key === 'Enter') guarded(runGenerate); | |
| }); | |
| $('prompt-input').addEventListener('input', checkPromptHint); | |
| $('live-encoder').addEventListener('change', checkPromptHint); | |
| $('checker').addEventListener('change', (e) => $('output').classList.toggle('checker', e.target.checked)); | |
| $('output').classList.add('checker'); | |
| $('btn-sheet').addEventListener('click', downloadSheet); | |
| $('lora-file').addEventListener('change', async (e) => { | |
| const f = e.target.files[0]; | |
| e.target.value = ''; | |
| if (f) { | |
| try { | |
| await addLoraFile(f); | |
| } catch (err) { | |
| progress(`LoRA: ${err.message}`, null, true); | |
| } | |
| } | |
| }); | |
| } | |
| async function init() { | |
| setEngine(hasWebGPU() ? 'WebGPU available' : 'No WebGPU · WASM fallback', hasWebGPU() ? 'ok' : 'wasm'); | |
| if (!hasWebGPU()) $('backend-select').value = 'wasm'; | |
| bindControls(); | |
| try { | |
| state.library = await (await fetch('data/library.json')).json(); | |
| } catch (err) { | |
| progress(`Could not load the prompt library: ${err.message}`, null, true); | |
| return; | |
| } | |
| setupLibrary(); | |
| setupPresets(); | |
| renderLoras(); | |
| onModelChange(); | |
| } | |
| init(); | |