@hviana/sema 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/AGENTS.md +470 -0
- package/AUTHORS.md +12 -0
- package/COMMERCIAL-LICENSE.md +19 -0
- package/CONTRIBUTING.md +15 -0
- package/HOW_IT_WORKS.md +4210 -0
- package/LICENSE.md +117 -0
- package/README.md +290 -0
- package/TRADEMARKS.md +19 -0
- package/example/demo.ts +46 -0
- package/example/train_base.ts +2675 -0
- package/index.html +893 -0
- package/package.json +25 -0
- package/src/alphabet.ts +34 -0
- package/src/alu/README.md +332 -0
- package/src/alu/src/alu.ts +541 -0
- package/src/alu/src/expr.ts +339 -0
- package/src/alu/src/index.ts +115 -0
- package/src/alu/src/kernel-arith.ts +377 -0
- package/src/alu/src/kernel-bits.ts +199 -0
- package/src/alu/src/kernel-logic.ts +102 -0
- package/src/alu/src/kernel-nd.ts +235 -0
- package/src/alu/src/kernel-numeric.ts +466 -0
- package/src/alu/src/operation.ts +344 -0
- package/src/alu/src/parser.ts +574 -0
- package/src/alu/src/resonance.ts +161 -0
- package/src/alu/src/text.ts +83 -0
- package/src/alu/src/value.ts +327 -0
- package/src/alu/test/alu.test.ts +1004 -0
- package/src/bytes.ts +62 -0
- package/src/config.ts +227 -0
- package/src/derive/README.md +295 -0
- package/src/derive/src/deduction.ts +263 -0
- package/src/derive/src/index.ts +24 -0
- package/src/derive/src/priority-queue.ts +70 -0
- package/src/derive/src/rewrite.ts +127 -0
- package/src/derive/src/trie.ts +242 -0
- package/src/derive/test/derive.test.ts +137 -0
- package/src/extension.ts +42 -0
- package/src/geometry.ts +511 -0
- package/src/index.ts +38 -0
- package/src/ingest-cache.ts +224 -0
- package/src/mind/articulation.ts +137 -0
- package/src/mind/attention.ts +1061 -0
- package/src/mind/canonical.ts +107 -0
- package/src/mind/graph-search.ts +1100 -0
- package/src/mind/index.ts +18 -0
- package/src/mind/junction.ts +347 -0
- package/src/mind/learning.ts +246 -0
- package/src/mind/match.ts +507 -0
- package/src/mind/mechanisms/alu.ts +33 -0
- package/src/mind/mechanisms/cast.ts +568 -0
- package/src/mind/mechanisms/confluence.ts +268 -0
- package/src/mind/mechanisms/cover.ts +248 -0
- package/src/mind/mechanisms/extraction.ts +422 -0
- package/src/mind/mechanisms/recall.ts +241 -0
- package/src/mind/mind.ts +483 -0
- package/src/mind/pipeline-mechanism.ts +326 -0
- package/src/mind/pipeline.ts +300 -0
- package/src/mind/primitives.ts +201 -0
- package/src/mind/rationale.ts +275 -0
- package/src/mind/reasoning.ts +198 -0
- package/src/mind/recognition.ts +234 -0
- package/src/mind/resonance.ts +0 -0
- package/src/mind/trace.ts +108 -0
- package/src/mind/traverse.ts +556 -0
- package/src/mind/types.ts +281 -0
- package/src/rabitq-hnsw/README.md +303 -0
- package/src/rabitq-hnsw/src/database.ts +492 -0
- package/src/rabitq-hnsw/src/heap.ts +90 -0
- package/src/rabitq-hnsw/src/hnsw.ts +514 -0
- package/src/rabitq-hnsw/src/index.ts +15 -0
- package/src/rabitq-hnsw/src/prng.ts +39 -0
- package/src/rabitq-hnsw/src/rabitq.ts +308 -0
- package/src/rabitq-hnsw/src/store.ts +994 -0
- package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
- package/src/store-sqlite.ts +928 -0
- package/src/store.ts +2148 -0
- package/src/vec.ts +124 -0
- package/test/00-extract.test.mjs +151 -0
- package/test/01-floor.test.mjs +20 -0
- package/test/02-roundtrip.test.mjs +83 -0
- package/test/03-recall.test.mjs +98 -0
- package/test/04-think.test.mjs +627 -0
- package/test/05-concepts.test.mjs +84 -0
- package/test/08-storage.test.mjs +948 -0
- package/test/09-edges.test.mjs +65 -0
- package/test/11-universality.test.mjs +180 -0
- package/test/13-conversation.test.mjs +228 -0
- package/test/14-scaling.test.mjs +503 -0
- package/test/15-decomposition-gap.test.mjs +0 -0
- package/test/16-bridge.test.mjs +250 -0
- package/test/17-intelligence.test.mjs +240 -0
- package/test/18-alu.test.mjs +209 -0
- package/test/19-nd.test.mjs +254 -0
- package/test/20-stability.test.mjs +489 -0
- package/test/21-partial.test.mjs +158 -0
- package/test/22-multihop.test.mjs +130 -0
- package/test/23-rationale.test.mjs +316 -0
- package/test/24-generalization.test.mjs +416 -0
- package/test/25-embedding.test.mjs +75 -0
- package/test/26-cooperative.test.mjs +89 -0
- package/test/27-saturation-drop.test.mjs +637 -0
- package/test/28-unknowable.test.mjs +88 -0
- package/test/29-counterfactual.test.mjs +476 -0
- package/test/30-conflict-resolution.test.mjs +166 -0
- package/test/31-audit.test.mjs +288 -0
- package/test/32-confluence.test.mjs +173 -0
- package/test/33-multi-candidate.test.mjs +222 -0
- package/test/34-cross-region.test.mjs +252 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import { Heap } from "./heap.js";
|
|
2
|
+
import { Prng } from "./prng.js";
|
|
3
|
+
import { QueryContext, RaBitQuantizer } from "./rabitq.js";
|
|
4
|
+
import { NodeRec, Store } from "./store.js";
|
|
5
|
+
|
|
6
|
+
export interface HnswParams {
|
|
7
|
+
M: number;
|
|
8
|
+
efConstruction: number;
|
|
9
|
+
efSearch: number;
|
|
10
|
+
seed: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface KnnHit {
|
|
14
|
+
/** external (user) id */
|
|
15
|
+
id: number;
|
|
16
|
+
/** estimated cosine distance (1 - cosine) */
|
|
17
|
+
distance: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Hierarchical Navigable Small World graph (Malkov & Yashunin, 2018) backed by
|
|
22
|
+
* 1-bit RaBitQ codes that live in SQLite (see Store) rather than in RAM. The
|
|
23
|
+
* algorithm is the textbook one; the only difference is that codes and adjacency
|
|
24
|
+
* lists are read and written through the store on demand, so the resident set is
|
|
25
|
+
* the working set of the current operation -- never the whole graph.
|
|
26
|
+
*
|
|
27
|
+
* Distances use the codes throughout:
|
|
28
|
+
* - searching with a full-precision query uses RaBitQ's accurate estimator;
|
|
29
|
+
* - building the graph and searching by code compare two codes by sign-bit
|
|
30
|
+
* Hamming distance.
|
|
31
|
+
* Building on codes alone is what lets `compact` rebuild an honest index with no
|
|
32
|
+
* access to the original vectors.
|
|
33
|
+
*/
|
|
34
|
+
export class HnswIndex {
|
|
35
|
+
readonly M: number;
|
|
36
|
+
readonly Mmax0: number;
|
|
37
|
+
readonly efConstruction: number;
|
|
38
|
+
|
|
39
|
+
private readonly mL: number;
|
|
40
|
+
private readonly quantizer: RaBitQuantizer;
|
|
41
|
+
private readonly store: Store;
|
|
42
|
+
private readonly seed: number;
|
|
43
|
+
private readonly levelRng: Prng;
|
|
44
|
+
|
|
45
|
+
// tiny global scalars, cached from meta and written through on change
|
|
46
|
+
private entry: number;
|
|
47
|
+
private maxLevel: number;
|
|
48
|
+
private live: number;
|
|
49
|
+
private total: number;
|
|
50
|
+
private _efSearch: number;
|
|
51
|
+
|
|
52
|
+
// Per-operation working set: the records the current insert/query is actively
|
|
53
|
+
// comparing. Cleared at the start of every op and bounded by efConstruction /
|
|
54
|
+
// efSearch (the nodes one operation can touch), never by the collection size.
|
|
55
|
+
// This is the algorithm's working memory -- it makes each touched node cost one
|
|
56
|
+
// storage read per op -- not a tunable cache. The only cache is SQLite's page
|
|
57
|
+
// cache (see Store), sized in MB.
|
|
58
|
+
private readonly working = new Map<number, NodeRec>();
|
|
59
|
+
private readonly visited = new Set<number>();
|
|
60
|
+
// Epoch-tagged visited marks — the Set above without per-candidate hashing:
|
|
61
|
+
// visitedTag[id] === visitedEpoch means "seen this operation", and bumping
|
|
62
|
+
// the epoch clears the whole set in O(1). Semantically IDENTICAL to the
|
|
63
|
+
// Set (results never differ); used only when the store has a cache budget,
|
|
64
|
+
// because the array is 4 B per internal id — amortized working memory that
|
|
65
|
+
// grows with the collection, which the cacheSizeMb:0 flat-memory mode must
|
|
66
|
+
// not pay. The epoch wrap (2³²−1 ops) refills the array once.
|
|
67
|
+
private visitedTag = new Uint32Array(1024);
|
|
68
|
+
private visitedEpoch = 0;
|
|
69
|
+
|
|
70
|
+
private seenTag(id: number, epoch: number): boolean {
|
|
71
|
+
return id < this.visitedTag.length && this.visitedTag[id] === epoch;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private markVisited(id: number, epoch: number): void {
|
|
75
|
+
if (id >= this.visitedTag.length) {
|
|
76
|
+
const grown = new Uint32Array(
|
|
77
|
+
Math.max(id + 1, this.visitedTag.length * 2),
|
|
78
|
+
);
|
|
79
|
+
grown.set(this.visitedTag);
|
|
80
|
+
this.visitedTag = grown;
|
|
81
|
+
}
|
|
82
|
+
this.visitedTag[id] = epoch;
|
|
83
|
+
}
|
|
84
|
+
private readonly candHeap = new Heap(true); // min-heap: nearest first
|
|
85
|
+
private readonly resHeap = new Heap(false); // max-heap: farthest first
|
|
86
|
+
private readonly singleEp: number[] = [0];
|
|
87
|
+
private readonly idxScratch: number[] = [];
|
|
88
|
+
private readonly distScratch: number[] = [];
|
|
89
|
+
private readonly freshScratch: number[] = [];
|
|
90
|
+
|
|
91
|
+
// distance dispatch: a full-precision query sets qCtx; building or a code
|
|
92
|
+
// query sets refBytes (code<->code). `building` only suppresses the counter.
|
|
93
|
+
private qCtx: QueryContext | null = null;
|
|
94
|
+
private refBytes: Uint8Array | null = null;
|
|
95
|
+
private building = false;
|
|
96
|
+
|
|
97
|
+
lastQueryDistComps = 0;
|
|
98
|
+
/** Storage row reads issued by the most recent query (cache-independent). */
|
|
99
|
+
lastQueryStorageReads = 0;
|
|
100
|
+
|
|
101
|
+
constructor(quantizer: RaBitQuantizer, store: Store, params: HnswParams) {
|
|
102
|
+
this.quantizer = quantizer;
|
|
103
|
+
this.store = store;
|
|
104
|
+
this.M = params.M;
|
|
105
|
+
this.Mmax0 = this.M * 2;
|
|
106
|
+
this.efConstruction = params.efConstruction;
|
|
107
|
+
this._efSearch = params.efSearch;
|
|
108
|
+
this.mL = 1 / Math.log(this.M);
|
|
109
|
+
this.seed = params.seed >>> 0;
|
|
110
|
+
|
|
111
|
+
const s = store.loadState();
|
|
112
|
+
this.entry = s.entryPoint;
|
|
113
|
+
this.maxLevel = s.maxLevel;
|
|
114
|
+
this.live = s.live;
|
|
115
|
+
this.total = s.total;
|
|
116
|
+
this.levelRng = new Prng(this.seed);
|
|
117
|
+
this.levelRng.restore(s.rng);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
get size(): number {
|
|
121
|
+
return this.live;
|
|
122
|
+
}
|
|
123
|
+
get physicalSize(): number {
|
|
124
|
+
return this.total;
|
|
125
|
+
}
|
|
126
|
+
get bytesPerVector(): number {
|
|
127
|
+
return this.quantizer.codeWords * 4;
|
|
128
|
+
}
|
|
129
|
+
get efSearch(): number {
|
|
130
|
+
return this._efSearch;
|
|
131
|
+
}
|
|
132
|
+
set efSearch(v: number) {
|
|
133
|
+
this._efSearch = Math.max(1, v | 0);
|
|
134
|
+
this.store.setEfSearch(this._efSearch);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private persistState(): void {
|
|
138
|
+
this.store.saveState({
|
|
139
|
+
entryPoint: this.entry,
|
|
140
|
+
maxLevel: this.maxLevel,
|
|
141
|
+
live: this.live,
|
|
142
|
+
total: this.total,
|
|
143
|
+
rng: this.levelRng.snapshot(),
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private randomLevel(): number {
|
|
148
|
+
let u = this.levelRng.next();
|
|
149
|
+
if (u < 1e-12) u = 1e-12;
|
|
150
|
+
return Math.floor(-Math.log(u) * this.mL);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Fetch a node record into the operation's working set. The first touch in an
|
|
155
|
+
* op is a storage read; later touches in the same op reuse it. The set is
|
|
156
|
+
* cleared per op and bounded by efConstruction / efSearch, so storage reads
|
|
157
|
+
* per op equal the number of *distinct* nodes the op visits -- minimal, and
|
|
158
|
+
* independent of any cache.
|
|
159
|
+
*/
|
|
160
|
+
private node(id: number): NodeRec {
|
|
161
|
+
const hit = this.working.get(id);
|
|
162
|
+
if (hit !== undefined) return hit;
|
|
163
|
+
const rec = this.store.getNode(id);
|
|
164
|
+
if (rec === null) throw new Error(`node ${id} not found`);
|
|
165
|
+
this.working.set(id, rec);
|
|
166
|
+
return rec;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Prefetch several nodes into the working set with ONE batched storage
|
|
170
|
+
* read for the misses. Point queries per neighbour made statement
|
|
171
|
+
* dispatch — not distance arithmetic — the dominant cost of a large
|
|
172
|
+
* build; the batch keeps `reads` accounting identical per row. */
|
|
173
|
+
private fetchNodes(ids: number[], count = ids.length): void {
|
|
174
|
+
// getNodesInto skips ids already present in `working` itself — no
|
|
175
|
+
// second pre-filter pass over the same map here.
|
|
176
|
+
this.store.getNodesInto(ids, this.working, count);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Distance from the current source (query vector or reference code) to a node. */
|
|
180
|
+
private distOf(rec: NodeRec): number {
|
|
181
|
+
if (this.qCtx !== null) {
|
|
182
|
+
this.lastQueryDistComps++;
|
|
183
|
+
return this.quantizer.estimate(rec.code, 0, this.qCtx);
|
|
184
|
+
}
|
|
185
|
+
if (!this.building) this.lastQueryDistComps++;
|
|
186
|
+
return this.quantizer.codeDistanceBytes(
|
|
187
|
+
this.refBytes as Uint8Array,
|
|
188
|
+
rec.code,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Code-to-code distance between two stored nodes (graph wiring only). */
|
|
193
|
+
private codeDist(a: number, b: number): number {
|
|
194
|
+
return this.quantizer.codeDistanceBytes(
|
|
195
|
+
this.node(a).code,
|
|
196
|
+
this.node(b).code,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* SEARCH-LAYER (Algorithm 2). Frontier in `candHeap`, bounded result set in
|
|
202
|
+
* `resHeap` (non-deleted only). Deleted nodes are traversed for routing but
|
|
203
|
+
* never returned. `visited` is a per-call set sized by the nodes seen here.
|
|
204
|
+
*/
|
|
205
|
+
private searchLayer(entryPoints: number[], ef: number, layer: number): void {
|
|
206
|
+
const cand = this.candHeap;
|
|
207
|
+
const res = this.resHeap;
|
|
208
|
+
cand.clear();
|
|
209
|
+
res.clear();
|
|
210
|
+
// Visited marks: epoch tags when RAM-for-speed is allowed, the plain Set
|
|
211
|
+
// in flat-memory mode. Identical semantics either way.
|
|
212
|
+
const useTags = this.store.cacheEnabled;
|
|
213
|
+
let epoch = 0;
|
|
214
|
+
const visited = this.visited;
|
|
215
|
+
if (useTags) {
|
|
216
|
+
epoch = ++this.visitedEpoch;
|
|
217
|
+
if (epoch === 0xffffffff) {
|
|
218
|
+
this.visitedTag.fill(0);
|
|
219
|
+
epoch = this.visitedEpoch = 1;
|
|
220
|
+
}
|
|
221
|
+
} else {
|
|
222
|
+
visited.clear();
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
for (let k = 0; k < entryPoints.length; k++) {
|
|
226
|
+
const ep = entryPoints[k];
|
|
227
|
+
if (useTags) {
|
|
228
|
+
if (this.seenTag(ep, epoch)) continue;
|
|
229
|
+
this.markVisited(ep, epoch);
|
|
230
|
+
} else {
|
|
231
|
+
if (visited.has(ep)) continue;
|
|
232
|
+
visited.add(ep);
|
|
233
|
+
}
|
|
234
|
+
const rec = this.node(ep);
|
|
235
|
+
const d = this.distOf(rec);
|
|
236
|
+
cand.push(d, ep);
|
|
237
|
+
if (rec.deleted === 0) {
|
|
238
|
+
res.push(d, ep);
|
|
239
|
+
if (res.size > ef) res.pop();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
while (cand.size > 0) {
|
|
244
|
+
const cd = cand.topKey();
|
|
245
|
+
if (res.size >= ef && cd > res.topKey()) break;
|
|
246
|
+
const c = cand.topVal();
|
|
247
|
+
cand.pop();
|
|
248
|
+
const nbrs = this.store.getNeighbors(c, layer);
|
|
249
|
+
if (nbrs === null) continue;
|
|
250
|
+
// Batch: mark the unvisited neighbours, fetch their codes in one
|
|
251
|
+
// storage read, then score them in the original order.
|
|
252
|
+
const fresh = this.freshScratch;
|
|
253
|
+
fresh.length = 0;
|
|
254
|
+
for (let i = 0; i < nbrs.length; i++) {
|
|
255
|
+
const e = nbrs[i];
|
|
256
|
+
if (useTags) {
|
|
257
|
+
if (this.seenTag(e, epoch)) continue;
|
|
258
|
+
this.markVisited(e, epoch);
|
|
259
|
+
} else {
|
|
260
|
+
if (visited.has(e)) continue;
|
|
261
|
+
visited.add(e);
|
|
262
|
+
}
|
|
263
|
+
fresh.push(e);
|
|
264
|
+
}
|
|
265
|
+
if (fresh.length > 1) this.fetchNodes(fresh);
|
|
266
|
+
for (let i = 0; i < fresh.length; i++) {
|
|
267
|
+
const e = fresh[i];
|
|
268
|
+
const rec = this.node(e);
|
|
269
|
+
const d = this.distOf(rec);
|
|
270
|
+
const worst = res.size > 0 ? res.topKey() : Infinity;
|
|
271
|
+
if (res.size < ef || d < worst) {
|
|
272
|
+
cand.push(d, e);
|
|
273
|
+
if (rec.deleted === 0) {
|
|
274
|
+
res.push(d, e);
|
|
275
|
+
if (res.size > ef) res.pop();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Greedy single-best descent from `fromLayer` down to (but not into) `toLayer`. */
|
|
283
|
+
private greedyDescend(
|
|
284
|
+
entry: number,
|
|
285
|
+
fromLayer: number,
|
|
286
|
+
toLayer: number,
|
|
287
|
+
): number {
|
|
288
|
+
let cur = entry;
|
|
289
|
+
const ep = this.singleEp;
|
|
290
|
+
for (let layer = fromLayer; layer > toLayer; layer--) {
|
|
291
|
+
ep[0] = cur;
|
|
292
|
+
this.searchLayer(ep, 1, layer);
|
|
293
|
+
if (this.resHeap.size > 0) cur = this.resHeap.vals[0];
|
|
294
|
+
}
|
|
295
|
+
return cur;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* SELECT-NEIGHBORS-HEURISTIC (Algorithm 4) on codes. Picks up to `M` diverse
|
|
300
|
+
* neighbours from `candIds`, preferring those closer to `base` than to any
|
|
301
|
+
* already-chosen neighbour, then fills remaining slots with the closest
|
|
302
|
+
* leftovers (keep-pruned connections). Appends to `out`.
|
|
303
|
+
*/
|
|
304
|
+
private selectNeighbors(
|
|
305
|
+
base: number,
|
|
306
|
+
candIds: number[],
|
|
307
|
+
count: number,
|
|
308
|
+
M: number,
|
|
309
|
+
out: number[],
|
|
310
|
+
): void {
|
|
311
|
+
const idx = this.idxScratch;
|
|
312
|
+
const ds = this.distScratch;
|
|
313
|
+
this.fetchNodes(candIds, count); // one batched read for the misses
|
|
314
|
+
idx.length = count;
|
|
315
|
+
ds.length = count;
|
|
316
|
+
for (let i = 0; i < count; i++) {
|
|
317
|
+
idx[i] = i;
|
|
318
|
+
ds[i] = this.codeDist(base, candIds[i]);
|
|
319
|
+
}
|
|
320
|
+
idx.sort((a, b) => ds[a] - ds[b]);
|
|
321
|
+
for (let s = 0; s < count; s++) {
|
|
322
|
+
if (out.length >= M) break;
|
|
323
|
+
const i = idx[s];
|
|
324
|
+
const cid = candIds[i];
|
|
325
|
+
if (cid === base) continue;
|
|
326
|
+
const cd = ds[i];
|
|
327
|
+
let keep = true;
|
|
328
|
+
for (let j = 0; j < out.length; j++) {
|
|
329
|
+
if (this.codeDist(cid, out[j]) < cd) {
|
|
330
|
+
keep = false;
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (keep) out.push(cid);
|
|
335
|
+
}
|
|
336
|
+
if (out.length < M) {
|
|
337
|
+
for (let s = 0; s < count && out.length < M; s++) {
|
|
338
|
+
const cid = candIds[idx[s]];
|
|
339
|
+
if (cid === base) continue;
|
|
340
|
+
let dup = false;
|
|
341
|
+
for (let j = 0; j < out.length; j++) {
|
|
342
|
+
if (out[j] === cid) {
|
|
343
|
+
dup = true;
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (!dup) out.push(cid);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Insert a vector's code under external id `ext`; returns the internal node id.
|
|
354
|
+
* All graph reads/writes go through the store; the caller owns the transaction.
|
|
355
|
+
*/
|
|
356
|
+
insert(ext: number, code: Uint8Array, efC?: number): number {
|
|
357
|
+
const ef = efC !== undefined && efC >= 1
|
|
358
|
+
? Math.min(efC, this.efConstruction)
|
|
359
|
+
: this.efConstruction;
|
|
360
|
+
this.working.clear();
|
|
361
|
+
const level = this.randomLevel();
|
|
362
|
+
const id = this.store.addNode(ext, level, code);
|
|
363
|
+
this.total++;
|
|
364
|
+
this.working.set(id, { code, deleted: 0, ext });
|
|
365
|
+
|
|
366
|
+
if (this.entry === -1) {
|
|
367
|
+
this.entry = id;
|
|
368
|
+
this.maxLevel = level;
|
|
369
|
+
this.live++;
|
|
370
|
+
this.persistState();
|
|
371
|
+
return id;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
this.qCtx = null;
|
|
375
|
+
this.refBytes = code;
|
|
376
|
+
this.building = true;
|
|
377
|
+
|
|
378
|
+
let entry = this.entry;
|
|
379
|
+
const topLayer = this.maxLevel;
|
|
380
|
+
if (topLayer > level) entry = this.greedyDescend(entry, topLayer, level);
|
|
381
|
+
|
|
382
|
+
let entryPoints = [entry];
|
|
383
|
+
const startLayer = Math.min(topLayer, level);
|
|
384
|
+
for (let layer = startLayer; layer >= 0; layer--) {
|
|
385
|
+
this.searchLayer(entryPoints, ef, layer);
|
|
386
|
+
const res = this.resHeap;
|
|
387
|
+
const wCount = res.size;
|
|
388
|
+
|
|
389
|
+
const selected: number[] = [];
|
|
390
|
+
this.selectNeighbors(id, res.vals, wCount, this.M, selected);
|
|
391
|
+
if (selected.length > 0) this.store.setNeighbors(id, layer, selected);
|
|
392
|
+
|
|
393
|
+
const cap = layer === 0 ? this.Mmax0 : this.M;
|
|
394
|
+
for (let s = 0; s < selected.length; s++) {
|
|
395
|
+
const nb = selected[s];
|
|
396
|
+
const cur = this.store.getNeighbors(nb, layer);
|
|
397
|
+
const list: number[] = cur ? Array.from(cur) : [];
|
|
398
|
+
list.push(id);
|
|
399
|
+
if (list.length > cap) {
|
|
400
|
+
const pruned: number[] = [];
|
|
401
|
+
this.selectNeighbors(nb, list, list.length, cap, pruned);
|
|
402
|
+
this.store.setNeighbors(nb, layer, pruned);
|
|
403
|
+
} else {
|
|
404
|
+
this.store.setNeighbors(nb, layer, list);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
if (wCount > 0) {
|
|
409
|
+
const next = new Array<number>(wCount);
|
|
410
|
+
for (let i = 0; i < wCount; i++) next[i] = res.vals[i];
|
|
411
|
+
entryPoints = next;
|
|
412
|
+
} else {
|
|
413
|
+
entryPoints = [entry];
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
this.building = false;
|
|
418
|
+
this.refBytes = null;
|
|
419
|
+
this.live++;
|
|
420
|
+
if (level > this.maxLevel) {
|
|
421
|
+
this.maxLevel = level;
|
|
422
|
+
this.entry = id;
|
|
423
|
+
}
|
|
424
|
+
this.persistState();
|
|
425
|
+
return id;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** k-NN with a full-precision query vector (accurate estimator). */
|
|
429
|
+
searchKnn(vec: ArrayLike<number>, k: number, ef?: number): KnnHit[] {
|
|
430
|
+
this.lastQueryDistComps = 0;
|
|
431
|
+
this.store.resetReads();
|
|
432
|
+
this.working.clear();
|
|
433
|
+
this.building = false;
|
|
434
|
+
this.refBytes = null;
|
|
435
|
+
if (this.entry === -1 || k <= 0) {
|
|
436
|
+
this.lastQueryStorageReads = 0;
|
|
437
|
+
return [];
|
|
438
|
+
}
|
|
439
|
+
this.qCtx = this.quantizer.prepareQuery(vec);
|
|
440
|
+
const hits = this.collectKnn(k, Math.max(ef ?? this._efSearch, k));
|
|
441
|
+
this.qCtx = null;
|
|
442
|
+
this.lastQueryStorageReads = this.store.reads;
|
|
443
|
+
return hits;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** k-NN with an already-quantized code (sign-bit Hamming / angular distance). */
|
|
447
|
+
searchKnnByCode(codeBytes: Uint8Array, k: number, ef?: number): KnnHit[] {
|
|
448
|
+
this.lastQueryDistComps = 0;
|
|
449
|
+
this.store.resetReads();
|
|
450
|
+
this.working.clear();
|
|
451
|
+
this.building = false;
|
|
452
|
+
this.qCtx = null;
|
|
453
|
+
if (this.entry === -1 || k <= 0) {
|
|
454
|
+
this.lastQueryStorageReads = 0;
|
|
455
|
+
return [];
|
|
456
|
+
}
|
|
457
|
+
this.refBytes = codeBytes;
|
|
458
|
+
const hits = this.collectKnn(k, Math.max(ef ?? this._efSearch, k));
|
|
459
|
+
this.refBytes = null;
|
|
460
|
+
this.lastQueryStorageReads = this.store.reads;
|
|
461
|
+
return hits;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private collectKnn(k: number, efs: number): KnnHit[] {
|
|
465
|
+
let entry = this.entry;
|
|
466
|
+
if (this.maxLevel > 0) entry = this.greedyDescend(entry, this.maxLevel, 0);
|
|
467
|
+
this.singleEp[0] = entry;
|
|
468
|
+
this.searchLayer(this.singleEp, efs, 0);
|
|
469
|
+
|
|
470
|
+
const res = this.resHeap;
|
|
471
|
+
const n = res.size;
|
|
472
|
+
const hits: KnnHit[] = new Array(n);
|
|
473
|
+
for (let i = 0; i < n; i++) {
|
|
474
|
+
let d = res.keys[i];
|
|
475
|
+
if (d < 0) d = 0;
|
|
476
|
+
hits[i] = { id: this.node(res.vals[i]).ext as number, distance: d };
|
|
477
|
+
}
|
|
478
|
+
hits.sort((a, b) => a.distance - b.distance);
|
|
479
|
+
if (hits.length > k) hits.length = k;
|
|
480
|
+
return hits;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Tombstone a live node by internal id. Caller owns the transaction. */
|
|
484
|
+
remove(id: number): boolean {
|
|
485
|
+
const rec = this.store.getNode(id);
|
|
486
|
+
if (rec === null || rec.deleted === 1) return false;
|
|
487
|
+
this.store.tombstone(id);
|
|
488
|
+
this.live--;
|
|
489
|
+
this.persistState();
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Reclaim tombstones with a graph-preserving splice (see
|
|
495
|
+
* {@link Store.spliceCompact}): live nodes keep their internal ids and their
|
|
496
|
+
* wiring; each dead neighbour is replaced by its own live neighbours. Codes
|
|
497
|
+
* are untouched, so the index loses nothing beyond what deletion itself
|
|
498
|
+
* removes. The previous implementation replayed every live code through a
|
|
499
|
+
* full HNSW insert — O(live · ef · log N) storage reads, HOURS on a trained
|
|
500
|
+
* multi-million-node store, inside one WAL-bloating transaction. The splice
|
|
501
|
+
* is a streaming pass with batched commits, then a VACUUM to return the
|
|
502
|
+
* freed pages.
|
|
503
|
+
*/
|
|
504
|
+
compact(): void {
|
|
505
|
+
const r = this.store.spliceCompact(this.M, this.Mmax0, this.entry);
|
|
506
|
+
this.entry = r.entry;
|
|
507
|
+
this.maxLevel = r.maxLevel;
|
|
508
|
+
this.live = r.live;
|
|
509
|
+
this.total = r.live;
|
|
510
|
+
this.persistState();
|
|
511
|
+
this.working.clear();
|
|
512
|
+
this.store.vacuum();
|
|
513
|
+
}
|
|
514
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { VectorDatabase } from "./database.js";
|
|
2
|
+
export type {
|
|
3
|
+
DatabaseOptions,
|
|
4
|
+
ExternalId,
|
|
5
|
+
QueryResult,
|
|
6
|
+
StorageStats,
|
|
7
|
+
} from "./database.js";
|
|
8
|
+
export { HnswIndex } from "./hnsw.js";
|
|
9
|
+
export type { HnswParams, KnnHit } from "./hnsw.js";
|
|
10
|
+
export { RaBitQuantizer } from "./rabitq.js";
|
|
11
|
+
export type { QueryContext, RaBitQOptions } from "./rabitq.js";
|
|
12
|
+
export { Store } from "./store.js";
|
|
13
|
+
export type { GlobalState, NodeRec, StoreConfig } from "./store.js";
|
|
14
|
+
export { Heap } from "./heap.js";
|
|
15
|
+
export { Prng } from "./prng.js";
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small deterministic pseudo-random number generator (mulberry32).
|
|
3
|
+
*
|
|
4
|
+
* Pure ECMAScript. It is used so that the random orthogonal rotation of the
|
|
5
|
+
* RaBitQ quantizer and the HNSW level assignment are reproducible and can be
|
|
6
|
+
* regenerated after (de)serialization without storing large matrices.
|
|
7
|
+
*/
|
|
8
|
+
export class Prng {
|
|
9
|
+
private state: number;
|
|
10
|
+
|
|
11
|
+
constructor(seed: number) {
|
|
12
|
+
this.state = seed >>> 0;
|
|
13
|
+
if (this.state === 0) this.state = 0x9e3779b9;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Uniform float in [0, 1). */
|
|
17
|
+
next(): number {
|
|
18
|
+
let t = (this.state = (this.state + 0x6d2b79f5) | 0);
|
|
19
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
20
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
21
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Uniform integer in [0, n). */
|
|
25
|
+
int(n: number): number {
|
|
26
|
+
return (this.next() * n) | 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Current internal state (one uint32), for persisting/resuming the stream. */
|
|
30
|
+
snapshot(): number {
|
|
31
|
+
return this.state >>> 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Resume the stream from a previously snapshotted state. */
|
|
35
|
+
restore(state: number): void {
|
|
36
|
+
this.state = state >>> 0;
|
|
37
|
+
if (this.state === 0) this.state = 0x9e3779b9;
|
|
38
|
+
}
|
|
39
|
+
}
|