vector-index 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +1447 -12
  3. package/build-browser.js +67 -0
  4. package/index.js +38 -6
  5. package/package.json +70 -6
  6. package/src/async.js +458 -0
  7. package/src/clustering.js +226 -0
  8. package/src/embeddings/als.js +211 -0
  9. package/src/embeddings/bpr.js +149 -0
  10. package/src/embeddings/embeddings.js +222 -0
  11. package/src/embeddings/evaluate.js +193 -0
  12. package/src/embeddings/graph.js +376 -0
  13. package/src/embeddings/idmap.js +120 -0
  14. package/src/embeddings/interactions.js +123 -0
  15. package/src/embeddings/memory.js +52 -0
  16. package/src/embeddings/node2vec.js +142 -0
  17. package/src/embeddings/sgns.js +191 -0
  18. package/src/embeddings/skipgram.js +128 -0
  19. package/src/embeddings/trainer.js +147 -0
  20. package/src/embeddings/walker.js +208 -0
  21. package/src/errors.js +41 -0
  22. package/src/heap.js +82 -0
  23. package/src/index/block-codec.js +191 -0
  24. package/src/index/diskann-block-engine.js +891 -0
  25. package/src/index/diskann.js +331 -0
  26. package/src/index/engine-common.js +159 -0
  27. package/src/index/flat.js +49 -0
  28. package/src/index/hnsw.js +282 -0
  29. package/src/index/ivf.js +232 -0
  30. package/src/index/prune.js +70 -0
  31. package/src/index/vector-index.js +391 -0
  32. package/src/lru.js +32 -0
  33. package/src/math.js +666 -0
  34. package/src/metric.js +62 -0
  35. package/src/quant/bq.js +172 -0
  36. package/src/quant/pq.js +418 -0
  37. package/src/quant/scan.js +52 -0
  38. package/src/quant/sq.js +274 -0
  39. package/src/quant/turboquant.js +527 -0
  40. package/src/reduce/pca.js +253 -0
  41. package/src/results.js +86 -0
  42. package/src/search.js +52 -0
  43. package/src/sparse/sparse-index.js +349 -0
  44. package/src/store.js +476 -0
  45. package/src/typed.js +23 -0
  46. package/src/validate.js +130 -0
@@ -0,0 +1,376 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // createGraph({ directed, weighted }) — an in-memory graph in CSR form
7
+ //
8
+ // CSR (compressed sparse row): all adjacency lists back to back in one
9
+ // typed array, plus an offsets array. node v's neighbors are
10
+ // neighbors[offsets[v] .. offsets[v+1]). cost per stored entry: 4 bytes
11
+ // (+4 for the weight in a weighted graph); per node: 4 bytes + the id map.
12
+ // an undirected edge is stored twice (once from each side).
13
+ //
14
+ // building is incremental:
15
+ // - addEdge / addEdges only append to a small "pending" buffer (O(1));
16
+ // - compile() merges pending edges into the CSR: the pending entries are
17
+ // radix-sorted by (source, target) in O(entries + nodes), then merged
18
+ // row by row with the existing sorted CSR. no comparison sort, no
19
+ // per-node objects. duplicates are merged (weights summed).
20
+ // - compile runs automatically before anything that reads adjacency
21
+ // (degree, neighbors, training), so calling it is optional.
22
+ //
23
+ // rows are kept sorted by internal index, so "is x a neighbor of t" — the
24
+ // inner question of node2vec — is a binary search.
25
+ //
26
+ // limits: up to 2^32 − 1 nodes and 2^32 − 1 stored entries per graph.
27
+ // ===========================
28
+
29
+ import { binarySearch } from '../math.js';
30
+ import { ERR, createError } from '../errors.js';
31
+ import { pairedApi, createTaskQueue, createEmitter, now } from '../async.js';
32
+ import { checkId, checkOptions, boolOption } from '../validate.js';
33
+ import { grow } from '../typed.js';
34
+ import { createIdMap } from './idmap.js';
35
+
36
+ const MAX_ENTRIES = 0xFFFFFFFF;
37
+ const PROGRESS_MS = 100;
38
+
39
+ function createGraph(options) {
40
+ const opts = checkOptions(options, ['directed', 'weighted'], 'createGraph');
41
+ const directed = boolOption(opts, 'directed', false);
42
+ const weighted = boolOption(opts, 'weighted', false);
43
+
44
+ const ids = createIdMap(0);
45
+ const events = createEmitter();
46
+ const queue = createTaskQueue();
47
+
48
+ // pending edges, one entry per added edge (undirected ones are mirrored at compile)
49
+ let pFrom = new Uint32Array(1024);
50
+ let pTo = new Uint32Array(1024);
51
+ let pW = weighted ? new Float32Array(1024) : null;
52
+ let pCount = 0;
53
+
54
+ // compiled CSR — replaced as a whole by compile, never mutated in place,
55
+ // so a training job can keep reading an old snapshot safely
56
+ let csr = {
57
+ n: 0,
58
+ offsets: new Uint32Array(1),
59
+ neighbors: new Uint32Array(0),
60
+ weights: weighted ? new Float32Array(0) : null,
61
+ edges: 0,
62
+ directed,
63
+ weighted
64
+ };
65
+
66
+ // ---------- writes ----------
67
+
68
+ function checkWeight(weight, what) {
69
+ if (!weighted) {
70
+ if (weight !== undefined && weight !== null) {
71
+ throw createError(ERR.INVALID_ARGUMENT,
72
+ what + ': this graph is unweighted — create it with { weighted: true } to pass weights');
73
+ }
74
+ return 1;
75
+ }
76
+ if (weight === undefined || weight === null) return 1;
77
+ if (typeof weight !== 'number' || !Number.isFinite(weight) || weight <= 0) {
78
+ throw createError(ERR.INVALID_ARGUMENT, what + ': weight must be a finite number > 0, got ' + weight);
79
+ }
80
+ return weight;
81
+ }
82
+
83
+ function pushPending(a, b, w) {
84
+ if (pCount === pFrom.length) {
85
+ pFrom = grow(pFrom, pCount + 1);
86
+ pTo = grow(pTo, pCount + 1);
87
+ if (pW) pW = grow(pW, pCount + 1);
88
+ }
89
+ pFrom[pCount] = a;
90
+ pTo[pCount] = b;
91
+ if (pW) pW[pCount] = w;
92
+ pCount++;
93
+ }
94
+
95
+ function addEdge(from, to, weight) {
96
+ checkId(from, 'from');
97
+ checkId(to, 'to');
98
+ const w = checkWeight(weight, 'addEdge');
99
+ pushPending(ids.getOrAdd(from), ids.getOrAdd(to), w);
100
+ }
101
+
102
+ function* addEdges(edges) {
103
+ if (!edges || typeof edges !== 'object') {
104
+ throw createError(ERR.INVALID_ARGUMENT, 'addEdges: expected { from, to, weights? }');
105
+ }
106
+ const { from, to, weights } = edges;
107
+ if (!from || !to || typeof from.length !== 'number' || typeof to.length !== 'number') {
108
+ throw createError(ERR.INVALID_ARGUMENT, 'addEdges: from and to must be arrays or typed arrays');
109
+ }
110
+ if (from.length !== to.length) {
111
+ throw createError(ERR.INVALID_ARGUMENT,
112
+ 'addEdges: from and to must have the same length (' + from.length + ' vs ' + to.length + ')');
113
+ }
114
+ if (weights != null) {
115
+ if (!weighted) {
116
+ throw createError(ERR.INVALID_ARGUMENT,
117
+ 'addEdges: this graph is unweighted — create it with { weighted: true } to pass weights');
118
+ }
119
+ if (typeof weights.length !== 'number' || weights.length !== from.length) {
120
+ throw createError(ERR.INVALID_ARGUMENT, 'addEdges: weights must have the same length as from/to');
121
+ }
122
+ }
123
+ const m = from.length;
124
+ // validate everything first, so a bad entry leaves the graph unchanged
125
+ for (let i = 0; i < m; i++) {
126
+ checkId(from[i], 'from[' + i + ']');
127
+ checkId(to[i], 'to[' + i + ']');
128
+ if (weights != null) checkWeight(weights[i], 'addEdges: weights[' + i + ']');
129
+ if ((i & 4095) === 4095) yield;
130
+ }
131
+ if (pCount + m > pFrom.length) {
132
+ pFrom = grow(pFrom, pCount + m);
133
+ pTo = grow(pTo, pCount + m);
134
+ if (pW) pW = grow(pW, pCount + m);
135
+ }
136
+ for (let i = 0; i < m; i++) {
137
+ pFrom[pCount] = ids.getOrAdd(from[i]);
138
+ pTo[pCount] = ids.getOrAdd(to[i]);
139
+ if (pW) pW[pCount] = weights != null ? weights[i] : 1;
140
+ pCount++;
141
+ if ((i & 4095) === 4095) yield;
142
+ }
143
+ return m;
144
+ }
145
+
146
+ // ---------- compile ----------
147
+
148
+ function* compileJob() {
149
+ if (pCount === 0 && csr.n === ids.size) return csr;
150
+ const n = ids.size;
151
+ const old = csr;
152
+ const t0 = now();
153
+ let lastEmit = t0;
154
+ const progress = (done, total) => {
155
+ const t = now();
156
+ if (t - lastEmit >= PROGRESS_MS) {
157
+ lastEmit = t;
158
+ events.emit('progress', { phase: 'compile', done, total });
159
+ }
160
+ };
161
+
162
+ // 1. expand pending edges into entries (mirror undirected ones)
163
+ let E = 0;
164
+ for (let i = 0; i < pCount; i++) {
165
+ E += (directed || pFrom[i] === pTo[i]) ? 1 : 2;
166
+ if ((i & 0xFFFF) === 0xFFFF) yield;
167
+ }
168
+ if (old.neighbors.length + E > MAX_ENTRIES) {
169
+ throw createError(ERR.TOO_LARGE, 'graph would exceed ' + MAX_ENTRIES + ' adjacency entries');
170
+ }
171
+ let S = new Uint32Array(E), D = new Uint32Array(E);
172
+ let W = weighted ? new Float32Array(E) : null;
173
+ let e = 0;
174
+ for (let i = 0; i < pCount; i++) {
175
+ const a = pFrom[i], b = pTo[i];
176
+ S[e] = a; D[e] = b; if (W) W[e] = pW[i]; e++;
177
+ if (!directed && a !== b) { S[e] = b; D[e] = a; if (W) W[e] = pW[i]; e++; }
178
+ if ((i & 0xFFFF) === 0xFFFF) yield;
179
+ }
180
+ yield;
181
+
182
+ // 2. LSD radix sort by (S, D): stable counting sort by D, then by S
183
+ const cnt = new Uint32Array(n + 1);
184
+ for (let i = 0; i < E; i++) {
185
+ cnt[D[i] + 1]++;
186
+ if ((i & 0xFFFF) === 0xFFFF) yield;
187
+ }
188
+ for (let v = 0; v < n; v++) {
189
+ cnt[v + 1] += cnt[v];
190
+ if ((v & 0xFFFF) === 0xFFFF) yield;
191
+ }
192
+ const S1 = new Uint32Array(E), D1 = new Uint32Array(E);
193
+ const W1 = W ? new Float32Array(E) : null;
194
+ for (let i = 0; i < E; i++) {
195
+ const p = cnt[D[i]]++;
196
+ S1[p] = S[i]; D1[p] = D[i]; if (W1) W1[p] = W[i];
197
+ if ((i & 0xFFFF) === 0xFFFF) yield;
198
+ }
199
+ S = null;
200
+ const pOff = cnt; // reuse: becomes the pending row offsets
201
+ pOff.fill(0);
202
+ for (let i = 0; i < E; i++) {
203
+ pOff[S1[i] + 1]++;
204
+ if ((i & 0xFFFF) === 0xFFFF) yield;
205
+ }
206
+ for (let v = 0; v < n; v++) {
207
+ pOff[v + 1] += pOff[v];
208
+ if ((v & 0xFFFF) === 0xFFFF) yield;
209
+ }
210
+ const cursor = pOff.slice(0, n);
211
+ for (let i = 0; i < E; i++) { // reuse D / W as the sorted output
212
+ const p = cursor[S1[i]]++;
213
+ D[p] = D1[i]; if (W) W[p] = W1[i];
214
+ if ((i & 0xFFFF) === 0xFFFF) yield;
215
+ }
216
+ // now D[pOff[v] .. pOff[v+1]) are v's new neighbors, sorted
217
+
218
+ // 3. merge with the old CSR row by row, merging duplicates
219
+ const cap = old.neighbors.length + E;
220
+ let nb = new Uint32Array(cap);
221
+ let wt = weighted ? new Float32Array(cap) : null;
222
+ const offsets = new Uint32Array(n + 1);
223
+ const oOff = old.offsets, oNb = old.neighbors, oW = old.weights, oN = old.n;
224
+ let out = 0;
225
+ for (let v = 0; v < n; v++) {
226
+ offsets[v] = out;
227
+ let i = v < oN ? oOff[v] : 0;
228
+ const iEnd = v < oN ? oOff[v + 1] : 0;
229
+ let j = pOff[v];
230
+ const jEnd = pOff[v + 1];
231
+ let last = -1;
232
+ while (i < iEnd || j < jEnd) {
233
+ let x, w;
234
+ if (j >= jEnd || (i < iEnd && oNb[i] <= D[j])) {
235
+ x = oNb[i]; w = oW ? oW[i] : 1; i++;
236
+ } else {
237
+ x = D[j]; w = W ? W[j] : 1; j++;
238
+ }
239
+ if (x === last) {
240
+ if (wt) wt[out - 1] += w; // duplicate edge: sum the weights
241
+ } else {
242
+ nb[out] = x;
243
+ if (wt) wt[out] = w;
244
+ out++;
245
+ last = x;
246
+ }
247
+ }
248
+ if ((v & 4095) === 4095) { progress(v, n); yield; }
249
+ }
250
+ offsets[n] = out;
251
+
252
+ // trim the duplicate slack when it's worth a copy
253
+ if (cap - out > (cap >> 3)) {
254
+ nb = nb.slice(0, out);
255
+ if (wt) wt = wt.slice(0, out);
256
+ } else if (cap !== out) {
257
+ nb = nb.subarray(0, out);
258
+ if (wt) wt = wt.subarray(0, out);
259
+ }
260
+
261
+ let loops = 0;
262
+ if (!directed) {
263
+ for (let v = 0; v < n; v++) {
264
+ if (binarySearch(nb, offsets[v], offsets[v + 1], v) >= 0) loops++;
265
+ if ((v & 0xFFFF) === 0xFFFF) yield;
266
+ }
267
+ }
268
+
269
+ csr = {
270
+ n,
271
+ offsets,
272
+ neighbors: nb,
273
+ weights: wt,
274
+ edges: directed ? out : (out + loops) / 2,
275
+ directed,
276
+ weighted
277
+ };
278
+ pCount = 0;
279
+ if (pFrom.length > 1024) {
280
+ pFrom = new Uint32Array(1024);
281
+ pTo = new Uint32Array(1024);
282
+ if (pW) pW = new Float32Array(1024);
283
+ }
284
+ events.emit('progress', { phase: 'compile', done: n, total: n });
285
+ return csr;
286
+ }
287
+
288
+ const dirty = () => pCount > 0 || csr.n !== ids.size;
289
+
290
+ // ---------- reads ----------
291
+
292
+ function indexOrThrow(id, what) {
293
+ checkId(id, what);
294
+ const v = ids.get(id);
295
+ if (v < 0) throw createError(ERR.NOT_FOUND, what + ' ' + id + ' is not in the graph');
296
+ return v;
297
+ }
298
+
299
+ function hasNode(id) {
300
+ checkId(id);
301
+ return ids.get(id) >= 0;
302
+ }
303
+
304
+ function* degree(id) {
305
+ const v = indexOrThrow(id, 'id');
306
+ if (dirty()) yield* compileJob();
307
+ return csr.offsets[v + 1] - csr.offsets[v];
308
+ }
309
+
310
+ // → { ids: Float64Array, weights: Float32Array | null } (copies)
311
+ function* neighbors(id) {
312
+ const v = indexOrThrow(id, 'id');
313
+ if (dirty()) yield* compileJob();
314
+ const a = csr.offsets[v], b = csr.offsets[v + 1];
315
+ const out = new Float64Array(b - a);
316
+ for (let i = a; i < b; i++) out[i - a] = ids.idOf(csr.neighbors[i]);
317
+ return { ids: out, weights: csr.weights ? csr.weights.slice(a, b) : null };
318
+ }
319
+
320
+ // compiles first, like every read of adjacency, so the counts always
321
+ // include every edge added so far
322
+ function* stats() {
323
+ if (dirty()) yield* compileJob();
324
+ return {
325
+ nodes: ids.size,
326
+ edges: csr.edges,
327
+ directed,
328
+ weighted,
329
+ bytes: ids.bytes() + csr.offsets.byteLength + csr.neighbors.buffer.byteLength +
330
+ (csr.weights ? csr.weights.buffer.byteLength : 0) +
331
+ pFrom.byteLength + pTo.byteLength + (pW ? pW.byteLength : 0)
332
+ };
333
+ }
334
+
335
+ const api = pairedApi({
336
+ addEdge,
337
+ addEdges,
338
+ compile: function* compile() { yield* compileJob(); },
339
+ degree,
340
+ neighbors,
341
+ hasNode,
342
+ stats,
343
+ // internal: compile, then return the immutable snapshot — in one queued step
344
+ _prepare: function* prepare() {
345
+ yield* compileJob();
346
+ return { csr, ids, n: csr.n };
347
+ }
348
+ }, { queue, reads: ['hasNode'] });
349
+
350
+ return {
351
+ addEdge: api.addEdge, addEdgeSync: api.addEdgeSync,
352
+ addEdges: api.addEdges, addEdgesSync: api.addEdgesSync,
353
+ compile: api.compile, compileSync: api.compileSync,
354
+ degree: api.degree, degreeSync: api.degreeSync,
355
+ neighbors: api.neighbors, neighborsSync: api.neighborsSync,
356
+ hasNode: api.hasNode, hasNodeSync: api.hasNodeSync,
357
+ stats: api.stats, statsSync: api.statsSync,
358
+ get directed() { return directed; },
359
+ get weighted() { return weighted; },
360
+ on: events.on,
361
+ off: events.off,
362
+ // internal: the compiled, immutable snapshot (CSR + id map). later edits
363
+ // build a new CSR, so a running training job keeps a consistent view.
364
+ _prepare: api._prepare,
365
+ _prepareSync: api._prepareSync
366
+ };
367
+ }
368
+
369
+ function isGraph(g) {
370
+ return !!g && typeof g._prepareSync === 'function';
371
+ }
372
+
373
+ export {
374
+ createGraph,
375
+ isGraph
376
+ };
@@ -0,0 +1,120 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // id map: external id (safe integer, 0 … 2^53−1) ⇄ dense internal index (0 … n−1)
7
+ //
8
+ // why not a JS Map: V8 caps a Map at 2^24 (~16.7M) entries, and each entry
9
+ // costs ~40–80 bytes. this is an open-addressing hash table over two typed
10
+ // arrays (linear probing, load ≤ 0.6): ~20 bytes per id for the table plus
11
+ // 8 bytes for the reverse array — and no object per entry for the GC to walk.
12
+ //
13
+ // indices are assigned in first-seen order and never change or get reused,
14
+ // so anything indexed by them (CSR rows, embedding rows) stays valid while
15
+ // the map keeps growing.
16
+ // ===========================
17
+
18
+ import { grow } from '../typed.js';
19
+
20
+ const EMPTY = -1;
21
+ const MAX_LOAD = 0.6;
22
+
23
+ function hashId(id) {
24
+ const lo = id >>> 0; // low 32 bits (exact for safe integers)
25
+ const hi = (id - lo) / 4294967296; // high 21 bits
26
+ let h = lo ^ Math.imul(hi, 0x9E3779B1);
27
+ h = Math.imul(h ^ (h >>> 16), 0x85EBCA6B);
28
+ h = Math.imul(h ^ (h >>> 13), 0xC2B2AE35);
29
+ return (h ^ (h >>> 16)) >>> 0;
30
+ }
31
+
32
+ function createIdMap(expected) {
33
+ let cap = 16;
34
+ while (cap * MAX_LOAD < (expected || 0)) cap *= 2;
35
+ let mask = cap - 1;
36
+ let keys = new Float64Array(cap).fill(EMPTY);
37
+ let vals = new Uint32Array(cap);
38
+ let ids = new Float64Array(Math.max(16, expected || 0)); // index → id
39
+ let size = 0;
40
+
41
+ function find(id) {
42
+ let i = hashId(id) & mask;
43
+ while (true) {
44
+ const k = keys[i];
45
+ if (k === id) return i;
46
+ if (k === EMPTY) return ~i; // not present: ~slot where it would go
47
+ i = (i + 1) & mask;
48
+ }
49
+ }
50
+
51
+ function rehash(newCap) {
52
+ const oldKeys = keys, oldVals = vals;
53
+ cap = newCap;
54
+ mask = cap - 1;
55
+ keys = new Float64Array(cap).fill(EMPTY);
56
+ vals = new Uint32Array(cap);
57
+ for (let i = 0; i < oldKeys.length; i++) {
58
+ const k = oldKeys[i];
59
+ if (k === EMPTY) continue;
60
+ let j = hashId(k) & mask;
61
+ while (keys[j] !== EMPTY) j = (j + 1) & mask;
62
+ keys[j] = k;
63
+ vals[j] = oldVals[i];
64
+ }
65
+ }
66
+
67
+ return {
68
+ get size() { return size; },
69
+
70
+ // index of id, or -1
71
+ get(id) {
72
+ const s = find(id);
73
+ return s >= 0 ? vals[s] : -1;
74
+ },
75
+
76
+ // index of id, adding it when missing
77
+ getOrAdd(id) {
78
+ let s = find(id);
79
+ if (s >= 0) return vals[s];
80
+ if (size + 1 > cap * MAX_LOAD) {
81
+ rehash(cap * 2);
82
+ s = find(id);
83
+ }
84
+ s = ~s;
85
+ const index = size++;
86
+ keys[s] = id;
87
+ vals[s] = index;
88
+ if (index >= ids.length) ids = grow(ids, index + 1);
89
+ ids[index] = id;
90
+ return index;
91
+ },
92
+
93
+ idOf(index) {
94
+ return ids[index];
95
+ },
96
+
97
+ // the first n ids as a Float64Array view (no copy) — valid until the next add
98
+ idsView(n) {
99
+ return ids.subarray(0, n === undefined ? size : n);
100
+ },
101
+
102
+ bytes() {
103
+ return keys.byteLength + vals.byteLength + ids.byteLength;
104
+ }
105
+ };
106
+ }
107
+
108
+ // build a map from a list of ids (index i ↔ ids[i]); throws on duplicates
109
+ function idMapFromIds(idList) {
110
+ const map = createIdMap(idList.length);
111
+ for (let i = 0; i < idList.length; i++) {
112
+ if (map.getOrAdd(idList[i]) !== i) return null; // duplicate id
113
+ }
114
+ return map;
115
+ }
116
+
117
+ export {
118
+ createIdMap,
119
+ idMapFromIds
120
+ };
@@ -0,0 +1,123 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // interactions — the user × item matrix that ALS and BPR learn from
7
+ //
8
+ // input (columnar, like graph.addEdges):
9
+ // { users: [u0, u1, ...], items: [i0, i1, ...], weights?: [w0, w1, ...] }
10
+ // one entry per event: user u interacted with item i (bought, played,
11
+ // clicked), weight = how much (a count, seconds watched; default 1).
12
+ // users and items are separate id spaces — user 7 and item 7 are unrelated.
13
+ // repeated (user, item) pairs are summed.
14
+ //
15
+ // output: both directions as CSR, rows sorted, no duplicates
16
+ // byUser offsets[nUsers + 1], cols (item rows), vals (summed weights)
17
+ // byItem offsets[nItems + 1], cols (user rows), vals
18
+ // plus the two id maps (row ↔ id).
19
+ // ===========================
20
+
21
+ import { ERR, createError } from '../errors.js';
22
+ import { checkId } from '../validate.js';
23
+ import { createIdMap } from './idmap.js';
24
+
25
+ function checkInteractions(x) {
26
+ if (!x || typeof x !== 'object') {
27
+ throw createError(ERR.INVALID_ARGUMENT, 'train: expected { users, items[, weights] }');
28
+ }
29
+ const { users, items, weights } = x;
30
+ if (!users || typeof users.length !== 'number' || !items || typeof items.length !== 'number') {
31
+ throw createError(ERR.INVALID_ARGUMENT, 'train: users and items must be arrays of ids');
32
+ }
33
+ if (users.length !== items.length) {
34
+ throw createError(ERR.INVALID_ARGUMENT, 'train: users and items must have the same length');
35
+ }
36
+ if (weights != null && (typeof weights.length !== 'number' || weights.length !== users.length)) {
37
+ throw createError(ERR.INVALID_ARGUMENT, 'train: weights must have the same length as users');
38
+ }
39
+ if (users.length === 0) throw createError(ERR.INVALID_ARGUMENT, 'train: no interactions');
40
+ }
41
+
42
+ // a copy taken when train() is called, so the caller may reuse its arrays
43
+ function copyInteractions(x) {
44
+ checkInteractions(x);
45
+ return {
46
+ users: Float64Array.from(x.users),
47
+ items: Float64Array.from(x.items),
48
+ weights: x.weights == null ? null : Float64Array.from(x.weights)
49
+ };
50
+ }
51
+
52
+ // CSR of (row → col, val) from parallel arrays; sorts every row by col and
53
+ // merges duplicates (summing vals). a generator: yields now and then
54
+ function* buildCSR(rows, cols, vals, nRows) {
55
+ const n = rows.length;
56
+ const offsets = new Uint32Array(nRows + 1);
57
+ for (let k = 0; k < n; k++) offsets[rows[k] + 1]++;
58
+ for (let r = 0; r < nRows; r++) offsets[r + 1] += offsets[r];
59
+ const pos = offsets.slice(0, nRows);
60
+ const c = new Uint32Array(n);
61
+ const v = new Float64Array(n);
62
+ for (let k = 0; k < n; k++) {
63
+ const p = pos[rows[k]]++;
64
+ c[p] = cols[k];
65
+ v[p] = vals ? vals[k] : 1;
66
+ if ((k & 0xFFFF) === 0xFFFF) yield;
67
+ }
68
+ // sort each row by column (insertion sort on short rows, else index sort)
69
+ // and merge duplicates in place
70
+ const outOff = new Uint32Array(nRows + 1);
71
+ let w = 0;
72
+ let work = 0; // yield by work done, not by rows: rows can be long
73
+ for (let r = 0; r < nRows; r++) {
74
+ const a = offsets[r], b = offsets[r + 1];
75
+ if (b - a > 32) {
76
+ const idx = Array.from({ length: b - a }, (_, i) => a + i).sort((x, y) => c[x] - c[y]);
77
+ const cs = idx.map(i => c[i]), vs = idx.map(i => v[i]);
78
+ for (let i = 0; i < cs.length; i++) { c[a + i] = cs[i]; v[a + i] = vs[i]; }
79
+ } else {
80
+ for (let i = a + 1; i < b; i++) {
81
+ const ci = c[i], vi = v[i];
82
+ let j = i - 1;
83
+ while (j >= a && c[j] > ci) { c[j + 1] = c[j]; v[j + 1] = v[j]; j--; }
84
+ c[j + 1] = ci; v[j + 1] = vi;
85
+ }
86
+ }
87
+ outOff[r] = w;
88
+ for (let i = a; i < b; i++) {
89
+ if (w > outOff[r] && c[w - 1] === c[i]) v[w - 1] += v[i];
90
+ else { c[w] = c[i]; v[w] = v[i]; w++; }
91
+ }
92
+ work += 8 + (b - a) * (b - a > 32 ? 12 : 2);
93
+ if (work > 20000) { work = 0; yield true; }
94
+ }
95
+ outOff[nRows] = w;
96
+ return { offsets: outOff, cols: c.subarray(0, w), vals: v.subarray(0, w) };
97
+ }
98
+
99
+ function* buildInteractions(x) {
100
+ const n = x.users.length;
101
+ const userMap = createIdMap(0);
102
+ const itemMap = createIdMap(0);
103
+ const ur = new Uint32Array(n), ir = new Uint32Array(n);
104
+ for (let k = 0; k < n; k++) {
105
+ checkId(x.users[k], 'users[' + k + ']');
106
+ checkId(x.items[k], 'items[' + k + ']');
107
+ if (x.weights) {
108
+ const wk = x.weights[k];
109
+ if (!(wk > 0) || !Number.isFinite(wk)) {
110
+ throw createError(ERR.INVALID_ARGUMENT, 'weights[' + k + '] must be a positive finite number, got ' + wk);
111
+ }
112
+ }
113
+ ur[k] = userMap.getOrAdd(x.users[k]);
114
+ ir[k] = itemMap.getOrAdd(x.items[k]);
115
+ if ((k & 0xFFFF) === 0xFFFF) yield;
116
+ }
117
+ const nUsers = userMap.size, nItems = itemMap.size;
118
+ const byUser = yield* buildCSR(ur, ir, x.weights, nUsers);
119
+ const byItem = yield* buildCSR(ir, ur, x.weights, nItems);
120
+ return { userMap, itemMap, nUsers, nItems, byUser, byItem, nnz: byUser.cols.length };
121
+ }
122
+
123
+ export { copyInteractions, buildInteractions };
@@ -0,0 +1,52 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // estimateMemory({ nodes, edges, dimensions, directed, weighted })
7
+ // → { graph, training, embeddings, peak } in bytes
8
+ //
9
+ // plan before you load: the numbers follow the exact array sizes used by
10
+ // the library (graph CSR + id map, the two training matrices, walk scratch).
11
+ // ===========================
12
+
13
+ import { ERR, createError } from '../errors.js';
14
+ import { checkOptions } from '../validate.js';
15
+
16
+ function estimateMemory(options) {
17
+ const opts = checkOptions(options, ['nodes', 'edges', 'dimensions', 'directed', 'weighted'], 'estimateMemory');
18
+ const nodes = opts.nodes, edges = opts.edges;
19
+ const dims = opts.dimensions === undefined ? 128 : opts.dimensions;
20
+ for (const [k, v] of [['nodes', nodes], ['edges', edges], ['dimensions', dims]]) {
21
+ if (!Number.isSafeInteger(v) || v < 0) {
22
+ throw createError(ERR.INVALID_ARGUMENT, 'estimateMemory: ' + k + ' must be a non-negative integer');
23
+ }
24
+ }
25
+ const entries = opts.directed ? edges : 2 * edges;
26
+ const perEntry = 4 + (opts.weighted ? 4 : 0);
27
+
28
+ // id map: hash table at load ≤ 0.6 (12 bytes per slot, power-of-two size) + reverse ids
29
+ let slots = 16;
30
+ while (slots * 0.6 < nodes) slots *= 2;
31
+ const idMap = slots * 12 + nodes * 8;
32
+ const graph = idMap + (nodes + 1) * 4 + entries * perEntry;
33
+
34
+ // compile peak: pending edges (12–16 B each) + radix buffers + new CSR
35
+ const compileExtra = edges * (8 + (opts.weighted ? 4 : 0)) + entries * (16 + (opts.weighted ? 8 : 0));
36
+
37
+ const matrix = nodes * dims * 4;
38
+ const training = 2 * matrix + nodes * (8 + 8 + 4 + 4) + // counts, alias, keep, order
39
+ (opts.weighted ? entries * 4 : 0); // cumulative weights
40
+ const embeddings = matrix;
41
+
42
+ return {
43
+ graph,
44
+ training,
45
+ embeddings,
46
+ peak: graph + Math.max(compileExtra, training)
47
+ };
48
+ }
49
+
50
+ export {
51
+ estimateMemory
52
+ };