|
| 1 | +/** |
| 2 | + * Product quantization helpers. |
| 3 | + * |
| 4 | + * Codebooks are stored segment-major. For segment s with bounds |
| 5 | + * [bounds[s], bounds[s + 1]), the codebook block starts at |
| 6 | + * `centroids * bounds[s]` and contains `centroids * segmentDim` float32s. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @import { DistanceMetric, HypVectorMetadata } from './types.js' |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * Build product-quantized codes for a set of vectors. |
| 15 | + * |
| 16 | + * @param {object} options |
| 17 | + * @param {Float32Array[]} options.vectors |
| 18 | + * @param {number} options.dimension |
| 19 | + * @param {number} options.segments |
| 20 | + * @param {number} options.centroids |
| 21 | + * @param {number} options.iterations |
| 22 | + * @param {number} options.sampleSize |
| 23 | + * @param {number} options.seed |
| 24 | + * @returns {{ codes: Uint8Array[], codebooks: Float32Array, segments: number, centroids: number }} |
| 25 | + */ |
| 26 | +export function buildPq({ vectors, dimension, segments, centroids, iterations, sampleSize, seed }) { |
| 27 | + if (!Number.isInteger(segments) || segments <= 0) { |
| 28 | + throw new Error(`pqSegments must be a positive integer, got ${segments}`) |
| 29 | + } |
| 30 | + if (!Number.isInteger(centroids) || centroids <= 1 || centroids > 256) { |
| 31 | + throw new Error(`pqCentroids must be an integer in [2, 256], got ${centroids}`) |
| 32 | + } |
| 33 | + const effectiveSegments = Math.min(segments, dimension) |
| 34 | + const bounds = pqSegmentBounds(dimension, effectiveSegments) |
| 35 | + const sample = sampleIndices(vectors.length, sampleSize) |
| 36 | + const codebooks = new Float32Array(centroids * dimension) |
| 37 | + |
| 38 | + for (let s = 0; s < effectiveSegments; s += 1) { |
| 39 | + trainSegment({ |
| 40 | + vectors, |
| 41 | + sample, |
| 42 | + start: bounds[s], |
| 43 | + end: bounds[s + 1], |
| 44 | + centroids, |
| 45 | + iterations, |
| 46 | + seed: seed + s * 1009, |
| 47 | + out: codebooks, |
| 48 | + }) |
| 49 | + } |
| 50 | + |
| 51 | + const codes = new Array(vectors.length) |
| 52 | + for (let i = 0; i < vectors.length; i += 1) { |
| 53 | + codes[i] = encodePqVector(vectors[i], codebooks, dimension, effectiveSegments, centroids) |
| 54 | + } |
| 55 | + |
| 56 | + return { codes, codebooks, segments: effectiveSegments, centroids } |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * Return segment boundaries that cover [0, dimension). |
| 61 | + * |
| 62 | + * @param {number} dimension |
| 63 | + * @param {number} segments |
| 64 | + * @returns {Uint32Array} |
| 65 | + */ |
| 66 | +export function pqSegmentBounds(dimension, segments) { |
| 67 | + const bounds = new Uint32Array(segments + 1) |
| 68 | + for (let s = 0; s <= segments; s += 1) { |
| 69 | + bounds[s] = Math.floor(s * dimension / segments) |
| 70 | + } |
| 71 | + return bounds |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * Encode one vector against trained PQ codebooks. |
| 76 | + * |
| 77 | + * @param {Float32Array} vector |
| 78 | + * @param {Float32Array} codebooks |
| 79 | + * @param {number} dimension |
| 80 | + * @param {number} segments |
| 81 | + * @param {number} centroids |
| 82 | + * @returns {Uint8Array} |
| 83 | + */ |
| 84 | +export function encodePqVector(vector, codebooks, dimension, segments, centroids) { |
| 85 | + const bounds = pqSegmentBounds(dimension, segments) |
| 86 | + const code = new Uint8Array(segments) |
| 87 | + for (let s = 0; s < segments; s += 1) { |
| 88 | + const start = bounds[s] |
| 89 | + const end = bounds[s + 1] |
| 90 | + code[s] = nearestCentroid(vector, codebooks, start, end, centroids) |
| 91 | + } |
| 92 | + return code |
| 93 | +} |
| 94 | + |
| 95 | +/** |
| 96 | + * Build per-segment lookup tables for approximate PQ scoring. |
| 97 | + * |
| 98 | + * For euclidean search the table stores squared L2 contributions and lower |
| 99 | + * values are better. For dot/cosine search it stores dot-product |
| 100 | + * contributions and higher values are better. |
| 101 | + * |
| 102 | + * @param {Float32Array} query |
| 103 | + * @param {HypVectorMetadata} meta |
| 104 | + * @param {DistanceMetric} metric |
| 105 | + * @returns {{ table: Float32Array, approxMetric: DistanceMetric }} |
| 106 | + */ |
| 107 | +export function buildPqTables(query, meta, metric) { |
| 108 | + if (!meta.hasPq || !meta.pqCodebooks || !meta.pqSegments || !meta.pqCentroids) { |
| 109 | + throw new Error('PQ metadata is missing') |
| 110 | + } |
| 111 | + const table = new Float32Array(meta.pqSegments * meta.pqCentroids) |
| 112 | + const bounds = pqSegmentBounds(meta.dimension, meta.pqSegments) |
| 113 | + for (let s = 0; s < meta.pqSegments; s += 1) { |
| 114 | + const start = bounds[s] |
| 115 | + const end = bounds[s + 1] |
| 116 | + const dim = end - start |
| 117 | + const block = meta.pqCentroids * start |
| 118 | + for (let c = 0; c < meta.pqCentroids; c += 1) { |
| 119 | + const centroid = block + c * dim |
| 120 | + let score = 0 |
| 121 | + if (metric === 'euclidean') { |
| 122 | + for (let d = 0; d < dim; d += 1) { |
| 123 | + const delta = query[start + d] - meta.pqCodebooks[centroid + d] |
| 124 | + score += delta * delta |
| 125 | + } |
| 126 | + } else { |
| 127 | + for (let d = 0; d < dim; d += 1) { |
| 128 | + score += query[start + d] * meta.pqCodebooks[centroid + d] |
| 129 | + } |
| 130 | + } |
| 131 | + table[s * meta.pqCentroids + c] = score |
| 132 | + } |
| 133 | + } |
| 134 | + return { table, approxMetric: metric === 'euclidean' ? 'euclidean' : 'dot' } |
| 135 | +} |
| 136 | + |
| 137 | +/** |
| 138 | + * Train one subspace codebook with k-means over a deterministic sample. |
| 139 | + * |
| 140 | + * @param {object} options |
| 141 | + * @param {Float32Array[]} options.vectors |
| 142 | + * @param {Int32Array} options.sample |
| 143 | + * @param {number} options.start |
| 144 | + * @param {number} options.end |
| 145 | + * @param {number} options.centroids |
| 146 | + * @param {number} options.iterations |
| 147 | + * @param {number} options.seed |
| 148 | + * @param {Float32Array} options.out |
| 149 | + */ |
| 150 | +function trainSegment({ vectors, sample, start, end, centroids, iterations, seed, out }) { |
| 151 | + const dim = end - start |
| 152 | + const block = centroids * start |
| 153 | + const sampleCount = sample.length |
| 154 | + if (sampleCount === 0) return |
| 155 | + |
| 156 | + for (let c = 0; c < centroids; c += 1) { |
| 157 | + const src = vectors[sample[Math.floor(c * sampleCount / centroids)]] |
| 158 | + out.set(src.subarray(start, end), block + c * dim) |
| 159 | + } |
| 160 | + |
| 161 | + for (let iter = 0; iter < iterations; iter += 1) { |
| 162 | + const counts = new Int32Array(centroids) |
| 163 | + const sums = new Float32Array(centroids * dim) |
| 164 | + |
| 165 | + for (let i = 0; i < sampleCount; i += 1) { |
| 166 | + const vector = vectors[sample[i]] |
| 167 | + const best = nearestCentroid(vector, out, start, end, centroids) |
| 168 | + counts[best] += 1 |
| 169 | + const sumOff = best * dim |
| 170 | + for (let d = 0; d < dim; d += 1) sums[sumOff + d] += vector[start + d] |
| 171 | + } |
| 172 | + |
| 173 | + for (let c = 0; c < centroids; c += 1) { |
| 174 | + const dst = block + c * dim |
| 175 | + if (counts[c] === 0) { |
| 176 | + const src = vectors[sample[reseedIndex(seed, iter, c, sampleCount)]] |
| 177 | + out.set(src.subarray(start, end), dst) |
| 178 | + continue |
| 179 | + } |
| 180 | + const inv = 1 / counts[c] |
| 181 | + const sumOff = c * dim |
| 182 | + for (let d = 0; d < dim; d += 1) out[dst + d] = sums[sumOff + d] * inv |
| 183 | + } |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/** |
| 188 | + * Find the nearest centroid for one segment under squared L2. |
| 189 | + * |
| 190 | + * @param {Float32Array} vector |
| 191 | + * @param {Float32Array} codebooks |
| 192 | + * @param {number} start |
| 193 | + * @param {number} end |
| 194 | + * @param {number} centroids |
| 195 | + * @returns {number} |
| 196 | + */ |
| 197 | +function nearestCentroid(vector, codebooks, start, end, centroids) { |
| 198 | + const dim = end - start |
| 199 | + const block = centroids * start |
| 200 | + let best = 0 |
| 201 | + let bestDist = Infinity |
| 202 | + for (let c = 0; c < centroids; c += 1) { |
| 203 | + const off = block + c * dim |
| 204 | + let dist = 0 |
| 205 | + for (let d = 0; d < dim; d += 1) { |
| 206 | + const delta = vector[start + d] - codebooks[off + d] |
| 207 | + dist += delta * delta |
| 208 | + if (dist >= bestDist) break |
| 209 | + } |
| 210 | + if (dist < bestDist) { |
| 211 | + bestDist = dist |
| 212 | + best = c |
| 213 | + } |
| 214 | + } |
| 215 | + return best |
| 216 | +} |
| 217 | + |
| 218 | +/** |
| 219 | + * Deterministic evenly-spaced sample indices. |
| 220 | + * |
| 221 | + * @param {number} count |
| 222 | + * @param {number} sampleSize |
| 223 | + * @returns {Int32Array} |
| 224 | + */ |
| 225 | +function sampleIndices(count, sampleSize) { |
| 226 | + const n = Math.min(count, Math.max(1, sampleSize)) |
| 227 | + const out = new Int32Array(n) |
| 228 | + for (let i = 0; i < n; i += 1) out[i] = Math.floor(i * count / n) |
| 229 | + return out |
| 230 | +} |
| 231 | + |
| 232 | +/** |
| 233 | + * @param {number} seed |
| 234 | + * @param {number} iter |
| 235 | + * @param {number} centroid |
| 236 | + * @param {number} sampleCount |
| 237 | + * @returns {number} |
| 238 | + */ |
| 239 | +function reseedIndex(seed, iter, centroid, sampleCount) { |
| 240 | + let s = (seed ^ Math.imul(iter + 1, 2654435761) ^ Math.imul(centroid + 1, 2246822519)) >>> 0 |
| 241 | + s = Math.imul(s, 1664525) + 1013904223 >>> 0 |
| 242 | + return s % sampleCount |
| 243 | +} |
0 commit comments