cite-demo / lib /cite.js
cjdd3b's picture
Add model switch: Cite 32M (default) / Cite 68M
a2d7085 verified
Raw History Blame Contribute Delete
7.3 kB
/** Browser Cite runtime: Hub download + cache + ORT WASM inference. */
const HUB_MODEL = "localangle/cite";
const HUB_BASE = `https://huggingface.co/${HUB_MODEL}/resolve/main`;
const CACHE_NAME = "cite-web-v3";
/** Browser builds on the Hub. The 32M build stays the default; 68M is larger, slower, more accurate. */
export const MODELS = {
"32m": { label: "32M", folder: "web" },
"68m": { label: "68M", folder: "web-68m" },
};
export const DEFAULT_MODEL = "32m";
export function splitParagraphs(article) {
const text = article.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();
if (!text) return [];
const pieces = /\n\s*\n/.test(text) ? text.split(/\n\s*\n/) : text.split("\n");
return pieces.map((p) => p.replace(/\s+/g, " ").trim()).filter(Boolean);
}
async function cachedFetch(url, onProgress) {
const cache = await caches.open(CACHE_NAME);
const hit = await cache.match(url);
if (hit) return hit.arrayBuffer();
const response = await fetch(url);
if (!response.ok) throw new Error(`download failed ${response.status}: ${url}`);
const total = Number(response.headers.get("Content-Length") || 0);
if (!response.body || !onProgress || !total) {
const buffer = await response.arrayBuffer();
await cache.put(url, new Response(buffer.slice(0)));
return buffer;
}
const reader = response.body.getReader();
const chunks = [];
let received = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
received += value.byteLength;
onProgress(received / total);
}
const merged = new Uint8Array(received);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.byteLength;
}
await cache.put(url, new Response(merged.buffer.slice(0)));
return merged.buffer;
}
function encodeWithTokenizer(tokenizer, special, question, blocks, maxTokens) {
const { maskId, clsId, sepId } = special;
const q = tokenizer.encode(question, { add_special_tokens: false });
const ids = [clsId, ...q, sepId];
if (ids.length + 1 > maxTokens) {
throw new Error(`question alone needs ${ids.length + 1} tokens (soft cap ${maxTokens})`);
}
const positions = [];
for (const text of blocks) {
const piece = [maskId, ...tokenizer.encode(text, { add_special_tokens: false })];
if (ids.length + piece.length + 1 > maxTokens) break;
positions.push(ids.length);
ids.push(...piece);
}
ids.push(sepId);
return {
input_ids: ids,
block_positions: positions,
n_blocks: blocks.length,
truncated_blocks: blocks.length - positions.length,
};
}
function platt(logit, slope, bias) {
return 1 / (1 + Math.exp(-(slope * logit + bias)));
}
export class CiteWeb {
constructor(variant = DEFAULT_MODEL) {
if (!MODELS[variant]) throw new Error(`unknown model ${variant}`);
this.variant = variant;
this.label = MODELS[variant].label;
this.base = `${HUB_BASE}/${MODELS[variant].folder}`;
this.ready = false;
this.meta = null;
this.session = null;
this.tokenizer = null;
this.vocabMap = null;
this.ort = null;
}
async load({ onProgress } = {}) {
const ortModule = await import(
"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/ort.wasm.mjs"
);
const ort = ortModule.default ?? ortModule;
if (!ort?.env?.wasm) {
throw new Error("onnxruntime-web failed to load (no ort.env.wasm)");
}
ort.env.wasm.wasmPaths = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/";
ort.env.wasm.numThreads = 1;
this.ort = ort;
const { AutoTokenizer } = await import(
"https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.5.1"
);
const report = (fraction, label) => {
if (onProgress) onProgress(fraction, label);
};
report(0.02, "meta");
const metaBuf = await cachedFetch(`${this.base}/cite-web.json`, (f) => report(0.02 + 0.03 * f, "meta"));
this.meta = JSON.parse(new TextDecoder().decode(metaBuf));
report(0.08, "tokenizer");
this.tokenizer = await AutoTokenizer.from_pretrained(HUB_MODEL);
report(0.2, "vocab");
const mapBuf = await cachedFetch(`${this.base}/${this.meta.vocab_map}`, (f) =>
report(0.2 + 0.05 * f, "vocab")
);
this.vocabMap = new Int32Array(mapBuf);
report(0.3, "model");
const modelBuf = await cachedFetch(`${this.base}/${this.meta.model}`, (f) =>
report(0.3 + 0.65 * f, "model")
);
this.session = await ort.InferenceSession.create(modelBuf, {
executionProviders: ["wasm"],
});
report(1, "ready");
this.ready = true;
return {
softCap: this.meta.soft_cap,
sizeMb: this.meta.size_mb,
thresholds: this.meta.thresholds,
package: HUB_MODEL,
label: this.label,
};
}
/** Free the WASM session before switching to another build. */
async release() {
this.ready = false;
try {
await this.session?.release?.();
} catch {
// best effort
}
this.session = null;
}
async predict(question, blocks) {
if (!this.ready) throw new Error("model not loaded");
const { Tensor } = this.ort;
const encoded = encodeWithTokenizer(
this.tokenizer,
{
maskId: this.meta.mask_token_id,
// Older cite-web.json files lack these; the ids are fixed for this tokenizer.
clsId: this.meta.cls_token_id ?? 50281,
sepId: this.meta.sep_token_id ?? 50282,
},
question,
blocks,
this.meta.soft_cap
);
const mapped = Int32Array.from(encoded.input_ids, (id) => this.vocabMap[id] ?? 0);
const inputIds = new Tensor(
"int64",
BigInt64Array.from(mapped, (v) => BigInt(v)),
[1, mapped.length]
);
if (!encoded.block_positions.length) {
return {
scores: blocks.map((_, index) => ({
index,
logit: null,
probability: 0,
needed: false,
contributing: false,
})),
tokens: encoded.input_ids.length,
truncated_paragraphs: encoded.truncated_blocks,
ms: 0,
soft_cap: this.meta.soft_cap,
};
}
const positions = new Tensor(
"int64",
BigInt64Array.from(encoded.block_positions, (v) => BigInt(v)),
[encoded.block_positions.length]
);
const started = performance.now();
const out = await this.session.run({ input_ids: inputIds, positions });
const logits = Array.from(out.logits.data);
const { slope, bias } = this.meta.platt;
const neededT = this.meta.thresholds.needed;
const contribT = this.meta.thresholds.contributing;
const scores = blocks.map((_, index) => {
if (index >= logits.length) {
return { index, logit: null, probability: 0, needed: false, contributing: false };
}
const logit = Number(logits[index]);
const probability = platt(logit, slope, bias);
return {
index,
logit,
probability,
needed: probability >= neededT,
contributing: probability >= contribT,
};
});
return {
scores,
tokens: encoded.input_ids.length,
truncated_paragraphs: encoded.truncated_blocks,
ms: Math.round((performance.now() - started) * 10) / 10,
soft_cap: this.meta.soft_cap,
};
}
}