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.
Files changed (46) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1456 -2
  3. package/build-browser.js +67 -0
  4. package/index.js +39 -0
  5. package/package.json +72 -4
  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,226 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ import { dotAt, normalizeAt } from './math.js';
6
+ // ===========================
7
+ // clustering — e-means (Meta FAIR, "e-means: outperforming k-means
8
+ // (in one-tenth the epochs)", arXiv 2611.09501), used by IVF (centroids)
9
+ // and PQ (codebooks). Internal module, not part of the public API.
10
+ //
11
+ // Lloyd's k-means moves every centroid ONCE per full pass over the data, so
12
+ // it needs ~20 passes. e-means updates after every mini-batch: each centroid
13
+ // is the ratio of two exponential moving averages — of the count and of the
14
+ // sum of the points assigned to it —
15
+ //
16
+ // N_j ← γ·N_j + (1−γ)·n_j S_j ← γ·S_j + (1−γ)·s_j c_j = S_j / N_j
17
+ //
18
+ // so centroids move thousands of times in the first pass, and assignments
19
+ // made against stale centroids fade out instead of being averaged in
20
+ // forever (what holds back classic mini-batch k-means).
21
+ //
22
+ // - step α = 1−γ: cosine-annealed from α₀ down to 0.1·α₀
23
+ // - α₀ and the batch size B come from the paper's fitted scaling laws
24
+ // (no tuning): functions of n, k and the number of epochs T
25
+ // - dead clusters (N_j < 0.1·mean N) are revived every 5 batches by
26
+ // splitting a donor chosen ∝ N — the ablation's most important part
27
+ // - final centroids = mean of the points assigned in the last epoch
28
+ // (never worse on the training set than the EMA read-off)
29
+ //
30
+ // spherical: true → cosine geometry (IVF): points are unit vectors,
31
+ // assignment by the largest dot product, centroids re-normalized.
32
+ // spherical: false → squared euclidean (PQ sub-spaces).
33
+ //
34
+ // measured against the Lloyd it replaces (20–25 iterations): 6–11× faster
35
+ // for IVF and ~7× for PQ, with equal or lower k-means loss and equal recall
36
+ // (clustering.bench.js).
37
+ // ===========================
38
+
39
+ const EPS = 0.1; // final step = EPS · α₀
40
+ const TAU = 0.1; // revive clusters with N < TAU · mean N
41
+ const REVIVE_EVERY = 5; // batches
42
+ const DELTA = 1 / 128; // split perturbation (the paper uses the BF16 epsilon)
43
+
44
+ // epochs: small problems are cheap anyway, so they get more passes for
45
+ // stability; large ones get the 3 that already match 20 Lloyd iterations
46
+ function defaultEpochs(n, k, d) {
47
+ return n * k * d < 5e7 ? 5 : 3;
48
+ }
49
+
50
+ function pow2round(x) {
51
+ return Math.pow(2, Math.round(Math.log2(Math.max(1, x))));
52
+ }
53
+
54
+ // the paper's scaling laws (Table 2)
55
+ function emeansParams(n, k, T) {
56
+ let B = 0.035 * Math.pow(k, 0.13) * Math.pow(n, 0.88) * Math.pow(T, 0.81);
57
+ if (n > 2e6) B /= 8;
58
+ B = Math.max(1, Math.min(n, pow2round(B)));
59
+ const a0 = Math.min(
60
+ 0.824 * Math.pow(k, -0.46) * Math.pow(B, 0.90) * Math.pow(n, -0.45) * Math.pow(T, -0.11), 1);
61
+ return { B, a0 };
62
+ }
63
+
64
+ // nearest centroid — module-level hot loops (see math.js on why)
65
+ function nearestDot(X, xo, C, k, d) {
66
+ let best = 0, bs = -Infinity;
67
+ for (let c = 0; c < k; c++) {
68
+ const s = dotAt(X, xo, C, c * d, d);
69
+ if (s > bs) { bs = s; best = c; }
70
+ }
71
+ return best;
72
+ }
73
+
74
+ // argmin ||x − c||² = argmax (x·c − |c|²/2)
75
+ function nearestL2(X, xo, C, halfNorms, k, d) {
76
+ let best = 0, bs = -Infinity;
77
+ for (let c = 0; c < k; c++) {
78
+ const s = dotAt(X, xo, C, c * d, d) - halfNorms[c];
79
+ if (s > bs) { bs = s; best = c; }
80
+ }
81
+ return best;
82
+ }
83
+
84
+ // X: Float32Array(n·d), rows are the points (unit vectors when spherical)
85
+ // opts: { spherical, rng, epochs?, onEpoch?(epoch, epochs) }
86
+ // returns Float32Array(k·d). A generator: yields once per point, so the
87
+ // caller's time-slicing keeps every slice short.
88
+ function* emeans(X, n, d, k, opts) {
89
+ const spherical = !!opts.spherical;
90
+ const rng = opts.rng;
91
+ const T = opts.epochs || defaultEpochs(n, k, d);
92
+ const { B, a0 } = emeansParams(n, k, T);
93
+
94
+ // init: k random points (distinct when there are enough)
95
+ const C = new Float32Array(k * d);
96
+ const used = new Set();
97
+ for (let c = 0; c < k; c++) {
98
+ let idx;
99
+ if (used.size >= n) idx = Math.floor(rng() * n);
100
+ else {
101
+ do { idx = Math.floor(rng() * n); } while (used.has(idx));
102
+ used.add(idx);
103
+ }
104
+ C.set(X.subarray(idx * d, idx * d + d), c * d);
105
+ }
106
+
107
+ // EMA state; the tiny initial weight returns the init centroids exactly
108
+ // while carrying almost no weight
109
+ const N = new Float64Array(k).fill(1e-10);
110
+ const S = new Float64Array(k * d);
111
+ for (let i = 0; i < k * d; i++) S[i] = C[i] * 1e-10;
112
+
113
+ const halfNorms = new Float64Array(k);
114
+ const bn = new Float64Array(k);
115
+ const bs = new Float64Array(k * d);
116
+ const perm = new Uint32Array(n);
117
+ for (let i = 0; i < n; i++) perm[i] = i;
118
+ const lastAsg = new Int32Array(n).fill(-1);
119
+
120
+ const batches = Math.max(1, Math.floor(n / B));
121
+ const M = T * batches;
122
+ let t = 0;
123
+
124
+ function readOff() {
125
+ for (let c = 0; c < k; c++) {
126
+ const inv = 1 / N[c], o = c * d;
127
+ for (let j = 0; j < d; j++) C[o + j] = S[o + j] * inv;
128
+ if (spherical) normalizeAt(C, o, d);
129
+ else {
130
+ let q = 0;
131
+ for (let j = 0; j < d; j++) q += C[o + j] * C[o + j];
132
+ halfNorms[c] = q * 0.5;
133
+ }
134
+ }
135
+ }
136
+
137
+ function revive() {
138
+ let mean = 0;
139
+ for (let c = 0; c < k; c++) mean += N[c];
140
+ mean /= k;
141
+ const taken = new Uint8Array(k);
142
+ const dead = [];
143
+ for (let c = 0; c < k; c++) if (N[c] < TAU * mean) { dead.push(c); taken[c] = 1; }
144
+ for (const c of dead) {
145
+ // donor drawn ∝ N among clusters not already split or dead
146
+ let tot = 0;
147
+ for (let j = 0; j < k; j++) if (!taken[j]) tot += N[j];
148
+ if (!(tot > 0)) return;
149
+ let r = rng() * tot, donor = -1;
150
+ for (let j = 0; j < k; j++) {
151
+ if (taken[j]) continue;
152
+ r -= N[j];
153
+ if (r <= 0) { donor = j; break; }
154
+ }
155
+ if (donor < 0) return;
156
+ taken[donor] = 1;
157
+ // split the donor in two near-identical children, half the weight each
158
+ const half = N[donor] / 2, inv = 1 / N[donor];
159
+ for (let j = 0; j < d; j++) {
160
+ const cd = S[donor * d + j] * inv;
161
+ const sgn = (j & 1) ? -1 : 1;
162
+ S[c * d + j] = cd * (1 + sgn * DELTA) * half;
163
+ S[donor * d + j] = cd * (1 - sgn * DELTA) * half;
164
+ }
165
+ N[c] = half;
166
+ N[donor] = half;
167
+ }
168
+ }
169
+
170
+ for (let ep = 0; ep < T; ep++) {
171
+ // fresh shuffle every epoch
172
+ for (let i = n - 1; i > 0; i--) {
173
+ const j = Math.floor(rng() * (i + 1));
174
+ const x = perm[i]; perm[i] = perm[j]; perm[j] = x;
175
+ }
176
+ const last = ep === T - 1;
177
+ for (let b = 0; b < batches; b++) {
178
+ const alpha = a0 * (EPS + (1 - EPS) * 0.5 * (1 + Math.cos(Math.PI * t / M)));
179
+ const gamma = 1 - alpha;
180
+ t++;
181
+ readOff();
182
+ bn.fill(0);
183
+ bs.fill(0);
184
+ const end = (b === batches - 1) ? n : (b + 1) * B; // last batch takes the remainder
185
+ for (let q = b * B; q < end; q++) {
186
+ const v = perm[q], vo = v * d;
187
+ const c = spherical ? nearestDot(X, vo, C, k, d) : nearestL2(X, vo, C, halfNorms, k, d);
188
+ if (last) lastAsg[v] = c;
189
+ bn[c]++;
190
+ const so = c * d;
191
+ for (let j = 0; j < d; j++) bs[so + j] += X[vo + j];
192
+ yield;
193
+ }
194
+ for (let c = 0; c < k; c++) N[c] = gamma * N[c] + alpha * bn[c];
195
+ for (let i = 0; i < k * d; i++) S[i] = gamma * S[i] + alpha * bs[i];
196
+ if (t % REVIVE_EVERY === 0) revive();
197
+ yield;
198
+ }
199
+ if (opts.onEpoch) opts.onEpoch(ep + 1, T);
200
+ }
201
+
202
+ // finalize: mean of the points assigned during the last epoch; a cluster
203
+ // that got none keeps its EMA centroid
204
+ readOff();
205
+ const sums = new Float64Array(k * d);
206
+ const cnt = new Int32Array(k);
207
+ for (let v = 0; v < n; v++) {
208
+ const c = lastAsg[v];
209
+ if (c < 0) continue;
210
+ cnt[c]++;
211
+ const so = c * d, vo = v * d;
212
+ for (let j = 0; j < d; j++) sums[so + j] += X[vo + j];
213
+ if ((v & 1023) === 1023) yield;
214
+ }
215
+ for (let c = 0; c < k; c++) {
216
+ if (cnt[c] === 0) continue;
217
+ const o = c * d, inv = 1 / cnt[c];
218
+ for (let j = 0; j < d; j++) C[o + j] = sums[o + j] * inv;
219
+ if (spherical) normalizeAt(C, o, d);
220
+ }
221
+ return C;
222
+ }
223
+
224
+ export {
225
+ emeans
226
+ };
@@ -0,0 +1,211 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // createALS(options) — matrix factorization for implicit feedback
7
+ // (Hu, Koren & Volinsky, "Collaborative Filtering for Implicit Feedback
8
+ // Datasets", ICDM 2008)
9
+ //
10
+ // learns a vector per user (x_u) and per item (y_i) so that ⟨x_u, y_i⟩ is
11
+ // high for what the user would like. implicit feedback — purchases, plays,
12
+ // clicks — says what people did, never what they disliked, so EVERY
13
+ // (user, item) pair counts: preference p = 1 if they interacted, 0 if not,
14
+ // with confidence c = 1 + alpha · weight. the loss
15
+ //
16
+ // Σ_u Σ_i c_ui (p_ui − ⟨x_u, y_i⟩)² + λ (Σ‖x_u‖² + Σ‖y_i‖²)
17
+ //
18
+ // is minimized by alternating: with the items fixed, every user is a small
19
+ // least-squares problem; then the other way around.
20
+ //
21
+ // solving each one exactly costs D³; like the `implicit` library, each row
22
+ // takes a few conjugate-gradient steps from its previous value instead
23
+ // (Takács, Pilászy & Tikk 2011): D² + (its interactions)·D per step. the
24
+ // sum over ALL items never happens per user: Σ_i y_i y_iᵀ = YᵀY is computed
25
+ // once per half-iteration, and only the user's own items add a correction.
26
+ //
27
+ // train(interactions, cb) / trainSync(interactions) → { users, items }
28
+ // interactions: { users, items[, weights] } (see interactions.js)
29
+ // users, items: embeddings objects (vector, similar, toBytes, …)
30
+ // cancel(), on/off ('progress', 'epoch'), training, options
31
+ //
32
+ // recommend: put the items in an index with metric 'dot' and search with
33
+ // the user's vector.
34
+ // ===========================
35
+
36
+ import { rngState, randFloat, dotAt } from '../math.js';
37
+ import { checkOptions, intOption, numOption, seedOption } from '../validate.js';
38
+ import { copyInteractions, buildInteractions } from './interactions.js';
39
+ import { createEmbeddings } from './embeddings.js';
40
+ import { createTrainerBase } from './trainer.js';
41
+
42
+ const OPTIONS = ['dimensions', 'iterations', 'regularization', 'alpha', 'cgSteps', 'seed'];
43
+
44
+ function createALS(options) {
45
+ const opts = checkOptions(options, OPTIONS, 'createALS');
46
+ const resolved = Object.freeze({
47
+ dimensions: intOption(opts, 'dimensions', 64, 1, 4096),
48
+ iterations: intOption(opts, 'iterations', 15, 1, 1e6),
49
+ regularization: numOption(opts, 'regularization', 0.01, 0, 1e6),
50
+ alpha: numOption(opts, 'alpha', 1, 0, 1e9),
51
+ cgSteps: intOption(opts, 'cgSteps', 3, 1, 1000),
52
+ seed: seedOption(opts)
53
+ });
54
+ const base = createTrainerBase();
55
+
56
+ function* trainJob(input) {
57
+ const o = resolved;
58
+ const D = o.dimensions;
59
+ const lambda = o.regularization;
60
+ const alpha = o.alpha;
61
+ const data = yield* buildInteractions(input);
62
+ const { nUsers, nItems, byUser, byItem } = data;
63
+ const rng = rngState(o.seed);
64
+
65
+ // small random start (both sides), as float32 like every embedding
66
+ const X = new Float32Array(nUsers * D);
67
+ const Y = new Float32Array(nItems * D);
68
+ const scale = 0.01;
69
+ for (let i = 0; i < X.length; i++) {
70
+ X[i] = (randFloat(rng) - 0.5) * scale;
71
+ if ((i & 0x1FFFF) === 0x1FFFF) yield;
72
+ }
73
+ for (let i = 0; i < Y.length; i++) {
74
+ Y[i] = (randFloat(rng) - 0.5) * scale;
75
+ if ((i & 0x1FFFF) === 0x1FFFF) yield;
76
+ }
77
+
78
+ const G = new Float64Array(D * D); // YᵀY of the fixed side
79
+ // yield by work (multiply-adds), not by rows: a row costs D² here, so
80
+ // with large D a fixed row count would hold the thread for too long
81
+ const BUDGET = 1 << 18;
82
+ let work = 0;
83
+ const x = new Float64Array(D), r = new Float64Array(D), p = new Float64Array(D), Ap = new Float64Array(D);
84
+
85
+ // G = Fᵀ F over the rows of F (n × D)
86
+ function* gram(F, n) {
87
+ G.fill(0);
88
+ for (let row = 0; row < n; row++) {
89
+ const o2 = row * D;
90
+ for (let a = 0; a < D; a++) {
91
+ const fa = F[o2 + a];
92
+ if (fa === 0) continue;
93
+ const ga = a * D;
94
+ for (let b = a; b < D; b++) G[ga + b] += fa * F[o2 + b];
95
+ }
96
+ work += D * D / 2;
97
+ if (work > BUDGET) { work = 0; yield true; }
98
+ }
99
+ for (let a = 0; a < D; a++) for (let b = 0; b < a; b++) G[a * D + b] = G[b * D + a];
100
+ }
101
+
102
+ // out = G v + λ v + Σ_obs (c − 1) ⟨y, v⟩ y (A v without forming A)
103
+ function applyA(v, out, F, off, cols, vals, a, b) {
104
+ for (let i = 0; i < D; i++) {
105
+ let s = lambda * v[i];
106
+ const gi = i * D;
107
+ for (let j = 0; j < D; j++) s += G[gi + j] * v[j];
108
+ out[i] = s;
109
+ }
110
+ for (let k = a; k < b; k++) {
111
+ const yo = cols[k] * D;
112
+ const cm1 = alpha * vals[k];
113
+ let s = 0;
114
+ for (let j = 0; j < D; j++) s += F[yo + j] * v[j];
115
+ s *= cm1;
116
+ for (let j = 0; j < D; j++) out[j] += s * F[yo + j];
117
+ }
118
+ }
119
+
120
+ // one side: every row of T (n rows) re-solved against the fixed F
121
+ function* solveSide(T, n, F, csr, epoch, startDone, tracker) {
122
+ const { offsets, cols, vals } = csr;
123
+ for (let row = 0; row < n; row++) {
124
+ const a = offsets[row], b = offsets[row + 1];
125
+ const to = row * D;
126
+ for (let i = 0; i < D; i++) x[i] = T[to + i];
127
+ // r = b − A x, with b = Σ_obs c y
128
+ applyA(x, r, F, 0, cols, vals, a, b);
129
+ for (let i = 0; i < D; i++) r[i] = -r[i];
130
+ for (let k = a; k < b; k++) {
131
+ const yo = cols[k] * D;
132
+ const c = 1 + alpha * vals[k];
133
+ for (let j = 0; j < D; j++) r[j] += c * F[yo + j];
134
+ }
135
+ let rs = 0;
136
+ for (let i = 0; i < D; i++) { p[i] = r[i]; rs += r[i] * r[i]; }
137
+ for (let step = 0; step < o.cgSteps && rs > 1e-20; step++) {
138
+ applyA(p, Ap, F, 0, cols, vals, a, b);
139
+ let pAp = 0;
140
+ for (let i = 0; i < D; i++) pAp += p[i] * Ap[i];
141
+ if (!(pAp > 0)) break;
142
+ const s = rs / pAp;
143
+ let rsNew = 0;
144
+ for (let i = 0; i < D; i++) {
145
+ x[i] += s * p[i];
146
+ r[i] -= s * Ap[i];
147
+ rsNew += r[i] * r[i];
148
+ }
149
+ const beta = rsNew / rs;
150
+ for (let i = 0; i < D; i++) p[i] = r[i] + beta * p[i];
151
+ rs = rsNew;
152
+ }
153
+ for (let i = 0; i < D; i++) T[to + i] = x[i];
154
+ tracker.tick(epoch, startDone + row + 1);
155
+ work += (o.cgSteps + 1) * (D * D + 2 * (b - a) * D);
156
+ if (work > BUDGET) { work = 0; yield true; }
157
+ }
158
+ }
159
+
160
+ // the full loss, without visiting all nUsers × nItems pairs:
161
+ // Σ_u [ x_uᵀ G x_u + Σ_obs (c (1 − s)² − s²) ] + λ (‖X‖² + ‖Y‖²), s = ⟨x_u, y_i⟩
162
+ function* lossNow() {
163
+ yield* gram(Y, nItems);
164
+ let total = 0;
165
+ const { offsets, cols, vals } = byUser;
166
+ for (let u = 0; u < nUsers; u++) {
167
+ const xo = u * D;
168
+ for (let i = 0; i < D; i++) {
169
+ let s = 0;
170
+ const gi = i * D;
171
+ for (let j = 0; j < D; j++) s += G[gi + j] * X[xo + j];
172
+ total += X[xo + i] * s;
173
+ }
174
+ for (let k = offsets[u]; k < offsets[u + 1]; k++) {
175
+ const s = dotAt(X, xo, Y, cols[k] * D, D);
176
+ const c = 1 + alpha * vals[k];
177
+ total += c * (1 - s) * (1 - s) - s * s;
178
+ }
179
+ work += D * D + (offsets[u + 1] - offsets[u]) * D;
180
+ if (work > BUDGET) { work = 0; yield true; }
181
+ }
182
+ let reg = 0;
183
+ for (let i = 0; i < X.length; i++) reg += X[i] * X[i];
184
+ for (let i = 0; i < Y.length; i++) reg += Y[i] * Y[i];
185
+ return (total + lambda * reg) / data.nnz;
186
+ }
187
+
188
+ let lastLoss = 0;
189
+ const lossSource = { takeLoss: () => lastLoss };
190
+ const perEpoch = nUsers + nItems;
191
+ const tracker = base.createTracker(lossSource, o.iterations, o.iterations * perEpoch);
192
+ for (let epoch = 1; epoch <= o.iterations; epoch++) {
193
+ const start = (epoch - 1) * perEpoch;
194
+ yield* gram(Y, nItems);
195
+ yield* solveSide(X, nUsers, Y, byUser, epoch, start, tracker);
196
+ yield* gram(X, nUsers);
197
+ yield* solveSide(Y, nItems, X, byItem, epoch, start + nUsers, tracker);
198
+ lastLoss = yield* lossNow();
199
+ tracker.endEpoch(epoch, epoch * perEpoch);
200
+ }
201
+
202
+ return {
203
+ users: createEmbeddings(data.userMap, nUsers, D, X),
204
+ items: createEmbeddings(data.itemMap, nItems, D, Y)
205
+ };
206
+ }
207
+
208
+ return base.publicApi(resolved, base.inputMethods(copyInteractions, trainJob));
209
+ }
210
+
211
+ export { createALS };
@@ -0,0 +1,149 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // createBPR(options) — Bayesian Personalized Ranking
7
+ // (Rendle, Freudenthaler, Gantner & Schmidt-Thieme, UAI 2009)
8
+ //
9
+ // learns to RANK rather than to predict a score: for a user u, an item i
10
+ // they interacted with and an item j they didn't, the model should score i
11
+ // above j. one SGD step per sampled triple (u, i, j):
12
+ //
13
+ // x_uij = ⟨x_u, y_i − y_j⟩ z = σ(−x_uij)
14
+ // x_u += lr (z (y_i − y_j) − λ x_u)
15
+ // y_i += lr (z x_u − λ y_i) y_j += lr (−z x_u − λ y_j)
16
+ //
17
+ // the same idea as skip-gram's negative sampling (sgns.js): pull the
18
+ // observed pair together, push a random one apart.
19
+ //
20
+ // item bias: the last coordinate. users hold 1 there (never updated),
21
+ // items learn their bias b_i in it, so ⟨x_u, y_i⟩ already includes b_i
22
+ // (as in the `implicit` library) — a popular item can win without matching
23
+ // the user's taste exactly, and the vectors go straight into an index with
24
+ // metric 'dot'.
25
+ //
26
+ // train(interactions, cb) / trainSync(interactions) → { users, items }
27
+ // cancel(), on/off ('progress', 'epoch' — loss = mean −log σ(x_uij)),
28
+ // training, options
29
+ // ===========================
30
+
31
+ import { rngState, randFloat } from '../math.js';
32
+ import { ERR, createError } from '../errors.js';
33
+ import { checkOptions, intOption, numOption, seedOption } from '../validate.js';
34
+ import { copyInteractions, buildInteractions } from './interactions.js';
35
+ import { createEmbeddings } from './embeddings.js';
36
+ import { createTrainerBase } from './trainer.js';
37
+
38
+ const OPTIONS = ['dimensions', 'epochs', 'learningRate', 'regularization', 'seed'];
39
+ const SLICE = 64; // samples between yields
40
+
41
+ function createBPR(options) {
42
+ const opts = checkOptions(options, OPTIONS, 'createBPR');
43
+ const resolved = Object.freeze({
44
+ dimensions: intOption(opts, 'dimensions', 64, 2, 4096),
45
+ epochs: intOption(opts, 'epochs', 50, 1, 1e6),
46
+ learningRate: numOption(opts, 'learningRate', 0.05, 0, 100, true),
47
+ regularization: numOption(opts, 'regularization', 0.01, 0, 1e6),
48
+ seed: seedOption(opts)
49
+ });
50
+ const base = createTrainerBase();
51
+
52
+ function* trainJob(input) {
53
+ const o = resolved;
54
+ const D = o.dimensions;
55
+ const F = D - 1; // learned factors; coordinate F is the bias
56
+ const lr = o.learningRate, lambda = o.regularization;
57
+ const data = yield* buildInteractions(input);
58
+ const { nUsers, nItems, byUser, nnz } = data;
59
+ if (nItems < 2) throw createError(ERR.INVALID_ARGUMENT, 'train: BPR needs at least 2 items');
60
+ const rng = rngState(o.seed);
61
+
62
+ const X = new Float32Array(nUsers * D);
63
+ const Y = new Float32Array(nItems * D);
64
+ for (let u = 0; u < nUsers; u++) {
65
+ for (let f = 0; f < F; f++) X[u * D + f] = (randFloat(rng) - 0.5) / F;
66
+ X[u * D + F] = 1;
67
+ if ((u & 1023) === 1023) yield;
68
+ }
69
+ for (let i = 0; i < nItems; i++) {
70
+ for (let f = 0; f < F; f++) Y[i * D + f] = (randFloat(rng) - 0.5) / F;
71
+ if ((i & 1023) === 1023) yield;
72
+ }
73
+
74
+ // the user of every stored interaction, to sample (u, i) uniformly
75
+ const { offsets, cols } = byUser;
76
+ const userOf = new Uint32Array(nnz);
77
+ for (let u = 0; u < nUsers; u++) for (let k = offsets[u]; k < offsets[u + 1]; k++) userOf[k] = u;
78
+
79
+ // does user u have item j? rows are sorted: binary search
80
+ function has(u, j) {
81
+ let lo = offsets[u], hi = offsets[u + 1];
82
+ while (lo < hi) {
83
+ const mid = (lo + hi) >>> 1;
84
+ const c = cols[mid];
85
+ if (c === j) return true;
86
+ if (c < j) lo = mid + 1; else hi = mid;
87
+ }
88
+ return false;
89
+ }
90
+
91
+ let lossSum = 0, lossN = 0;
92
+ const core = {
93
+ takeLoss() {
94
+ const l = lossN ? lossSum / lossN : 0;
95
+ lossSum = 0; lossN = 0;
96
+ return l;
97
+ }
98
+ };
99
+ const total = o.epochs * nnz;
100
+ const tracker = base.createTracker(core, o.epochs, total);
101
+ let done = 0;
102
+
103
+ for (let epoch = 1; epoch <= o.epochs; epoch++) {
104
+ for (let s = 0; s < nnz; s++) {
105
+ const k = Math.floor(randFloat(rng) * nnz);
106
+ const u = userOf[k], i = cols[k];
107
+ // a negative: a random item the user didn't touch (a few tries;
108
+ // for a user who touched almost everything, skip the sample)
109
+ let j = -1;
110
+ for (let t = 0; t < 8; t++) {
111
+ const c = Math.floor(randFloat(rng) * nItems);
112
+ if (!has(u, c)) { j = c; break; }
113
+ }
114
+ if (j >= 0) {
115
+ const xo = u * D, io = i * D, jo = j * D;
116
+ let xuij = 0;
117
+ for (let f = 0; f < D; f++) xuij += X[xo + f] * (Y[io + f] - Y[jo + f]);
118
+ const z = 1 / (1 + Math.exp(xuij)); // σ(−x_uij)
119
+ lossSum += xuij > -30 ? Math.log(1 + Math.exp(-xuij)) : -xuij;
120
+ lossN++;
121
+ for (let f = 0; f < F; f++) {
122
+ const xu = X[xo + f], yi = Y[io + f], yj = Y[jo + f];
123
+ X[xo + f] += lr * (z * (yi - yj) - lambda * xu);
124
+ Y[io + f] += lr * (z * xu - lambda * yi);
125
+ Y[jo + f] += lr * (-z * xu - lambda * yj);
126
+ }
127
+ // bias (the user's coordinate stays 1)
128
+ Y[io + F] += lr * (z - lambda * Y[io + F]);
129
+ Y[jo + F] += lr * (-z - lambda * Y[jo + F]);
130
+ }
131
+ done++;
132
+ if ((s & (SLICE - 1)) === SLICE - 1) {
133
+ tracker.tick(epoch, done);
134
+ yield;
135
+ }
136
+ }
137
+ tracker.endEpoch(epoch, done);
138
+ }
139
+
140
+ return {
141
+ users: createEmbeddings(data.userMap, nUsers, D, X),
142
+ items: createEmbeddings(data.itemMap, nItems, D, Y)
143
+ };
144
+ }
145
+
146
+ return base.publicApi(resolved, base.inputMethods(copyInteractions, trainJob));
147
+ }
148
+
149
+ export { createBPR };