Elffuss BraidHub

utopia-ia/elffuss public

main · 9.9 KiBRawPermalink
1// SEMANTIC side of the context engine (the companion to context.js).
2//
3// ─────────────────────────────────────────────────────────────────────────────
4// WHY IT EXISTS
5//
6// `context.js` already ships the complete hybrid path (`packHistoryAsync`):
7// BM25 and embeddings fused by rank. What it was missing was an `embed`
8// function, so it fell back to the lexical path and in production only BM25 ran.
9//
10// Measured on LoCoMo (200 questions, the benchmark repo's own F1, a real model
11// answering, same token budget):
12//
13// FULL context, uncompressed .......... 22.56
14// BM25 (what ran until now) ........... 23.59
15// embeddings alone .................... 23.95
16// RANK fusion (this) .................. 28.09 ← +4.50 over BM25
17//
18// The reason it adds anything is not that the semantic side is "better": overall
19// they TIE (23.59 vs 23.95). They do DIFFERENT jobs. Splitting the same
20// questions by vocabulary overlap between question and answer:
21//
22// no overlap (n=107) overlap (n=93)
23// BM25 ...................... 18.60 29.33
24// embeddings ................ 24.28 23.58
25// rank fusion ............... 24.05 32.73
26//
27// When the question does NOT literally name what it is looking for, BM25 sinks
28// (18.60) and the semantic side holds up (24.28). When it does name it, BM25
29// wins (29.33). The fusion keeps both. The semantic side does not replace the
30// lexical one: it covers its blind spot. That — and not an overall gain — is
31// what is being wired up here.
32//
33// ─────────────────────────────────────────────────────────────────────────────
34// MODEL CHOSEN — Xenova/multilingual-e5-small, dtype q8 (118 MB)
35//
36// Hard requirements and how it meets them:
37// · transformers.js: it is the official ONNX conversion by the library's own
38// maintainer → it loads with the SAME `pipeline()` providers/onnx.js uses.
39// · small: 118 MB at q8. It is the lightest variant in the repo (q4 weighs
40// MORE — 398 MB — because the embedding matrix of a 250k vocabulary does not
41// quantise as well; here "fewer bits" does not mean less disk).
42// · multilingual: XLM-R tokeniser, 100 languages. The prompts are in Spanish
43// and the code is in English, and that crossing is exactly the lexical
44// blind spot.
45// · licence: MIT (intfloat/multilingual-e5-small upstream).
46// · a 512-token window, which is what the blocks the packer assembles need;
47// this is not a single-sentence model.
48//
49// Rejected, and why:
50// · Xenova/all-MiniLM-L6-v2 (23 MB, Apache-2.0) — 5× cheaper, but English
51// ONLY. Spanish is precisely the case we came here to cover.
52// · Xenova/paraphrase-multilingual-MiniLM-L12-v2 (118 MB, Apache-2.0) — same
53// weight, but it is tuned for SENTENCE paraphrase with a 128-token window:
54// it would cut the blocks in half.
55// · onnx-community/embeddinggemma-300m-ONNX (175 MB at q4f16 + external
56// weights) — better quality, but 1.5× the download and a Gemma licence
57// (commercial use permitted, but with a use policy and redistribution
58// obligations), not a clean commercial licence.
59// · ibm-granite/granite-embedding-107m-multilingual (Apache-2.0) — only
60// publishes ONNX in fp32: 428 MB, 3.6× the download.
61// · minishlab/potion-multilingual-128M (MIT) — static and extremely fast, but
62// its only ONNX weighs 512 MB and transformers.js does not support it
63// out of the box.
64//
65// DTYPE BY DEVICE — measured, not assumed. Same model, same batch of blocks,
66// changing only dtype and device (relative cost, 1.0 = the best):
67//
68// fp16 / WebGPU .... 1.0× (235 MB) ← the pick when there is an adapter
69// q4f16/ WebGPU .... 0.6× (205 MB) with medium blocks; see point 2
70// q8 / wasm ...... 8.9× (118 MB) ← the safety net
71// fp32 / wasm ...... 11.0× (470 MB)
72// q8 / WebGPU .... 14.1× (118 MB) ← WORSE than on CPU
73//
74// Two things that contradict intuition, which is why they are written down:
75// 1. 8-bit integers are NOT accelerated on WebGPU: ORT-web has no kernels for
76// those operators and ends up bouncing back and forth to the CPU. The
77// smallest file turns out to be the SLOWEST on the GPU. Picking a dtype by
78// download size, without measuring, would have given the worst possible
79// combination.
80// 2. With SHORT texts — which is our case, see the block sizing in context.js —
81// 4-bit flips around and loses to fp16 (2.6× slower on single lines): at
82// those lengths you pay more to undo the quantisation than you save in
83// bandwidth. Hence fp16 and not q4f16, even though q4f16 wins on large
84// blocks.
85//
86// Hence the rule: fp16 if there is a real WebGPU adapter, and q8/wasm as the
87// safety net. The safety net WORKS but it is ~9× slower, to the point of being
88// noticeable on every turn, and that is one of the reasons the semantic side is
89// off by default (see context.js).
90// ─────────────────────────────────────────────────────────────────────────────
91
92import { createEmbedCache } from './context.js';
93
94export const EMBED_MODEL = {
95 id: 'Xenova/multilingual-e5-small',
96 dims: 384,
97 label: 'multilingual-e5-small',
98 // dtype → file → download
99 webgpu: { dtype: 'fp16', sizeMB: 235 },
100 wasm: { dtype: 'q8', sizeMB: 118 },
101};
102
103// The model's window is 512 tokens; trimming before tokenising avoids paying to
104// split text the model itself is going to discard.
105const MAX_CHARS = 2000;
106
107// Small batches: transformers.js pads every batch up to its longest item, so a
108// giant batch makes everyone pay the length of the worst element.
109const BATCH = 16;
110
111// e5 was ALWAYS trained with a prefix ('query: ' / 'passage: '), never with bare
112// text. the packer calls the same `embed` for the question and for the blocks,
113// and there is no way to tell them apart without touching the core; the model's
114// authors document using 'query: ' on BOTH sides for symmetric use. Dropping it
115// altogether would be worse: the model never saw that distribution.
116const PREFIX = 'query: ';
117
118let pipePromise = null;
119export let backend = null; // {device, dtype, sizeMB} once resolved
120
121/**
122 * LAZY loading: none of this is touched at startup. The whole module is
123 * dynamically imported from context.js only when the flag is on, and the model
124 * is not downloaded until the first request that genuinely uses it.
125 */
126function getPipe(onProgress) {
127 if (!pipePromise) {
128 pipePromise = (async () => {
129 const tf = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@4');
130 // navigator.gpu can EXIST without a real adapter (same care as in
131 // providers/onnx.js): check the adapter, not the object. Choosing wrong
132 // here means downloading 235 MB only to end up running on the CPU.
133 let device = 'wasm';
134 if (navigator.gpu) {
135 try { device = (await navigator.gpu.requestAdapter()) ? 'webgpu' : 'wasm'; }
136 catch { device = 'wasm'; }
137 }
138 const cfg = { device, ...EMBED_MODEL[device] };
139 const pipe = await tf.pipeline('feature-extraction', EMBED_MODEL.id, {
140 device,
141 dtype: cfg.dtype,
142 progress_callback: onProgress,
143 });
144 backend = cfg; // only once it is genuinely ready: isReady() does not lie
145 return pipe;
146 })().catch(e => {
147 pipePromise = null; // do not let a network failure leave the module dead
148 backend = null;
149 throw e;
150 });
151 }
152 return pipePromise;
153}
154
155/** Optional preload (e.g. from Settings) without blocking any turn. */
156export function warmup(onProgress) { return getPipe(onProgress); }
157
158/** Already loaded? Useful to decide whether a turn will pay for the download. */
159export function isReady() { return backend !== null; }
160
161/**
162 * embed(texts) → normalised 384-dimension vectors.
163 * The exact contract `packHistoryAsync` expects: if this throws, the packer
164 * takes the lexical path without breaking and without complaining.
165 */
166export async function embed(texts) {
167 if (!texts || !texts.length) return [];
168 const pipe = await getPipe();
169 const out = [];
170 for (let i = 0; i < texts.length; i += BATCH) {
171 const batch = texts.slice(i, i + BATCH)
172 .map(t => PREFIX + String(t == null ? '' : t).slice(0, MAX_CHARS));
173 const t = await pipe(batch, { pooling: 'mean', normalize: true });
174 for (const v of t.tolist()) out.push(Float32Array.from(v));
175 }
176 return out;
177}
178
179// Session cache BY CONTENT. This is not an optimisation: it is what makes the
180// idea viable at all. the packer reassembles the blocks from the start of the
181// history on every turn, so without a cache a text already encoded on turn 3
182// would be re-encoded on turn 4, on turn 5 and on turn 20 — the cost would grow
183// with the SQUARE of the number of turns. With a cache, each block is encoded
184// once per session and a turn only pays for the new blocks.
185// The ceiling is deliberately generous: the packer chunks the ENTIRE history on
186// every turn, so if the cache evicts entries the next turn asks for again, they
187// get re-encoded for nothing. These are 384-float vectors: ~12 MB when full.
188let cache = null;
189export function embedCache() {
190 // The signature is createEmbedCache(embed, max) with a NUMBER. Passing an
191 // object here meant `store.size > max` compared a number against an object,
192 // which is always false: the cache grew without bound and never evicted.
193 if (!cache) cache = createEmbedCache(embed, 8000);
194 return cache;
195}
196
197/** For diagnostics/settings: how many texts the session has cached so far. */
198export function embedCacheSize() { return cache ? cache.size() : 0; }