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