vector-index 0.0.1 → 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.
Files changed (46) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +1447 -12
  3. package/build-browser.js +67 -0
  4. package/index.js +38 -6
  5. package/package.json +70 -6
  6. package/src/async.js +458 -0
  7. package/src/clustering.js +226 -0
  8. package/src/embeddings/als.js +211 -0
  9. package/src/embeddings/bpr.js +149 -0
  10. package/src/embeddings/embeddings.js +222 -0
  11. package/src/embeddings/evaluate.js +193 -0
  12. package/src/embeddings/graph.js +376 -0
  13. package/src/embeddings/idmap.js +120 -0
  14. package/src/embeddings/interactions.js +123 -0
  15. package/src/embeddings/memory.js +52 -0
  16. package/src/embeddings/node2vec.js +142 -0
  17. package/src/embeddings/sgns.js +191 -0
  18. package/src/embeddings/skipgram.js +128 -0
  19. package/src/embeddings/trainer.js +147 -0
  20. package/src/embeddings/walker.js +208 -0
  21. package/src/errors.js +41 -0
  22. package/src/heap.js +82 -0
  23. package/src/index/block-codec.js +191 -0
  24. package/src/index/diskann-block-engine.js +891 -0
  25. package/src/index/diskann.js +331 -0
  26. package/src/index/engine-common.js +159 -0
  27. package/src/index/flat.js +49 -0
  28. package/src/index/hnsw.js +282 -0
  29. package/src/index/ivf.js +232 -0
  30. package/src/index/prune.js +70 -0
  31. package/src/index/vector-index.js +391 -0
  32. package/src/lru.js +32 -0
  33. package/src/math.js +666 -0
  34. package/src/metric.js +62 -0
  35. package/src/quant/bq.js +172 -0
  36. package/src/quant/pq.js +418 -0
  37. package/src/quant/scan.js +52 -0
  38. package/src/quant/sq.js +274 -0
  39. package/src/quant/turboquant.js +527 -0
  40. package/src/reduce/pca.js +253 -0
  41. package/src/results.js +86 -0
  42. package/src/search.js +52 -0
  43. package/src/sparse/sparse-index.js +349 -0
  44. package/src/store.js +476 -0
  45. package/src/typed.js +23 -0
  46. package/src/validate.js +130 -0
@@ -0,0 +1,391 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // Vector Index — pluggable ANN library
7
+ // algorithms: flat, hnsw, ivf, diskann, diskann-blocks
8
+ //
9
+ // every algorithm exposes exactly the same object:
10
+ //
11
+ // add(id, vector, cb) delete(id, cb) search(query, k[, { filter }], cb)
12
+ // searchBatch(queries, k[, { filter }], cb)
13
+ // stats(cb) compact(cb) train(vectors, cb)
14
+ // build(cb) restore([rootId], cb) getRootId()
15
+ // on(event, fn) off(event[, fn])
16
+ // algorithm, dimensions, metric, vectors, requiresTraining
17
+ //
18
+ // option `metric`: 'cosine' (default), 'l2' or 'dot' (see ../metric.js)
19
+ //
20
+ // option `vectors` — how the index stores vectors:
21
+ // omitted every vector in full (Float32; normalized for cosine)
22
+ // { encode, decode, prepare, similarity }
23
+ // in the caller's own format (typically compressed). the index
24
+ // knows nothing about the format; it only calls:
25
+ // encode(vector) → Uint8Array, same size every time
26
+ // decode(bytes) → vector (graph construction)
27
+ // prepare(query) → any value, once per operation
28
+ // similarity(prepared, data, offset) → number, higher = closer
29
+ // plain synchronous functions — computation, not I/O. `data` is
30
+ // the index's own buffer: read only [offset, offset + size).
31
+ //
32
+ // the rule across the library: I/O goes through events (block:*, meta:*),
33
+ // computation is passed as functions (vectors.*).
34
+ //
35
+ // callbacks follow the contract in async.js: required, err-first, always
36
+ // asynchronous, exactly once. a method that doesn't apply to the chosen
37
+ // algorithm calls back with err.code === 'NOT_SUPPORTED'.
38
+ //
39
+ // this file is the factory: options, the write queue, the public methods.
40
+ // the engines live next to it:
41
+ // flat.js ivf.js diskann.js hnsw.js in memory (engine-common.js: what they share)
42
+ // diskann-block-engine.js nodes in the caller's storage (block-codec.js)
43
+ // prune.js the neighbor rule every graph uses
44
+ // metric logic: ../metric.js; vector storage: ../store.js
45
+ // ===========================
46
+
47
+ import { ERR, createError } from '../errors.js';
48
+ import { createEmitter, requireCallback, onceAsync, callAsync, defer, createTaskQueue, runJobSliced, queuedCall, queuedJob } from '../async.js';
49
+ import { checkVector, checkVectorsJob, checkPositiveInt, checkId } from '../validate.js';
50
+ import { checkMetric } from '../metric.js';
51
+ import { checkSearchOptions, batchJob } from '../search.js';
52
+ import { createDiskANNBlockEngine } from './diskann-block-engine.js';
53
+ import { createFlatEngine } from './flat.js';
54
+ import { createIVFEngine } from './ivf.js';
55
+ import { createDiskANNEngine } from './diskann.js';
56
+ import { createHNSWEngine } from './hnsw.js';
57
+
58
+ const BATCH_PARALLEL = 8; // diskann-blocks: searches in flight per searchBatch
59
+ const ALGORITHMS = ['flat', 'hnsw', 'ivf', 'diskann', 'diskann-blocks'];
60
+ const FORMAT_FUNCTIONS = ['encode', 'decode', 'prepare', 'similarity'];
61
+
62
+ // option `vectors`: omitted → null (full vectors), or an object with the
63
+ // four functions. returns a private copy, so later changes to the caller's
64
+ // object can't swap functions under a running index.
65
+ function checkFormat(v) {
66
+ if (v == null) return null;
67
+ if (typeof v !== 'object') {
68
+ throw createError(ERR.INVALID_ARGUMENT,
69
+ 'vectors must be an object { ' + FORMAT_FUNCTIONS.join(', ') + ' }, got ' + typeof v);
70
+ }
71
+ const out = {};
72
+ for (const name of FORMAT_FUNCTIONS) {
73
+ if (typeof v[name] !== 'function') {
74
+ throw createError(ERR.INVALID_ARGUMENT, 'vectors.' + name + ' must be a function, got ' + typeof v[name]);
75
+ }
76
+ out[name] = v[name];
77
+ }
78
+ return out;
79
+ }
80
+
81
+ function createVectorIndex(opts) {
82
+ opts = opts || {};
83
+ const algorithm = opts.algorithm || 'hnsw';
84
+ const dimensions = checkPositiveInt(opts.dimensions, 'dimensions');
85
+ const metric = checkMetric(opts.metric);
86
+
87
+ if (ALGORITHMS.indexOf(algorithm) === -1) {
88
+ throw createError(ERR.INVALID_ARGUMENT,
89
+ 'unknown algorithm: ' + algorithm + ' (expected one of: ' + ALGORITHMS.join(', ') + ')');
90
+ }
91
+
92
+ const format = checkFormat(opts.vectors);
93
+ const vectors = format ? 'custom' : 'full';
94
+ if (format && algorithm === 'diskann-blocks') {
95
+ throw createError(ERR.NOT_SUPPORTED,
96
+ 'option vectors is not supported by diskann-blocks (its vectors already live in your storage)');
97
+ }
98
+
99
+ // 'progress' notifications of the in-memory engines. the block engine has
100
+ // its own emitter (it also carries the storage events).
101
+ const emitter = createEmitter();
102
+
103
+ let engine;
104
+ if (algorithm === 'hnsw') {
105
+ engine = createHNSWEngine({
106
+ dimensions,
107
+ M: opts.M || 16,
108
+ efConstruction: opts.efConstruction || 200,
109
+ efSearch: opts.efSearch || 50,
110
+ seed: opts.seed,
111
+ format,
112
+ metric,
113
+ emit: emitter.emit
114
+ });
115
+ } else if (algorithm === 'flat') {
116
+ engine = createFlatEngine({ dimensions, format, metric, emit: emitter.emit });
117
+ } else if (algorithm === 'ivf') {
118
+ engine = createIVFEngine({
119
+ dimensions,
120
+ nlist: opts.nlist || 100,
121
+ nprobe: opts.nprobe || 10,
122
+ seed: opts.seed,
123
+ format,
124
+ metric,
125
+ emit: emitter.emit
126
+ });
127
+ } else if (algorithm === 'diskann') {
128
+ engine = createDiskANNEngine({
129
+ dimensions,
130
+ R: opts.R || 64,
131
+ L: opts.L || 100,
132
+ alpha: opts.alpha || 1.2,
133
+ seed: opts.seed,
134
+ format,
135
+ metric,
136
+ emit: emitter.emit
137
+ });
138
+ } else {
139
+ engine = createDiskANNBlockEngine({
140
+ dimensions,
141
+ metric,
142
+ R: opts.R || 32,
143
+ L: opts.L || 100,
144
+ alpha: opts.alpha || 1.0,
145
+ cacheSize: opts.cacheSize || 1000,
146
+ codeBits: opts.codeBits, // bits per coordinate of the neighbor codes (default 4)
147
+ beamWidth: opts.beamWidth, // blocks read in parallel per search step (default 4)
148
+ metaWriteInterval: opts.metaWriteInterval // max writes between metadata saves (default 64)
149
+ });
150
+ }
151
+
152
+ // engines are either synchronous (flat/hnsw/ivf/diskann) or follow the
153
+ // callback contract themselves (diskann-blocks, which has its own write
154
+ // queue because its writes wait on storage).
155
+ const isAsync = !!engine.isAsync;
156
+
157
+ // ===========================
158
+ // write queue (in-memory engines)
159
+ //
160
+ // add / delete / train / build / compact all go through one FIFO queue:
161
+ // - when nothing long is running, a write executes immediately — the
162
+ // queue is invisible;
163
+ // - while a time-sliced train / build / compact is running, writes wait
164
+ // and then execute in call order;
165
+ // - search and stats never wait: they read whatever is committed now.
166
+ // ===========================
167
+ const queue = createTaskQueue();
168
+
169
+ const enqueueWrite = (name, cb, fn) => queuedCall(queue, cb, fn);
170
+ const enqueueJob = (name, cb, makeIter) => queuedJob(queue, cb, makeIter);
171
+
172
+ // report a validation error through the callback (async, like any error)
173
+ function fail(cb, err) {
174
+ defer(() => cb(err));
175
+ }
176
+
177
+ function notSupported(method) {
178
+ return createError(ERR.NOT_SUPPORTED, method + '() is not supported by algorithm "' + algorithm + '"');
179
+ }
180
+
181
+ // ===========================
182
+ // compact as a job: re-insert the live vectors into a fresh engine on the
183
+ // side, then swap it in with one assignment. searches before the swap
184
+ // see the old index, searches after it see the new one — never a half.
185
+ // ===========================
186
+ function* compactJob() {
187
+ const live = engine.liveEntries();
188
+ const fresh = engine.cloneEmpty();
189
+ const reportEvery = Math.max(1, Math.floor(live.length / 20));
190
+ for (let i = 0; i < live.length; i++) {
191
+ // custom format: the stored bytes move as they are (no re-encoding)
192
+ fresh.add(live[i].id, live[i].vector, live[i].bytes);
193
+ if ((i + 1) % reportEvery === 0 || i === live.length - 1) {
194
+ emitter.emit('progress', {
195
+ phase: 'compact',
196
+ processed: i + 1,
197
+ total: live.length,
198
+ percent: Math.round((i + 1) / live.length * 100)
199
+ });
200
+ }
201
+ yield;
202
+ }
203
+ engine = fresh;
204
+ }
205
+
206
+ // ===========================
207
+ // public API
208
+ // ===========================
209
+
210
+ function add(id, vector, cb) {
211
+ requireCallback(cb, 'add');
212
+ try {
213
+ checkId(id);
214
+ checkVector(vector, dimensions);
215
+ } catch (err) {
216
+ return fail(cb, err);
217
+ }
218
+ // the engines copy the vector into their own storage on insert. when the
219
+ // write runs right away that copy is enough; when it has to wait in the
220
+ // queue (a compact is running) take a copy now, so the caller may reuse
221
+ // its array as soon as add() returns
222
+ if (isAsync) return engine.add(id, vector, cb);
223
+ const vec = queue.idle() ? vector : Float32Array.from(vector);
224
+ enqueueWrite('add', cb, () => { engine.add(id, vec); });
225
+ }
226
+
227
+ function del(id, cb) {
228
+ requireCallback(cb, 'delete');
229
+ try {
230
+ checkId(id);
231
+ } catch (err) {
232
+ return fail(cb, err);
233
+ }
234
+ if (isAsync) engine.delete(id, cb);
235
+ else enqueueWrite('delete', cb, () => { engine.delete(id); });
236
+ }
237
+
238
+ // search(query, k[, options], cb) — options: { filter(id) → boolean }
239
+ function search(query, k, options, cb) {
240
+ if (typeof options === 'function' && cb === undefined) {
241
+ cb = options;
242
+ options = undefined;
243
+ }
244
+ requireCallback(cb, 'search');
245
+ let accept;
246
+ try {
247
+ checkVector(query, dimensions, 'query');
248
+ checkPositiveInt(k, 'k');
249
+ accept = checkSearchOptions(options);
250
+ } catch (err) {
251
+ return fail(cb, err);
252
+ }
253
+ if (isAsync) return engine.search(query, k, cb, accept);
254
+ callAsync('search', cb, () => engine.search(query, k, accept));
255
+ }
256
+
257
+ // searchBatch(queries, k[, options], cb) → one result list per query, in
258
+ // order. reads never wait in the write queue. in memory: time-sliced, a
259
+ // pause between queries, so a large batch never freezes the thread. with
260
+ // diskann-blocks: up to BATCH_PARALLEL searches wait on storage at once.
261
+ function searchBatch(queries, k, options, cb) {
262
+ if (typeof options === 'function' && cb === undefined) {
263
+ cb = options;
264
+ options = undefined;
265
+ }
266
+ requireCallback(cb, 'searchBatch');
267
+ let accept;
268
+ try {
269
+ if (!Array.isArray(queries)) {
270
+ throw createError(ERR.INVALID_ARGUMENT, 'searchBatch: queries must be an array of vectors');
271
+ }
272
+ checkPositiveInt(k, 'k');
273
+ accept = checkSearchOptions(options);
274
+ } catch (err) {
275
+ return fail(cb, err);
276
+ }
277
+ if (isAsync) return searchBatchAsync(queries, k, accept, onceAsync(cb));
278
+ runJobSliced(() => batchJob(queries, (q, what) => checkVector(q, dimensions, what),
279
+ (q) => engine.search(q, k, accept)), onceAsync(cb));
280
+ }
281
+
282
+ function searchBatchAsync(queries, k, accept, done) {
283
+ try {
284
+ queries.forEach((q, i) => checkVector(q, dimensions, 'queries[' + i + ']'));
285
+ } catch (err) {
286
+ return done(err);
287
+ }
288
+ const out = new Array(queries.length);
289
+ let next = 0, running = 0, failed = false;
290
+ if (queries.length === 0) return done(null, out);
291
+ (function launch() {
292
+ while (!failed && running < BATCH_PARALLEL && next < queries.length) {
293
+ const i = next++;
294
+ running++;
295
+ engine.search(queries[i], k, (err, r) => {
296
+ running--;
297
+ if (failed) return;
298
+ if (err) {
299
+ failed = true;
300
+ return done(err);
301
+ }
302
+ out[i] = r;
303
+ if (next === queries.length && running === 0) return done(null, out);
304
+ launch();
305
+ }, accept);
306
+ }
307
+ })();
308
+ }
309
+
310
+ function stats(cb) {
311
+ requireCallback(cb, 'stats');
312
+ const decorate = (s) => Object.assign({ algorithm, dimensions, vectors }, s);
313
+ if (isAsync) engine.stats((err, s) => (err ? cb(err) : cb(null, decorate(s))));
314
+ else callAsync('stats', cb, () => decorate(engine.stats()));
315
+ }
316
+
317
+ function compact(cb) {
318
+ requireCallback(cb, 'compact');
319
+ if (isAsync) return engine.compact(cb);
320
+ enqueueJob('compact', cb, compactJob);
321
+ }
322
+
323
+ function train(vectors, cb) {
324
+ requireCallback(cb, 'train');
325
+ if (!isAsync && !engine.trainJob) return fail(cb, notSupported('train'));
326
+ if (isAsync) return engine.train(vectors, cb);
327
+ // validate + copy the sample inside the sliced job as well
328
+ enqueueJob('train', cb, function* () {
329
+ yield* checkVectorsJob(vectors, dimensions);
330
+ const copies = new Array(vectors.length);
331
+ for (let i = 0; i < vectors.length; i++) {
332
+ copies[i] = Float32Array.from(vectors[i]);
333
+ if ((i & 255) === 255) yield;
334
+ }
335
+ return yield* engine.trainJob(copies);
336
+ });
337
+ }
338
+
339
+ function build(cb) {
340
+ requireCallback(cb, 'build');
341
+ if (isAsync) return engine.build(cb);
342
+ if (!engine.buildJob) return fail(cb, notSupported('build'));
343
+ enqueueJob('build', cb, () => engine.buildJob());
344
+ }
345
+
346
+ // restore([rootId], cb)
347
+ function restore(rootId, cb) {
348
+ if (typeof rootId === 'function' && cb === undefined) {
349
+ cb = rootId;
350
+ rootId = null;
351
+ }
352
+ requireCallback(cb, 'restore');
353
+ if (!engine.restore) return fail(cb, notSupported('restore'));
354
+ engine.restore(rootId, cb);
355
+ }
356
+
357
+ // synchronous getter (not an operation): the current entry-point id,
358
+ // or null for algorithms without a persisted root
359
+ function getRootId() {
360
+ return engine.getRootId ? engine.getRootId() : null;
361
+ }
362
+
363
+ const events = isAsync ? engine : emitter;
364
+
365
+ return {
366
+ add,
367
+ delete: del,
368
+ search,
369
+ searchBatch,
370
+ stats,
371
+ compact,
372
+ train,
373
+ build,
374
+ restore,
375
+ getRootId,
376
+ on: events.on,
377
+ off: events.off,
378
+ // config
379
+ algorithm,
380
+ dimensions,
381
+ metric,
382
+ vectors,
383
+ requiresTraining: algorithm === 'ivf',
384
+ // for debugging — a getter, since compact() swaps the engine
385
+ get _engine() { return engine; }
386
+ };
387
+ }
388
+
389
+ export {
390
+ createVectorIndex
391
+ };
package/src/lru.js ADDED
@@ -0,0 +1,32 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // simple LRU cache
7
+ // ===========================
8
+ function createLRU(capacity) {
9
+ const map = new Map();
10
+
11
+ function get(key) {
12
+ if (!map.has(key)) return undefined;
13
+ const value = map.get(key);
14
+ // move to end (most recently used)
15
+ map.delete(key);
16
+ map.set(key, value);
17
+ return value;
18
+ }
19
+
20
+ function set(key, value) {
21
+ if (map.has(key)) {
22
+ map.delete(key);
23
+ } else if (map.size >= capacity) {
24
+ map.delete(map.keys().next().value); // evict the least recently used
25
+ }
26
+ map.set(key, value);
27
+ }
28
+
29
+ return { get, set, delete: (key) => map.delete(key), clear: () => map.clear(), size: () => map.size };
30
+ }
31
+
32
+ export { createLRU };