vector-index 0.0.0-stage → 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 -0
- package/README.md +1456 -2
- package/build-browser.js +67 -0
- package/index.js +39 -0
- package/package.json +72 -4
- 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
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
// ===========================
|
|
6
|
+
// TurboQuant — data-oblivious vector quantization
|
|
7
|
+
// based on Zandieh et al. 2025 (arXiv:2504.19874)
|
|
8
|
+
//
|
|
9
|
+
// key idea: rotate input with structured random rotation,
|
|
10
|
+
// then apply optimal per-coordinate scalar quantization.
|
|
11
|
+
// no training on data — codebook is fixed by dimension + bits.
|
|
12
|
+
//
|
|
13
|
+
// API (same shape as every quantizer in this package):
|
|
14
|
+
// every operation exists as name(..., cb) and nameSync(...)
|
|
15
|
+
// encode(vector) → Uint8Array(codeSize)
|
|
16
|
+
// decode(code) → Float32Array(dimensions)
|
|
17
|
+
// distance(query, code) → squared L2 between query and the encoded vector
|
|
18
|
+
// (exact stored norm + quantized direction)
|
|
19
|
+
// scan(query, codes, k) → [{ index, distance }]: the k closest codes in a
|
|
20
|
+
// buffer of codes laid back to back
|
|
21
|
+
// prepare(query) → prepared query (plain data) for similarityAt
|
|
22
|
+
// similarityAt(prepared, codes, offset)
|
|
23
|
+
// → estimate of ⟨query, x⟩ for the code at offset,
|
|
24
|
+
// higher = closer. prepare once, call per code.
|
|
25
|
+
// train(...) → NOT_SUPPORTED (requiresTraining === false)
|
|
26
|
+
// TurboQuantProd adds innerProduct(query, code) → unbiased ⟨query, x⟩
|
|
27
|
+
//
|
|
28
|
+
// code layout
|
|
29
|
+
// TurboQuant: [packed codes: ceil(paddedDim·bits/8) B][norm: float32 LE]
|
|
30
|
+
// TurboQuantProd: [TurboQuant code at bits-1][QJL sign bits: ceil(d/8) B]
|
|
31
|
+
// [residual norm: float32 LE]
|
|
32
|
+
// ===========================
|
|
33
|
+
|
|
34
|
+
import { computeBoundaries, createRng, gaussianSample, getGaussianCentroids, nextPow2, normalizedCopy, packBits, unpackBits, walshHadamard } from '../math.js';
|
|
35
|
+
import { ERR, createError } from '../errors.js';
|
|
36
|
+
import { pairedApi, createEmitter } from '../async.js';
|
|
37
|
+
import { checkVector, checkCode, checkPositiveInt } from '../validate.js';
|
|
38
|
+
import { scanTopK, checkCodes } from './scan.js';
|
|
39
|
+
|
|
40
|
+
const NORM_BYTES = 4;
|
|
41
|
+
|
|
42
|
+
function readFloat32(code, offset) {
|
|
43
|
+
return new DataView(code.buffer, code.byteOffset, code.byteLength).getFloat32(offset, true);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// allocation-free little-endian float32 read for the scan hot loop
|
|
47
|
+
// (a DataView per code would allocate on every iteration)
|
|
48
|
+
const F32_SCRATCH = new Float32Array(1);
|
|
49
|
+
const U8_SCRATCH = new Uint8Array(F32_SCRATCH.buffer);
|
|
50
|
+
const HOST_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
|
|
51
|
+
function readFloat32At(bytes, off) {
|
|
52
|
+
if (!HOST_LITTLE_ENDIAN) return readFloat32(bytes, off);
|
|
53
|
+
U8_SCRATCH[0] = bytes[off];
|
|
54
|
+
U8_SCRATCH[1] = bytes[off + 1];
|
|
55
|
+
U8_SCRATCH[2] = bytes[off + 2];
|
|
56
|
+
U8_SCRATCH[3] = bytes[off + 3];
|
|
57
|
+
return F32_SCRATCH[0];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function writeFloat32(code, offset, value) {
|
|
61
|
+
new DataView(code.buffer, code.byteOffset, code.byteLength).setFloat32(offset, value, true);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createTurboQuant(opts) {
|
|
65
|
+
opts = opts || {};
|
|
66
|
+
const dimensions = checkPositiveInt(opts.dimensions, 'dimensions');
|
|
67
|
+
const bits = opts.bits;
|
|
68
|
+
const seed = opts.seed == null ? 42 : opts.seed;
|
|
69
|
+
const normalize = !!opts.normalize;
|
|
70
|
+
const input = normalize ? normalizedCopy : (v) => v; // applied to every incoming vector
|
|
71
|
+
|
|
72
|
+
if (!Number.isInteger(bits) || bits < 1 || bits > 8) {
|
|
73
|
+
throw createError(ERR.INVALID_ARGUMENT, 'bits must be an integer between 1 and 8');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const levels = 1 << bits;
|
|
77
|
+
|
|
78
|
+
// pad dimensions to next power of 2 for Walsh-Hadamard
|
|
79
|
+
const paddedDim = nextPow2(dimensions);
|
|
80
|
+
const packedSize = Math.ceil(paddedDim * bits / 8);
|
|
81
|
+
const codeSize = packedSize + NORM_BYTES;
|
|
82
|
+
|
|
83
|
+
const rng = createRng(seed);
|
|
84
|
+
|
|
85
|
+
// random signs for D1 and D2 in rotation R = D2 · H · D1
|
|
86
|
+
// structured random rotation — fixed once per instance
|
|
87
|
+
const D1 = new Int8Array(paddedDim);
|
|
88
|
+
const D2 = new Int8Array(paddedDim);
|
|
89
|
+
for (let i = 0; i < paddedDim; i++) {
|
|
90
|
+
D1[i] = rng() < 0.5 ? -1 : 1;
|
|
91
|
+
D2[i] = rng() < 0.5 ? -1 : 1;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Lloyd-Max optimal centroids for the standard Gaussian
|
|
95
|
+
// (unit-norm vector coordinates after rotation converge to Gaussian
|
|
96
|
+
// in high dimensions; centroids are optimal for this distribution)
|
|
97
|
+
//
|
|
98
|
+
// for a random unit vector in R^d, each rotated coordinate has
|
|
99
|
+
// std ≈ 1/sqrt(d), so we normalize centroids accordingly at use time
|
|
100
|
+
const centroids = getGaussianCentroids(levels);
|
|
101
|
+
const boundaries = computeBoundaries(centroids);
|
|
102
|
+
const scale = Math.sqrt(paddedDim);
|
|
103
|
+
|
|
104
|
+
// no events are emitted today (nothing to train); on/off exist so every
|
|
105
|
+
// quantizer has the same shape
|
|
106
|
+
const emitter = createEmitter();
|
|
107
|
+
|
|
108
|
+
// ===========================
|
|
109
|
+
// apply structured rotation R = D2 · H · D1 (with 1/sqrt(n) scale)
|
|
110
|
+
// ===========================
|
|
111
|
+
function rotate(input) {
|
|
112
|
+
const x = new Float32Array(paddedDim);
|
|
113
|
+
for (let i = 0; i < dimensions; i++) x[i] = input[i];
|
|
114
|
+
for (let i = 0; i < paddedDim; i++) x[i] *= D1[i];
|
|
115
|
+
walshHadamard(x);
|
|
116
|
+
const invSqrtN = 1 / Math.sqrt(paddedDim);
|
|
117
|
+
for (let i = 0; i < paddedDim; i++) x[i] *= D2[i] * invSqrtN;
|
|
118
|
+
return x;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// inverse rotation: R^T = D1 · H · D2 (H is symmetric), same scale
|
|
122
|
+
function rotateInverse(x) {
|
|
123
|
+
for (let i = 0; i < paddedDim; i++) x[i] *= D2[i];
|
|
124
|
+
walshHadamard(x);
|
|
125
|
+
const invSqrtN = 1 / Math.sqrt(paddedDim);
|
|
126
|
+
for (let i = 0; i < paddedDim; i++) x[i] *= D1[i] * invSqrtN;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// find quantization bin using binary search on boundaries
|
|
130
|
+
function quantizeOne(value) {
|
|
131
|
+
const scaled = value * scale;
|
|
132
|
+
let lo = 0;
|
|
133
|
+
let hi = boundaries.length;
|
|
134
|
+
while (lo < hi) {
|
|
135
|
+
const mid = (lo + hi) >> 1;
|
|
136
|
+
if (scaled < boundaries[mid]) hi = mid;
|
|
137
|
+
else lo = mid + 1;
|
|
138
|
+
}
|
|
139
|
+
return lo;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ===========================
|
|
143
|
+
// encode: vector -> Uint8Array(codeSize) = packed codes + float32 norm
|
|
144
|
+
// ===========================
|
|
145
|
+
function encodeSync(vector) {
|
|
146
|
+
checkVector(vector, dimensions);
|
|
147
|
+
vector = input(vector);
|
|
148
|
+
|
|
149
|
+
// preserve norm — quantize direction, store magnitude separately
|
|
150
|
+
let norm = 0;
|
|
151
|
+
for (let i = 0; i < dimensions; i++) norm += vector[i] * vector[i];
|
|
152
|
+
norm = Math.sqrt(norm);
|
|
153
|
+
|
|
154
|
+
const codes = new Uint8Array(paddedDim);
|
|
155
|
+
if (norm === 0) {
|
|
156
|
+
// zero vector: middle centroid everywhere; norm 0 makes decode exact
|
|
157
|
+
codes.fill(levels >> 1);
|
|
158
|
+
} else {
|
|
159
|
+
const unit = new Float32Array(dimensions);
|
|
160
|
+
const invNorm = 1 / norm;
|
|
161
|
+
for (let i = 0; i < dimensions; i++) unit[i] = vector[i] * invNorm;
|
|
162
|
+
|
|
163
|
+
const rotated = rotate(unit);
|
|
164
|
+
for (let i = 0; i < paddedDim; i++) codes[i] = quantizeOne(rotated[i]);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const out = new Uint8Array(codeSize);
|
|
168
|
+
out.set(packBits(codes, bits), 0);
|
|
169
|
+
writeFloat32(out, packedSize, norm);
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ===========================
|
|
174
|
+
// decode: Uint8Array(codeSize) -> reconstructed vector
|
|
175
|
+
// ===========================
|
|
176
|
+
function decodeSync(code) {
|
|
177
|
+
checkCode(code, codeSize);
|
|
178
|
+
const norm = readFloat32(code, packedSize);
|
|
179
|
+
const codes = unpackBits(code.subarray(0, packedSize), bits, paddedDim);
|
|
180
|
+
|
|
181
|
+
const rotated = new Float32Array(paddedDim);
|
|
182
|
+
for (let i = 0; i < paddedDim; i++) rotated[i] = centroids[codes[i]] / scale;
|
|
183
|
+
|
|
184
|
+
rotateInverse(rotated);
|
|
185
|
+
|
|
186
|
+
// truncate padding and rescale to original norm
|
|
187
|
+
const result = new Float32Array(dimensions);
|
|
188
|
+
for (let i = 0; i < dimensions; i++) result[i] = rotated[i] * norm;
|
|
189
|
+
return result;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ===========================
|
|
193
|
+
// query-side evaluation — no decoding of codes
|
|
194
|
+
//
|
|
195
|
+
// the code stores c (quantized rotated direction) and ‖x‖. for a query q:
|
|
196
|
+
// ⟨q, x̂⟩ = ‖x‖ · ⟨R·pad(q), c / scale⟩
|
|
197
|
+
// which is exactly the inner product with the decoded vector, but costs one
|
|
198
|
+
// multiply-add per coordinate instead of an inverse rotation per code.
|
|
199
|
+
// the query is rotated once (O(d log d)) and reused for every code.
|
|
200
|
+
// ===========================
|
|
201
|
+
const mask = (1 << bits) - 1;
|
|
202
|
+
|
|
203
|
+
function prepare(query) {
|
|
204
|
+
query = input(query);
|
|
205
|
+
const qr = rotate(query);
|
|
206
|
+
const qs = new Float64Array(paddedDim);
|
|
207
|
+
for (let i = 0; i < paddedDim; i++) qs[i] = qr[i] / scale;
|
|
208
|
+
let qNormSq = 0;
|
|
209
|
+
for (let i = 0; i < dimensions; i++) qNormSq += query[i] * query[i];
|
|
210
|
+
return { qs, qNormSq };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ⟨R·pad(q)/scale, c⟩ for the code at byte offset `off`
|
|
214
|
+
function directionDot(prep, codes, off) {
|
|
215
|
+
const qs = prep.qs;
|
|
216
|
+
let sum = 0;
|
|
217
|
+
if (bits === 8) {
|
|
218
|
+
for (let i = 0; i < paddedDim; i++) sum += qs[i] * centroids[codes[off + i]];
|
|
219
|
+
return sum;
|
|
220
|
+
}
|
|
221
|
+
for (let i = 0; i < paddedDim; i++) {
|
|
222
|
+
const bitPos = i * bits;
|
|
223
|
+
const byte = off + (bitPos >> 3);
|
|
224
|
+
const shift = bitPos & 7;
|
|
225
|
+
let w = codes[byte];
|
|
226
|
+
if (shift + bits > 8) w |= codes[byte + 1] << 8;
|
|
227
|
+
sum += qs[i] * centroids[(w >> shift) & mask];
|
|
228
|
+
}
|
|
229
|
+
return sum;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function normAt(codes, off) {
|
|
233
|
+
return readFloat32At(codes, off + packedSize);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ⟨q, x̂⟩ for the code at `off`
|
|
237
|
+
function innerProductAt(prep, codes, off) {
|
|
238
|
+
return normAt(codes, off) * directionDot(prep, codes, off);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ‖q − x‖² ≈ ‖q‖² + ‖x‖² − 2⟨q, x̂⟩, with the exact stored ‖x‖
|
|
242
|
+
function distanceAt(prep, codes, off) {
|
|
243
|
+
const norm = normAt(codes, off);
|
|
244
|
+
return Math.max(0, prep.qNormSq + norm * norm - 2 * norm * directionDot(prep, codes, off));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ===========================
|
|
248
|
+
// distance: squared L2 between the query and the encoded vector, using
|
|
249
|
+
// its exact norm and quantized direction (same formula as scan)
|
|
250
|
+
// ===========================
|
|
251
|
+
function distanceSync(query, code) {
|
|
252
|
+
checkVector(query, dimensions, 'query');
|
|
253
|
+
checkCode(code, codeSize);
|
|
254
|
+
return distanceAt(prepare(query), code, 0);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ===========================
|
|
258
|
+
// scan: the k codes closest to the query in a buffer of codes
|
|
259
|
+
// ===========================
|
|
260
|
+
function* scanJob(query, codes, k) {
|
|
261
|
+
checkVector(query, dimensions, 'query');
|
|
262
|
+
checkCodes(codes, codeSize, k);
|
|
263
|
+
const prep = prepare(query);
|
|
264
|
+
return yield* scanTopK(codes, codeSize, k, (off) => distanceAt(prep, codes, off));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function trainSync(vectors) {
|
|
268
|
+
throw createError(ERR.NOT_SUPPORTED, 'TurboQuant does not need training (requiresTraining is false)');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ===========================
|
|
272
|
+
// prepare + similarityAt — one query against many codes: estimate of
|
|
273
|
+
// ⟨query, x⟩, higher = closer. prepare does the per-query work once
|
|
274
|
+
// (rotation); similarityAt does no argument checks (hot path).
|
|
275
|
+
// ===========================
|
|
276
|
+
function prepareSync(query) {
|
|
277
|
+
checkVector(query, dimensions, 'query');
|
|
278
|
+
return prepare(query);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function similarityAtSync(prepared, codes, offset) {
|
|
282
|
+
return innerProductAt(prepared, codes, offset);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return Object.assign(
|
|
286
|
+
pairedApi({
|
|
287
|
+
train: trainSync,
|
|
288
|
+
encode: encodeSync,
|
|
289
|
+
decode: decodeSync,
|
|
290
|
+
distance: distanceSync,
|
|
291
|
+
scan: scanJob,
|
|
292
|
+
prepare: prepareSync,
|
|
293
|
+
similarityAt: similarityAtSync
|
|
294
|
+
}),
|
|
295
|
+
{
|
|
296
|
+
on: emitter.on,
|
|
297
|
+
off: emitter.off,
|
|
298
|
+
// config
|
|
299
|
+
dimensions,
|
|
300
|
+
paddedDim,
|
|
301
|
+
bits,
|
|
302
|
+
codeSize,
|
|
303
|
+
normalize,
|
|
304
|
+
requiresTraining: false,
|
|
305
|
+
isTrained: () => true,
|
|
306
|
+
// internal (used by TurboQuantProd) / debug
|
|
307
|
+
_prepare: prepare,
|
|
308
|
+
_innerProductAt: innerProductAt,
|
|
309
|
+
_distanceAt: distanceAt,
|
|
310
|
+
_normAt: normAt,
|
|
311
|
+
_getRotation: () => ({ D1, D2 }),
|
|
312
|
+
_getCentroids: () => ({ centroids, boundaries }),
|
|
313
|
+
_rotate: rotate,
|
|
314
|
+
_rotateInverse: rotateInverse
|
|
315
|
+
}
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// ===========================
|
|
320
|
+
// TurboQuantProd — unbiased inner product quantizer
|
|
321
|
+
// two-stage: TurboQuantMse at (b-1) bits + 1-bit QJL on residual
|
|
322
|
+
// based on Zandieh et al. 2025, Algorithm 2
|
|
323
|
+
//
|
|
324
|
+
// key property: E[⟨y, x̃⟩] = ⟨y, x⟩ (unbiased)
|
|
325
|
+
// ===========================
|
|
326
|
+
|
|
327
|
+
function createTurboQuantProd(opts) {
|
|
328
|
+
opts = opts || {};
|
|
329
|
+
const dimensions = checkPositiveInt(opts.dimensions, 'dimensions');
|
|
330
|
+
const bits = opts.bits;
|
|
331
|
+
const seed = opts.seed == null ? 42 : opts.seed;
|
|
332
|
+
const normalize = !!opts.normalize;
|
|
333
|
+
const input = normalize ? normalizedCopy : (v) => v; // applied to every incoming vector
|
|
334
|
+
|
|
335
|
+
if (!Number.isInteger(bits) || bits < 2 || bits > 9) {
|
|
336
|
+
throw createError(ERR.INVALID_ARGUMENT,
|
|
337
|
+
'TurboQuantProd bits must be an integer between 2 and 9 (1 for QJL + 1..8 for MSE)');
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const mseBits = bits - 1; // stage 1 uses one less bit
|
|
341
|
+
const qjlBits = 1; // stage 2 always uses 1 bit for QJL
|
|
342
|
+
|
|
343
|
+
// stage 1: MSE quantizer
|
|
344
|
+
const mseQuantizer = createTurboQuant({ dimensions, bits: mseBits, seed });
|
|
345
|
+
const paddedDim = mseQuantizer.paddedDim;
|
|
346
|
+
|
|
347
|
+
// stage 2: QJL projection matrix S (mProj × dimensions), standard Gaussian
|
|
348
|
+
// rows. the residual lives in the original space, so S does too.
|
|
349
|
+
// seed is offset so rotation and S are independent random streams.
|
|
350
|
+
const rng = createRng((seed * 31 + 17) >>> 0);
|
|
351
|
+
const mProj = dimensions;
|
|
352
|
+
const S = new Float32Array(mProj * dimensions);
|
|
353
|
+
for (let i = 0; i < S.length; i++) S[i] = gaussianSample(rng);
|
|
354
|
+
|
|
355
|
+
const mseSize = mseQuantizer.codeSize;
|
|
356
|
+
const qjlSize = Math.ceil(mProj / 8);
|
|
357
|
+
const codeSize = mseSize + qjlSize + NORM_BYTES;
|
|
358
|
+
|
|
359
|
+
const emitter = createEmitter();
|
|
360
|
+
|
|
361
|
+
// apply S · x — matrix-vector product
|
|
362
|
+
function projectQJL(input) {
|
|
363
|
+
const result = new Float32Array(mProj);
|
|
364
|
+
for (let i = 0; i < mProj; i++) {
|
|
365
|
+
let sum = 0;
|
|
366
|
+
for (let j = 0; j < dimensions; j++) sum += S[i * dimensions + j] * input[j];
|
|
367
|
+
result[i] = sum;
|
|
368
|
+
}
|
|
369
|
+
return result;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function mseCode(code) {
|
|
373
|
+
return code.subarray(0, mseSize);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ===========================
|
|
377
|
+
// encode: vector -> [mse code][qjl bits][residual norm]
|
|
378
|
+
// ===========================
|
|
379
|
+
function encodeSync(vector) {
|
|
380
|
+
checkVector(vector, dimensions);
|
|
381
|
+
vector = input(vector);
|
|
382
|
+
|
|
383
|
+
const mse = mseQuantizer.encodeSync(vector);
|
|
384
|
+
const xHat = mseQuantizer.decodeSync(mse);
|
|
385
|
+
|
|
386
|
+
// residual r = x - x̂ (not normalized — the estimator works on it directly)
|
|
387
|
+
const residual = new Float32Array(dimensions);
|
|
388
|
+
let residualNormSq = 0;
|
|
389
|
+
for (let i = 0; i < dimensions; i++) {
|
|
390
|
+
residual[i] = vector[i] - xHat[i];
|
|
391
|
+
residualNormSq += residual[i] * residual[i];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// 1-bit QJL: sign of each projection of the residual
|
|
395
|
+
const projected = projectQJL(residual);
|
|
396
|
+
|
|
397
|
+
const out = new Uint8Array(codeSize);
|
|
398
|
+
out.set(mse, 0);
|
|
399
|
+
for (let i = 0; i < mProj; i++) {
|
|
400
|
+
if (projected[i] >= 0) out[mseSize + (i >> 3)] |= (1 << (i & 7));
|
|
401
|
+
}
|
|
402
|
+
writeFloat32(out, mseSize + qjlSize, Math.sqrt(residualNormSq));
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ===========================
|
|
407
|
+
// decode: returns the MSE-stage reconstruction x̂.
|
|
408
|
+
// the 1-bit QJL part can't reconstruct the residual — it is only used to
|
|
409
|
+
// correct inner products at query time (innerProduct / distance).
|
|
410
|
+
// ===========================
|
|
411
|
+
function decodeSync(code) {
|
|
412
|
+
checkCode(code, codeSize);
|
|
413
|
+
return mseQuantizer.decodeSync(mseCode(code));
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// ===========================
|
|
417
|
+
// query preparation: rotate the query for the MSE stage and project it
|
|
418
|
+
// with S for the QJL stage — once per query. S·q is an O(d²) product: done
|
|
419
|
+
// per code (as before) it dominated everything; scan() does it once for
|
|
420
|
+
// the whole buffer.
|
|
421
|
+
// ===========================
|
|
422
|
+
const QJL_SCALE = Math.sqrt(Math.PI / 2) / mProj;
|
|
423
|
+
|
|
424
|
+
function prepare(query) {
|
|
425
|
+
query = input(query);
|
|
426
|
+
const mse = mseQuantizer._prepare(query);
|
|
427
|
+
return { mse, sq: projectQJL(query), qNormSq: mse.qNormSq };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// ===========================
|
|
431
|
+
// innerProduct: unbiased estimator of ⟨query, x⟩
|
|
432
|
+
//
|
|
433
|
+
// ⟨q, x⟩ = ⟨q, x̂⟩ + ⟨q, r⟩
|
|
434
|
+
// ⟨q, r⟩ ≈ sqrt(π/2) · ‖r‖ · (1/m) · Σ sign(S_i·r) · (S_i·q)
|
|
435
|
+
// ===========================
|
|
436
|
+
function innerProductAt(prep, codes, off) {
|
|
437
|
+
const ipMse = mseQuantizer._innerProductAt(prep.mse, codes, off);
|
|
438
|
+
const residualNorm = readFloat32At(codes, off + mseSize + qjlSize);
|
|
439
|
+
if (residualNorm === 0) return ipMse;
|
|
440
|
+
const sq = prep.sq;
|
|
441
|
+
const qjlOff = off + mseSize;
|
|
442
|
+
let dot = 0;
|
|
443
|
+
for (let i = 0; i < mProj; i++) {
|
|
444
|
+
dot += ((codes[qjlOff + (i >> 3)] >> (i & 7)) & 1) ? sq[i] : -sq[i];
|
|
445
|
+
}
|
|
446
|
+
return ipMse + QJL_SCALE * residualNorm * dot;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// ‖q − x‖² = ‖q‖² + ‖x‖² − 2⟨q, x⟩, with ‖x‖ stored exactly by the MSE stage
|
|
450
|
+
function distanceAt(prep, codes, off) {
|
|
451
|
+
const xNorm = mseQuantizer._normAt(codes, off);
|
|
452
|
+
return Math.max(0, prep.qNormSq + xNorm * xNorm - 2 * innerProductAt(prep, codes, off));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// single code: prepares the query each time (O(d²)) — for many codes use scan
|
|
456
|
+
function innerProductSync(query, code) {
|
|
457
|
+
checkVector(query, dimensions, 'query');
|
|
458
|
+
checkCode(code, codeSize);
|
|
459
|
+
return innerProductAt(prepare(query), code, 0);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function distanceSync(query, code) {
|
|
463
|
+
checkVector(query, dimensions, 'query');
|
|
464
|
+
checkCode(code, codeSize);
|
|
465
|
+
return distanceAt(prepare(query), code, 0);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// the k codes closest to the query (smallest distance) in a buffer
|
|
469
|
+
function* scanJob(query, codes, k) {
|
|
470
|
+
checkVector(query, dimensions, 'query');
|
|
471
|
+
checkCodes(codes, codeSize, k);
|
|
472
|
+
const prep = prepare(query);
|
|
473
|
+
return yield* scanTopK(codes, codeSize, k, (off) => distanceAt(prep, codes, off));
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function trainSync(vectors) {
|
|
477
|
+
throw createError(ERR.NOT_SUPPORTED, 'TurboQuantProd does not need training (requiresTraining is false)');
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// ===========================
|
|
481
|
+
// prepare + similarityAt — one query against many codes: estimate of
|
|
482
|
+
// ⟨query, x⟩, higher = closer. prepare does the per-query work once
|
|
483
|
+
// (rotation, projection); similarityAt does no argument checks (hot path).
|
|
484
|
+
// ===========================
|
|
485
|
+
function prepareSync(query) {
|
|
486
|
+
checkVector(query, dimensions, 'query');
|
|
487
|
+
return prepare(query);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function similarityAtSync(prepared, codes, offset) {
|
|
491
|
+
return innerProductAt(prepared, codes, offset);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
return Object.assign(
|
|
495
|
+
pairedApi({
|
|
496
|
+
train: trainSync,
|
|
497
|
+
encode: encodeSync,
|
|
498
|
+
decode: decodeSync,
|
|
499
|
+
distance: distanceSync,
|
|
500
|
+
innerProduct: innerProductSync,
|
|
501
|
+
scan: scanJob,
|
|
502
|
+
prepare: prepareSync,
|
|
503
|
+
similarityAt: similarityAtSync
|
|
504
|
+
}),
|
|
505
|
+
{
|
|
506
|
+
on: emitter.on,
|
|
507
|
+
off: emitter.off,
|
|
508
|
+
dimensions,
|
|
509
|
+
paddedDim,
|
|
510
|
+
bits,
|
|
511
|
+
mseBits,
|
|
512
|
+
qjlBits,
|
|
513
|
+
codeSize,
|
|
514
|
+
normalize,
|
|
515
|
+
requiresTraining: false,
|
|
516
|
+
isTrained: () => true,
|
|
517
|
+
// debug
|
|
518
|
+
_mseQuantizer: mseQuantizer,
|
|
519
|
+
_projectQJL: projectQJL
|
|
520
|
+
}
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export {
|
|
525
|
+
createTurboQuant,
|
|
526
|
+
createTurboQuantProd
|
|
527
|
+
};
|