vector-index 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -21
- package/README.md +1447 -12
- package/build-browser.js +67 -0
- package/index.js +38 -6
- package/package.json +70 -6
- package/src/async.js +458 -0
- package/src/clustering.js +226 -0
- package/src/embeddings/als.js +211 -0
- package/src/embeddings/bpr.js +149 -0
- package/src/embeddings/embeddings.js +222 -0
- package/src/embeddings/evaluate.js +193 -0
- package/src/embeddings/graph.js +376 -0
- package/src/embeddings/idmap.js +120 -0
- package/src/embeddings/interactions.js +123 -0
- package/src/embeddings/memory.js +52 -0
- package/src/embeddings/node2vec.js +142 -0
- package/src/embeddings/sgns.js +191 -0
- package/src/embeddings/skipgram.js +128 -0
- package/src/embeddings/trainer.js +147 -0
- package/src/embeddings/walker.js +208 -0
- package/src/errors.js +41 -0
- package/src/heap.js +82 -0
- package/src/index/block-codec.js +191 -0
- package/src/index/diskann-block-engine.js +891 -0
- package/src/index/diskann.js +331 -0
- package/src/index/engine-common.js +159 -0
- package/src/index/flat.js +49 -0
- package/src/index/hnsw.js +282 -0
- package/src/index/ivf.js +232 -0
- package/src/index/prune.js +70 -0
- package/src/index/vector-index.js +391 -0
- package/src/lru.js +32 -0
- package/src/math.js +666 -0
- package/src/metric.js +62 -0
- package/src/quant/bq.js +172 -0
- package/src/quant/pq.js +418 -0
- package/src/quant/scan.js +52 -0
- package/src/quant/sq.js +274 -0
- package/src/quant/turboquant.js +527 -0
- package/src/reduce/pca.js +253 -0
- package/src/results.js +86 -0
- package/src/search.js +52 -0
- package/src/sparse/sparse-index.js +349 -0
- package/src/store.js +476 -0
- package/src/typed.js +23 -0
- package/src/validate.js +130 -0
package/src/math.js
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
// ===========================
|
|
6
|
+
// math — every pure numeric function of the library, in one place.
|
|
7
|
+
// no state, no I/O, no imports: numbers and typed arrays in, numbers and
|
|
8
|
+
// typed arrays out. internal, not part of the public API.
|
|
9
|
+
//
|
|
10
|
+
// vectors dotAt, l2sqAt, l2sqAtBounded, cosine, normalizeAt, normalizedCopy
|
|
11
|
+
// random rngState, randFloat, createRng, gaussianSample, buildAlias
|
|
12
|
+
// gaussian getGaussianCentroids, gaussianInverseCDF, computeBoundaries
|
|
13
|
+
// transforms walshHadamard, nextPow2
|
|
14
|
+
// bits packBits, unpackBits, popcount32, POPCOUNT_TABLE
|
|
15
|
+
// linear alg. orthonormalizeColumnsSteps, symmetricEigen(Steps)
|
|
16
|
+
// search binarySearch
|
|
17
|
+
//
|
|
18
|
+
// the hot loops (dotAt, randFloat, popcount32) are module-level functions on
|
|
19
|
+
// purpose: a closure re-created per instance gets optimized from scratch by
|
|
20
|
+
// V8, a module-level function is shared and stays fast. importing them from
|
|
21
|
+
// another module costs nothing — V8 inlines across modules.
|
|
22
|
+
// ===========================
|
|
23
|
+
|
|
24
|
+
// ===========================
|
|
25
|
+
// VECTORS
|
|
26
|
+
// ===========================
|
|
27
|
+
|
|
28
|
+
// dotAt — Σ a[ao+i] · b[bo+i], the hot loop of the whole library (every
|
|
29
|
+
// search, e-means, node2vec training). four accumulators shorten the
|
|
30
|
+
// dependency chain between iterations; running indices instead of base + i
|
|
31
|
+
// are 1.1–1.5× faster on Float32Array (fewer index computations).
|
|
32
|
+
function dotAt(a, ao, b, bo, d) {
|
|
33
|
+
let f0 = 0, f1 = 0, f2 = 0, f3 = 0;
|
|
34
|
+
const end = ao + (d & ~3);
|
|
35
|
+
let i = ao, j = bo;
|
|
36
|
+
for (; i < end; i += 4, j += 4) {
|
|
37
|
+
f0 += a[i] * b[j];
|
|
38
|
+
f1 += a[i + 1] * b[j + 1];
|
|
39
|
+
f2 += a[i + 2] * b[j + 2];
|
|
40
|
+
f3 += a[i + 3] * b[j + 3];
|
|
41
|
+
}
|
|
42
|
+
for (const e = ao + d; i < e; i++, j++) f0 += a[i] * b[j];
|
|
43
|
+
return (f0 + f1) + (f2 + f3);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// l2sqAt — ‖a[ao..] − b[bo..]‖², squared euclidean distance. same shape as
|
|
47
|
+
// dotAt (four accumulators, running indices): the hot loop of metric 'l2'.
|
|
48
|
+
function l2sqAt(a, ao, b, bo, d) {
|
|
49
|
+
let f0 = 0, f1 = 0, f2 = 0, f3 = 0;
|
|
50
|
+
const end = ao + (d & ~3);
|
|
51
|
+
let i = ao, j = bo;
|
|
52
|
+
for (; i < end; i += 4, j += 4) {
|
|
53
|
+
const e0 = a[i] - b[j], e1 = a[i + 1] - b[j + 1], e2 = a[i + 2] - b[j + 2], e3 = a[i + 3] - b[j + 3];
|
|
54
|
+
f0 += e0 * e0;
|
|
55
|
+
f1 += e1 * e1;
|
|
56
|
+
f2 += e2 * e2;
|
|
57
|
+
f3 += e3 * e3;
|
|
58
|
+
}
|
|
59
|
+
for (const e = ao + d; i < e; i++, j++) { const x = a[i] - b[j]; f0 += x * x; }
|
|
60
|
+
return (f0 + f1) + (f2 + f3);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// l2sqAtBounded — ‖a − b‖², but stops as soon as the partial sum exceeds
|
|
64
|
+
// `limit` and returns that partial sum (already > limit). squared
|
|
65
|
+
// differences only add up, so a vector stopped here is farther than the
|
|
66
|
+
// limit: a top-k scan that passes its k-th distance as the limit gets
|
|
67
|
+
// exactly the same results, sooner. checked every 16 dimensions, so the
|
|
68
|
+
// check costs little next to the work it can skip. work (a Float64Array(1),
|
|
69
|
+
// optional): the dimensions actually read are added to work[0], so the
|
|
70
|
+
// caller can tell whether stopping early is paying off.
|
|
71
|
+
function l2sqAtBounded(a, ao, b, bo, d, limit, work) {
|
|
72
|
+
let s = 0;
|
|
73
|
+
let i = ao, j = bo;
|
|
74
|
+
const end = ao + d;
|
|
75
|
+
while (i < end) {
|
|
76
|
+
const stop = Math.min(end, i + 16);
|
|
77
|
+
let f0 = 0, f1 = 0, f2 = 0, f3 = 0;
|
|
78
|
+
for (; i + 3 < stop; i += 4, j += 4) {
|
|
79
|
+
const e0 = a[i] - b[j], e1 = a[i + 1] - b[j + 1], e2 = a[i + 2] - b[j + 2], e3 = a[i + 3] - b[j + 3];
|
|
80
|
+
f0 += e0 * e0;
|
|
81
|
+
f1 += e1 * e1;
|
|
82
|
+
f2 += e2 * e2;
|
|
83
|
+
f3 += e3 * e3;
|
|
84
|
+
}
|
|
85
|
+
for (; i < stop; i++, j++) { const x = a[i] - b[j]; f0 += x * x; }
|
|
86
|
+
s += (f0 + f1) + (f2 + f3);
|
|
87
|
+
if (s > limit) break;
|
|
88
|
+
}
|
|
89
|
+
if (work) work[0] += i - ao;
|
|
90
|
+
return s;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ===========================
|
|
94
|
+
// cosine similarity between two equal-length vectors
|
|
95
|
+
// returns 1 for identical direction, 0 for orthogonal, -1 for opposite
|
|
96
|
+
// returns 0 if either vector is all zeros (edge case)
|
|
97
|
+
// ===========================
|
|
98
|
+
function cosine(a, b) {
|
|
99
|
+
let dot = 0, na = 0, nb = 0;
|
|
100
|
+
for (let i = 0; i < a.length; i++) {
|
|
101
|
+
dot += a[i] * b[i];
|
|
102
|
+
na += a[i] * a[i];
|
|
103
|
+
nb += b[i] * b[i];
|
|
104
|
+
}
|
|
105
|
+
const denom = Math.sqrt(na) * Math.sqrt(nb);
|
|
106
|
+
if (denom === 0) return 0;
|
|
107
|
+
return dot / denom;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
// normalizes a[o .. o+d) in place to unit L2 norm. returns false (and leaves
|
|
112
|
+
// it unchanged) for a zero vector.
|
|
113
|
+
function normalizeAt(a, o, d) {
|
|
114
|
+
let q = 0;
|
|
115
|
+
for (let j = 0; j < d; j++) q += a[o + j] * a[o + j];
|
|
116
|
+
if (q === 0) return false;
|
|
117
|
+
q = 1 / Math.sqrt(q);
|
|
118
|
+
for (let j = 0; j < d; j++) a[o + j] *= q;
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// a normalized Float32Array copy (unit L2 norm). a zero vector stays zero.
|
|
123
|
+
function normalizedCopy(vector) {
|
|
124
|
+
const n = vector.length;
|
|
125
|
+
const out = new Float32Array(n);
|
|
126
|
+
let norm = 0;
|
|
127
|
+
for (let i = 0; i < n; i++) norm += vector[i] * vector[i];
|
|
128
|
+
const inv = norm > 0 ? 1 / Math.sqrt(norm) : 0;
|
|
129
|
+
for (let i = 0; i < n; i++) out[i] = vector[i] * inv;
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ===========================
|
|
134
|
+
// RANDOM — mulberry32: tiny, fast, seedable, one uint32 of state
|
|
135
|
+
// ===========================
|
|
136
|
+
|
|
137
|
+
// hot paths call randFloat(state) directly with a Uint32Array(1) state:
|
|
138
|
+
// a module-level function over explicit state stays fast no matter how many
|
|
139
|
+
// trainers exist (a closure per instance loses V8's specialization after
|
|
140
|
+
// the first one — measured 1.6× slower).
|
|
141
|
+
function rngState(seed) {
|
|
142
|
+
const s = new Uint32Array(1);
|
|
143
|
+
s[0] = seed >>> 0;
|
|
144
|
+
return s;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function randFloat(s) {
|
|
148
|
+
const st = (s[0] + 0x6D2B79F5) >>> 0;
|
|
149
|
+
s[0] = st;
|
|
150
|
+
let t = Math.imul(st ^ (st >>> 15), st | 1);
|
|
151
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
152
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// createRng(seed) → rng(), uniform floats in [0, 1): the same generator as
|
|
156
|
+
// randFloat, as a closure, for code that isn't hot. seed can be any integer;
|
|
157
|
+
// omitted → a fresh random stream.
|
|
158
|
+
function createRng(seed) {
|
|
159
|
+
const s = rngState(seed == null ? Math.random() * 0xffffffff : seed);
|
|
160
|
+
return function rng() {
|
|
161
|
+
return randFloat(s);
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ===========================
|
|
166
|
+
// gaussianSample(rng) — draw one sample from N(0, 1) using Box-Muller
|
|
167
|
+
// rng must be a function returning uniform [0, 1) (e.g. from createRng)
|
|
168
|
+
// ===========================
|
|
169
|
+
function gaussianSample(rng) {
|
|
170
|
+
const u1 = Math.max(rng(), 1e-10);
|
|
171
|
+
const u2 = rng();
|
|
172
|
+
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Vose alias table over weights w[0..V) → { prob, alias } (generator: yields)
|
|
176
|
+
function* buildAlias(weights) {
|
|
177
|
+
const V = weights.length;
|
|
178
|
+
const prob = new Float32Array(V);
|
|
179
|
+
const alias = new Uint32Array(V);
|
|
180
|
+
let sum = 0;
|
|
181
|
+
for (let i = 0; i < V; i++) sum += weights[i];
|
|
182
|
+
if (!(sum > 0)) {
|
|
183
|
+
for (let i = 0; i < V; i++) { prob[i] = 1; alias[i] = i; }
|
|
184
|
+
return { prob, alias };
|
|
185
|
+
}
|
|
186
|
+
const scaled = new Float64Array(V);
|
|
187
|
+
const small = new Uint32Array(V);
|
|
188
|
+
const large = new Uint32Array(V);
|
|
189
|
+
let ns = 0, nl = 0;
|
|
190
|
+
for (let i = 0; i < V; i++) {
|
|
191
|
+
scaled[i] = weights[i] * V / sum;
|
|
192
|
+
if (scaled[i] < 1) small[ns++] = i;
|
|
193
|
+
else large[nl++] = i;
|
|
194
|
+
if ((i & 0xFFFF) === 0xFFFF) yield;
|
|
195
|
+
}
|
|
196
|
+
let steps = 0;
|
|
197
|
+
while (ns > 0 && nl > 0) {
|
|
198
|
+
if ((++steps & 0xFFFF) === 0) yield;
|
|
199
|
+
const s = small[--ns];
|
|
200
|
+
const l = large[--nl];
|
|
201
|
+
prob[s] = scaled[s];
|
|
202
|
+
alias[s] = l;
|
|
203
|
+
scaled[l] = scaled[l] + scaled[s] - 1;
|
|
204
|
+
if (scaled[l] < 1) small[ns++] = l;
|
|
205
|
+
else large[nl++] = l;
|
|
206
|
+
}
|
|
207
|
+
while (nl > 0) { const l = large[--nl]; prob[l] = 1; alias[l] = l; }
|
|
208
|
+
while (ns > 0) { const s = small[--ns]; prob[s] = 1; alias[s] = s; }
|
|
209
|
+
return { prob, alias };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ===========================
|
|
213
|
+
// GAUSSIAN
|
|
214
|
+
// ===========================
|
|
215
|
+
|
|
216
|
+
// Lloyd-Max optimal centroids for standard Gaussian
|
|
217
|
+
//
|
|
218
|
+
// for a standard normal distribution, the optimal L=2^bits levels are
|
|
219
|
+
// computed by iterative Lloyd's algorithm. the result depends only on
|
|
220
|
+
// `levels`, so it is computed once per bit-width and shared by every instance.
|
|
221
|
+
const centroidCache = new Map();
|
|
222
|
+
function getGaussianCentroids(levels) {
|
|
223
|
+
if (!centroidCache.has(levels)) centroidCache.set(levels, computeGaussianCentroids(levels));
|
|
224
|
+
return centroidCache.get(levels);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function computeGaussianCentroids(levels) {
|
|
228
|
+
// use samples from Gaussian to run Lloyd's algorithm
|
|
229
|
+
// deterministic — fixed seed means the centroids are always the same
|
|
230
|
+
const nSamples = 100000;
|
|
231
|
+
const samples = new Float64Array(nSamples);
|
|
232
|
+
|
|
233
|
+
const det = createRng(12345);
|
|
234
|
+
for (let i = 0; i < nSamples; i++) {
|
|
235
|
+
samples[i] = gaussianSample(det);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// initialize centroids uniformly on quantile grid of Gaussian
|
|
239
|
+
const centroids = new Float64Array(levels);
|
|
240
|
+
for (let i = 0; i < levels; i++) {
|
|
241
|
+
const p = (i + 0.5) / levels;
|
|
242
|
+
centroids[i] = gaussianInverseCDF(p);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Lloyd's algorithm: alternate assignment and centroid update
|
|
246
|
+
const assignments = new Int32Array(nSamples);
|
|
247
|
+
const iterations = 50;
|
|
248
|
+
|
|
249
|
+
for (let iter = 0; iter < iterations; iter++) {
|
|
250
|
+
// assign each sample to nearest centroid
|
|
251
|
+
// centroids stay sorted (quantile init + Lloyd preserves order on 1-D),
|
|
252
|
+
// so a binary search over midpoints finds the nearest in O(log levels)
|
|
253
|
+
let changed = 0;
|
|
254
|
+
for (let s = 0; s < nSamples; s++) {
|
|
255
|
+
const x = samples[s];
|
|
256
|
+
let lo = 0, hi = levels - 1;
|
|
257
|
+
while (lo < hi) {
|
|
258
|
+
const mid = (lo + hi) >> 1;
|
|
259
|
+
if (x < (centroids[mid] + centroids[mid + 1]) / 2) hi = mid;
|
|
260
|
+
else lo = mid + 1;
|
|
261
|
+
}
|
|
262
|
+
const best = lo;
|
|
263
|
+
if (assignments[s] !== best) {
|
|
264
|
+
assignments[s] = best;
|
|
265
|
+
changed++;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// update centroids to mean of assigned samples
|
|
270
|
+
const sums = new Float64Array(levels);
|
|
271
|
+
const counts = new Int32Array(levels);
|
|
272
|
+
for (let s = 0; s < nSamples; s++) {
|
|
273
|
+
const c = assignments[s];
|
|
274
|
+
sums[c] += samples[s];
|
|
275
|
+
counts[c]++;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
for (let c = 0; c < levels; c++) {
|
|
279
|
+
if (counts[c] > 0) {
|
|
280
|
+
centroids[c] = sums[c] / counts[c];
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (changed === 0) break;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// sort centroids ascending — required for boundary computation
|
|
288
|
+
const sorted = Array.from(centroids).sort((a, b) => a - b);
|
|
289
|
+
return new Float32Array(sorted);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// approximate inverse Gaussian CDF (Beasley-Springer-Moro)
|
|
293
|
+
function gaussianInverseCDF(p) {
|
|
294
|
+
const a = [
|
|
295
|
+
-3.969683028665376e+01,
|
|
296
|
+
2.209460984245205e+02,
|
|
297
|
+
-2.759285104469687e+02,
|
|
298
|
+
1.383577518672690e+02,
|
|
299
|
+
-3.066479806614716e+01,
|
|
300
|
+
2.506628277459239e+00
|
|
301
|
+
];
|
|
302
|
+
const b = [
|
|
303
|
+
-5.447609879822406e+01,
|
|
304
|
+
1.615858368580409e+02,
|
|
305
|
+
-1.556989798598866e+02,
|
|
306
|
+
6.680131188771972e+01,
|
|
307
|
+
-1.328068155288572e+01
|
|
308
|
+
];
|
|
309
|
+
const c = [
|
|
310
|
+
-7.784894002430293e-03,
|
|
311
|
+
-3.223964580411365e-01,
|
|
312
|
+
-2.400758277161838e+00,
|
|
313
|
+
-2.549732539343734e+00,
|
|
314
|
+
4.374664141464968e+00,
|
|
315
|
+
2.938163982698783e+00
|
|
316
|
+
];
|
|
317
|
+
const d = [
|
|
318
|
+
7.784695709041462e-03,
|
|
319
|
+
3.224671290700398e-01,
|
|
320
|
+
2.445134137142996e+00,
|
|
321
|
+
3.754408661907416e+00
|
|
322
|
+
];
|
|
323
|
+
|
|
324
|
+
const pLow = 0.02425;
|
|
325
|
+
const pHigh = 1 - pLow;
|
|
326
|
+
|
|
327
|
+
let q, r;
|
|
328
|
+
|
|
329
|
+
if (p < pLow) {
|
|
330
|
+
q = Math.sqrt(-2 * Math.log(p));
|
|
331
|
+
return (((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) /
|
|
332
|
+
((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1);
|
|
333
|
+
} else if (p <= pHigh) {
|
|
334
|
+
q = p - 0.5;
|
|
335
|
+
r = q * q;
|
|
336
|
+
return (((((a[0]*r + a[1])*r + a[2])*r + a[3])*r + a[4])*r + a[5])*q /
|
|
337
|
+
(((((b[0]*r + b[1])*r + b[2])*r + b[3])*r + b[4])*r + 1);
|
|
338
|
+
} else {
|
|
339
|
+
q = Math.sqrt(-2 * Math.log(1 - p));
|
|
340
|
+
return -(((((c[0]*q + c[1])*q + c[2])*q + c[3])*q + c[4])*q + c[5]) /
|
|
341
|
+
((((d[0]*q + d[1])*q + d[2])*q + d[3])*q + 1);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// boundaries between centroids (midpoints)
|
|
346
|
+
function computeBoundaries(centroids) {
|
|
347
|
+
const boundaries = new Float32Array(centroids.length - 1);
|
|
348
|
+
for (let i = 0; i < centroids.length - 1; i++) {
|
|
349
|
+
boundaries[i] = (centroids[i] + centroids[i + 1]) / 2;
|
|
350
|
+
}
|
|
351
|
+
return boundaries;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ===========================
|
|
355
|
+
// TRANSFORMS
|
|
356
|
+
// ===========================
|
|
357
|
+
|
|
358
|
+
// Walsh-Hadamard transform (in-place, O(n log n)); x.length must be a power of 2
|
|
359
|
+
function walshHadamard(x) {
|
|
360
|
+
const n = x.length;
|
|
361
|
+
let h = 1;
|
|
362
|
+
while (h < n) {
|
|
363
|
+
for (let i = 0; i < n; i += h * 2) {
|
|
364
|
+
for (let j = i; j < i + h; j++) {
|
|
365
|
+
const a = x[j];
|
|
366
|
+
const b = x[j + h];
|
|
367
|
+
x[j] = a + b;
|
|
368
|
+
x[j + h] = a - b;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
h *= 2;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function nextPow2(n) {
|
|
376
|
+
let p = 1;
|
|
377
|
+
while (p < n) p <<= 1;
|
|
378
|
+
return p;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// ===========================
|
|
382
|
+
// BITS
|
|
383
|
+
// ===========================
|
|
384
|
+
|
|
385
|
+
// bit packing — continuous little-endian bitstream, any width 1..8
|
|
386
|
+
//
|
|
387
|
+
// code i occupies bits [i*bits, i*bits + bits) of the stream.
|
|
388
|
+
// a code may straddle a byte boundary (e.g. bits=3, 5, 6, 7), so we
|
|
389
|
+
// write/read through a 16-bit window: the low byte and the next one.
|
|
390
|
+
function packBits(codes, bits) {
|
|
391
|
+
const n = codes.length;
|
|
392
|
+
const out = new Uint8Array(Math.ceil(n * bits / 8));
|
|
393
|
+
|
|
394
|
+
if (bits === 8) {
|
|
395
|
+
out.set(codes);
|
|
396
|
+
return out;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const mask = (1 << bits) - 1;
|
|
400
|
+
for (let i = 0; i < n; i++) {
|
|
401
|
+
const bitPos = i * bits;
|
|
402
|
+
const byteIdx = bitPos >> 3;
|
|
403
|
+
const shift = bitPos & 7;
|
|
404
|
+
const v = (codes[i] & mask) << shift; // up to 15 bits wide
|
|
405
|
+
out[byteIdx] |= v & 0xff;
|
|
406
|
+
if (shift + bits > 8) out[byteIdx + 1] |= v >> 8;
|
|
407
|
+
}
|
|
408
|
+
return out;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function unpackBits(packed, bits, count) {
|
|
412
|
+
if (bits === 8) return packed.slice(0, count);
|
|
413
|
+
|
|
414
|
+
const codes = new Uint8Array(count);
|
|
415
|
+
const mask = (1 << bits) - 1;
|
|
416
|
+
for (let i = 0; i < count; i++) {
|
|
417
|
+
const bitPos = i * bits;
|
|
418
|
+
const byteIdx = bitPos >> 3;
|
|
419
|
+
const shift = bitPos & 7;
|
|
420
|
+
let window = packed[byteIdx];
|
|
421
|
+
if (shift + bits > 8) window |= packed[byteIdx + 1] << 8;
|
|
422
|
+
codes[i] = (window >> shift) & mask;
|
|
423
|
+
}
|
|
424
|
+
return codes;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// popcount of a 32-bit word (SWAR: count bits in parallel within the word)
|
|
428
|
+
function popcount32(x) {
|
|
429
|
+
x = x - ((x >>> 1) & 0x55555555);
|
|
430
|
+
x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
|
|
431
|
+
return Math.imul((x + (x >>> 4)) & 0x0F0F0F0F, 0x01010101) >>> 24;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// popcount for a single byte — number of set bits
|
|
435
|
+
// small precomputed table for speed
|
|
436
|
+
const POPCOUNT_TABLE = (() => {
|
|
437
|
+
const table = new Uint8Array(256);
|
|
438
|
+
for (let i = 0; i < 256; i++) {
|
|
439
|
+
let count = 0;
|
|
440
|
+
let n = i;
|
|
441
|
+
while (n) {
|
|
442
|
+
count += n & 1;
|
|
443
|
+
n >>= 1;
|
|
444
|
+
}
|
|
445
|
+
table[i] = count;
|
|
446
|
+
}
|
|
447
|
+
return table;
|
|
448
|
+
})();
|
|
449
|
+
|
|
450
|
+
// ===========================
|
|
451
|
+
// LINEAR ALGEBRA (small, dense, row-major)
|
|
452
|
+
// ===========================
|
|
453
|
+
|
|
454
|
+
// generators (…Steps) that yield between steps, for long jobs that must
|
|
455
|
+
// not freeze the thread; symmetricEigen is also a plain function.
|
|
456
|
+
|
|
457
|
+
// orthonormalizes the columns of M (rows × cols, row-major) in place —
|
|
458
|
+
// modified Gram-Schmidt, run twice ("twice is enough", Giraud et al. 2005)
|
|
459
|
+
// for orthogonality to machine precision. a column that becomes zero (rank
|
|
460
|
+
// deficiency) is left zero. yields after every column.
|
|
461
|
+
function* orthonormalizeColumnsSteps(M, rows, cols) {
|
|
462
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
463
|
+
for (let j = 0; j < cols; j++) {
|
|
464
|
+
for (let p = 0; p < j; p++) {
|
|
465
|
+
let dot = 0;
|
|
466
|
+
for (let i = 0; i < rows; i++) dot += M[i * cols + j] * M[i * cols + p];
|
|
467
|
+
for (let i = 0; i < rows; i++) M[i * cols + j] -= dot * M[i * cols + p];
|
|
468
|
+
}
|
|
469
|
+
let nrm = 0;
|
|
470
|
+
for (let i = 0; i < rows; i++) nrm += M[i * cols + j] * M[i * cols + j];
|
|
471
|
+
nrm = Math.sqrt(nrm);
|
|
472
|
+
const inv = nrm > 1e-12 ? 1 / nrm : 0;
|
|
473
|
+
for (let i = 0; i < rows; i++) M[i * cols + j] *= inv;
|
|
474
|
+
yield true;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// eigen-decomposition of a symmetric matrix A (n × n, row-major; A is not
|
|
480
|
+
// modified): Householder reduction to tridiagonal form, then the implicit
|
|
481
|
+
// QL algorithm (tred2 / tql2 — EISPACK, as in JAMA). O(n³) once, about 10×
|
|
482
|
+
// fewer operations than Jacobi sweeps. returns { values, vectors } with
|
|
483
|
+
// values descending and vectors[i * n + j] = component i of eigenvector j.
|
|
484
|
+
// yields between rows / iterations.
|
|
485
|
+
function* symmetricEigenSteps(A, n) {
|
|
486
|
+
const V = Float64Array.from(A); // V[i * n + j]
|
|
487
|
+
const dg = new Float64Array(n), e = new Float64Array(n);
|
|
488
|
+
for (let j = 0; j < n; j++) dg[j] = V[(n - 1) * n + j];
|
|
489
|
+
|
|
490
|
+
// tred2: Householder tridiagonalization
|
|
491
|
+
for (let i = n - 1; i > 0; i--) {
|
|
492
|
+
let scale = 0, h = 0;
|
|
493
|
+
for (let k = 0; k < i; k++) scale += Math.abs(dg[k]);
|
|
494
|
+
if (scale === 0) {
|
|
495
|
+
e[i] = dg[i - 1];
|
|
496
|
+
for (let j = 0; j < i; j++) {
|
|
497
|
+
dg[j] = V[(i - 1) * n + j];
|
|
498
|
+
V[i * n + j] = 0;
|
|
499
|
+
V[j * n + i] = 0;
|
|
500
|
+
}
|
|
501
|
+
} else {
|
|
502
|
+
for (let k = 0; k < i; k++) { dg[k] /= scale; h += dg[k] * dg[k]; }
|
|
503
|
+
let f = dg[i - 1];
|
|
504
|
+
let gg = Math.sqrt(h);
|
|
505
|
+
if (f > 0) gg = -gg;
|
|
506
|
+
e[i] = scale * gg;
|
|
507
|
+
h -= f * gg;
|
|
508
|
+
dg[i - 1] = f - gg;
|
|
509
|
+
for (let j = 0; j < i; j++) e[j] = 0;
|
|
510
|
+
for (let j = 0; j < i; j++) {
|
|
511
|
+
f = dg[j];
|
|
512
|
+
V[j * n + i] = f;
|
|
513
|
+
gg = e[j] + V[j * n + j] * f;
|
|
514
|
+
for (let k = j + 1; k <= i - 1; k++) {
|
|
515
|
+
gg += V[k * n + j] * dg[k];
|
|
516
|
+
e[k] += V[k * n + j] * f;
|
|
517
|
+
}
|
|
518
|
+
e[j] = gg;
|
|
519
|
+
}
|
|
520
|
+
f = 0;
|
|
521
|
+
for (let j = 0; j < i; j++) { e[j] /= h; f += e[j] * dg[j]; }
|
|
522
|
+
const hh = f / (h + h);
|
|
523
|
+
for (let j = 0; j < i; j++) e[j] -= hh * dg[j];
|
|
524
|
+
for (let j = 0; j < i; j++) {
|
|
525
|
+
f = dg[j];
|
|
526
|
+
gg = e[j];
|
|
527
|
+
for (let k = j; k <= i - 1; k++) V[k * n + j] -= (f * e[k] + gg * dg[k]);
|
|
528
|
+
dg[j] = V[(i - 1) * n + j];
|
|
529
|
+
V[i * n + j] = 0;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
dg[i] = h;
|
|
533
|
+
yield true;
|
|
534
|
+
}
|
|
535
|
+
for (let i = 0; i < n - 1; i++) {
|
|
536
|
+
V[(n - 1) * n + i] = V[i * n + i];
|
|
537
|
+
V[i * n + i] = 1;
|
|
538
|
+
const h = dg[i + 1];
|
|
539
|
+
if (h !== 0) {
|
|
540
|
+
for (let k = 0; k <= i; k++) dg[k] = V[k * n + i + 1] / h;
|
|
541
|
+
for (let j = 0; j <= i; j++) {
|
|
542
|
+
let gg = 0;
|
|
543
|
+
for (let k = 0; k <= i; k++) gg += V[k * n + i + 1] * V[k * n + j];
|
|
544
|
+
for (let k = 0; k <= i; k++) V[k * n + j] -= gg * dg[k];
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
for (let k = 0; k <= i; k++) V[k * n + i + 1] = 0;
|
|
548
|
+
yield true;
|
|
549
|
+
}
|
|
550
|
+
for (let j = 0; j < n; j++) { dg[j] = V[(n - 1) * n + j]; V[(n - 1) * n + j] = 0; }
|
|
551
|
+
V[(n - 1) * n + n - 1] = 1;
|
|
552
|
+
e[0] = 0;
|
|
553
|
+
|
|
554
|
+
// tql2: implicit QL on the tridiagonal matrix
|
|
555
|
+
for (let i = 1; i < n; i++) e[i - 1] = e[i];
|
|
556
|
+
e[n - 1] = 0;
|
|
557
|
+
let f = 0, tst1 = 0;
|
|
558
|
+
const eps = Math.pow(2, -52);
|
|
559
|
+
for (let l = 0; l < n; l++) {
|
|
560
|
+
tst1 = Math.max(tst1, Math.abs(dg[l]) + Math.abs(e[l]));
|
|
561
|
+
let m = l;
|
|
562
|
+
while (m < n) {
|
|
563
|
+
if (Math.abs(e[m]) <= eps * tst1) break;
|
|
564
|
+
m++;
|
|
565
|
+
}
|
|
566
|
+
if (m > l) {
|
|
567
|
+
do {
|
|
568
|
+
let gg = dg[l];
|
|
569
|
+
let p = (dg[l + 1] - gg) / (2 * e[l]);
|
|
570
|
+
let r = Math.hypot(p, 1);
|
|
571
|
+
if (p < 0) r = -r;
|
|
572
|
+
dg[l] = e[l] / (p + r);
|
|
573
|
+
dg[l + 1] = e[l] * (p + r);
|
|
574
|
+
const dl1 = dg[l + 1];
|
|
575
|
+
let h = gg - dg[l];
|
|
576
|
+
for (let i = l + 2; i < n; i++) dg[i] -= h;
|
|
577
|
+
f += h;
|
|
578
|
+
p = dg[m];
|
|
579
|
+
let c = 1, c2 = c, c3 = c;
|
|
580
|
+
const el1 = e[l + 1];
|
|
581
|
+
let s = 0, s2 = 0;
|
|
582
|
+
for (let i = m - 1; i >= l; i--) {
|
|
583
|
+
c3 = c2;
|
|
584
|
+
c2 = c;
|
|
585
|
+
s2 = s;
|
|
586
|
+
gg = c * e[i];
|
|
587
|
+
h = c * p;
|
|
588
|
+
r = Math.hypot(p, e[i]);
|
|
589
|
+
e[i + 1] = s * r;
|
|
590
|
+
s = e[i] / r;
|
|
591
|
+
c = p / r;
|
|
592
|
+
p = c * dg[i] - s * gg;
|
|
593
|
+
dg[i + 1] = h + s * (c * gg + s * dg[i]);
|
|
594
|
+
for (let k = 0; k < n; k++) {
|
|
595
|
+
h = V[k * n + i + 1];
|
|
596
|
+
V[k * n + i + 1] = s * V[k * n + i] + c * h;
|
|
597
|
+
V[k * n + i] = c * V[k * n + i] - s * h;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
p = -s * s2 * c3 * el1 * e[l] / dl1;
|
|
601
|
+
e[l] = s * p;
|
|
602
|
+
dg[l] = c * p;
|
|
603
|
+
} while (Math.abs(e[l]) > eps * tst1);
|
|
604
|
+
}
|
|
605
|
+
dg[l] = dg[l] + f;
|
|
606
|
+
e[l] = 0;
|
|
607
|
+
yield true;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => dg[b] - dg[a]);
|
|
611
|
+
const values = new Float64Array(n), vectors = new Float64Array(n * n);
|
|
612
|
+
order.forEach((src, j) => {
|
|
613
|
+
values[j] = dg[src];
|
|
614
|
+
for (let i = 0; i < n; i++) vectors[i * n + j] = V[i * n + src];
|
|
615
|
+
});
|
|
616
|
+
return { values, vectors };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function runSteps(it) {
|
|
620
|
+
let r = it.next();
|
|
621
|
+
while (!r.done) r = it.next();
|
|
622
|
+
return r.value;
|
|
623
|
+
}
|
|
624
|
+
const symmetricEigen = (A, n) => runSteps(symmetricEigenSteps(A, n));
|
|
625
|
+
|
|
626
|
+
// ===========================
|
|
627
|
+
// SEARCH
|
|
628
|
+
// ===========================
|
|
629
|
+
|
|
630
|
+
// index of x in sorted arr[lo, hi), or -1
|
|
631
|
+
function binarySearch(arr, lo, hi, x) {
|
|
632
|
+
while (lo < hi) {
|
|
633
|
+
const mid = (lo + hi) >>> 1;
|
|
634
|
+
const m = arr[mid];
|
|
635
|
+
if (m < x) lo = mid + 1;
|
|
636
|
+
else if (m > x) hi = mid;
|
|
637
|
+
else return mid;
|
|
638
|
+
}
|
|
639
|
+
return -1;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
export {
|
|
643
|
+
dotAt,
|
|
644
|
+
l2sqAt,
|
|
645
|
+
l2sqAtBounded,
|
|
646
|
+
cosine,
|
|
647
|
+
normalizeAt,
|
|
648
|
+
normalizedCopy,
|
|
649
|
+
rngState,
|
|
650
|
+
randFloat,
|
|
651
|
+
createRng,
|
|
652
|
+
gaussianSample,
|
|
653
|
+
buildAlias,
|
|
654
|
+
getGaussianCentroids,
|
|
655
|
+
computeBoundaries,
|
|
656
|
+
walshHadamard,
|
|
657
|
+
nextPow2,
|
|
658
|
+
packBits,
|
|
659
|
+
unpackBits,
|
|
660
|
+
popcount32,
|
|
661
|
+
POPCOUNT_TABLE,
|
|
662
|
+
orthonormalizeColumnsSteps,
|
|
663
|
+
symmetricEigen,
|
|
664
|
+
symmetricEigenSteps,
|
|
665
|
+
binarySearch
|
|
666
|
+
};
|