// 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:
ImageContent. 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 in
export 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 });
// token_embd_on_gpu: false because the embedding table holds the image: look it up on the CPU copy
try { await w.loadModel([blob], { n_ctx: n, n_gpu_layers: gpu ? 999 : 0, token_embd_on_gpu: false }); 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 = ' ';
turns.forEach((t, i) => { rest += (i ? '###Human: ' : '') + t.q + '###Assistant:' + (t.a !== null ? ' ' + t.a : ''); });
const head = await this.w.tokenize(`${SYSTEM}###Human:
`, { 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() });
}
}