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.
- package/LICENSE +201 -21
- package/README.md +1447 -12
- package/build-browser.js +67 -0
- package/index.js +38 -6
- package/package.json +70 -6
- 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
package/README.md
CHANGED
|
@@ -1,22 +1,1457 @@
|
|
|
1
|
-
|
|
1
|
+
<h1 align="center">vector-index</h1>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<strong>Vector search, compression and embeddings for Node.js & Browsers</strong>
|
|
5
|
+
</p>
|
|
4
6
|
|
|
5
|
-
>
|
|
7
|
+
<p align="center">
|
|
8
|
+
Pure JavaScript. No dependencies, no native bindings, no WASM. Never blocks the event loop.
|
|
9
|
+
</p>
|
|
6
10
|
|
|
7
|
-
|
|
11
|
+
<p align="center">
|
|
12
|
+
<a href="https://www.npmjs.com/package/vector-index"><img src="https://img.shields.io/npm/v/vector-index?color=blue" alt="npm version"></a>
|
|
13
|
+
<img src="https://img.shields.io/github/license/colocohen/vector-index?color=brightgreen" alt="license">
|
|
14
|
+
</p>
|
|
8
15
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## What's Inside
|
|
19
|
+
|
|
20
|
+
| | what it does | modules |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| **Search** | finds the nearest vectors among millions, in milliseconds — by cosine, euclidean distance or inner product, with filters | **Flat** (exact), **HNSW** (graph), **IVF** (inverted file, e-means clustering), **DiskANN** (graph for external storage), and a **sparse index** for keyword vectors (BM25, SPLADE) |
|
|
23
|
+
| **Compression** | shrinks vectors 4–32× and compares them without decompressing; or keeps fewer dimensions | **SQ** (scalar), **PQ** (product), **BQ** (binary), **TurboQuant** (data-oblivious), **PCA** |
|
|
24
|
+
| **Embeddings** | turns relationships — who bought what, who follows whom — into vectors | **node2vec**, **DeepWalk**, **item2vec**, and for recommendations **ALS**, **BPR** |
|
|
25
|
+
|
|
26
|
+
Each part works on its own. Vectors from a text or image model go straight into search; vectors from the embeddings part go there too, or are compared directly. They connect through plain `Float32Array`s.
|
|
27
|
+
|
|
28
|
+
The library gives you the algorithm and gets out of the way. Persistence, distribution, transport, monitoring — all your code, not ours. Callback-style API throughout, with one contract everywhere (see [Callback contract](#callback-contract)).
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Quick Start
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { createVectorIndex } from 'vector-index';
|
|
36
|
+
|
|
37
|
+
const index = createVectorIndex({
|
|
38
|
+
algorithm: 'hnsw',
|
|
39
|
+
dimensions: 384,
|
|
40
|
+
M: 16,
|
|
41
|
+
efSearch: 50
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// ids are integers (0 … Number.MAX_SAFE_INTEGER) — typically your database ids
|
|
45
|
+
const docs = [
|
|
46
|
+
{ id: 1, text: "carbonara recipe" },
|
|
47
|
+
{ id: 2, text: "how to make spaghetti" },
|
|
48
|
+
{ id: 3, text: "history of ancient Rome" }
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
let pending = docs.length;
|
|
52
|
+
for (const { id, text } of docs) {
|
|
53
|
+
index.add(id, embeddingFor(text), (err) => {
|
|
54
|
+
if (err) return console.error(err.code, err.message);
|
|
55
|
+
if (--pending === 0) searchNow();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function searchNow() {
|
|
60
|
+
index.search(embeddingFor("italian food"), 5, (err, results) => {
|
|
61
|
+
if (err) return console.error(err.code, err.message);
|
|
62
|
+
for (const r of results) console.log(r.id, r.score);
|
|
63
|
+
// 1 0.87
|
|
64
|
+
// 2 0.82
|
|
65
|
+
// 3 0.61
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A search is guaranteed to see every `add` whose callback has already fired — on every algorithm, including `diskann-blocks` where writes go through your storage.
|
|
71
|
+
|
|
72
|
+
Switching algorithms is a single field:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
const index = createVectorIndex({ algorithm: 'flat', dimensions: 384 });
|
|
76
|
+
const index = createVectorIndex({ algorithm: 'ivf', dimensions: 384, nlist: 100, nprobe: 10 });
|
|
77
|
+
const index = createVectorIndex({ algorithm: 'diskann', dimensions: 384, R: 32, L: 100 });
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Install
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
npm install vector-index
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
ES module, for Node.js 18+ and every modern browser:
|
|
90
|
+
|
|
91
|
+
```js
|
|
92
|
+
import { createVectorIndex, createPQ, createNode2Vec, ERR } from 'vector-index';
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Bundlers (Vite, webpack, esbuild) import it as is and drop the parts you don't use.
|
|
96
|
+
|
|
97
|
+
**Browser without a bundler** — a single file that sets `window.VectorIndex`:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm install -D esbuild
|
|
101
|
+
node build-browser.js # → dist/vector-index.browser.js and .min.js (~74 kB)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```html
|
|
105
|
+
<script src="dist/vector-index.browser.min.js"></script>
|
|
106
|
+
<script>
|
|
107
|
+
const { createVectorIndex, createNode2Vec } = window.VectorIndex;
|
|
108
|
+
</script>
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## Algorithms
|
|
114
|
+
|
|
115
|
+
| Algorithm | Build | Search | Memory | Recall | Requires train() |
|
|
116
|
+
|-----------------|----------|----------|----------|----------|------------------|
|
|
117
|
+
| flat | fast | slow | high | 100% | no |
|
|
118
|
+
| hnsw | slow | fast | high | ~99% | no |
|
|
119
|
+
| ivf | medium | fast | low | tunable | yes |
|
|
120
|
+
| diskann | medium | fast | medium | ~99% | no |
|
|
121
|
+
| diskann-blocks | medium | fast | very low | ~99% | no |
|
|
122
|
+
|
|
123
|
+
### Flat
|
|
124
|
+
|
|
125
|
+
Brute-force scan. Every query compares against every vector. Exact results, no approximation.
|
|
126
|
+
|
|
127
|
+
Use for datasets up to ~10K vectors, or as a ground-truth baseline for other algorithms.
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
const index = createVectorIndex({
|
|
131
|
+
algorithm: 'flat',
|
|
132
|
+
dimensions: 128
|
|
133
|
+
});
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### HNSW
|
|
137
|
+
|
|
138
|
+
Hierarchical Navigable Small World graph. Each node connects to a few neighbors across multiple layers. Search descends from sparse top layers to dense layer zero.
|
|
139
|
+
|
|
140
|
+
Fast search, high recall, high memory. Best for datasets up to ~10M vectors when memory allows.
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
const index = createVectorIndex({
|
|
144
|
+
algorithm: 'hnsw',
|
|
145
|
+
dimensions: 128,
|
|
146
|
+
M: 16, // neighbors per node
|
|
147
|
+
efConstruction: 200, // beam width during build
|
|
148
|
+
efSearch: 50 // beam width during search — raise for recall, lower for speed
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Neighbor selection uses the Malkov heuristic (candidates are kept only if closer to the target than to any already-selected neighbor), which spreads connections across directions rather than clustering them in one region.
|
|
153
|
+
|
|
154
|
+
### IVF
|
|
155
|
+
|
|
156
|
+
Inverted File index. K-means partitions vectors into `nlist` clusters. Each query examines only the `nprobe` closest clusters.
|
|
157
|
+
|
|
158
|
+
The clusters are learned with **e-means** (Meta FAIR, arXiv 2611.09501) — a mini-batch k-means whose centroids are exponential moving averages, so they move after every batch instead of once per pass. 3–5 passes over the sample replace the 20 iterations of classic Lloyd k-means: `train` is 5–6× faster, with the same or better recall. PQ trains its codebooks with the same algorithm (~5.5× faster, same reconstruction error). Nothing to configure — batch size and step size come from the paper's scaling laws.
|
|
159
|
+
|
|
160
|
+
Low memory, fast search, tunable recall. Best when memory matters or when you have hundreds of millions of vectors.
|
|
161
|
+
|
|
162
|
+
```js
|
|
163
|
+
const index = createVectorIndex({
|
|
164
|
+
algorithm: 'ivf',
|
|
165
|
+
dimensions: 128,
|
|
166
|
+
nlist: 100, // number of clusters (rule of thumb: sqrt(n))
|
|
167
|
+
nprobe: 10, // clusters to search per query
|
|
168
|
+
seed: 42
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// train first — pass a representative sample
|
|
172
|
+
index.train(trainingVectors, (err) => {
|
|
173
|
+
index.add(1, vec, (err) => {});
|
|
174
|
+
index.search(query, 10, (err, results) => {});
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`nprobe` is the recall/speed dial. `nprobe=1` is very fast and low recall, `nprobe=nlist` is equivalent to brute force.
|
|
179
|
+
|
|
180
|
+
### DiskANN
|
|
181
|
+
|
|
182
|
+
Vamana graph — a single-layer graph with robust pruning. Different structure from HNSW, similar performance in memory but designed to be moved onto storage without changing the algorithm.
|
|
183
|
+
|
|
184
|
+
```js
|
|
185
|
+
const index = createVectorIndex({
|
|
186
|
+
algorithm: 'diskann',
|
|
187
|
+
dimensions: 128,
|
|
188
|
+
R: 64, // max neighbors per node
|
|
189
|
+
L: 100, // candidate pool size during build/search
|
|
190
|
+
alpha: 1.2, // robust pruning parameter — spreads connections across directions
|
|
191
|
+
seed: 42
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
for (const v of vectors) index.add(v.id, v.vec, () => {});
|
|
195
|
+
|
|
196
|
+
// optional: two-pass rebuild for better recall
|
|
197
|
+
index.build((err) => {
|
|
198
|
+
index.search(query, 10, (err, results) => {});
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`build()` is a bulk operation that re-runs Vamana construction over the full dataset (pass 1 with `alpha=1.0`, pass 2 with the configured alpha). It's expensive but gives markedly higher recall on datasets larger than a few thousand vectors.
|
|
203
|
+
|
|
204
|
+
### DiskANN with block storage
|
|
205
|
+
|
|
206
|
+
Same Vamana algorithm, but nodes live in external storage (IndexedDB, filesystem, S3 — anything the caller wants) accessed through storage events. A small LRU cache keeps recently-used blocks in memory, so memory use doesn't grow with the index.
|
|
207
|
+
|
|
208
|
+
It's an **LM-DiskANN** ("low-memory DiskANN") index: next to the ids of its neighbors, every block holds a compressed copy (a TurboQuant code, no training needed) of each neighbor's vector. Reading one block is enough to estimate how close each of its neighbors is to the query, without reading their blocks:
|
|
209
|
+
|
|
210
|
+
- **search** reads one block per node it expands, up to `beamWidth` of them in parallel, and ranks the final results by exact vectors;
|
|
211
|
+
- **insert** prunes full neighbor lists using the codes already in the block, instead of reading every neighbor.
|
|
212
|
+
|
|
213
|
+
The library doesn't touch disk. It emits events; the caller handles them.
|
|
214
|
+
|
|
215
|
+
```js
|
|
216
|
+
const index = createVectorIndex({
|
|
217
|
+
algorithm: 'diskann-blocks',
|
|
218
|
+
dimensions: 128,
|
|
219
|
+
R: 32,
|
|
220
|
+
L: 100,
|
|
221
|
+
alpha: 1.0,
|
|
222
|
+
cacheSize: 1000, // number of node blocks to keep in memory
|
|
223
|
+
codeBits: 4, // bits per coordinate of the neighbor codes (1–8)
|
|
224
|
+
beamWidth: 4, // blocks read in parallel per search step
|
|
225
|
+
metaWriteInterval: 64 // max writes between metadata saves during a long stream of writes
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
// caller wires storage through events. block ids are the node ids (numbers)
|
|
229
|
+
index.on('block:read', (id, cb) => storage.get('block:' + id, cb));
|
|
230
|
+
index.on('block:write', (id, data, cb) => storage.put('block:' + id, data, cb));
|
|
231
|
+
index.on('block:delete', (id, cb) => storage.del('block:' + id, cb));
|
|
232
|
+
index.on('block:keys', (cb) => storage.keys('block:', cb)); // every stored id — only compact() needs it
|
|
233
|
+
|
|
234
|
+
// one metadata record per index (counts, entry point, running centroid)
|
|
235
|
+
index.on('meta:read', (cb) => storage.get('meta', cb));
|
|
236
|
+
index.on('meta:write', (data, cb) => storage.put('meta', data, cb));
|
|
237
|
+
|
|
238
|
+
// first session — insert as usual
|
|
239
|
+
for (const v of vectors) index.add(v.id, v.vec, (err) => {});
|
|
240
|
+
|
|
241
|
+
// second session — restore the index from storage.
|
|
242
|
+
// the metadata record remembers the entry point, so no argument is needed
|
|
243
|
+
index.restore((err) => {
|
|
244
|
+
index.search(query, 10, (err, results) => {});
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
**What gets stored.**
|
|
249
|
+
- **One block per node**, keyed by its numeric id. It holds the vector (normalized for cosine), the out-edges with a code for each neighbor, and a deleted flag.
|
|
250
|
+
- **One metadata record**, through `meta:read` / `meta:write`. It holds the counts, the entry point, the running centroid, and the code configuration.
|
|
251
|
+
- It's written when the write queue empties, and at least every `metaWriteInterval` writes during a long stream. So once every callback has fired, the stored metadata is current.
|
|
252
|
+
- `restore()` reads it back. A restored index has the same `stats()`, rejects the same duplicate ids, and can delete any existing id.
|
|
253
|
+
- The metadata has its own events instead of a reserved block key, so every number is a valid id.
|
|
254
|
+
- **`root:change`** still fires whenever the entry point moves, if you want to track it yourself.
|
|
255
|
+
|
|
256
|
+
**Choosing `codeBits` and `beamWidth`.** Measured on 5,000 128-dim vectors (R=32, L=64):
|
|
257
|
+
|
|
258
|
+
| codeBits | recall@10 | avg block size |
|
|
259
|
+
|---|---|---|
|
|
260
|
+
| 1 | 95.5% | 990 B |
|
|
261
|
+
| 2 | 99.3% | 1,267 B |
|
|
262
|
+
| 4 (default) | 100% | 1,807 B |
|
|
263
|
+
| 8 | 100% | 2,883 B |
|
|
264
|
+
|
|
265
|
+
For comparison, without neighbor codes a block is about 650 B, but search reads about 5× more blocks.
|
|
266
|
+
|
|
267
|
+
`beamWidth` trades a few extra reads for fewer sequential round trips to storage. It matters when every read has real latency, as with IndexedDB or the network. A query takes about 62 round trips at `beamWidth: 1`, 17 at 4 (with 4% more reads), and 10 at 8 (9% more reads).
|
|
268
|
+
|
|
269
|
+
**Deletes are soft.** `delete()` rewrites the node's block with a deleted flag — it does not emit `block:delete`. The node stays in the graph as a bridge for search but is never returned and never chosen as a new neighbor. `compact()` removes them for good (see [compact](#compact)). Re-adding a deleted id overwrites its block with the new vector; codes of the old vector that other blocks hold for it are only estimates, and the exact distance is always taken from the block itself.
|
|
270
|
+
|
|
271
|
+
**Choosing L for good recall.** L is the candidate pool size during search — the single biggest lever for recall. As the dataset grows, L needs to grow with it; `L ≈ √n` is a reasonable starting point, and L=200–400 is enough for tens of thousands.
|
|
272
|
+
|
|
273
|
+
**Writes are serialized internally.** Firing many `add()` calls in parallel is safe — the engine queues them and processes one at a time. Reads (search, stats) don't queue.
|
|
274
|
+
|
|
275
|
+
**Any storage backend works.** IndexedDB in the browser, files on Node, Redis, S3 — the events are the only surface. See below for an IndexedDB example.
|
|
276
|
+
|
|
277
|
+
#### IndexedDB example
|
|
278
|
+
|
|
279
|
+
```js
|
|
280
|
+
const req = indexedDB.open('my-vectors', 1);
|
|
281
|
+
req.onupgradeneeded = (e) => {
|
|
282
|
+
e.target.result.createObjectStore('blocks'); // key: node id (number)
|
|
283
|
+
e.target.result.createObjectStore('meta'); // one record under the key 'index'
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
req.onsuccess = () => {
|
|
287
|
+
const db = req.result;
|
|
288
|
+
const index = createVectorIndex({ algorithm: 'diskann-blocks', dimensions: 384 });
|
|
289
|
+
|
|
290
|
+
index.on('block:read', (id, cb) => {
|
|
291
|
+
const r = db.transaction('blocks').objectStore('blocks').get(id);
|
|
292
|
+
r.onsuccess = () => cb(null, r.result || null);
|
|
293
|
+
r.onerror = () => cb(r.error);
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
index.on('block:write', (id, data, cb) => {
|
|
297
|
+
const r = db.transaction('blocks', 'readwrite').objectStore('blocks').put(data, id);
|
|
298
|
+
r.onsuccess = () => cb(null);
|
|
299
|
+
r.onerror = () => cb(r.error);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
index.on('block:delete', (id, cb) => {
|
|
303
|
+
const r = db.transaction('blocks', 'readwrite').objectStore('blocks').delete(id);
|
|
304
|
+
r.onsuccess = () => cb(null);
|
|
305
|
+
r.onerror = () => cb(r.error);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
index.on('meta:read', (cb) => {
|
|
309
|
+
const r = db.transaction('meta').objectStore('meta').get('index');
|
|
310
|
+
r.onsuccess = () => cb(null, r.result || null);
|
|
311
|
+
r.onerror = () => cb(r.error);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
index.on('meta:write', (data, cb) => {
|
|
315
|
+
const r = db.transaction('meta', 'readwrite').objectStore('meta').put(data, 'index');
|
|
316
|
+
r.onsuccess = () => cb(null);
|
|
317
|
+
r.onerror = () => cb(r.error);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// reopening an existing database: restore before using the index
|
|
321
|
+
index.restore((err) => {
|
|
322
|
+
if (err && err.code !== 'NOT_FOUND') throw err; // NOT_FOUND = empty, first run
|
|
323
|
+
// ready
|
|
324
|
+
});
|
|
325
|
+
};
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
### Metric — `cosine`, `l2` or `dot`
|
|
329
|
+
|
|
330
|
+
```js
|
|
331
|
+
createVectorIndex({ algorithm: 'hnsw', dimensions: 3, metric: 'l2' }) // or 'euclidean'
|
|
332
|
+
createVectorIndex({ algorithm: 'hnsw', dimensions: 3, metric: 'dot' }) // or 'ip'
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
| | `metric: 'cosine'` (default) | `metric: 'l2'` | `metric: 'dot'` |
|
|
336
|
+
|---|---|---|---|
|
|
337
|
+
| compares | the **direction** only: `[1, 1]` and `[5, 5]` are identical | the **straight-line distance**: `[1, 1]` and `[5, 5]` are far apart | the **inner product** ⟨q, x⟩: direction *and* length, `[5, 5]` beats `[1, 1]` |
|
|
338
|
+
| vectors | normalized on the way in | kept as given | kept as given |
|
|
339
|
+
| results | `[{ id, score }]`, cosine similarity, higher = closer | `[{ id, distance }]`, euclidean distance, lower = closer | `[{ id, score }]`, ⟨q, x⟩, higher = closer |
|
|
340
|
+
| use it for | text and image embeddings (OpenAI, sentence-transformers, CLIP…) | coordinates, sensor readings, raw features, models trained with L2 | recommendations: user · item vectors from matrix factorization, where the length says how popular or strong an item is |
|
|
341
|
+
|
|
342
|
+
For normalized vectors, which is what most embedding models return, both give the same ranking (‖a − b‖² = 2 − 2·cos), so cosine stays the default. Use `l2` when a vector's length carries meaning: cosine would throw it away silently.
|
|
343
|
+
|
|
344
|
+
With `l2`, flat and IVF scans also stop computing a vector's distance as soon as its partial sum passes the current k-th distance (early abandoning). Squared differences only add up, so the results are exactly the same. It's measured per query and switched off when it doesn't pay: 2.6–3.5× faster on clustered data at 128–768 dimensions, no change on uniform data, off below 64 dimensions.
|
|
345
|
+
|
|
346
|
+
Every algorithm supports `cosine` and `l2`. Inside, engines compare by squared L2 for `l2`, which is also what DiskANN's α-pruning was designed for; IVF clusters with euclidean e-means. `diskann-blocks` records the metric in its metadata, and `restore` with a different metric fails with `INVALID_ARGUMENT` (indexes saved before the metric existed restore as cosine).
|
|
347
|
+
|
|
348
|
+
**`dot`** works on every algorithm. Inner product isn't a distance: an item can be "closer" to a query than to itself, which breaks the assumptions graphs are built on. So the index uses the standard reduction to L2 (Bachrach et al. 2014): every stored vector gets one more coordinate, √(M² − ‖x‖²) with M the largest norm, and queries get 0 there. The largest inner product is then exactly the nearest neighbor, and graphs are built on a real metric. M follows the data by itself, nothing to configure.
|
|
349
|
+
|
|
350
|
+
Measured on recommendation-like data (topic directions × log-normal popularity): HNSW 0.97 recall@10 at the default `efSearch`, DiskANN 0.91, `diskann-blocks` 0.86 at the default `L` and 0.93 with `L: 200`. On `diskann-blocks`, √(M² − ‖x‖²) is computed from the norm each block and each neighbor code already carries, so when a longer vector raises M no block is rewritten; M itself is kept in the metadata. On data made of far-apart clusters, the answers sit in a different cluster than the query, and graph search has to cross between them: raise `efSearch` / `L` (400 brought recall back to 1.0 in the tests), or use IVF.
|
|
351
|
+
|
|
352
|
+
### Compressed vectors — option `vectors`
|
|
353
|
+
|
|
354
|
+
By default an index stores every vector in full: 4 bytes per dimension, about 6 KB for a 1536-dim embedding, so 6 GB for a million. With the `vectors` option, the index stores vectors **in your format** instead, usually compressed. You give it four plain functions; it knows nothing about what they do.
|
|
355
|
+
|
|
356
|
+
```js
|
|
357
|
+
import { createVectorIndex, createSQ } from 'vector-index';
|
|
358
|
+
|
|
359
|
+
const sq = createSQ({ dimensions: 384, bits: 8, normalize: true }); // standalone, knows no index
|
|
360
|
+
|
|
361
|
+
sq.train(sample, (err) => {
|
|
362
|
+
const index = createVectorIndex({
|
|
363
|
+
algorithm: 'hnsw',
|
|
364
|
+
dimensions: 384,
|
|
365
|
+
vectors: {
|
|
366
|
+
encode: sq.encodeSync, // vector → bytes
|
|
367
|
+
decode: sq.decodeSync, // bytes → vector
|
|
368
|
+
prepare: sq.prepareSync, // query → prepared query (once per search)
|
|
369
|
+
similarity: sq.similarityAtSync // (prepared, data, offset) → number
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
index.add(1, vector, (err) => {}); // stored as 384 bytes instead of 1536
|
|
374
|
+
index.search(query, 10, (err, results) => {}); // [{ id, score }] — same shape as always
|
|
375
|
+
});
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
The index doesn't know the quantizer, and the quantizer doesn't know the index. You connect them. Everything else works unchanged: `delete`, `compact`, `stats`, `train` (IVF), `build` (DiskANN), time-slicing, the write queue.
|
|
379
|
+
|
|
380
|
+
| function | called | must return |
|
|
381
|
+
|---|---|---|
|
|
382
|
+
| `encode(vector)` | once per `add` | a `Uint8Array`, the same size for every vector (fixed by the first one) |
|
|
383
|
+
| `decode(bytes)` | while building the graph, to compare stored vectors | a vector of `dimensions` numbers |
|
|
384
|
+
| `prepare(query)` | once per `add` and `search` | anything: a table, an object, the query itself |
|
|
385
|
+
| `similarity(prepared, data, offset)` | thousands of times per operation | a number, higher = closer |
|
|
386
|
+
|
|
387
|
+
**Why functions and not events?** The rule across the library: **I/O goes through events, computation is passed as functions.** Reading a block from IndexedDB is I/O. It may be slow and asynchronous, so it's an event with a callback (`block:read`). Comparing a query to a code is computation: fast, synchronous, thousands of times per search. So it's a function, like the comparator you pass to `Array.prototype.sort`.
|
|
388
|
+
|
|
389
|
+
- All four functions are synchronous.
|
|
390
|
+
- `prepare` returns data, not a function, and `similarity` turns that data plus a code into a number.
|
|
391
|
+
- `data` is the index's own buffer:
|
|
392
|
+
- read only the bytes at `[offset, offset + size)`;
|
|
393
|
+
- don't write to it, and don't keep a reference to it after the call.
|
|
394
|
+
|
|
395
|
+
With `metric: 'cosine'` the index L2-normalizes vectors before `encode` and `prepare` (similarity is cosine). Train your quantizer on normalized vectors too. With the built-in quantizers, that's `normalize: true`.
|
|
396
|
+
|
|
397
|
+
With `metric: 'l2'` vectors go to `encode` and `prepare` as given; keep the quantizer's default `normalize: false`. `similarity` still returns ≈ ⟨query, x⟩: the index stores ‖x̂‖² of every decoded vector and turns it into a distance, ‖q − x̂‖² = ‖q‖² − 2⟨q, x̂⟩ + ‖x̂‖². The same format works for both metrics.
|
|
398
|
+
|
|
399
|
+
If `encode`, `decode` or `prepare` throws, the operation calls back with `INVALID_ARGUMENT`, and the original error is on `err.cause`. Library errors from the quantizer, like `NOT_TRAINED`, pass through as they are.
|
|
400
|
+
|
|
401
|
+
**Memory**, per vector including all overhead (20,000 × 128 dims):
|
|
402
|
+
|
|
403
|
+
| | full | SQ8 | PQ (m=32) | TurboQuant 4-bit |
|
|
404
|
+
|---|---|---|---|---|
|
|
405
|
+
| flat | 910 B | 279 B | 121 B | 180 B |
|
|
406
|
+
| hnsw | 1,167 B | 562 B | 462 B | — |
|
|
407
|
+
|
|
408
|
+
**Recall** depends only on the compression, not on the graph: Flat and HNSW lose exactly the same. Measured on 10,000 vectors: SQ8 97%, SQ4 72%, TurboQuant 4-bit 70%, PQ 44%. To get it back, **ask for more candidates and rerank them** with full vectors from your own storage. The index stays out of it:
|
|
409
|
+
|
|
410
|
+
```js
|
|
411
|
+
index.search(query, 100, (err, candidates) => {
|
|
412
|
+
db.getVectors(candidates.map(c => c.id), (err, full) => {
|
|
413
|
+
const top10 = full
|
|
414
|
+
.map((v, i) => ({ id: candidates[i].id, score: cosine(query, v) }))
|
|
415
|
+
.sort((a, b) => b.score - a.score)
|
|
416
|
+
.slice(0, 10);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
| | 10 candidates | 50 | 100 |
|
|
422
|
+
|---|---|---|---|
|
|
423
|
+
| PQ + rerank | 44% | 89% | 99% |
|
|
424
|
+
| SQ4 + rerank | 72% | 99.8% | 100% |
|
|
425
|
+
|
|
426
|
+
**Your own format** works the same way. For example, a hand-made int8:
|
|
427
|
+
|
|
428
|
+
```js
|
|
429
|
+
vectors: {
|
|
430
|
+
encode: (v) => {
|
|
431
|
+
const b = new Int8Array(384);
|
|
432
|
+
for (let i = 0; i < 384; i++) b[i] = Math.round(v[i] * 127);
|
|
433
|
+
return new Uint8Array(b.buffer);
|
|
434
|
+
},
|
|
435
|
+
decode: (bytes) => Float32Array.from(new Int8Array(bytes.buffer, bytes.byteOffset, 384), x => x / 127),
|
|
436
|
+
prepare: (query) => query,
|
|
437
|
+
similarity: (q, data, offset) => {
|
|
438
|
+
let dot = 0;
|
|
439
|
+
for (let i = 0; i < 384; i++) {
|
|
440
|
+
const x = data[offset + i];
|
|
441
|
+
dot += q[i] * (x > 127 ? x - 256 : x) / 127;
|
|
442
|
+
}
|
|
443
|
+
return dot;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
**Notes.**
|
|
449
|
+
- Building a graph (HNSW, DiskANN) compares stored vectors with each other through `decode`, so it's slower than with full vectors: about 1.2× with SQ and PQ, more with TurboQuant, whose decode includes an inverse rotation. Search isn't affected.
|
|
450
|
+
- Up to 4,096 decoded vectors are cached during construction.
|
|
451
|
+
- `diskann-blocks` doesn't take the `vectors` option: its vectors already live in your storage.
|
|
452
|
+
|
|
453
|
+
## API
|
|
454
|
+
|
|
455
|
+
Every algorithm returns an object with exactly the same methods. A method that doesn't apply to the chosen algorithm still exists and calls back with `err.code === 'NOT_SUPPORTED'` — there is no `switch` on algorithm in your code.
|
|
456
|
+
|
|
457
|
+
```js
|
|
458
|
+
index.add(id, vector, (err) => {})
|
|
459
|
+
index.delete(id, (err) => {})
|
|
460
|
+
index.search(query, k[, { filter }], (err, results) => {})
|
|
461
|
+
index.searchBatch(queries, k[, { filter }], (err, resultLists) => {})
|
|
462
|
+
index.stats((err, stats) => {})
|
|
463
|
+
index.compact((err) => {}) // diskann-blocks: needs a block:keys handler
|
|
464
|
+
index.train(vectors, (err) => {}) // ivf only, NOT_SUPPORTED elsewhere
|
|
465
|
+
index.build((err) => {}) // diskann only, NOT_SUPPORTED elsewhere
|
|
466
|
+
index.restore([rootId], (err) => {}) // diskann-blocks only, NOT_SUPPORTED elsewhere
|
|
467
|
+
index.getRootId() // sync getter — null except on diskann-blocks
|
|
468
|
+
index.on(event, fn) / index.off(event[, fn])
|
|
469
|
+
|
|
470
|
+
index.algorithm // 'hnsw', ...
|
|
471
|
+
index.dimensions
|
|
472
|
+
index.metric // 'cosine' (default), 'l2' or 'dot'
|
|
473
|
+
index.vectors // 'full' (default) or 'custom' (option vectors)
|
|
474
|
+
index.requiresTraining // true for ivf
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
Events: `progress` (ivf `train`, diskann `build`, `compact`); `block:read` / `block:write` / `block:delete`, `meta:read` / `meta:write` and `root:change` (diskann-blocks). Events are for notifications and I/O only — computation is passed as functions (option `vectors`).
|
|
478
|
+
|
|
479
|
+
Long operations (`train`, `build`, `compact`) never freeze the event loop. See [Long operations don't block](#long-operations-dont-block).
|
|
480
|
+
|
|
481
|
+
### Callback contract
|
|
482
|
+
|
|
483
|
+
The same rules hold for every callback in the package — index methods, quantizers and the storage events you implement.
|
|
484
|
+
|
|
485
|
+
1. **The callback is last and required.** Calling without one is a programmer error and throws a `TypeError` immediately, like Node core. Every other error goes to the callback.
|
|
486
|
+
2. **Always asynchronous.** The callback never runs before the call returns, even when the answer is known right away (an empty index, a validation error, a cache hit).
|
|
487
|
+
3. **Exactly once.** Either `cb(err)` or `cb(null, result)`, never both, never twice.
|
|
488
|
+
4. **Your exceptions stay yours.** If your callback throws, the library doesn't catch it (that would hide the bug or call you twice): it surfaces as an uncaught exception, and the index keeps working.
|
|
489
|
+
5. **Every error has a stable `err.code`.** Compare against the exported `ERR` constants instead of parsing messages.
|
|
490
|
+
|
|
491
|
+
| `err.code` | when |
|
|
492
|
+
|---|---|
|
|
493
|
+
| `INVALID_ARGUMENT` | wrong type or value (id that isn't an integer in 0…`MAX_SAFE_INTEGER`, `k <= 0`, NaN in a vector, missing callback, a `vectors.*` function returning the wrong type or throwing) |
|
|
494
|
+
| `DIMENSION_MISMATCH` | vector or code has the wrong length, or `vectors.encode` returned a different size than before |
|
|
495
|
+
| `DUPLICATE_ID` | `add` of an id that is live |
|
|
496
|
+
| `NOT_FOUND` | `delete` of an unknown id, missing root / metadata block |
|
|
497
|
+
| `ALREADY_DELETED` | `delete` of an id that is already deleted |
|
|
498
|
+
| `NOT_TRAINED` | ivf / SQ / PQ used before `train` |
|
|
499
|
+
| `NOT_SUPPORTED` | method doesn't apply to this algorithm or quantizer |
|
|
500
|
+
| `STORAGE` | a required storage handler (`block:*`, `meta:*`) isn't registered, or it failed / threw (original error on `err.cause`) |
|
|
501
|
+
| `CORRUPT_DATA` | stored bytes can't be decoded (also `loadEmbeddings`) |
|
|
502
|
+
| `BUSY` | a `Sync` call while an async job runs on the same graph or trainer, or `train` while already training |
|
|
503
|
+
| `CANCELLED` | a training was stopped with `cancel()` |
|
|
504
|
+
| `TOO_LARGE` | a graph would exceed 2³²−1 adjacency entries |
|
|
505
|
+
|
|
506
|
+
```js
|
|
507
|
+
import { ERR } from 'vector-index';
|
|
508
|
+
|
|
509
|
+
index.add(1, vec, (err) => {
|
|
510
|
+
if (err && err.code === ERR.DUPLICATE_ID) return; // already indexed
|
|
511
|
+
if (err) throw err;
|
|
512
|
+
});
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
### add
|
|
516
|
+
|
|
517
|
+
Adds a vector. **Ids are integers from 0 to `Number.MAX_SAFE_INTEGER`** (2⁵³ − 1) — strings, negative numbers and fractions are rejected with `INVALID_ARGUMENT`. Database auto-increment ids fit directly. If your keys are strings or UUIDs, keep your own map from key to number. Vectors may be an `Array` or a typed array; the library always keeps its own copy. Rejects live duplicate ids, wrong dimensions and non-finite values. A **deleted** id can be added again.
|
|
518
|
+
|
|
519
|
+
### delete
|
|
520
|
+
|
|
521
|
+
Soft delete — the node is marked and skipped in search results, but stays in the graph and is still traversed during search, so deleting many nodes does not cut the graph apart. Cheap. Run `compact()` to actually remove them.
|
|
522
|
+
|
|
523
|
+
### search
|
|
524
|
+
|
|
525
|
+
```js
|
|
526
|
+
index.search(query, k, (err, results) => {})
|
|
527
|
+
index.search(query, k, { filter: (id) => boolean }, (err, results) => {})
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
Returns `[{ id, score }, ...]` sorted by cosine similarity (or inner product with `metric: 'dot'`), higher is better. With `metric: 'l2'`: `[{ id, distance }, ...]` sorted by euclidean distance, lower is better.
|
|
531
|
+
|
|
532
|
+
**`filter`**: only ids for which it returns true come back. "Similar, but in stock", "only this seller", "not what the user already bought". Your metadata stays yours; the index only asks about ids. It's a plain synchronous function, like a comparator to `sort`. If it throws, the search calls back with `INVALID_ARGUMENT` and the original error on `err.cause`.
|
|
533
|
+
|
|
534
|
+
Why not ask for more results and filter them yourself? That works while the filter keeps most items. With a filter that keeps 1%, you'd need 100× the results, and there's no way to know in advance how many are enough. Inside the index:
|
|
535
|
+
|
|
536
|
+
- **flat** checks the filter before comparing: exact.
|
|
537
|
+
- **HNSW** filters during the traversal. A node that fails the filter still routes the search (like a deleted node) but never takes a result slot.
|
|
538
|
+
- **IVF and DiskANN** widen the search by how selective the filter is, estimated on a sample of 200 nodes. IVF probes `nprobe ÷ pass rate` lists; DiskANN widens its beam.
|
|
539
|
+
- **Very selective filters** (under 5% passing, or an index under 2,000 vectors) switch to an exact scan of the matching nodes. That's cheaper than a graph search hunting for rare matches, and exact. If a graph search still finds fewer than k, the same scan runs.
|
|
540
|
+
- **diskann-blocks** has no list of nodes in memory to scan, so it widens its beam (×4, up to 3 times) until k matches are found.
|
|
541
|
+
|
|
542
|
+
Measured on 4,000 vectors, recall@10 against the exact filtered answer: flat 100%, HNSW 100% at every pass rate from 50% down to 0.25%, IVF 95%+, diskann-blocks 91–100%.
|
|
543
|
+
|
|
544
|
+
### searchBatch
|
|
545
|
+
|
|
546
|
+
```js
|
|
547
|
+
index.searchBatch([q1, q2, q3], 10, (err, lists) => {
|
|
548
|
+
// lists[i] is exactly what search(queries[i], 10) returns
|
|
549
|
+
});
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
Many queries in one call, with the same options as `search`. The results come back in the order of the queries. In memory, the batch runs time-sliced, with a pause between queries, so 10,000 queries never freeze the thread the way a synchronous loop of searches would. On `diskann-blocks`, up to 8 searches wait on storage at once. If any query is invalid, the whole batch fails with that error.
|
|
553
|
+
|
|
554
|
+
### stats
|
|
555
|
+
|
|
556
|
+
Snapshot of the index. Fields depend on the algorithm — all include `algorithm`, `dimensions`, `total`, `alive`, `deleted`, `ratio`.
|
|
557
|
+
|
|
558
|
+
```js
|
|
559
|
+
index.stats((err, s) => {
|
|
560
|
+
console.log(s);
|
|
561
|
+
// { algorithm: 'hnsw', dimensions: 384, total: 1000, alive: 850, deleted: 150, ratio: 0.15, ... }
|
|
562
|
+
});
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
### compact
|
|
566
|
+
|
|
567
|
+
Rebuilds the index from live nodes only, discarding deleted ones. You decide when to run it. Runs time-sliced. The new index is built on the side and swapped in at the end, and emits `progress`.
|
|
568
|
+
|
|
569
|
+
**On `diskann-blocks`** the index lives in your storage, so it can't be rebuilt on the side. `compact()` repairs it in place instead (FreshDiskANN's delete consolidation, Singh et al. 2021). It needs one more storage handler, `block:keys`, answering with every stored id:
|
|
570
|
+
|
|
571
|
+
1. Read every block (in batches, through `block:read`) and collect the deleted nodes.
|
|
572
|
+
2. Every live node that points to a deleted one gets a new neighbor list: its live neighbors plus the deleted node's live neighbors, pruned by the same rule as an insert. This bridges over the gap. Distances come from the codes already in those blocks, so no extra reads.
|
|
573
|
+
3. Write the metadata: an entry point off the deleted nodes, and counts recomputed from what was read.
|
|
574
|
+
4. `block:delete` every deleted node.
|
|
575
|
+
|
|
576
|
+
The graph is valid at every step. Until step 4 the deleted nodes still exist and still route; after step 2 nothing points to them. If storage fails mid-way, the index keeps working, and the next `compact()` finishes the job and corrects the counts. Searches run during compact; writes wait in the queue. Progress phases: `compact:scan`, `compact:repair`.
|
|
577
|
+
|
|
578
|
+
Measured: 1,500 nodes with 2 of every 3 deleted → storage down to the 500 live blocks, no edge left pointing to a removed block, recall unchanged.
|
|
579
|
+
|
|
580
|
+
```js
|
|
581
|
+
index.stats((err, s) => {
|
|
582
|
+
if (!err && s.ratio > 0.2) index.compact((err) => {});
|
|
583
|
+
});
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
### train
|
|
587
|
+
|
|
588
|
+
Only for `ivf`. Learns cluster centroids from a training sample. Call once before `add()`. Emits `progress`.
|
|
589
|
+
|
|
590
|
+
### build
|
|
591
|
+
|
|
592
|
+
Only for `diskann`. Two-pass rebuild that pushes recall up on larger datasets. Call after inserting the bulk of your vectors. Emits `progress`.
|
|
593
|
+
|
|
594
|
+
### restore / getRootId
|
|
595
|
+
|
|
596
|
+
Only for `diskann-blocks`. Reopens an index whose blocks already exist in storage. `rootId` is optional — the metadata record remembers the entry point. Calls back with `NOT_FOUND` when there is no metadata yet (a fresh, empty store).
|
|
597
|
+
|
|
598
|
+
### createSparseIndex: keyword vectors
|
|
599
|
+
|
|
600
|
+
```js
|
|
601
|
+
import { createSparseIndex } from 'vector-index';
|
|
602
|
+
|
|
603
|
+
const sparse = createSparseIndex();
|
|
604
|
+
sparse.add(id, { indices: [812, 15, 4410], values: [2.1, 1.4, 0.9] }, cb);
|
|
605
|
+
sparse.search(query, 10[, { filter }], (err, results) => {}); // [{ id, score }], score = ⟨q, x⟩
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
A **sparse** vector has many dimensions, often one per word of a vocabulary, of which only a handful are non-zero, so only those are given. They come from keyword weighting (BM25, TF-IDF) or from learned sparse models (SPLADE). They catch what dense embeddings miss: a part number, a model name, a rare word. That makes them the other half of [hybrid search](#hybrid-search-meaning--exact-words).
|
|
609
|
+
|
|
610
|
+
The index is an inverted index: one posting list per dimension. A query only reads the lists of its own dimensions. The top k come from **MaxScore** (Turtle & Flood 1995), which is exact: every list knows the largest contribution it can make, and lists that together can't beat the current k-th score are only probed for candidates that still could, never scanned.
|
|
611
|
+
|
|
612
|
+
Same contract as the vector index: `add`, `delete` (soft), `search`, `searchBatch`, `stats`, `compact` (time-sliced, `progress` events), callbacks, write queue, `filter`. Dimensions are integers from 0 to 2³² − 1. Repeated dimensions in one vector are summed, and zeros dropped. Values can be any finite number: negative ones only weaken the pruning, never the exactness.
|
|
613
|
+
|
|
614
|
+
**Measured** (`node bench/sparse.bench.js`): 100,000 documents of 50–150 words from a 30,000-word Zipf vocabulary, 7.7M postings, 3–7-word queries. MaxScore runs at 0.3–0.6 ms per query, against 44 ms for scanning the same lists in full: 70–140× faster, with identical results.
|
|
615
|
+
|
|
616
|
+
Turning text into sparse vectors (tokenizing, stemming, BM25 weights) is text processing, not vector search, and isn't in the library. The [hybrid search recipe](#hybrid-search-meaning--exact-words) shows a minimal BM25 to start with.
|
|
617
|
+
|
|
618
|
+
### fuseResults / mergeResults
|
|
619
|
+
|
|
620
|
+
Two pure helpers for combining result lists. No index needed.
|
|
621
|
+
|
|
622
|
+
```js
|
|
623
|
+
import { fuseResults, mergeResults } from 'vector-index';
|
|
624
|
+
|
|
625
|
+
fuseResults([listA, listB, ...], { k: 60, weights: [1, 1], limit }) // → [{ id, score }]
|
|
626
|
+
mergeResults([shard1, shard2, ...], k) // → the global top k
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
**`fuseResults`** is for lists from **different** searches: a vector search and a keyword search, or two embedding models. Their scores are on different scales (cosine 0–1, BM25 7.3 or 12.8), so they can't be added. Reciprocal Rank Fusion (Cormack et al., SIGIR 2009) uses only the rank: `score(id) = Σ weight / (k + rank)`, with `k = 60` by default. An id that's high in both lists wins:
|
|
630
|
+
|
|
631
|
+
```js
|
|
632
|
+
// vector: [A, B, C] keyword: [B, D, A]
|
|
633
|
+
fuseResults([vector, keyword])
|
|
634
|
+
// B: 1/62 + 1/61 = 0.0325 A: 1/61 + 1/63 = 0.0323 D: 1/62 = 0.0161 C: 1/63 = 0.0159
|
|
635
|
+
// → [B, A, D, C]
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
**`mergeResults`** is for lists from the **same** search over different shards. Their scores are comparable, so the global top k is a plain merge (by `score` descending, or `distance` ascending for `l2`). An id found on several shards keeps its best entry. Three shards merged give exactly the top 10 of one index holding everything.
|
|
639
|
+
|
|
640
|
+
### Storage handlers (diskann-blocks)
|
|
641
|
+
|
|
642
|
+
Your `block:read`, `block:write`, `block:delete`, `block:keys` (only for `compact`), `meta:read` and `meta:write` handlers follow the same contract from the other side: call `cb` once, with `(err)` or `(null, result)`; `block:read` and `meta:read` answer `null` when there is nothing stored. Block ids are numbers; data is always a `Uint8Array`. Synchronous answers (an in-memory `Map`) and asynchronous ones (IndexedDB, files, network) both work. Each storage event takes exactly one handler — registering a second one throws; call `off(event)` first. `root:change` is a plain notification and accepts any number of listeners.
|
|
643
|
+
|
|
644
|
+
## Quantization
|
|
645
|
+
|
|
646
|
+
Four quantizers as standalone modules. They compress vectors — you decide how to combine them with an index.
|
|
647
|
+
|
|
648
|
+
All of them have the same shape:
|
|
649
|
+
|
|
650
|
+
| member | |
|
|
651
|
+
|---|---|
|
|
652
|
+
| `encode(vector, cb)` / `encodeSync(vector)` | → `Uint8Array` of exactly `codeSize` bytes |
|
|
653
|
+
| `decode(code, cb)` / `decodeSync(code)` | → `Float32Array(dimensions)` |
|
|
654
|
+
| `distance(query, code, cb)` / `distanceSync(query, code)` | query is a raw vector, code is a stored code |
|
|
655
|
+
| `scan(query, codes, k, cb)` / `scanSync(query, codes, k)` | the k closest codes in a buffer of codes laid back to back → `[{ index, distance }]`, closest first |
|
|
656
|
+
| `prepare(query, cb)` / `prepareSync(query)` | the query's per-query data (a table, a rotated vector…) for `similarityAt` |
|
|
657
|
+
| `similarityAt(prepared, codes, offset, cb)` / `similarityAtSync(...)` | ≈ ⟨query, x⟩ for the code at `offset`, higher = closer. Prepare once, call per code. This is what you pass to an index's `vectors` option |
|
|
658
|
+
| `train(vectors, cb)` / `trainSync(vectors)` | SQ, PQ — `NOT_SUPPORTED` on BQ and TurboQuant |
|
|
659
|
+
| `on('progress', fn)` / `off(...)` | progress during `train` |
|
|
660
|
+
| `dimensions`, `codeSize`, `requiresTraining`, `isTrained()` | |
|
|
661
|
+
|
|
662
|
+
**Option `normalize: true`** (every quantizer): every incoming vector — training sample, `encode` input, query — is L2-normalized first. Use it when the codes stand for directions, i.e. cosine similarity, and always behind an index's `vectors` option.
|
|
663
|
+
|
|
664
|
+
**Every operation exists twice**, like `fs.readFile` / `fs.readFileSync`: `name(..., cb)` follows the [callback contract](#callback-contract); `nameSync(...)` returns the value and throws on error (same `err.code`s). Both compute exactly the same result. Use the Sync form inside hot loops (scanning a million codes), where deferring a callback per code would cost more than the distance itself. `train(sample, cb)` is time-sliced and never blocks; `trainSync(sample)` blocks until done.
|
|
665
|
+
|
|
666
|
+
Codes are always plain `Uint8Array`s — store them, send them, concatenate them.
|
|
667
|
+
|
|
668
|
+
**`scan` is the fast path for one query against many codes.** It prepares the query once per call: a lookup table for SQ and PQ, the rotated query for TurboQuant, the projected query for TurboQuantProd. Then it runs a tight loop over a single buffer. It returns exactly the same distances as calling `distanceSync` on each code. The callback form is time-sliced, so scanning millions of codes doesn't block.
|
|
669
|
+
|
|
670
|
+
```js
|
|
671
|
+
// codes of n vectors, back to back
|
|
672
|
+
const buf = new Uint8Array(n * pq.codeSize);
|
|
673
|
+
vectors.forEach((v, i) => buf.set(pq.encodeSync(v), i * pq.codeSize));
|
|
674
|
+
|
|
675
|
+
pq.scan(query, buf, 10, (err, top) => {
|
|
676
|
+
// top: [{ index: 412, distance: 0.83 }, ...] — index = position in the buffer
|
|
677
|
+
});
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
Throughput on 128-dim vectors, compared with one `distanceSync`-style call per code (`node bench/perf.bench.js`):
|
|
681
|
+
|
|
682
|
+
| | per-code calls | `scanSync` |
|
|
683
|
+
|---|---|---|
|
|
684
|
+
| PQ (m=16) | 4.7 M codes/s | 6.5 M codes/s |
|
|
685
|
+
| SQ8 | 0.8 M codes/s | 1.9 M codes/s |
|
|
686
|
+
| BQ | 6.2 M codes/s | 9.4 M codes/s |
|
|
687
|
+
| TurboQuantProd (4 bits) | 0.01 M codes/s | 0.50 M codes/s |
|
|
688
|
+
|
|
689
|
+
### SQ (Scalar Quantization)
|
|
690
|
+
|
|
691
|
+
`float32` per dimension becomes `int8` (4x compression) or `int4` (8x compression). Simple, near-lossless.
|
|
692
|
+
|
|
693
|
+
```js
|
|
694
|
+
import { createSQ } from 'vector-index';
|
|
695
|
+
|
|
696
|
+
const sq = createSQ({
|
|
697
|
+
dimensions: 128,
|
|
698
|
+
bits: 8 // 4 or 8
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
sq.on('progress', (p) => console.log(p.phase, p.percent));
|
|
702
|
+
|
|
703
|
+
sq.train(sample, (err) => {
|
|
704
|
+
if (err) return console.error(err.code, err.message);
|
|
705
|
+
sq.encode(vector, (err, code) => {
|
|
706
|
+
// code is Uint8Array — 128 bytes at 8-bit, 64 bytes at 4-bit
|
|
707
|
+
sq.decode(code, (err, reconstructed) => {});
|
|
708
|
+
sq.distance(query, code, (err, squaredL2) => {});
|
|
709
|
+
});
|
|
710
|
+
});
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
### PQ (Product Quantization)
|
|
714
|
+
|
|
715
|
+
Splits the vector into `m` sub-vectors, learns a codebook of `2^nbits` centroids for each, replaces each sub-vector with an index. Aggressive compression (32-64x) at the cost of some recall.
|
|
716
|
+
|
|
717
|
+
```js
|
|
718
|
+
import { createPQ } from 'vector-index';
|
|
719
|
+
|
|
720
|
+
const pq = createPQ({
|
|
721
|
+
dimensions: 128,
|
|
722
|
+
m: 8, // sub-vectors — dimensions must divide by m
|
|
723
|
+
nbits: 8, // 2^nbits centroids per sub-vector
|
|
724
|
+
rotation: 'pca', // optional: see below
|
|
725
|
+
seed: 42
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
pq.on('progress', (p) => {});
|
|
729
|
+
|
|
730
|
+
pq.train(sample, (err) => {
|
|
731
|
+
if (err) return console.error(err.code, err.message);
|
|
732
|
+
pq.encode(vector, (err, code) => {
|
|
733
|
+
// code is Uint8Array of length m — 8 bytes for a 128-dim vector
|
|
734
|
+
pq.decode(code, (err, approx) => {});
|
|
735
|
+
});
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
// one query against many codes: build the lookup table once, then scan
|
|
739
|
+
// with the Sync form — this is the hot loop
|
|
740
|
+
pq.buildDistanceTable(query, (err, table) => {
|
|
741
|
+
for (const code of allCodes) {
|
|
742
|
+
const d = pq.tableDistanceSync(table, code);
|
|
743
|
+
}
|
|
744
|
+
});
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
PQ is best on data with structure — real embeddings from sentence models, image encoders, and so on. On uniformly random data recall drops sharply, because random vectors have no clusters for k-means to find.
|
|
748
|
+
|
|
749
|
+
**`rotation: 'pca'`** (the parametric OPQ of Ge, He, Ke & Sun, CVPR 2013). PQ cuts a vector into `m` consecutive pieces and compresses each one on its own. That works when the information is spread evenly over the pieces. In real embeddings it rarely is: a few directions carry most of the signal, so some pieces waste their 256 centroids on almost nothing while others are crowded. With the option, `train` rotates the space onto the principal directions and deals them out so every piece gets an equal share of the variance. A rotation keeps every distance and inner product, so nothing changes outside: vectors and queries are rotated on the way in, `decode` rotates back, `getRotation()` returns the matrix.
|
|
750
|
+
|
|
751
|
+
Measured (`node bench/opq.bench.js`, 64 dims, 8 bytes per vector, same codebooks otherwise):
|
|
752
|
+
|
|
753
|
+
| data | relative error | recall@10 |
|
|
754
|
+
|---|---|---|
|
|
755
|
+
| uneven variance in random directions | 0.234 → **0.029** | 0.52 → **0.78** |
|
|
756
|
+
| clusters, uneven variance | 0.015 → **0.007** | 0.48 → **0.63** |
|
|
757
|
+
| isotropic (nothing to rearrange) | 0.336 → 0.338 | 0.26 → 0.26 |
|
|
758
|
+
|
|
759
|
+
The full OPQ algorithm adds alternating refinement rounds on top. In these measurements they added nothing, at 7× the training time, so they aren't offered. The cost of the rotation: d² operations per encoded vector and per query, and one d × d eigen-decomposition in `train` (about 4 s at 768 dimensions, time-sliced).
|
|
760
|
+
|
|
761
|
+
### BQ (Binary Quantization)
|
|
762
|
+
|
|
763
|
+
The simplest possible quantizer: `sign(x)` per coordinate. Each float becomes one bit. 32× compression, no training, and comparisons are Hamming distance (XOR + popcount) — an order of magnitude faster than cosine on floats.
|
|
764
|
+
|
|
765
|
+
```js
|
|
766
|
+
import { createBQ } from 'vector-index';
|
|
767
|
+
|
|
768
|
+
const bq = createBQ({ dimensions: 384 });
|
|
769
|
+
|
|
770
|
+
bq.encode(vector, (err, code) => {
|
|
771
|
+
// code is Uint8Array of length dimensions/8 — 48 bytes for 384 dims
|
|
772
|
+
bq.distance(queryVector, code, (err, hamming) => {}); // query as a vector
|
|
773
|
+
bq.similarity(queryVector, code, (err, cosineApprox) => {});
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
// scanning many stored codes: encode the query once, compare code-to-code
|
|
777
|
+
const queryCode = bq.encodeSync(queryVector);
|
|
778
|
+
for (const code of allCodes) {
|
|
779
|
+
const h = bq.hammingSync(queryCode, code);
|
|
780
|
+
}
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
BQ is a coarse approximation — recall at k=10 is typically 20–40%. Its real use is as a pre-filter: scan a huge collection fast with Hamming, then re-rank the top few hundred candidates with the exact vector using cosine. Getting 100 candidates from BQ recovers roughly 70% of the true top-10; 500 candidates recovers ~99%.
|
|
784
|
+
|
|
785
|
+
### TurboQuant (data-oblivious quantization)
|
|
786
|
+
|
|
787
|
+
Based on Zandieh et al. 2025. Rotates the input with a structured random rotation (Walsh–Hadamard), then applies pre-computed Lloyd–Max centroids. **No training** — the codebook is fixed by dimension and bit-width alone. Ideal for streaming workloads (KV caches, changing datasets) where you can't afford to retrain a quantizer every time the distribution shifts.
|
|
788
|
+
|
|
789
|
+
Two variants:
|
|
790
|
+
|
|
791
|
+
```js
|
|
792
|
+
import { createTurboQuant, createTurboQuantProd } from 'vector-index';
|
|
793
|
+
|
|
794
|
+
// MSE-optimal — best for reconstruction and general nearest-neighbor search
|
|
795
|
+
const tq = createTurboQuant({
|
|
796
|
+
dimensions: 128,
|
|
797
|
+
bits: 4, // 1 to 8
|
|
798
|
+
seed: 42
|
|
799
|
+
});
|
|
800
|
+
|
|
801
|
+
tq.encode(vector, (err, code) => {
|
|
802
|
+
// code is Uint8Array(tq.codeSize): packed codes + the vector's norm (float32)
|
|
803
|
+
tq.decode(code, (err, reconstructed) => {});
|
|
804
|
+
tq.distance(query, code, (err, squaredL2) => {});
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
// distance = ‖q‖² + ‖x‖² − 2⟨q, x̂⟩ with the exact stored norm ‖x‖ and the
|
|
808
|
+
// quantized direction — computed from the rotated query, without decoding
|
|
809
|
+
|
|
810
|
+
// unbiased inner product — best for attention scoring / KV cache
|
|
811
|
+
const tqp = createTurboQuantProd({
|
|
812
|
+
dimensions: 128,
|
|
813
|
+
bits: 4,
|
|
814
|
+
seed: 42
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
tqp.encode(vector, (err, code) => {
|
|
818
|
+
tqp.innerProduct(query, code, (err, ip) => {
|
|
819
|
+
// unbiased estimate of <query, vector>
|
|
820
|
+
});
|
|
821
|
+
});
|
|
822
|
+
```
|
|
823
|
+
|
|
824
|
+
**Warning.** `TurboQuantProd` guarantees unbiased inner product estimation but has higher variance than `TurboQuantMse` in practice. Prefer `TurboQuant` (MSE variant) or `SQ` for general nearest-neighbor search; reserve `TurboQuantProd` for attention scoring where unbiasedness matters more than variance.
|
|
825
|
+
|
|
826
|
+
### PCA (fewer dimensions)
|
|
827
|
+
|
|
828
|
+
Embeddings often carry their information in far fewer directions than they have dimensions. PCA finds those directions and keeps only them. Quantizers make each number smaller; PCA keeps fewer numbers. Its output is an ordinary, shorter vector, so it goes into any index (and can be quantized on top).
|
|
829
|
+
|
|
830
|
+
```js
|
|
831
|
+
import { createPCA } from 'vector-index';
|
|
832
|
+
|
|
833
|
+
const pca = createPCA({ dimensions: 1536, components: 256, seed: 1 });
|
|
834
|
+
pca.train(sample, (err) => { // a few thousand vectors are enough
|
|
835
|
+
const short = pca.transformSync(vector); // Float32Array(256)
|
|
836
|
+
const back = pca.inverseSync(short); // Float32Array(1536), the closest it can rebuild
|
|
837
|
+
pca.getModel().explainedVarianceRatio; // how much of the signal each component keeps
|
|
838
|
+
});
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
| option | default | |
|
|
842
|
+
|---|---|---|
|
|
843
|
+
| `dimensions` | required | input size |
|
|
844
|
+
| `components` | required | output size |
|
|
845
|
+
| `iterations` | 4 | subspace iterations; more = closer to exact, rarely needed |
|
|
846
|
+
| `whiten` | false | divide each output by its standard deviation (unit variance) |
|
|
847
|
+
| `seed` | random | |
|
|
848
|
+
| `model` | — | what `getModel()` returned: the PCA starts trained with it |
|
|
849
|
+
|
|
850
|
+
The d × d covariance is never built: at 1536 dimensions that's 2.4 million cells and n·d² work. Instead, randomized subspace iteration (Halko, Martinsson & Tropp 2011) pushes a block of `components + 10` random directions through Xᵀ(X·V) a few times, and solves the small problem left at the end exactly. Training is time-sliced (longest freeze 16–20 ms on 4,000 × 768).
|
|
851
|
+
|
|
852
|
+
**Measured** (`node bench/pca.bench.js`): 6,000 × 256 vectors with 32 strong directions. The variance kept matches the exact eigen-decomposition to 0.1% at every size:
|
|
853
|
+
|
|
854
|
+
| components | memory | variance kept | recall@10 after reduction | train |
|
|
855
|
+
|---|---|---|---|---|
|
|
856
|
+
| 16 | 6% | 70.6% | 0.51 | 0.7 s |
|
|
857
|
+
| 32 | 13% | 85.9% | 0.79 | 1.0 s |
|
|
858
|
+
| 64 | 25% | 91.8% | 0.88 | 1.6 s |
|
|
859
|
+
| 128 | 50% | 97.8% | 0.95 | 2.7 s |
|
|
860
|
+
|
|
861
|
+
Measure on your own vectors before you commit: how much recall you lose depends entirely on the data. Some models (OpenAI's `text-embedding-3`, other Matryoshka-trained ones) can simply be cut to their first N dimensions, and don't need PCA.
|
|
862
|
+
|
|
863
|
+
## Combining index + quantization
|
|
864
|
+
|
|
865
|
+
Nothing in the library assumes a specific combination. The main one, compressed vectors inside an index, is the [`vectors` option](#compressed-vectors--option-vectors). A few more patterns:
|
|
866
|
+
|
|
867
|
+
**Cold storage.** Keep the exact vectors in HNSW for search; encode with PQ or SQ and store the codes in a database or ship them over the wire.
|
|
868
|
+
|
|
869
|
+
```js
|
|
870
|
+
index.add(id, vector, (err) => { /* ... */ });
|
|
871
|
+
pq.encode(vector, (err, code) => {
|
|
872
|
+
if (!err) db.put(id, code);
|
|
873
|
+
});
|
|
874
|
+
```
|
|
875
|
+
|
|
876
|
+
**Coarse filter + exact re-rank.** Scan compressed codes (BQ, PQ, or TurboQuant) to shortlist candidates, then re-rank the top few with the exact index.
|
|
877
|
+
|
|
878
|
+
```js
|
|
879
|
+
const table = pq.buildDistanceTableSync(query);
|
|
880
|
+
const shortlist = allCodes
|
|
881
|
+
.map((code, i) => ({ id: ids[i], d: pq.tableDistanceSync(table, code) }))
|
|
882
|
+
.sort((a, b) => a.d - b.d)
|
|
883
|
+
.slice(0, 100);
|
|
884
|
+
|
|
885
|
+
// re-rank the 100 candidates with the exact HNSW index
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
**Quantize before insertion.** Push each vector through `encode → decode` and add the reconstructed version to the index. Simulates how search will feel with quantization before you commit to storing codes.
|
|
889
|
+
|
|
890
|
+
---
|
|
891
|
+
|
|
892
|
+
## Embeddings
|
|
893
|
+
|
|
894
|
+
You give it relationships (who follows whom, what was bought together, which pages link to which). It gives back one vector per id. Similar vectors mean similar positions in the graph, so you can:
|
|
895
|
+
|
|
896
|
+
- find similar users or items;
|
|
897
|
+
- predict missing links ("people you may know");
|
|
898
|
+
- feed the vectors to a classifier;
|
|
899
|
+
- put them in a [search index](#embeddings--search) for fast search.
|
|
900
|
+
|
|
901
|
+
Ids are any integers from `0` to `Number.MAX_SAFE_INTEGER`. They can be user ids, product ids or page ids: the library doesn't care what a node is.
|
|
902
|
+
|
|
903
|
+
```js
|
|
904
|
+
import { createGraph, createNode2Vec } from 'vector-index';
|
|
905
|
+
|
|
906
|
+
const graph = createGraph(); // { directed, weighted }
|
|
907
|
+
graph.addEdges({ from: [1, 1, 2], to: [2, 3, 3] }, (err) => {
|
|
908
|
+
const n2v = createNode2Vec(graph, { dimensions: 64, seed: 42 });
|
|
909
|
+
n2v.on('progress', (p) => console.log(p.done, '/', p.total, 'loss', p.loss));
|
|
910
|
+
n2v.train((err, embeddings) => {
|
|
911
|
+
embeddings.vectorSync(1); // Float32Array(64)
|
|
912
|
+
embeddings.similarSync(1, 10); // [{ id, similarity }]
|
|
913
|
+
});
|
|
914
|
+
});
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
### Conventions
|
|
918
|
+
|
|
919
|
+
The same [callback contract](#callback-contract) as the rest of the library, plus:
|
|
920
|
+
|
|
921
|
+
- **Every operation has two forms:** `name(..., cb)` and `nameSync(...)`.
|
|
922
|
+
- Long operations (compile, training, loading, scans) run **time-sliced** in the async form: the work is cut into ~8ms slices, and the event loop (UI or server) is never blocked for long. On a 1M-node graph, the longest pause measured was 27–29ms.
|
|
923
|
+
- The `Sync` form runs the same code in one go.
|
|
924
|
+
- **Writes are queued.** Async writes to a graph run in FIFO order. A `Sync` call made while an async job is still running throws `BUSY` instead of breaking the order.
|
|
925
|
+
- **Determinism.** With the same `seed`, `train()` and `trainSync()` give **bit-identical** embeddings. Time-slicing does not change the result.
|
|
926
|
+
- **Events report, functions compute.** Events (`progress`, `epoch`) only report. Nothing in the API asks you to hand over a function.
|
|
927
|
+
|
|
928
|
+
Error codes are in the [table above](#callback-contract).
|
|
929
|
+
|
|
930
|
+
### `createGraph({ directed = false, weighted = false })`
|
|
931
|
+
|
|
932
|
+
| method | |
|
|
933
|
+
|---|---|
|
|
934
|
+
| `addEdge(from, to[, weight], cb)` | O(1): appends to a pending buffer |
|
|
935
|
+
| `addEdges({ from, to, weights? }, cb)` | bulk load. Arrays or typed arrays. All-or-nothing: one bad entry and nothing is added |
|
|
936
|
+
| `compile(cb)` | merges pending edges into the CSR. Runs automatically before anything that reads adjacency, so calling it is optional |
|
|
937
|
+
| `degree(id, cb)` | number of neighbors (out-degree in a directed graph) |
|
|
938
|
+
| `neighbors(id, cb)` | `{ ids: Float64Array, weights: Float32Array \| null }` |
|
|
939
|
+
| `hasNode(id, cb)` | never waits in the queue |
|
|
940
|
+
| `stats(cb)` | `{ nodes, edges, directed, weighted, bytes }` |
|
|
941
|
+
| `on/off('progress', fn)` | `{ phase: 'compile', done, total }` |
|
|
942
|
+
|
|
943
|
+
Duplicate edges are merged. In a weighted graph, their weights are **summed**, so you can feed raw interaction counts directly. An undirected edge counts once in `edges`.
|
|
944
|
+
|
|
945
|
+
### `createNode2Vec(graph, options)`
|
|
946
|
+
|
|
947
|
+
| option | default | meaning |
|
|
948
|
+
|---|---|---|
|
|
949
|
+
| `dimensions` | 128 | vector size |
|
|
950
|
+
| `walkLength` | 80 | steps per walk |
|
|
951
|
+
| `walksPerNode` | 10 | walks started from every node, per epoch |
|
|
952
|
+
| `p` | 1 | return parameter. Low `p` = walks stay local |
|
|
953
|
+
| `q` | 1 | in-out parameter. Low `q` = walks explore outward; high `q` = walks stay in the neighborhood. `p = q = 1` is DeepWalk, the fastest walk mode |
|
|
954
|
+
| `window` | 10 | context size on each side |
|
|
955
|
+
| `negative` | 5 | negative samples per positive pair |
|
|
956
|
+
| `epochs` | 1 | passes. Every epoch draws fresh walks |
|
|
957
|
+
| `learningRate` / `minLearningRate` | 0.025 / 0.0001 | linear decay |
|
|
958
|
+
| `sample` | 0.001 | down-sampling of very frequent nodes (hubs). 0 = off |
|
|
959
|
+
| `seed` | random | set it for reproducible results |
|
|
960
|
+
|
|
961
|
+
Methods and properties:
|
|
962
|
+
|
|
963
|
+
- `train(cb)` / `trainSync()` → embeddings.
|
|
964
|
+
- `cancel()` → the pending `train` callback gets a `CANCELLED` error.
|
|
965
|
+
- `training` — true while a training job runs.
|
|
966
|
+
- `options` — the resolved options, frozen.
|
|
967
|
+
- Events:
|
|
968
|
+
- `progress`: `{ phase: 'train', epoch, epochs, done, total, loss }`, at most every 200ms.
|
|
969
|
+
- `epoch`: `{ epoch, epochs, loss }`.
|
|
970
|
+
- `loss` is the average negative log-likelihood per pair, and should go down.
|
|
971
|
+
|
|
972
|
+
Training works on a **snapshot** of the graph. You can keep adding edges while a training job runs. The new edges are used by the next `train`.
|
|
973
|
+
|
|
974
|
+
### `createSkipGram(options)`: any sequences
|
|
975
|
+
|
|
976
|
+
This is the same engine, for data that is already in sequences: shopping sessions (item2vec), playlists, browsing paths, or walks you generated yourself.
|
|
977
|
+
|
|
978
|
+
```js
|
|
979
|
+
const sg = createSkipGram({ dimensions: 64, window: 5, epochs: 5, minCount: 2, seed: 1 });
|
|
980
|
+
sg.train([[12, 7, 99], [7, 99, 4]], (err, embeddings) => { ... });
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
It takes the same training options as node2vec (with defaults `window: 5`, `epochs: 5`), plus `minCount`: ids that appear fewer times than this get no vector. Token frequencies are counted exactly.
|
|
984
|
+
|
|
985
|
+
### `createALS(options)` and `createBPR(options)`: users and items for recommendations
|
|
986
|
+
|
|
987
|
+
node2vec and item2vec give **item ↔ item** similarity ("bought together", "people who liked this"). ALS and BPR learn **a vector for every user and every item in the same space**, from who did what. Recommending to a user is then one inner-product search: the user's vector against the items.
|
|
988
|
+
|
|
989
|
+
```js
|
|
990
|
+
import { createALS, createBPR } from 'vector-index';
|
|
991
|
+
|
|
992
|
+
const interactions = {
|
|
993
|
+
users: [1, 1, 2, 3, 3, 3], // who
|
|
994
|
+
items: [10, 11, 10, 11, 12, 13], // did what
|
|
995
|
+
weights: [1, 3, 1, 2, 1, 1] // how much (optional): plays, purchases, seconds
|
|
996
|
+
};
|
|
997
|
+
|
|
998
|
+
createALS({ dimensions: 64, seed: 1 }).train(interactions, (err, model) => {
|
|
999
|
+
if (err) throw err;
|
|
1000
|
+
model.users.vectorSync(1); // Float32Array(64)
|
|
1001
|
+
model.items.similarSync(10, 5); // items similar to item 10
|
|
1002
|
+
});
|
|
1003
|
+
```
|
|
1004
|
+
|
|
1005
|
+
User ids and item ids are separate spaces: user 7 and item 7 have nothing to do with each other. Repeated (user, item) pairs are summed. Both return two ordinary [embeddings objects](#the-embeddings-object), `users` and `items`, with everything they offer (`vector`, `similar`, `toBytes`…), plus the usual `cancel()`, `on('progress' | 'epoch')`, `training` and `trainSync`.
|
|
1006
|
+
|
|
1007
|
+
**ALS** (Hu, Koren & Volinsky 2008) is the classic for implicit feedback: purchases, plays, clicks, where people show what they did but never what they disliked. Every (user, item) pair counts: interacted = 1, didn't = 0, with more confidence the more they interacted (`1 + alpha · weight`). It alternates between solving all users with the items fixed and the other way around. Each solve is a few conjugate-gradient steps (as in the `implicit` library) instead of an exact D×D solve.
|
|
1008
|
+
|
|
1009
|
+
| option | default | |
|
|
1010
|
+
|---|---|---|
|
|
1011
|
+
| `dimensions` | 64 | |
|
|
1012
|
+
| `iterations` | 15 | each = all users + all items |
|
|
1013
|
+
| `regularization` | 0.01 | λ |
|
|
1014
|
+
| `alpha` | 1 | confidence per unit of weight |
|
|
1015
|
+
| `cgSteps` | 3 | conjugate-gradient steps per row |
|
|
1016
|
+
| `seed` | random | |
|
|
1017
|
+
|
|
1018
|
+
**BPR** (Rendle et al. 2009) learns to *rank*: for a user, an item they touched should score above a random one they didn't. It's one SGD step per sampled (user, item, other item), the same pull-together / push-apart idea as skip-gram's negative sampling. The last coordinate is an item bias (users hold 1 there), so popular items can win without a perfect taste match, and ⟨user, item⟩ already includes it.
|
|
1019
|
+
|
|
1020
|
+
| option | default | |
|
|
1021
|
+
|---|---|---|
|
|
1022
|
+
| `dimensions` | 64 | including the bias coordinate |
|
|
1023
|
+
| `epochs` | 50 | each = as many samples as interactions |
|
|
1024
|
+
| `learningRate` | 0.05 | |
|
|
1025
|
+
| `regularization` | 0.01 | |
|
|
1026
|
+
| `seed` | random | |
|
|
1027
|
+
|
|
1028
|
+
**Measured** (`node bench/recommend.bench.js`): 2,000 users × 1,000 items, 77k interactions generated from hidden tastes and popularity; one interaction per user hidden. HitRate@10 is how often the hidden item is in the user's top 10:
|
|
1029
|
+
|
|
1030
|
+
| | HitRate@10 | train |
|
|
1031
|
+
|---|---|---|
|
|
1032
|
+
| random | 0.010 | |
|
|
1033
|
+
| most popular | 0.070 | |
|
|
1034
|
+
| **ALS** (32 dims) | **0.334** | 1.7 s |
|
|
1035
|
+
| **BPR** (32 dims) | **0.344** | 1.5 s |
|
|
1036
|
+
| the true model that made the data | 0.420 | (the ceiling) |
|
|
1037
|
+
|
|
1038
|
+
Both reach about 80% of what's possible and 5× popularity. Training is time-sliced like everything else (longest freeze 15–28 ms on 300k interactions).
|
|
1039
|
+
|
|
1040
|
+
Which one? They're close. ALS has fewer knobs and is deterministic per iteration; BPR optimizes the ranking directly and handles very popular items through its bias. Try both on your data with a held-out split.
|
|
1041
|
+
|
|
1042
|
+
### `createWalker(graph, { walkLength, p, q, seed })`
|
|
1043
|
+
|
|
1044
|
+
`walk(startId, cb)` / `walkSync(startId)` → a `Float64Array` of ids. Use it to inspect walks, or to build your own pipeline that feeds `createSkipGram`.
|
|
1045
|
+
|
|
1046
|
+
### The embeddings object
|
|
1047
|
+
|
|
1048
|
+
| | |
|
|
1049
|
+
|---|---|
|
|
1050
|
+
| `size`, `dimensions` | |
|
|
1051
|
+
| `ids`, `data` | raw views, no copy: `Float64Array(size)` and `Float32Array(size × dimensions)`, row-major |
|
|
1052
|
+
| `has(id, cb)` | |
|
|
1053
|
+
| `vector(id, cb)` | `Float32Array` (a copy) |
|
|
1054
|
+
| `similar(idOrVector, k, cb)` | `[{ id, similarity }]` by cosine. This is a full scan, fine up to ~100k rows. Above that, put the vectors in a [search index](#embeddings--search) |
|
|
1055
|
+
| `estimate(neighborIds[, weights], cb)` | a vector for a node that **wasn't trained** (a new user or a new item): the weighted mean of its known neighbors' vectors. Unknown ids are skipped |
|
|
1056
|
+
| `toBytes(cb)` | `Uint8Array` |
|
|
1057
|
+
|
|
1058
|
+
`loadEmbeddings(bytes, cb)` reads the bytes back; a Node `Buffer` works, aligned or not. The format, little-endian:
|
|
1059
|
+
|
|
1060
|
+
- bytes 0–3: `'GEMB'`
|
|
1061
|
+
- bytes 4–7: version
|
|
1062
|
+
- bytes 8–11: dimensions
|
|
1063
|
+
- bytes 16–23: size
|
|
1064
|
+
- then `size` ids as f64
|
|
1065
|
+
- then `size × dimensions` values as f32
|
|
1066
|
+
|
|
1067
|
+
### Quality: `splitEdges` + `evaluateLinkPrediction`
|
|
1068
|
+
|
|
1069
|
+
```js
|
|
1070
|
+
splitEdges(graph, { testFraction: 0.1, seed: 1 }, (err, split) => {
|
|
1071
|
+
// split.train: a graph without the hidden edges (no node loses its last edge)
|
|
1072
|
+
// split.test / split.negatives: { from, to } — hidden real edges, and as many random non-edges
|
|
1073
|
+
createNode2Vec(split.train, opts).train((err, emb) => {
|
|
1074
|
+
evaluateLinkPrediction(emb, split, (err, r) => console.log(r.auc)); // 0.5 = random, 1 = perfect
|
|
1075
|
+
});
|
|
1076
|
+
});
|
|
1077
|
+
```
|
|
1078
|
+
|
|
1079
|
+
This is how you choose `p`, `q`, `dimensions` and the other options **for your own graph**.
|
|
1080
|
+
|
|
1081
|
+
### `estimateMemory({ nodes, edges, dimensions, directed, weighted })`
|
|
1082
|
+
|
|
1083
|
+
Returns `{ graph, training, embeddings, peak }` in bytes. It is computed from the exact array sizes the library allocates, so you can plan before you load. For the 1M-node graph below, the estimate was 74MB and the measured size was 74MB.
|
|
1084
|
+
|
|
1085
|
+
### How it works, and why it scales
|
|
1086
|
+
|
|
1087
|
+
| piece | what we do | why |
|
|
1088
|
+
|---|---|---|
|
|
1089
|
+
| ids | an open-addressing hash table on typed arrays: about 28 bytes per id | a JS `Map` stops at ~16.7M entries and costs 40–80 bytes per entry |
|
|
1090
|
+
| graph | **CSR**: all neighbor lists in one `Uint32Array` plus offsets. 4 bytes per entry (+4 for a weight) | no object per node or per edge, nothing for the GC to walk, cache-friendly |
|
|
1091
|
+
| building | pending edges are radix-sorted by (source, target) in O(E + N), then merged into the sorted CSR | incremental, with no comparison sort |
|
|
1092
|
+
| node2vec walks | **rejection sampling**: draw a neighbor first-order, then accept it with probability bias / maxBias. "Is x a neighbor of the previous node" is a binary search in a sorted row | the classic alias tables need O(Σ deg²) memory, which is what makes node2vec impossible on large graphs. Ours needs nothing per edge, and the transition probabilities are still exact (verified statistically in the tests) |
|
|
1093
|
+
| walk corpus | never stored: each walk is generated and trained on immediately | gensim-based implementations keep every walk (10 × 80 × N ids) |
|
|
1094
|
+
| negative sampling | alias table, 8 bytes per node | word2vec's table is 10⁸ entries (400MB) |
|
|
1095
|
+
| negatives per window | drawn once per center node, shared by all its contexts (pWord2Vec, Ji et al. 2016) | 1.43× faster on large graphs (the negative rows stay in cache), same quality |
|
|
1096
|
+
| frequencies | estimated from degrees: a random walk visits a node in proportion to its degree | no second pass over the walks |
|
|
1097
|
+
| hot loops | module-level functions over typed arrays, with explicit RNG state | closures per instance lost V8's optimizations after the first trainer (it was 1.6× slower) |
|
|
1098
|
+
|
|
1099
|
+
The data structures are flat typed arrays with no closures in the hot paths, so they map one-to-one onto Rust or WASM.
|
|
1100
|
+
|
|
1101
|
+
### Measured
|
|
1102
|
+
|
|
1103
|
+
All measurements are on one core of a 2.8GHz Xeon VM, with Node 22.
|
|
1104
|
+
|
|
1105
|
+
**Quality vs the reference implementation.** The test is link prediction (AUC) on the same graph and split: 5,000 nodes, 24.8k edges, 64 dimensions, 10 walks of 80 per node, window 10.
|
|
1106
|
+
|
|
1107
|
+
| | AUC | training time |
|
|
1108
|
+
|---|---|---|
|
|
1109
|
+
| gensim Word2Vec (C, 1 worker), with the same walks | 0.828 | 50s |
|
|
1110
|
+
| **vector-index**, DeepWalk (p = q = 1) | **0.828** | 128s (walks included) |
|
|
1111
|
+
| **vector-index**, node2vec q = 0.5 | **0.832** | 126s |
|
|
1112
|
+
|
|
1113
|
+
Quality is identical to the reference. Speed is about 2.5× slower than gensim's C code on one core, which is the ceiling for scalar JS. The remaining speedups are multiple cores and WASM SIMD (see Roadmap).
|
|
1114
|
+
|
|
1115
|
+
**Scale: 1M nodes, 5M edges, 64 dimensions** (`node bench/scale.bench.js`)
|
|
1116
|
+
|
|
1117
|
+
| | |
|
|
1118
|
+
|---|---|
|
|
1119
|
+
| `addEdges` (5M edges, sparse 64-bit ids) | 2.1s |
|
|
1120
|
+
| `compile` | 3.4s; longest event-loop gap 27ms |
|
|
1121
|
+
| graph in memory | 74MB |
|
|
1122
|
+
| training memory | 511MB (two matrices of N × D × 4 bytes); after training, only the embeddings: 256MB |
|
|
1123
|
+
| training throughput | ~26k tokens per second per core; longest event-loop gap 29ms |
|
|
1124
|
+
|
|
1125
|
+
Training cost is proportional to `nodes × walksPerNode × walkLength × window × (negative + 1) × dimensions`.
|
|
1126
|
+
|
|
1127
|
+
- With the defaults on 1M nodes, that is about 8.5 hours on one core.
|
|
1128
|
+
- With `walksPerNode: 4, walkLength: 40, window: 5`, it is about 1 hour, usually with little loss of quality. Check it with `evaluateLinkPrediction`.
|
|
1129
|
+
|
|
1130
|
+
---
|
|
1131
|
+
|
|
1132
|
+
## Embeddings + Search
|
|
1133
|
+
|
|
1134
|
+
The embeddings part gives one vector per id; the search part finds the nearest ones fast. 2,000 users who bought products, in 20 taste groups — who is most like user 7?
|
|
1135
|
+
|
|
1136
|
+
```js
|
|
1137
|
+
import { createGraph, createNode2Vec, createVectorIndex } from 'vector-index';
|
|
1138
|
+
|
|
1139
|
+
const graph = createGraph();
|
|
1140
|
+
graph.addEdges({ from: userIds, to: productIds }, (err) => {
|
|
1141
|
+
// relationships → one vector per id
|
|
1142
|
+
createNode2Vec(graph, { dimensions: 64 }).train((err, emb) => {
|
|
1143
|
+
// vectors → search index
|
|
1144
|
+
const index = createVectorIndex({ algorithm: 'hnsw', dimensions: 64 });
|
|
1145
|
+
let i = 0;
|
|
1146
|
+
(function next(err) {
|
|
1147
|
+
if (i === emb.size) return query();
|
|
1148
|
+
index.add(emb.ids[i], emb.data.subarray(i * 64, (i + 1) * 64), next);
|
|
1149
|
+
i++;
|
|
1150
|
+
})();
|
|
1151
|
+
|
|
1152
|
+
function query() {
|
|
1153
|
+
emb.vector(7, (err, v) => index.search(v, 6, (err, results) => {
|
|
1154
|
+
console.log(results.map(r => r.id)); // [7, 1567, 1287, 507, 1907, 1087] — all group 7
|
|
1155
|
+
}));
|
|
1156
|
+
}
|
|
1157
|
+
});
|
|
1158
|
+
});
|
|
1159
|
+
```
|
|
1160
|
+
|
|
1161
|
+
Nobody told the model about taste groups: it found them from what people bought. Below ~100k ids, `embeddings.similar()` scans them directly and the index isn't needed.
|
|
1162
|
+
|
|
1163
|
+
---
|
|
1164
|
+
|
|
1165
|
+
## Cookbook
|
|
1166
|
+
|
|
1167
|
+
Short recipes for things that come up in real projects. Each one uses only the public API.
|
|
1168
|
+
|
|
1169
|
+
### Which metric?
|
|
1170
|
+
|
|
1171
|
+
- **Text or image embeddings** from a model (OpenAI, sentence-transformers, CLIP…) → `cosine`, the default. These vectors are normalized anyway, and `l2` would rank them exactly the same.
|
|
1172
|
+
- **Measurements where size matters**: coordinates, sensor readings, prices, counts → `l2`. Cosine would treat `[1, 1]` and `[100, 100]` as identical.
|
|
1173
|
+
- **Recommendations from matrix factorization**: user vectors against item vectors, where a longer item vector means a more popular or stronger item → `dot`.
|
|
1174
|
+
|
|
1175
|
+
When in doubt, check whether your vectors all have length 1. If they do, the metric doesn't matter: keep `cosine`.
|
|
1176
|
+
|
|
1177
|
+
### "Similar, but only in stock"
|
|
1178
|
+
|
|
1179
|
+
Your metadata stays in your own data structures. The index only asks "may this id be returned?".
|
|
1180
|
+
|
|
1181
|
+
```js
|
|
1182
|
+
const product = new Map(); // id → { stock, sellerId, price }
|
|
1183
|
+
|
|
1184
|
+
index.search(queryVector, 10, {
|
|
1185
|
+
filter: (id) => product.get(id).stock > 0
|
|
1186
|
+
}, (err, results) => {
|
|
1187
|
+
// 10 in-stock products, even if 95% of the catalog is sold out
|
|
1188
|
+
});
|
|
1189
|
+
```
|
|
1190
|
+
|
|
1191
|
+
Conditions combine like any JavaScript:
|
|
1192
|
+
|
|
1193
|
+
```js
|
|
1194
|
+
filter: (id) => {
|
|
1195
|
+
const p = product.get(id);
|
|
1196
|
+
return p.sellerId === seller && p.price >= min && p.price <= max;
|
|
1197
|
+
}
|
|
1198
|
+
```
|
|
1199
|
+
|
|
1200
|
+
Keep the filter fast and synchronous: it's called during the search, possibly thousands of times. If your metadata lives in a database, load what the filter needs into a `Map` or `Set` first.
|
|
1201
|
+
|
|
1202
|
+
### "Recommended for you, minus what you already bought"
|
|
1203
|
+
|
|
1204
|
+
```js
|
|
1205
|
+
const bought = new Set(user.purchases); // ids
|
|
1206
|
+
|
|
1207
|
+
index.search(user.vector, 20, { filter: (id) => !bought.has(id) }, (err, results) => {});
|
|
1208
|
+
```
|
|
1209
|
+
|
|
1210
|
+
### Hybrid search: meaning + exact words
|
|
1211
|
+
|
|
1212
|
+
Embeddings understand meaning but miss exact matches like a model number, a part code or a rare name. Keyword vectors catch those. Keep both, search both, fuse the rankings:
|
|
1213
|
+
|
|
1214
|
+
```js
|
|
1215
|
+
import { createVectorIndex, createSparseIndex, fuseResults } from 'vector-index';
|
|
1216
|
+
|
|
1217
|
+
const dense = createVectorIndex({ algorithm: 'hnsw', dimensions: 384 });
|
|
1218
|
+
const sparse = createSparseIndex();
|
|
1219
|
+
|
|
1220
|
+
// a minimal BM25: word → dimension, weight by rarity and repetition
|
|
1221
|
+
const vocab = new Map(); // word → dimension
|
|
1222
|
+
const df = new Map(); // dimension → documents containing it
|
|
1223
|
+
let docs = 0, avgLen = 0;
|
|
1224
|
+
const words = (text) => text.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
|
|
1225
|
+
|
|
1226
|
+
function keywordVector(text, isQuery) {
|
|
1227
|
+
const counts = new Map();
|
|
1228
|
+
for (const w of words(text)) {
|
|
1229
|
+
if (!vocab.has(w)) { if (isQuery) continue; vocab.set(w, vocab.size); }
|
|
1230
|
+
const d = vocab.get(w);
|
|
1231
|
+
counts.set(d, (counts.get(d) || 0) + 1);
|
|
1232
|
+
}
|
|
1233
|
+
const indices = [...counts.keys()];
|
|
1234
|
+
if (isQuery) return { indices, values: indices.map(() => 1) };
|
|
1235
|
+
const len = words(text).length, k1 = 1.2, b = 0.75;
|
|
1236
|
+
return {
|
|
1237
|
+
indices,
|
|
1238
|
+
values: indices.map((d) => {
|
|
1239
|
+
const tf = counts.get(d);
|
|
1240
|
+
const idf = Math.log(1 + (docs - (df.get(d) || 0) + 0.5) / ((df.get(d) || 0) + 0.5));
|
|
1241
|
+
return idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len / (avgLen || len)));
|
|
1242
|
+
})
|
|
1243
|
+
};
|
|
1244
|
+
}
|
|
1245
|
+
// count df / docs / avgLen over your corpus first, then add every document:
|
|
1246
|
+
dense.add(id, embed(text), cb);
|
|
1247
|
+
sparse.add(id, keywordVector(text), cb);
|
|
1248
|
+
|
|
1249
|
+
// search: both, then one list
|
|
1250
|
+
dense.search(embed(q), 50, (err, semantic) => {
|
|
1251
|
+
sparse.search(keywordVector(q, true), 50, (err, keyword) => {
|
|
1252
|
+
const results = fuseResults([semantic, keyword], { limit: 10 });
|
|
1253
|
+
// ids high in both lists come first; an exact match high in just one still makes it
|
|
1254
|
+
});
|
|
1255
|
+
});
|
|
1256
|
+
```
|
|
1257
|
+
|
|
1258
|
+
For better keyword vectors, use a real tokenizer with stemming, or a SPLADE model: the sparse index takes whatever `{ indices, values }` you give it.
|
|
1259
|
+
|
|
1260
|
+
`weights` shifts the balance: `{ weights: [2, 1] }` trusts meaning twice as much as words. Ask each search for more than you'll show (50 for a page of 10). An id that only appears at rank 40 in one list can still be lifted by the other.
|
|
1261
|
+
|
|
1262
|
+
### Shards: one index over several machines or peers
|
|
1263
|
+
|
|
1264
|
+
Each shard holds a part of the vectors and answers the same query. Merging is a sort:
|
|
1265
|
+
|
|
1266
|
+
```js
|
|
1267
|
+
import { mergeResults } from 'vector-index';
|
|
1268
|
+
|
|
1269
|
+
// on every shard (a server, a worker, a P2P peer): its own index, the same query
|
|
1270
|
+
shard.index.search(query, 10, (err, results) => send(results));
|
|
1271
|
+
|
|
1272
|
+
// where the answers come together
|
|
1273
|
+
const top10 = mergeResults(answersFromAllShards, 10);
|
|
1274
|
+
```
|
|
1275
|
+
|
|
1276
|
+
Ask every shard for the full k. The global top 10 may all live on one shard. Scores from shards are comparable as long as they all use the same metric and the same kind of vectors. How the query reaches the shards (HTTP, WebSocket, WebRTC, a message queue) is your transport, not the library's.
|
|
1277
|
+
|
|
1278
|
+
### Shrinking big embeddings with PCA
|
|
1279
|
+
|
|
1280
|
+
1536-dim vectors at 4 bytes each are 6 KB apiece: 6 GB for a million. Train PCA once on a sample, then index and query in the reduced space:
|
|
1281
|
+
|
|
1282
|
+
```js
|
|
1283
|
+
const pca = createPCA({ dimensions: 1536, components: 256, seed: 1 });
|
|
1284
|
+
pca.trainSync(sampleOf(5000));
|
|
1285
|
+
|
|
1286
|
+
const index = createVectorIndex({ algorithm: 'hnsw', dimensions: 256 });
|
|
1287
|
+
index.add(id, pca.transformSync(vector), cb); // every vector, reduced
|
|
1288
|
+
index.search(pca.transformSync(query), 10, cb); // the query too
|
|
1289
|
+
```
|
|
1290
|
+
|
|
1291
|
+
Check recall on your own data first: search a few hundred queries in both spaces and compare. The PCA model is part of the index from now on: save `pca.getModel()` (four typed arrays) next to it, and load it with `createPCA({ dimensions: 1536, components: 256, model })`. If recall drops too much, ask the reduced index for more candidates and rerank them with the full vectors (next recipe).
|
|
1292
|
+
|
|
1293
|
+
### Compressed index, exact answers
|
|
1294
|
+
|
|
1295
|
+
With option `vectors`, the index holds only codes (SQ8 is 4× smaller, PQ up to 64×). Ask for a few more candidates than you need and rerank them with the full vectors from your own storage:
|
|
1296
|
+
|
|
1297
|
+
```js
|
|
1298
|
+
index.search(query, 50, (err, candidates) => {
|
|
1299
|
+
loadVectors(candidates.map(c => c.id), (err, full) => { // your storage
|
|
1300
|
+
const top = candidates
|
|
1301
|
+
.map((c, i) => ({ id: c.id, score: cosine(query, full[i]) }))
|
|
1302
|
+
.sort((a, b) => b.score - a.score)
|
|
1303
|
+
.slice(0, 10);
|
|
1304
|
+
});
|
|
1305
|
+
});
|
|
1306
|
+
```
|
|
1307
|
+
|
|
1308
|
+
More in [Combining index + quantization](#combining-index--quantization).
|
|
1309
|
+
|
|
1310
|
+
### "Recommended for you": ALS / BPR + a dot index
|
|
1311
|
+
|
|
1312
|
+
Train users and items from interactions, index the items with `metric: 'dot'`, search with the user's vector, and skip what they already have:
|
|
1313
|
+
|
|
1314
|
+
```js
|
|
1315
|
+
import { createBPR, createVectorIndex } from 'vector-index';
|
|
1316
|
+
|
|
1317
|
+
createBPR({ dimensions: 64 }).train({ users, items, weights }, (err, model) => {
|
|
1318
|
+
const index = createVectorIndex({ algorithm: 'hnsw', dimensions: 64, metric: 'dot' });
|
|
1319
|
+
let i = 0;
|
|
1320
|
+
(function next() {
|
|
1321
|
+
if (i < model.items.size) {
|
|
1322
|
+
const id = model.items.ids[i++];
|
|
1323
|
+
return index.add(id, model.items.vectorSync(id), next);
|
|
1324
|
+
}
|
|
1325
|
+
// ready: recommend to user 42
|
|
1326
|
+
const bought = new Set(purchasesOf(42));
|
|
1327
|
+
index.search(model.users.vectorSync(42), 20, { filter: (id) => !bought.has(id) }, (err, recs) => {
|
|
1328
|
+
// [{ id, score: ⟨user, item⟩ }], highest first
|
|
1329
|
+
});
|
|
1330
|
+
})();
|
|
1331
|
+
});
|
|
1332
|
+
```
|
|
1333
|
+
|
|
1334
|
+
"More like this item" needs no user at all: `model.items.similarSync(itemId, 10)`, or the item's own vector as the query.
|
|
1335
|
+
|
|
1336
|
+
With `cosine` instead, a niche item pointing exactly the user's way would beat a hit that points almost the same way. That's sometimes what you want ("more like my taste, less like the charts"), and it's a one-word change.
|
|
1337
|
+
|
|
1338
|
+
### Keeping a long-lived index healthy
|
|
1339
|
+
|
|
1340
|
+
Deletes are soft: the node stays as a bridge and is skipped in results. Many deletes make every search walk through more dead nodes. Check now and then, and compact when it's worth it:
|
|
1341
|
+
|
|
1342
|
+
```js
|
|
1343
|
+
setInterval(() => {
|
|
1344
|
+
index.stats((err, s) => {
|
|
1345
|
+
if (!err && s.ratio > 0.2) index.compact((err) => {}); // more than 20% deleted
|
|
1346
|
+
});
|
|
1347
|
+
}, 60 * 60 * 1000);
|
|
1348
|
+
```
|
|
1349
|
+
|
|
1350
|
+
On `diskann-blocks`, compact also needs `block:keys` to list what's in storage. With IndexedDB:
|
|
1351
|
+
|
|
1352
|
+
```js
|
|
1353
|
+
index.on('block:keys', (cb) => {
|
|
1354
|
+
const req = db.transaction('blocks').objectStore('blocks').getAllKeys();
|
|
1355
|
+
req.onsuccess = () => cb(null, req.result);
|
|
1356
|
+
req.onerror = () => cb(req.error);
|
|
1357
|
+
});
|
|
1358
|
+
```
|
|
1359
|
+
|
|
1360
|
+
Searches keep working while compact runs; adds and deletes wait for it in the queue.
|
|
1361
|
+
|
|
1362
|
+
---
|
|
1363
|
+
|
|
1364
|
+
## Design
|
|
1365
|
+
|
|
1366
|
+
Every algorithm implements the same interface, and every quantizer implements the same interface. A method that doesn't apply calls back with `NOT_SUPPORTED` instead of being absent or silently doing nothing. One callback contract (async, exactly once, coded errors) holds across the whole package, including the storage events you implement. There is no `switch` on algorithm in the caller's code.
|
|
1367
|
+
|
|
1368
|
+
Vectors may be passed as an `Array` or any typed array. Every input vector is copied, so the library never holds references to your original arrays — you can reuse an array as soon as `add()` returns. Non-finite values (NaN, Infinity) are rejected.
|
|
1369
|
+
|
|
1370
|
+
### Internal representation
|
|
1371
|
+
|
|
1372
|
+
None of this is visible through the API, but it explains the performance:
|
|
1373
|
+
|
|
1374
|
+
- **Vectors are stored contiguously**, in one `Float32Array` per index, normalized for cosine. Cosine similarity becomes a plain dot product, and `l2` a plain sum of squared differences: no norms or square roots at search time. With the `vectors` option, the same place holds your encoded bytes, back to back in one `Uint8Array`, and engines compare through your `similarity` function instead of a dot product. The graph code is the same either way.
|
|
1375
|
+
- **Ids are translated to dense internal slots** (0, 1, 2, ...) once, at the boundary. Graph edges, heaps and "visited" marks all work on slots in typed arrays (`Int32Array`, `Uint32Array`), so a search allocates almost nothing and never hashes an id.
|
|
1376
|
+
- **"Visited" uses epochs**: one `Uint32Array` per index, where a node counts as visited when its mark equals the current search number. Starting a search is a single increment.
|
|
1377
|
+
- **DiskANN's candidate list is kept sorted**, with a cursor at the first unexpanded entry, as in the reference implementation.
|
|
1378
|
+
- **Neighbor lists have slack.** DiskANN lets a list grow to 1.3·R before pruning it back to R. HNSW re-selects a full list without topping it back up. Either way, most new edges are a plain append rather than an O(R²) re-selection.
|
|
1379
|
+
|
|
1380
|
+
Measured with 10,000 128-dim vectors and 200 queries (`node bench/perf.bench.js`), before and after these changes:
|
|
1381
|
+
|
|
1382
|
+
| | build before | build now | search before | search now | recall@10 now |
|
|
1383
|
+
|---|---|---|---|---|---|
|
|
1384
|
+
| flat | 0.1 s | 0.1 s | 13.8 ms | 4.5 ms | 100% |
|
|
1385
|
+
| ivf | 2.1 s | 2.2 s | 1.9 ms | 0.66 ms | 100% |
|
|
1386
|
+
| hnsw | 60.5 s | 7.8 s | 0.79 ms | 0.31 ms | 99.9% |
|
|
1387
|
+
| diskann | 105.9 s | 12.5 s | 1.07 ms | 0.35 ms | 100% |
|
|
1388
|
+
| diskann-blocks (5k) | 23.6 s | 7.2 s | 3.8 ms | 1.0 ms | 100% |
|
|
1389
|
+
|
|
1390
|
+
In diskann-blocks, per query storage reads went from 335 to 64 and per insert from 412 to 54.
|
|
1391
|
+
|
|
1392
|
+
Events are used for two things only. Notifications — `progress` (SQ/PQ/IVF `train`, DiskANN `build`, `compact`) and `root:change` — accept any number of listeners. Requests — `block:*` and `meta:*` in `diskann-blocks` — are your storage backend: exactly one handler each, answering through a callback. Computation you plug in — the four functions of the `vectors` option — is never an event: it's passed as plain synchronous functions, like a comparator to `sort`.
|
|
1393
|
+
|
|
1394
|
+
### Long operations don't block
|
|
1395
|
+
|
|
1396
|
+
`train` (SQ, PQ, IVF), `build` (DiskANN) and `compact` are **time-sliced**: they do about 8 ms of work, hand the thread back to the event loop, and continue on the next tick. Timers, I/O and UI keep running during a 30-second `compact`. Measured on 64-dim data (`node bench/lag.bench.js`):
|
|
1397
|
+
|
|
1398
|
+
| operation | longest freeze before | longest freeze now |
|
|
1399
|
+
|---|---|---|
|
|
1400
|
+
| `SQ.train` 200k vectors | 115 ms | 17 ms |
|
|
1401
|
+
| `PQ.train` 5k vectors, k=256 | 7.2 s | 12 ms |
|
|
1402
|
+
| `ivf.train` 20k vectors, nlist=100 | 8.4 s | 26 ms |
|
|
1403
|
+
| `diskann.build` 3k vectors | 13.7 s | 14 ms |
|
|
1404
|
+
| `hnsw.compact` 5k vectors | 35.1 s | 16 ms |
|
|
1405
|
+
|
|
1406
|
+
The total time is the same within a few percent. A freeze can exceed 8 ms by the cost of one indivisible step — one graph insertion in `compact`, one node in `build`.
|
|
1407
|
+
|
|
1408
|
+
While a long operation runs:
|
|
1409
|
+
|
|
1410
|
+
- **Writes wait.** `add` / `delete` / `train` / `build` / `compact` go through one FIFO queue per index. When nothing long is running, a write executes immediately; otherwise it runs after the current job, in call order.
|
|
1411
|
+
- **Reads don't wait.** `search` and `stats` answer immediately from what is committed:
|
|
1412
|
+
- `compact` builds the new index on the side and swaps it in at the end, so searches see the old index until then, never a half-built one.
|
|
1413
|
+
- `train` computes the new model on the side and commits it at the end. In IVF, vectors already in the index are re-assigned to the new clusters, not dropped.
|
|
1414
|
+
- `build` replaces one node's neighbors at a time, so the graph is valid at every point and searches simply get better as it progresses.
|
|
1415
|
+
|
|
1416
|
+
The `xSync` quantizer methods (`trainSync`, ...) run the same code to completion in one go. That's their point: use them in workers, scripts and hot loops, never on a UI thread.
|
|
1417
|
+
|
|
1418
|
+
Time-slicing keeps the program responsive. It doesn't make the work faster: for that, run the library in a worker (it has no dependencies).
|
|
1419
|
+
|
|
1420
|
+
Nothing in the library reads or writes disk, network, or any external state on its own. Persistence is your `add` loop feeding from wherever, and your callback on `add` writing to wherever. Same for distribution, monitoring, and access control. `diskann-blocks` makes this the only way in — you cannot use it without wiring storage events, because there is nowhere else for the data to live.
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
---
|
|
12
1424
|
|
|
13
1425
|
## Roadmap
|
|
14
1426
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
1427
|
+
### Search
|
|
1428
|
+
|
|
1429
|
+
- SIMD / WASM kernels behind `searchBatch`: one query against many vectors per call (see the acceleration plan).
|
|
1430
|
+
- Float16 storage for full vectors (`Float16Array`): half the memory, almost no recall loss.
|
|
1431
|
+
|
|
1432
|
+
### Embeddings
|
|
1433
|
+
|
|
1434
|
+
- **v2**
|
|
1435
|
+
- Multi-core training with workers sharing one model (Hogwild over `SharedArrayBuffer`): roughly linear in the number of cores.
|
|
1436
|
+
- A `graph:neighbors` I/O event for graphs that live outside memory.
|
|
1437
|
+
- LINE.
|
|
1438
|
+
- Continuing training of existing embeddings with new nodes.
|
|
1439
|
+
- **v3**
|
|
1440
|
+
- metapath2vec for typed graphs (users, items, tags).
|
|
1441
|
+
- GraphSAGE inference.
|
|
1442
|
+
- **Rust / WASM**
|
|
1443
|
+
- The same structures with SIMD for the dot/update loops, where C reaches 3–20× the speed of scalar JS on this machine.
|
|
1444
|
+
|
|
1445
|
+
---
|
|
1446
|
+
|
|
1447
|
+
## Contributing
|
|
1448
|
+
|
|
1449
|
+
Issues and pull requests welcome. Particularly interested in:
|
|
1450
|
+
|
|
1451
|
+
- benchmarks against reference implementations (FAISS, hnswlib, DiskANN, gensim)
|
|
1452
|
+
- edge cases in delete / compact interaction
|
|
1453
|
+
|
|
19
1454
|
|
|
20
1455
|
## License
|
|
21
1456
|
|
|
22
|
-
|
|
1457
|
+
Apache-2.0
|