@hviana/sema 0.1.4 → 0.1.6
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/AGENTS.md +6 -5
- package/CITATION.cff +49 -0
- package/HOW_IT_WORKS.md +11 -12
- package/README.md +7 -5
- package/dist/example/train_base.js +13 -10
- package/dist/src/alu/src/index.js +1 -1
- package/dist/src/config.d.ts +16 -19
- package/dist/src/config.js +3 -8
- package/dist/src/index.d.ts +2 -2
- package/dist/src/index.js +2 -6
- package/dist/src/rabitq-ivf/src/database.d.ts +113 -0
- package/dist/src/rabitq-ivf/src/database.js +201 -0
- package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/index.d.ts +2 -5
- package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/index.js +1 -3
- package/dist/src/rabitq-ivf/src/ivf.d.ts +200 -0
- package/dist/src/rabitq-ivf/src/ivf.js +1165 -0
- package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/prng.d.ts +1 -1
- package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/prng.js +1 -1
- package/dist/src/store-sqlite.d.ts +26 -1
- package/dist/src/store-sqlite.js +190 -8
- package/dist/src/store.d.ts +2 -9
- package/dist/src/store.js +6 -23
- package/example/train_base.ts +13 -10
- package/package.json +2 -2
- package/src/alu/README.md +1 -1
- package/src/alu/src/index.ts +1 -1
- package/src/config.ts +19 -27
- package/src/index.ts +6 -11
- package/src/rabitq-ivf/README.md +56 -0
- package/src/rabitq-ivf/src/database.ts +276 -0
- package/src/{rabitq-hnsw → rabitq-ivf}/src/index.ts +2 -5
- package/src/rabitq-ivf/src/ivf.ts +1330 -0
- package/src/{rabitq-hnsw → rabitq-ivf}/src/prng.ts +1 -1
- package/src/store-sqlite.ts +196 -9
- package/src/store.ts +8 -32
- package/test/08-storage.test.mjs +3 -3
- package/test/14-scaling.test.mjs +2 -2
- package/test/35-ivf.test.mjs +263 -0
- package/test/36-bloom.test.mjs +123 -0
- package/dist/src/rabitq-hnsw/src/database.d.ts +0 -200
- package/dist/src/rabitq-hnsw/src/database.js +0 -388
- package/dist/src/rabitq-hnsw/src/heap.d.ts +0 -22
- package/dist/src/rabitq-hnsw/src/heap.js +0 -89
- package/dist/src/rabitq-hnsw/src/hnsw.d.ts +0 -125
- package/dist/src/rabitq-hnsw/src/hnsw.js +0 -474
- package/dist/src/rabitq-hnsw/src/store.d.ts +0 -162
- package/dist/src/rabitq-hnsw/src/store.js +0 -825
- package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +0 -1
- package/dist/src/rabitq-hnsw/test/hnsw.test.js +0 -948
- package/src/rabitq-hnsw/README.md +0 -303
- package/src/rabitq-hnsw/src/database.ts +0 -492
- package/src/rabitq-hnsw/src/heap.ts +0 -90
- package/src/rabitq-hnsw/src/hnsw.ts +0 -514
- package/src/rabitq-hnsw/src/store.ts +0 -994
- package/src/rabitq-hnsw/test/hnsw.test.ts +0 -1213
- /package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.d.ts +0 -0
- /package/dist/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.js +0 -0
- /package/src/{rabitq-hnsw → rabitq-ivf}/src/rabitq.ts +0 -0
|
@@ -1,388 +0,0 @@
|
|
|
1
|
-
import { HnswIndex } from "./hnsw.js";
|
|
2
|
-
import { RaBitQuantizer } from "./rabitq.js";
|
|
3
|
-
import { Store } from "./store.js";
|
|
4
|
-
const DEFAULTS = {
|
|
5
|
-
M: 16,
|
|
6
|
-
efConstruction: 200,
|
|
7
|
-
efSearch: 100,
|
|
8
|
-
queryBits: 8,
|
|
9
|
-
rotationRounds: 3,
|
|
10
|
-
seed: 0x1234abcd,
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* A persistent vector database: an HNSW graph over 1-bit RaBitQ codes (cosine),
|
|
14
|
-
* stored entirely in SQLite at `dbPath`. The graph IS the database -- there is no
|
|
15
|
-
* load/save step and no in-RAM copy of the data, so resident memory stays flat as
|
|
16
|
-
* the collection grows and the store survives process restarts. Reopening the
|
|
17
|
-
* same path restores the exact configuration (the rotation is regenerated from
|
|
18
|
-
* the persisted seed), so the codes already on disk remain valid.
|
|
19
|
-
*
|
|
20
|
-
* External ids are integers. The original float vectors are never retained --
|
|
21
|
-
* only the sign codes -- so a 256-d vector costs 32 bytes instead of 1024. `get`
|
|
22
|
-
* returns the stored code, which can be fed straight back into
|
|
23
|
-
* `insert`/`update`/`query`.
|
|
24
|
-
*/
|
|
25
|
-
export class VectorDatabase {
|
|
26
|
-
dim;
|
|
27
|
-
store;
|
|
28
|
-
quantizer;
|
|
29
|
-
index;
|
|
30
|
-
codeWords;
|
|
31
|
-
constructor(options) {
|
|
32
|
-
if (!options || typeof options.dbPath !== "string" ||
|
|
33
|
-
options.dbPath.length === 0) {
|
|
34
|
-
throw new Error("DatabaseOptions.dbPath (string) is required");
|
|
35
|
-
}
|
|
36
|
-
this.store = new Store(options.dbPath, options.cacheSizeMb ?? 64);
|
|
37
|
-
let cfg = this.store.loadConfig();
|
|
38
|
-
if (cfg === null) {
|
|
39
|
-
// Fresh database: derive the configuration from the options and persist it.
|
|
40
|
-
if (!Number.isInteger(options.dim) || options.dim <= 0) {
|
|
41
|
-
throw new Error("DatabaseOptions.dim must be a positive integer for a new database");
|
|
42
|
-
}
|
|
43
|
-
const dim = options.dim;
|
|
44
|
-
const centroid = options.centroid
|
|
45
|
-
? Float64Array.from(options.centroid)
|
|
46
|
-
: null;
|
|
47
|
-
const probe = new RaBitQuantizer(dim, { rounds: 1, seed: 0 });
|
|
48
|
-
cfg = {
|
|
49
|
-
dim,
|
|
50
|
-
m: options.M ?? DEFAULTS.M,
|
|
51
|
-
efConstruction: options.efConstruction ?? DEFAULTS.efConstruction,
|
|
52
|
-
efSearch: options.efSearch ?? DEFAULTS.efSearch,
|
|
53
|
-
queryBits: options.queryBits ?? DEFAULTS.queryBits,
|
|
54
|
-
rotationRounds: options.rotationRounds ?? DEFAULTS.rotationRounds,
|
|
55
|
-
seed: (options.seed ?? DEFAULTS.seed) >>> 0,
|
|
56
|
-
centroid,
|
|
57
|
-
codeWords: probe.codeWords,
|
|
58
|
-
paddedDim: probe.paddedDim,
|
|
59
|
-
};
|
|
60
|
-
this.store.initConfig(cfg);
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
// Reopened: keep the stored STRUCTURAL config, but allow tuning the two
|
|
64
|
-
// query-side knobs — efSearch and queryBits shape only how a query is
|
|
65
|
-
// executed, never what is stored, so honouring an explicit option here
|
|
66
|
-
// is safe and lets an existing database adopt better query settings.
|
|
67
|
-
if (options.efSearch !== undefined) {
|
|
68
|
-
cfg.efSearch = options.efSearch;
|
|
69
|
-
this.store.setEfSearch(options.efSearch);
|
|
70
|
-
}
|
|
71
|
-
if (options.queryBits !== undefined && options.queryBits !== cfg.queryBits) {
|
|
72
|
-
cfg.queryBits = options.queryBits;
|
|
73
|
-
this.store.setQueryBits(options.queryBits);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
this.dim = cfg.dim;
|
|
77
|
-
this.quantizer = new RaBitQuantizer(cfg.dim, {
|
|
78
|
-
queryBits: cfg.queryBits,
|
|
79
|
-
rounds: cfg.rotationRounds,
|
|
80
|
-
seed: cfg.seed,
|
|
81
|
-
centroid: cfg.centroid ?? undefined,
|
|
82
|
-
});
|
|
83
|
-
if (this.quantizer.codeWords !== cfg.codeWords) {
|
|
84
|
-
throw new Error("Stored code geometry does not match the quantizer (corrupt database?)");
|
|
85
|
-
}
|
|
86
|
-
this.codeWords = this.quantizer.codeWords;
|
|
87
|
-
this.index = new HnswIndex(this.quantizer, this.store, {
|
|
88
|
-
M: cfg.m,
|
|
89
|
-
efConstruction: cfg.efConstruction,
|
|
90
|
-
efSearch: cfg.efSearch,
|
|
91
|
-
seed: cfg.seed,
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
/** Number of live (non-deleted) vectors. */
|
|
95
|
-
get size() {
|
|
96
|
-
return this.index.size;
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Physical node count including tombstones from deletes/updates. When it grows
|
|
100
|
-
* well beyond `size`, call `compact()` to reclaim the space on disk.
|
|
101
|
-
*/
|
|
102
|
-
get physicalSize() {
|
|
103
|
-
return this.index.physicalSize;
|
|
104
|
-
}
|
|
105
|
-
get efSearch() {
|
|
106
|
-
return this.index.efSearch;
|
|
107
|
-
}
|
|
108
|
-
set efSearch(value) {
|
|
109
|
-
this.index.efSearch = value;
|
|
110
|
-
}
|
|
111
|
-
/** Distance computations performed during the most recent query. */
|
|
112
|
-
get lastQueryDistanceComputations() {
|
|
113
|
-
return this.index.lastQueryDistComps;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Storage row reads issued by the most recent query. This is the honest,
|
|
117
|
-
* cache-independent scalability metric: it counts every node/neighbour fetch
|
|
118
|
-
* that hit the database, so disabling the cache cannot hide a bad access pattern.
|
|
119
|
-
*/
|
|
120
|
-
get lastQueryStorageReads() {
|
|
121
|
-
return this.index.lastQueryStorageReads;
|
|
122
|
-
}
|
|
123
|
-
/** Per-vector storage cost of the index versus a Float32 baseline. */
|
|
124
|
-
get storage() {
|
|
125
|
-
const f32 = this.dim * 4;
|
|
126
|
-
const bpv = this.index.bytesPerVector;
|
|
127
|
-
return {
|
|
128
|
-
float32BytesPerVector: f32,
|
|
129
|
-
codeBytesPerVector: bpv,
|
|
130
|
-
bytesPerVector: bpv,
|
|
131
|
-
compressionRatio: f32 / bpv,
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
has(id) {
|
|
135
|
-
return this.store.idByExt(this.checkId(id)) !== null;
|
|
136
|
-
}
|
|
137
|
-
/** Stream every live external id (bounded memory). */
|
|
138
|
-
*keys() {
|
|
139
|
-
yield* this.store.liveExts();
|
|
140
|
-
}
|
|
141
|
-
/**
|
|
142
|
-
* Stream live entries whose INTERNAL id is > `after`, as
|
|
143
|
-
* {ext, internal} pairs in internal-id order. Internal ids are assigned
|
|
144
|
-
* monotonically at insert and preserved by {@link compact}, so the largest
|
|
145
|
-
* internal id a caller has seen is a durable incremental watermark: a later
|
|
146
|
-
* call with it yields exactly the entries added since.
|
|
147
|
-
*/
|
|
148
|
-
*keysSince(after) {
|
|
149
|
-
yield* this.store.liveExtsSince(after);
|
|
150
|
-
}
|
|
151
|
-
checkId(id) {
|
|
152
|
-
if (!Number.isInteger(id)) {
|
|
153
|
-
throw new Error(`External id must be an integer, got ${id}`);
|
|
154
|
-
}
|
|
155
|
-
return id;
|
|
156
|
-
}
|
|
157
|
-
/**
|
|
158
|
-
* Convert a value to code bytes, selecting by length:
|
|
159
|
-
* - `codeWords` elements -> an existing 1-bit code (e.g. from `get()`)
|
|
160
|
-
* - otherwise -> a raw `dim`-vector, encoded first
|
|
161
|
-
* `codeWords < dim` for any dim >= 2, so the two never collide.
|
|
162
|
-
*/
|
|
163
|
-
toCodeBytes(value) {
|
|
164
|
-
if (value.length === this.codeWords) {
|
|
165
|
-
return this.quantizer.codeToBytes(value);
|
|
166
|
-
}
|
|
167
|
-
if (value.length !== this.dim) {
|
|
168
|
-
throw new Error(`Vector dimension mismatch: expected ${this.dim}, got ${value.length}`);
|
|
169
|
-
}
|
|
170
|
-
return this.quantizer.codeToBytes(this.quantizer.encode(value));
|
|
171
|
-
}
|
|
172
|
-
// ------------------------------- CRUD ------------------------------------
|
|
173
|
-
/**
|
|
174
|
-
* Create. Accepts a raw `dim`-vector or a 1-bit code (`codeWords` words),
|
|
175
|
-
* detected by length. Throws if the id already exists (use `update`/`upsert`).
|
|
176
|
-
*/
|
|
177
|
-
insert(id, value) {
|
|
178
|
-
this.store.begin();
|
|
179
|
-
try {
|
|
180
|
-
this.insertCore(id, value);
|
|
181
|
-
this.store.commit();
|
|
182
|
-
}
|
|
183
|
-
catch (e) {
|
|
184
|
-
this.store.rollback();
|
|
185
|
-
throw e;
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
/** Insert with the caller owning the transaction (used by {@link upsertMany}).
|
|
189
|
-
* `ef` optionally narrows the construction beam for this one vector (a
|
|
190
|
-
* caller-declared cheap entry, e.g. a reach-only interior); omitted means
|
|
191
|
-
* the index's configured efConstruction. */
|
|
192
|
-
insertCore(id, value, ef) {
|
|
193
|
-
this.checkId(id);
|
|
194
|
-
if (this.store.idByExt(id) !== null) {
|
|
195
|
-
throw new Error(`External id already exists: ${id} (use update())`);
|
|
196
|
-
}
|
|
197
|
-
this.index.insert(id, this.toCodeBytes(value), ef);
|
|
198
|
-
}
|
|
199
|
-
upsert(id, value) {
|
|
200
|
-
const nodeId = this.store.idByExt(this.checkId(id));
|
|
201
|
-
if (nodeId === null) {
|
|
202
|
-
this.insert(id, value);
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
this.store.begin();
|
|
206
|
-
try {
|
|
207
|
-
this.updateAt(nodeId, id, value);
|
|
208
|
-
this.store.commit();
|
|
209
|
-
}
|
|
210
|
-
catch (e) {
|
|
211
|
-
this.store.rollback();
|
|
212
|
-
throw e;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Upsert many vectors under ONE transaction. The HNSW build touches the store
|
|
217
|
-
* on every wired edge, so a transaction per vector is one WAL commit per vector
|
|
218
|
-
* — which dominates a bulk load on disk. Wrapping the whole batch in a single
|
|
219
|
-
* transaction coalesces those commits into one while leaving the graph and its
|
|
220
|
-
* result identical (reads on the connection still see the uncommitted rows).
|
|
221
|
-
*
|
|
222
|
-
* This is purely about commit batching; it changes nothing about the storage
|
|
223
|
-
* model. Codes still live only in SQLite and are read on demand — the
|
|
224
|
-
* cache-independent per-operation read count is unchanged — so a batched load
|
|
225
|
-
* scales exactly as the per-item path does, just with far fewer fsyncs. A throw
|
|
226
|
-
* rolls the whole batch back, so the caller treats it as the per-item path on
|
|
227
|
-
* failure.
|
|
228
|
-
*/
|
|
229
|
-
upsertMany(entries) {
|
|
230
|
-
if (entries.length === 0)
|
|
231
|
-
return;
|
|
232
|
-
this.store.begin();
|
|
233
|
-
try {
|
|
234
|
-
for (const e of entries) {
|
|
235
|
-
const nodeId = this.store.idByExt(this.checkId(e.id));
|
|
236
|
-
if (nodeId !== null)
|
|
237
|
-
this.updateAt(nodeId, e.id, e.vector, e.ef);
|
|
238
|
-
else
|
|
239
|
-
this.insertCore(e.id, e.vector, e.ef);
|
|
240
|
-
}
|
|
241
|
-
this.store.commit();
|
|
242
|
-
}
|
|
243
|
-
catch (e) {
|
|
244
|
-
this.store.rollback();
|
|
245
|
-
throw e;
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Read the stored 1-bit code for an id (a copy as a Uint32Array), or null. The
|
|
250
|
-
* original vector is not retained; the code round-trips into insert/update/query.
|
|
251
|
-
*/
|
|
252
|
-
get(id) {
|
|
253
|
-
const nodeId = this.store.idByExt(this.checkId(id));
|
|
254
|
-
if (nodeId === null)
|
|
255
|
-
return null;
|
|
256
|
-
const rec = this.store.getNode(nodeId);
|
|
257
|
-
return rec ? this.quantizer.bytesToCode(rec.code) : null;
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Update the vector bound to an id (raw vector or code, detected by length).
|
|
261
|
-
* The previous node is tombstoned and a fresh one inserted. Throws if absent.
|
|
262
|
-
*/
|
|
263
|
-
update(id, value) {
|
|
264
|
-
this.store.begin();
|
|
265
|
-
try {
|
|
266
|
-
this.updateCore(id, value);
|
|
267
|
-
this.store.commit();
|
|
268
|
-
}
|
|
269
|
-
catch (e) {
|
|
270
|
-
this.store.rollback();
|
|
271
|
-
throw e;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
/** Update with the caller owning the transaction (used by {@link upsertMany}). */
|
|
275
|
-
updateCore(id, value) {
|
|
276
|
-
const oldId = this.store.idByExt(this.checkId(id));
|
|
277
|
-
if (oldId === null)
|
|
278
|
-
throw new Error(`Unknown external id: ${id}`);
|
|
279
|
-
this.updateAt(oldId, id, value);
|
|
280
|
-
}
|
|
281
|
-
/** Update when the live internal node id is already known.
|
|
282
|
-
*
|
|
283
|
-
* Skips the write entirely when the new code equals the stored one — the
|
|
284
|
-
* update would tombstone the node and replay a full graph insert for a
|
|
285
|
-
* byte-identical result. This is not a corner case: content-addressed
|
|
286
|
-
* callers re-upsert unchanged vectors wholesale after a restart (the same
|
|
287
|
-
* content always encodes to the same code), and each such no-op otherwise
|
|
288
|
-
* costs a tombstone (permanent routing/disk overhead until compaction)
|
|
289
|
-
* plus an O(ef·log N) reinsert. */
|
|
290
|
-
updateAt(nodeId, ext, value, ef) {
|
|
291
|
-
const bytes = this.toCodeBytes(value);
|
|
292
|
-
const rec = this.store.getNode(nodeId);
|
|
293
|
-
if (rec !== null && rec.code.length === bytes.length) {
|
|
294
|
-
let same = true;
|
|
295
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
296
|
-
if (rec.code[i] !== bytes[i]) {
|
|
297
|
-
same = false;
|
|
298
|
-
break;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
if (same)
|
|
302
|
-
return; // identical code — the update is a no-op
|
|
303
|
-
}
|
|
304
|
-
this.index.remove(nodeId); // frees the ext id, then re-insert under it
|
|
305
|
-
this.index.insert(ext, bytes, ef);
|
|
306
|
-
}
|
|
307
|
-
/**
|
|
308
|
-
* Delete many ids under ONE transaction — same commit-coalescing rationale
|
|
309
|
-
* as {@link upsertMany}: a tombstone per implicit transaction is one WAL
|
|
310
|
-
* commit per id, which dominates a bulk prune. Absent ids are skipped.
|
|
311
|
-
* Returns the number of vectors actually removed.
|
|
312
|
-
*/
|
|
313
|
-
deleteMany(ids) {
|
|
314
|
-
if (ids.length === 0)
|
|
315
|
-
return 0;
|
|
316
|
-
let removed = 0;
|
|
317
|
-
this.store.begin();
|
|
318
|
-
try {
|
|
319
|
-
for (const id of ids) {
|
|
320
|
-
const nodeId = this.store.idByExt(this.checkId(id));
|
|
321
|
-
if (nodeId !== null && this.index.remove(nodeId))
|
|
322
|
-
removed++;
|
|
323
|
-
}
|
|
324
|
-
this.store.commit();
|
|
325
|
-
}
|
|
326
|
-
catch (e) {
|
|
327
|
-
this.store.rollback();
|
|
328
|
-
throw e;
|
|
329
|
-
}
|
|
330
|
-
return removed;
|
|
331
|
-
}
|
|
332
|
-
/** Delete the vector bound to an id. Returns false if absent. */
|
|
333
|
-
delete(id) {
|
|
334
|
-
const nodeId = this.store.idByExt(this.checkId(id));
|
|
335
|
-
if (nodeId === null)
|
|
336
|
-
return false;
|
|
337
|
-
this.store.begin();
|
|
338
|
-
try {
|
|
339
|
-
this.index.remove(nodeId);
|
|
340
|
-
this.store.commit();
|
|
341
|
-
}
|
|
342
|
-
catch (e) {
|
|
343
|
-
this.store.rollback();
|
|
344
|
-
throw e;
|
|
345
|
-
}
|
|
346
|
-
return true;
|
|
347
|
-
}
|
|
348
|
-
/**
|
|
349
|
-
* Pre-fill the RAM caches (codes + neighbour lists) with sequential table
|
|
350
|
-
* scans, up to their budget-derived caps. Optional and purely a latency
|
|
351
|
-
* optimisation: a cold session otherwise pays the same warming through
|
|
352
|
-
* random point reads over its first minutes. Call once after open on a
|
|
353
|
-
* session that will do sustained inserts/queries. Returns rows warmed;
|
|
354
|
-
* a 0-budget database returns 0 immediately.
|
|
355
|
-
*/
|
|
356
|
-
warmCache() {
|
|
357
|
-
return this.store.warmCache();
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* Rebuild the graph from the live codes only, dropping tombstones and returning
|
|
361
|
-
* the freed pages to the filesystem. Lossless -- equivalent to the original
|
|
362
|
-
* build -- and needs no original vectors.
|
|
363
|
-
*/
|
|
364
|
-
compact() {
|
|
365
|
-
this.index.compact();
|
|
366
|
-
}
|
|
367
|
-
// ------------------------------ search -----------------------------------
|
|
368
|
-
/**
|
|
369
|
-
* k-NN search. The argument's length selects the mode:
|
|
370
|
-
* - `dim` elements -> a raw vector (accurate 4-bit-query estimator)
|
|
371
|
-
* - `codeWords` elements -> a 1-bit code (e.g. `get(id)`), by sign-bit Hamming
|
|
372
|
-
* Detection is by length, so a code is recognised whether it is a Uint32Array
|
|
373
|
-
* or a plain number[]. `codeWords < dim` for any dim >= 2, so they never collide.
|
|
374
|
-
*/
|
|
375
|
-
query(query, k = 10, opts) {
|
|
376
|
-
if (query.length === this.codeWords) {
|
|
377
|
-
return this.index.searchKnnByCode(this.quantizer.codeToBytes(query), k, opts?.ef);
|
|
378
|
-
}
|
|
379
|
-
if (query.length !== this.dim) {
|
|
380
|
-
throw new Error(`Vector dimension mismatch: expected ${this.dim}, got ${query.length}`);
|
|
381
|
-
}
|
|
382
|
-
return this.index.searchKnn(query, k, opts?.ef);
|
|
383
|
-
}
|
|
384
|
-
/** Close the underlying database. The instance must not be used afterwards. */
|
|
385
|
-
close() {
|
|
386
|
-
this.store.close();
|
|
387
|
-
}
|
|
388
|
-
}
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Binary heap over two parallel numeric arrays storing (key, value) pairs.
|
|
3
|
-
*
|
|
4
|
-
* When `minHeap` is true the smallest key sits at the root, otherwise the
|
|
5
|
-
* largest. Keys are distances, values are integer node ids. Parallel plain
|
|
6
|
-
* arrays are used (rather than an array of objects) to avoid per-element
|
|
7
|
-
* allocation in the search hot path.
|
|
8
|
-
*/
|
|
9
|
-
export declare class Heap {
|
|
10
|
-
readonly keys: number[];
|
|
11
|
-
readonly vals: number[];
|
|
12
|
-
private readonly minHeap;
|
|
13
|
-
constructor(minHeap: boolean);
|
|
14
|
-
get size(): number;
|
|
15
|
-
clear(): void;
|
|
16
|
-
topKey(): number;
|
|
17
|
-
topVal(): number;
|
|
18
|
-
/** true if `a` belongs closer to the root than `b`. */
|
|
19
|
-
private higher;
|
|
20
|
-
push(key: number, val: number): void;
|
|
21
|
-
pop(): void;
|
|
22
|
-
}
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Binary heap over two parallel numeric arrays storing (key, value) pairs.
|
|
3
|
-
*
|
|
4
|
-
* When `minHeap` is true the smallest key sits at the root, otherwise the
|
|
5
|
-
* largest. Keys are distances, values are integer node ids. Parallel plain
|
|
6
|
-
* arrays are used (rather than an array of objects) to avoid per-element
|
|
7
|
-
* allocation in the search hot path.
|
|
8
|
-
*/
|
|
9
|
-
export class Heap {
|
|
10
|
-
keys = [];
|
|
11
|
-
vals = [];
|
|
12
|
-
minHeap;
|
|
13
|
-
constructor(minHeap) {
|
|
14
|
-
this.minHeap = minHeap;
|
|
15
|
-
}
|
|
16
|
-
get size() {
|
|
17
|
-
return this.keys.length;
|
|
18
|
-
}
|
|
19
|
-
clear() {
|
|
20
|
-
this.keys.length = 0;
|
|
21
|
-
this.vals.length = 0;
|
|
22
|
-
}
|
|
23
|
-
topKey() {
|
|
24
|
-
return this.keys[0];
|
|
25
|
-
}
|
|
26
|
-
topVal() {
|
|
27
|
-
return this.vals[0];
|
|
28
|
-
}
|
|
29
|
-
/** true if `a` belongs closer to the root than `b`. */
|
|
30
|
-
higher(a, b) {
|
|
31
|
-
return this.minHeap ? a < b : a > b;
|
|
32
|
-
}
|
|
33
|
-
push(key, val) {
|
|
34
|
-
const keys = this.keys;
|
|
35
|
-
const vals = this.vals;
|
|
36
|
-
let i = keys.length;
|
|
37
|
-
keys.push(key);
|
|
38
|
-
vals.push(val);
|
|
39
|
-
while (i > 0) {
|
|
40
|
-
const parent = (i - 1) >> 1;
|
|
41
|
-
if (this.higher(keys[i], keys[parent])) {
|
|
42
|
-
const tk = keys[i];
|
|
43
|
-
keys[i] = keys[parent];
|
|
44
|
-
keys[parent] = tk;
|
|
45
|
-
const tv = vals[i];
|
|
46
|
-
vals[i] = vals[parent];
|
|
47
|
-
vals[parent] = tv;
|
|
48
|
-
i = parent;
|
|
49
|
-
}
|
|
50
|
-
else
|
|
51
|
-
break;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
pop() {
|
|
55
|
-
const keys = this.keys;
|
|
56
|
-
const vals = this.vals;
|
|
57
|
-
const n = keys.length;
|
|
58
|
-
if (n === 0)
|
|
59
|
-
return;
|
|
60
|
-
const lastKey = keys[n - 1];
|
|
61
|
-
const lastVal = vals[n - 1];
|
|
62
|
-
keys.pop();
|
|
63
|
-
vals.pop();
|
|
64
|
-
const m = keys.length;
|
|
65
|
-
if (m === 0)
|
|
66
|
-
return;
|
|
67
|
-
keys[0] = lastKey;
|
|
68
|
-
vals[0] = lastVal;
|
|
69
|
-
let i = 0;
|
|
70
|
-
while (true) {
|
|
71
|
-
const left = 2 * i + 1;
|
|
72
|
-
const right = left + 1;
|
|
73
|
-
let best = i;
|
|
74
|
-
if (left < m && this.higher(keys[left], keys[best]))
|
|
75
|
-
best = left;
|
|
76
|
-
if (right < m && this.higher(keys[right], keys[best]))
|
|
77
|
-
best = right;
|
|
78
|
-
if (best === i)
|
|
79
|
-
break;
|
|
80
|
-
const tk = keys[i];
|
|
81
|
-
keys[i] = keys[best];
|
|
82
|
-
keys[best] = tk;
|
|
83
|
-
const tv = vals[i];
|
|
84
|
-
vals[i] = vals[best];
|
|
85
|
-
vals[best] = tv;
|
|
86
|
-
i = best;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import { RaBitQuantizer } from "./rabitq.js";
|
|
2
|
-
import { Store } from "./store.js";
|
|
3
|
-
export interface HnswParams {
|
|
4
|
-
M: number;
|
|
5
|
-
efConstruction: number;
|
|
6
|
-
efSearch: number;
|
|
7
|
-
seed: number;
|
|
8
|
-
}
|
|
9
|
-
export interface KnnHit {
|
|
10
|
-
/** external (user) id */
|
|
11
|
-
id: number;
|
|
12
|
-
/** estimated cosine distance (1 - cosine) */
|
|
13
|
-
distance: number;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Hierarchical Navigable Small World graph (Malkov & Yashunin, 2018) backed by
|
|
17
|
-
* 1-bit RaBitQ codes that live in SQLite (see Store) rather than in RAM. The
|
|
18
|
-
* algorithm is the textbook one; the only difference is that codes and adjacency
|
|
19
|
-
* lists are read and written through the store on demand, so the resident set is
|
|
20
|
-
* the working set of the current operation -- never the whole graph.
|
|
21
|
-
*
|
|
22
|
-
* Distances use the codes throughout:
|
|
23
|
-
* - searching with a full-precision query uses RaBitQ's accurate estimator;
|
|
24
|
-
* - building the graph and searching by code compare two codes by sign-bit
|
|
25
|
-
* Hamming distance.
|
|
26
|
-
* Building on codes alone is what lets `compact` rebuild an honest index with no
|
|
27
|
-
* access to the original vectors.
|
|
28
|
-
*/
|
|
29
|
-
export declare class HnswIndex {
|
|
30
|
-
readonly M: number;
|
|
31
|
-
readonly Mmax0: number;
|
|
32
|
-
readonly efConstruction: number;
|
|
33
|
-
private readonly mL;
|
|
34
|
-
private readonly quantizer;
|
|
35
|
-
private readonly store;
|
|
36
|
-
private readonly seed;
|
|
37
|
-
private readonly levelRng;
|
|
38
|
-
private entry;
|
|
39
|
-
private maxLevel;
|
|
40
|
-
private live;
|
|
41
|
-
private total;
|
|
42
|
-
private _efSearch;
|
|
43
|
-
private readonly working;
|
|
44
|
-
private readonly visited;
|
|
45
|
-
private visitedTag;
|
|
46
|
-
private visitedEpoch;
|
|
47
|
-
private seenTag;
|
|
48
|
-
private markVisited;
|
|
49
|
-
private readonly candHeap;
|
|
50
|
-
private readonly resHeap;
|
|
51
|
-
private readonly singleEp;
|
|
52
|
-
private readonly idxScratch;
|
|
53
|
-
private readonly distScratch;
|
|
54
|
-
private readonly freshScratch;
|
|
55
|
-
private qCtx;
|
|
56
|
-
private refBytes;
|
|
57
|
-
private building;
|
|
58
|
-
lastQueryDistComps: number;
|
|
59
|
-
/** Storage row reads issued by the most recent query (cache-independent). */
|
|
60
|
-
lastQueryStorageReads: number;
|
|
61
|
-
constructor(quantizer: RaBitQuantizer, store: Store, params: HnswParams);
|
|
62
|
-
get size(): number;
|
|
63
|
-
get physicalSize(): number;
|
|
64
|
-
get bytesPerVector(): number;
|
|
65
|
-
get efSearch(): number;
|
|
66
|
-
set efSearch(v: number);
|
|
67
|
-
private persistState;
|
|
68
|
-
private randomLevel;
|
|
69
|
-
/**
|
|
70
|
-
* Fetch a node record into the operation's working set. The first touch in an
|
|
71
|
-
* op is a storage read; later touches in the same op reuse it. The set is
|
|
72
|
-
* cleared per op and bounded by efConstruction / efSearch, so storage reads
|
|
73
|
-
* per op equal the number of *distinct* nodes the op visits -- minimal, and
|
|
74
|
-
* independent of any cache.
|
|
75
|
-
*/
|
|
76
|
-
private node;
|
|
77
|
-
/** Prefetch several nodes into the working set with ONE batched storage
|
|
78
|
-
* read for the misses. Point queries per neighbour made statement
|
|
79
|
-
* dispatch — not distance arithmetic — the dominant cost of a large
|
|
80
|
-
* build; the batch keeps `reads` accounting identical per row. */
|
|
81
|
-
private fetchNodes;
|
|
82
|
-
/** Distance from the current source (query vector or reference code) to a node. */
|
|
83
|
-
private distOf;
|
|
84
|
-
/** Code-to-code distance between two stored nodes (graph wiring only). */
|
|
85
|
-
private codeDist;
|
|
86
|
-
/**
|
|
87
|
-
* SEARCH-LAYER (Algorithm 2). Frontier in `candHeap`, bounded result set in
|
|
88
|
-
* `resHeap` (non-deleted only). Deleted nodes are traversed for routing but
|
|
89
|
-
* never returned. `visited` is a per-call set sized by the nodes seen here.
|
|
90
|
-
*/
|
|
91
|
-
private searchLayer;
|
|
92
|
-
/** Greedy single-best descent from `fromLayer` down to (but not into) `toLayer`. */
|
|
93
|
-
private greedyDescend;
|
|
94
|
-
/**
|
|
95
|
-
* SELECT-NEIGHBORS-HEURISTIC (Algorithm 4) on codes. Picks up to `M` diverse
|
|
96
|
-
* neighbours from `candIds`, preferring those closer to `base` than to any
|
|
97
|
-
* already-chosen neighbour, then fills remaining slots with the closest
|
|
98
|
-
* leftovers (keep-pruned connections). Appends to `out`.
|
|
99
|
-
*/
|
|
100
|
-
private selectNeighbors;
|
|
101
|
-
/**
|
|
102
|
-
* Insert a vector's code under external id `ext`; returns the internal node id.
|
|
103
|
-
* All graph reads/writes go through the store; the caller owns the transaction.
|
|
104
|
-
*/
|
|
105
|
-
insert(ext: number, code: Uint8Array, efC?: number): number;
|
|
106
|
-
/** k-NN with a full-precision query vector (accurate estimator). */
|
|
107
|
-
searchKnn(vec: ArrayLike<number>, k: number, ef?: number): KnnHit[];
|
|
108
|
-
/** k-NN with an already-quantized code (sign-bit Hamming / angular distance). */
|
|
109
|
-
searchKnnByCode(codeBytes: Uint8Array, k: number, ef?: number): KnnHit[];
|
|
110
|
-
private collectKnn;
|
|
111
|
-
/** Tombstone a live node by internal id. Caller owns the transaction. */
|
|
112
|
-
remove(id: number): boolean;
|
|
113
|
-
/**
|
|
114
|
-
* Reclaim tombstones with a graph-preserving splice (see
|
|
115
|
-
* {@link Store.spliceCompact}): live nodes keep their internal ids and their
|
|
116
|
-
* wiring; each dead neighbour is replaced by its own live neighbours. Codes
|
|
117
|
-
* are untouched, so the index loses nothing beyond what deletion itself
|
|
118
|
-
* removes. The previous implementation replayed every live code through a
|
|
119
|
-
* full HNSW insert — O(live · ef · log N) storage reads, HOURS on a trained
|
|
120
|
-
* multi-million-node store, inside one WAL-bloating transaction. The splice
|
|
121
|
-
* is a streaming pass with batched commits, then a VACUUM to return the
|
|
122
|
-
* freed pages.
|
|
123
|
-
*/
|
|
124
|
-
compact(): void;
|
|
125
|
-
}
|