vector-index 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +1456 -2
- package/build-browser.js +67 -0
- package/index.js +39 -0
- package/package.json +72 -4
- package/src/async.js +458 -0
- package/src/clustering.js +226 -0
- package/src/embeddings/als.js +211 -0
- package/src/embeddings/bpr.js +149 -0
- package/src/embeddings/embeddings.js +222 -0
- package/src/embeddings/evaluate.js +193 -0
- package/src/embeddings/graph.js +376 -0
- package/src/embeddings/idmap.js +120 -0
- package/src/embeddings/interactions.js +123 -0
- package/src/embeddings/memory.js +52 -0
- package/src/embeddings/node2vec.js +142 -0
- package/src/embeddings/sgns.js +191 -0
- package/src/embeddings/skipgram.js +128 -0
- package/src/embeddings/trainer.js +147 -0
- package/src/embeddings/walker.js +208 -0
- package/src/errors.js +41 -0
- package/src/heap.js +82 -0
- package/src/index/block-codec.js +191 -0
- package/src/index/diskann-block-engine.js +891 -0
- package/src/index/diskann.js +331 -0
- package/src/index/engine-common.js +159 -0
- package/src/index/flat.js +49 -0
- package/src/index/hnsw.js +282 -0
- package/src/index/ivf.js +232 -0
- package/src/index/prune.js +70 -0
- package/src/index/vector-index.js +391 -0
- package/src/lru.js +32 -0
- package/src/math.js +666 -0
- package/src/metric.js +62 -0
- package/src/quant/bq.js +172 -0
- package/src/quant/pq.js +418 -0
- package/src/quant/scan.js +52 -0
- package/src/quant/sq.js +274 -0
- package/src/quant/turboquant.js +527 -0
- package/src/reduce/pca.js +253 -0
- package/src/results.js +86 -0
- package/src/search.js +52 -0
- package/src/sparse/sparse-index.js +349 -0
- package/src/store.js +476 -0
- package/src/typed.js +23 -0
- package/src/validate.js +130 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
// ===========================
|
|
6
|
+
// createSparseIndex(options) — search over SPARSE vectors
|
|
7
|
+
//
|
|
8
|
+
// a sparse vector has many dimensions (one per word of a vocabulary, often
|
|
9
|
+
// tens of thousands) of which only a handful are non-zero, so only those are
|
|
10
|
+
// given:
|
|
11
|
+
//
|
|
12
|
+
// { indices: [812, 15, 4410], values: [2.1, 1.4, 0.9] }
|
|
13
|
+
//
|
|
14
|
+
// they come from keyword weighting (BM25, TF-IDF) or from learned sparse
|
|
15
|
+
// models (SPLADE). they catch exact matches dense embeddings miss — a part
|
|
16
|
+
// number, a model name, a rare word — which makes them the other half of
|
|
17
|
+
// hybrid search (see fuseResults). score = inner product ⟨q, x⟩.
|
|
18
|
+
//
|
|
19
|
+
// inverted index: one posting list per dimension (the vectors that have it,
|
|
20
|
+
// in insertion order, with their value). a query touches only the lists of
|
|
21
|
+
// its own dimensions.
|
|
22
|
+
//
|
|
23
|
+
// top-k with MaxScore (Turtle & Flood 1995), exact: every list knows its
|
|
24
|
+
// largest contribution w·max. lists are ordered by that bound; while the
|
|
25
|
+
// sum of the smallest bounds can't beat the current k-th score, those lists
|
|
26
|
+
// are "non-essential" — a vector found only there can't make the top k, so
|
|
27
|
+
// candidates come from the other lists alone, and the non-essential ones are
|
|
28
|
+
// only probed (binary search) for candidates that could still make it.
|
|
29
|
+
//
|
|
30
|
+
// same contract as createVectorIndex: callbacks, write queue, soft deletes,
|
|
31
|
+
// compact (time-sliced), search options { filter }, searchBatch.
|
|
32
|
+
// add(id, vector, cb) delete(id, cb) search(query, k[, { filter }], cb)
|
|
33
|
+
// searchBatch(queries, k[, { filter }], cb) stats(cb) compact(cb) on/off
|
|
34
|
+
// results: [{ id, score }], highest first. values may be any finite number
|
|
35
|
+
// (negative ones only weaken MaxScore's pruning, never its exactness).
|
|
36
|
+
// ===========================
|
|
37
|
+
|
|
38
|
+
import { ERR, createError } from '../errors.js';
|
|
39
|
+
import { createEmitter, requireCallback, callAsync, defer, createTaskQueue, runJobSliced, queuedCall, queuedJob, onceAsync } from '../async.js';
|
|
40
|
+
import { checkId, checkPositiveInt } from '../validate.js';
|
|
41
|
+
import { createSlots } from '../store.js';
|
|
42
|
+
import { createHeap } from '../heap.js';
|
|
43
|
+
import { grow } from '../typed.js';
|
|
44
|
+
import { checkSearchOptions, batchJob } from '../search.js';
|
|
45
|
+
|
|
46
|
+
const MAX_DIMENSION = 0xFFFFFFFF;
|
|
47
|
+
|
|
48
|
+
// a sparse vector → { indices: Uint32Array (sorted, unique), values: Float32Array }
|
|
49
|
+
// repeated dimensions are summed, zeros dropped. the caller's arrays are copied.
|
|
50
|
+
function checkSparse(v, what) {
|
|
51
|
+
what = what || 'vector';
|
|
52
|
+
if (!v || typeof v !== 'object' || !v.indices || !v.values ||
|
|
53
|
+
typeof v.indices.length !== 'number' || typeof v.values.length !== 'number') {
|
|
54
|
+
throw createError(ERR.INVALID_ARGUMENT, what + ' must be { indices: [...], values: [...] }');
|
|
55
|
+
}
|
|
56
|
+
const n = v.indices.length;
|
|
57
|
+
if (v.values.length !== n) {
|
|
58
|
+
throw createError(ERR.DIMENSION_MISMATCH, what + ': indices and values must have the same length');
|
|
59
|
+
}
|
|
60
|
+
const pairs = new Array(n);
|
|
61
|
+
for (let i = 0; i < n; i++) {
|
|
62
|
+
const d = v.indices[i], x = v.values[i];
|
|
63
|
+
if (!Number.isInteger(d) || d < 0 || d > MAX_DIMENSION) {
|
|
64
|
+
throw createError(ERR.INVALID_ARGUMENT, what + '.indices[' + i + '] must be an integer in [0, 2^32 − 1], got ' + d);
|
|
65
|
+
}
|
|
66
|
+
if (!Number.isFinite(x)) {
|
|
67
|
+
throw createError(ERR.INVALID_ARGUMENT, what + '.values[' + i + '] must be a finite number, got ' + x);
|
|
68
|
+
}
|
|
69
|
+
pairs[i] = [d, x];
|
|
70
|
+
}
|
|
71
|
+
pairs.sort((a, b) => a[0] - b[0]);
|
|
72
|
+
const idx = [], val = [];
|
|
73
|
+
for (const [d, x] of pairs) {
|
|
74
|
+
if (idx.length && idx[idx.length - 1] === d) val[val.length - 1] += x;
|
|
75
|
+
else { idx.push(d); val.push(x); }
|
|
76
|
+
}
|
|
77
|
+
const outI = [], outV = [];
|
|
78
|
+
for (let i = 0; i < idx.length; i++) if (val[i] !== 0) { outI.push(idx[i]); outV.push(val[i]); }
|
|
79
|
+
return { indices: Uint32Array.from(outI), values: Float32Array.from(outV) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// the index data: slots (ids, tombstones), a forward copy of every vector
|
|
83
|
+
// (for compact) and the posting lists. rebuilt on the side by compact.
|
|
84
|
+
function createSparseData() {
|
|
85
|
+
const slots = createSlots(1024, (cap) => {
|
|
86
|
+
const s = new Uint32Array(cap + 1);
|
|
87
|
+
s.set(start);
|
|
88
|
+
start = s;
|
|
89
|
+
});
|
|
90
|
+
let start = new Uint32Array(slots.capacity + 1); // forward index: slot → [start, start+1)
|
|
91
|
+
let fDims = new Uint32Array(1024), fVals = new Float32Array(1024);
|
|
92
|
+
let used = 0;
|
|
93
|
+
const lists = new Map(); // dimension → posting list
|
|
94
|
+
let postings = 0;
|
|
95
|
+
|
|
96
|
+
function listOf(d) {
|
|
97
|
+
let l = lists.get(d);
|
|
98
|
+
if (!l) {
|
|
99
|
+
l = { slots: new Uint32Array(8), vals: new Float32Array(8), n: 0, max: -Infinity, min: Infinity };
|
|
100
|
+
lists.set(d, l);
|
|
101
|
+
}
|
|
102
|
+
return l;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function add(id, v) {
|
|
106
|
+
const slot = slots.claim(id);
|
|
107
|
+
const n = v.indices.length;
|
|
108
|
+
if (used + n > fDims.length) {
|
|
109
|
+
fDims = grow(fDims, used + n);
|
|
110
|
+
fVals = grow(fVals, used + n);
|
|
111
|
+
}
|
|
112
|
+
start[slot] = used;
|
|
113
|
+
fDims.set(v.indices, used);
|
|
114
|
+
fVals.set(v.values, used);
|
|
115
|
+
used += n;
|
|
116
|
+
start[slot + 1] = used;
|
|
117
|
+
for (let i = 0; i < n; i++) {
|
|
118
|
+
const l = listOf(v.indices[i]), x = v.values[i];
|
|
119
|
+
if (l.n === l.slots.length) {
|
|
120
|
+
l.slots = grow(l.slots, l.n + 1);
|
|
121
|
+
l.vals = grow(l.vals, l.n + 1);
|
|
122
|
+
}
|
|
123
|
+
l.slots[l.n] = slot; // slots only grow: every list stays sorted
|
|
124
|
+
l.vals[l.n++] = x;
|
|
125
|
+
if (x > l.max) l.max = x;
|
|
126
|
+
if (x < l.min) l.min = x;
|
|
127
|
+
}
|
|
128
|
+
postings += n;
|
|
129
|
+
slots.commit(id, slot);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function vectorOf(slot) {
|
|
133
|
+
return {
|
|
134
|
+
indices: fDims.slice(start[slot], start[slot + 1]),
|
|
135
|
+
values: fVals.slice(start[slot], start[slot + 1])
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
slots,
|
|
141
|
+
lists,
|
|
142
|
+
add,
|
|
143
|
+
vectorOf,
|
|
144
|
+
get postings() { return postings; }
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// first position ≥ from in a sorted list where slots[p] ≥ target
|
|
149
|
+
function seek(slots, n, from, target) {
|
|
150
|
+
if (from >= n || slots[from] >= target) return from;
|
|
151
|
+
let step = 1, lo = from, hi = from + 1;
|
|
152
|
+
while (hi < n && slots[hi] < target) { lo = hi; step *= 2; hi = from + step; }
|
|
153
|
+
if (hi > n) hi = n;
|
|
154
|
+
while (lo < hi) {
|
|
155
|
+
const mid = (lo + hi) >>> 1;
|
|
156
|
+
if (slots[mid] < target) lo = mid + 1; else hi = mid;
|
|
157
|
+
}
|
|
158
|
+
return lo;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// exact top-k by inner product, MaxScore. accept: wrapped filter or null
|
|
162
|
+
function searchData(data, q, k, accept) {
|
|
163
|
+
const { slots, lists } = data;
|
|
164
|
+
// the query's lists, each with its weight and upper bound
|
|
165
|
+
const terms = [];
|
|
166
|
+
for (let i = 0; i < q.indices.length; i++) {
|
|
167
|
+
const l = lists.get(q.indices[i]);
|
|
168
|
+
if (!l || l.n === 0) continue;
|
|
169
|
+
const w = q.values[i];
|
|
170
|
+
const ub = Math.max(0, w > 0 ? w * l.max : w * l.min);
|
|
171
|
+
terms.push({ l, w, ub });
|
|
172
|
+
}
|
|
173
|
+
if (terms.length === 0) return [];
|
|
174
|
+
terms.sort((a, b) => a.ub - b.ub);
|
|
175
|
+
const T = terms.length;
|
|
176
|
+
const prefix = new Float64Array(T); // prefix[i] = Σ ub of terms 0..i
|
|
177
|
+
let acc = 0;
|
|
178
|
+
for (let i = 0; i < T; i++) { acc += terms[i].ub; prefix[i] = acc; }
|
|
179
|
+
const pos = new Int32Array(T);
|
|
180
|
+
|
|
181
|
+
const heap = createHeap(false, k + 1); // min-heap on score: the top is the k-th best
|
|
182
|
+
let theta = -Infinity;
|
|
183
|
+
let first = 0; // terms[first..] are essential
|
|
184
|
+
const deleted = slots.deletedFlags;
|
|
185
|
+
|
|
186
|
+
while (true) {
|
|
187
|
+
// next candidate: the smallest slot under the essential cursors
|
|
188
|
+
let d = Infinity;
|
|
189
|
+
for (let i = first; i < T; i++) {
|
|
190
|
+
const t = terms[i];
|
|
191
|
+
if (pos[i] < t.l.n && t.l.slots[pos[i]] < d) d = t.l.slots[pos[i]];
|
|
192
|
+
}
|
|
193
|
+
if (d === Infinity) break;
|
|
194
|
+
|
|
195
|
+
let score = 0;
|
|
196
|
+
for (let i = first; i < T; i++) {
|
|
197
|
+
const t = terms[i];
|
|
198
|
+
if (pos[i] < t.l.n && t.l.slots[pos[i]] === d) {
|
|
199
|
+
score += t.w * t.l.vals[pos[i]];
|
|
200
|
+
pos[i]++;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (deleted[d] || (accept && !accept(slots.idOf(d)))) continue;
|
|
204
|
+
|
|
205
|
+
// the non-essential lists, largest bound first, while the candidate can still make it
|
|
206
|
+
for (let i = first - 1; i >= 0; i--) {
|
|
207
|
+
if (heap.size() === k && score + prefix[i] <= theta) { score = -Infinity; break; }
|
|
208
|
+
const t = terms[i];
|
|
209
|
+
pos[i] = seek(t.l.slots, t.l.n, pos[i], d);
|
|
210
|
+
if (pos[i] < t.l.n && t.l.slots[pos[i]] === d) score += t.w * t.l.vals[pos[i]];
|
|
211
|
+
}
|
|
212
|
+
if (score === -Infinity) continue;
|
|
213
|
+
|
|
214
|
+
if (heap.size() < k) {
|
|
215
|
+
heap.push(score, d);
|
|
216
|
+
if (heap.size() === k) theta = heap.topDist();
|
|
217
|
+
} else if (score > theta) {
|
|
218
|
+
heap.pop();
|
|
219
|
+
heap.push(score, d);
|
|
220
|
+
theta = heap.topDist();
|
|
221
|
+
} else {
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (heap.size() === k) while (first < T && prefix[first] <= theta) first++;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const { dist, slot } = heap.drainSorted(); // ascending
|
|
228
|
+
const out = new Array(dist.length);
|
|
229
|
+
for (let i = 0; i < dist.length; i++) out[dist.length - 1 - i] = { id: slots.idOf(slot[i]), score: dist[i] };
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function createSparseIndex(options) {
|
|
234
|
+
if (options != null && (typeof options !== 'object' || Object.keys(options).length > 0)) {
|
|
235
|
+
throw createError(ERR.INVALID_ARGUMENT, 'createSparseIndex takes no options yet');
|
|
236
|
+
}
|
|
237
|
+
let data = createSparseData();
|
|
238
|
+
const queue = createTaskQueue();
|
|
239
|
+
const emitter = createEmitter();
|
|
240
|
+
|
|
241
|
+
function fail(cb, err) {
|
|
242
|
+
defer(() => cb(err));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function add(id, vector, cb) {
|
|
246
|
+
requireCallback(cb, 'add');
|
|
247
|
+
let v;
|
|
248
|
+
try {
|
|
249
|
+
checkId(id);
|
|
250
|
+
v = checkSparse(vector);
|
|
251
|
+
} catch (err) {
|
|
252
|
+
return fail(cb, err);
|
|
253
|
+
}
|
|
254
|
+
queuedCall(queue, cb, () => { data.add(id, v); });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function del(id, cb) {
|
|
258
|
+
requireCallback(cb, 'delete');
|
|
259
|
+
try {
|
|
260
|
+
checkId(id);
|
|
261
|
+
} catch (err) {
|
|
262
|
+
return fail(cb, err);
|
|
263
|
+
}
|
|
264
|
+
queuedCall(queue, cb, () => { data.slots.remove(id); });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function search(query, k, options, cb) {
|
|
268
|
+
if (typeof options === 'function' && cb === undefined) {
|
|
269
|
+
cb = options;
|
|
270
|
+
options = undefined;
|
|
271
|
+
}
|
|
272
|
+
requireCallback(cb, 'search');
|
|
273
|
+
let q, accept;
|
|
274
|
+
try {
|
|
275
|
+
q = checkSparse(query, 'query');
|
|
276
|
+
checkPositiveInt(k, 'k');
|
|
277
|
+
accept = checkSearchOptions(options);
|
|
278
|
+
} catch (err) {
|
|
279
|
+
return fail(cb, err);
|
|
280
|
+
}
|
|
281
|
+
callAsync('search', cb, () => searchData(data, q, k, accept));
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function searchBatch(queries, k, options, cb) {
|
|
285
|
+
if (typeof options === 'function' && cb === undefined) {
|
|
286
|
+
cb = options;
|
|
287
|
+
options = undefined;
|
|
288
|
+
}
|
|
289
|
+
requireCallback(cb, 'searchBatch');
|
|
290
|
+
let accept;
|
|
291
|
+
try {
|
|
292
|
+
checkPositiveInt(k, 'k');
|
|
293
|
+
accept = checkSearchOptions(options);
|
|
294
|
+
} catch (err) {
|
|
295
|
+
return fail(cb, err);
|
|
296
|
+
}
|
|
297
|
+
runJobSliced(() => batchJob(queries, checkSparse, (q) => searchData(data, checkSparse(q), k, accept)), onceAsync(cb));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function stats(cb) {
|
|
301
|
+
requireCallback(cb, 'stats');
|
|
302
|
+
callAsync('stats', cb, () => {
|
|
303
|
+
const s = data.slots;
|
|
304
|
+
const total = s.count, deleted = total - s.live;
|
|
305
|
+
return {
|
|
306
|
+
total,
|
|
307
|
+
alive: s.live,
|
|
308
|
+
deleted,
|
|
309
|
+
ratio: total === 0 ? 0 : deleted / total,
|
|
310
|
+
dimensions: data.lists.size,
|
|
311
|
+
postings: data.postings,
|
|
312
|
+
avgNonZeros: total === 0 ? 0 : parseFloat((data.postings / total).toFixed(1))
|
|
313
|
+
};
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// rebuild from the live vectors on the side, swap at the end: searches
|
|
318
|
+
// see the old data until then, writes wait in the queue
|
|
319
|
+
function compact(cb) {
|
|
320
|
+
requireCallback(cb, 'compact');
|
|
321
|
+
queuedJob(queue, cb, function* () {
|
|
322
|
+
const old = data, s = old.slots, fresh = createSparseData();
|
|
323
|
+
const total = s.count;
|
|
324
|
+
for (let slot = 0; slot < total; slot++) {
|
|
325
|
+
if (!s.isDeleted(slot)) fresh.add(s.idOf(slot), old.vectorOf(slot));
|
|
326
|
+
if ((slot & 255) === 255) {
|
|
327
|
+
emitter.emit('progress', { phase: 'compact', processed: slot + 1, total, percent: Math.round((slot + 1) / total * 100) });
|
|
328
|
+
yield;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
data = fresh;
|
|
332
|
+
emitter.emit('progress', { phase: 'compact', processed: total, total, percent: 100 });
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
add,
|
|
338
|
+
delete: del,
|
|
339
|
+
search,
|
|
340
|
+
searchBatch,
|
|
341
|
+
stats,
|
|
342
|
+
compact,
|
|
343
|
+
on: emitter.on,
|
|
344
|
+
off: emitter.off,
|
|
345
|
+
kind: 'sparse'
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export { createSparseIndex };
|