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,142 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // createNode2Vec(graph, options) — node embeddings from random walks
7
+ //
8
+ // p = q = 1 → DeepWalk (fastest walk mode)
9
+ // p, q → node2vec: low q explores outward (structure /
10
+ // communities far away), low p stays local
11
+ // weighted graph → walks prefer heavier edges
12
+ //
13
+ // walks are generated on the fly and fed straight into the skip-gram
14
+ // trainer; memory is the model (2 × nodes × dimensions × 4 bytes during
15
+ // training, half of it after) plus the graph. no walk corpus is stored.
16
+ //
17
+ // methods: train(cb) / trainSync() → embeddings, cancel(), on/off,
18
+ // training (boolean), options (resolved, frozen)
19
+ //
20
+ // token frequencies (for negative sampling and subsampling) are estimated
21
+ // from the graph instead of counted over the walks: on an undirected graph
22
+ // a random walk visits a node in proportion to its (weighted) degree, so
23
+ // no second pass over the walks is needed. directed graphs use in-degree + 1.
24
+ // ===========================
25
+
26
+ import { randFloat, rngState } from '../math.js';
27
+ import { ERR, createError } from '../errors.js';
28
+ import { checkOptions, intOption, numOption, seedOption } from '../validate.js';
29
+ import { isGraph } from './graph.js';
30
+ import { createWalkEngine, walkOptions, buildCumulative } from './walker.js';
31
+ import { createSgnsCore } from './sgns.js';
32
+ import { createEmbeddings } from './embeddings.js';
33
+ import { createTrainerBase } from './trainer.js';
34
+
35
+ const OPTIONS = [
36
+ 'dimensions', 'walkLength', 'walksPerNode', 'p', 'q', 'window', 'negative',
37
+ 'epochs', 'learningRate', 'minLearningRate', 'sample', 'seed'
38
+ ];
39
+
40
+ function trainingOptions(opts) {
41
+ const o = {
42
+ dimensions: intOption(opts, 'dimensions', 128, 1, 4096),
43
+ window: intOption(opts, 'window', 10, 1, 1000),
44
+ negative: intOption(opts, 'negative', 5, 1, 1000),
45
+ epochs: intOption(opts, 'epochs', 1, 1, 1e6),
46
+ learningRate: numOption(opts, 'learningRate', 0.025, 0, 10, true),
47
+ minLearningRate: numOption(opts, 'minLearningRate', 0.0001, 0, 10),
48
+ sample: numOption(opts, 'sample', 0.001, 0, 1),
49
+ seed: seedOption(opts)
50
+ };
51
+ if (o.minLearningRate > o.learningRate) {
52
+ throw createError(ERR.INVALID_ARGUMENT, 'minLearningRate must be ≤ learningRate');
53
+ }
54
+ return o;
55
+ }
56
+
57
+ function createNode2Vec(graph, options) {
58
+ if (!isGraph(graph)) throw createError(ERR.INVALID_ARGUMENT, 'createNode2Vec: first argument must be a graph');
59
+ const opts = checkOptions(options, OPTIONS, 'createNode2Vec');
60
+ const resolved = Object.freeze({
61
+ ...trainingOptions(opts),
62
+ ...walkOptions(opts),
63
+ walksPerNode: intOption(opts, 'walksPerNode', 10, 1, 1e6)
64
+ });
65
+ const base = createTrainerBase();
66
+
67
+ function* trainJob(snap) {
68
+ const { csr, ids, n } = snap;
69
+ const o = resolved;
70
+ const D = o.dimensions;
71
+ const rng = rngState(o.seed);
72
+
73
+ // estimated visit frequencies
74
+ const counts = new Float64Array(n);
75
+ const { offsets, neighbors, weights } = csr;
76
+ if (!csr.directed) {
77
+ for (let v = 0; v < n; v++) {
78
+ if ((v & 0xFFFF) === 0xFFFF) yield;
79
+ if (weights) {
80
+ let s = 0;
81
+ for (let i = offsets[v]; i < offsets[v + 1]; i++) s += weights[i];
82
+ counts[v] = s;
83
+ } else {
84
+ counts[v] = offsets[v + 1] - offsets[v];
85
+ }
86
+ }
87
+ } else {
88
+ for (let v = 0; v < n; v++) counts[v] = 1;
89
+ for (let i = 0; i < neighbors.length; i++) {
90
+ counts[neighbors[i]] += weights ? weights[i] : 1;
91
+ if ((i & 0xFFFF) === 0xFFFF) yield;
92
+ }
93
+ }
94
+ yield;
95
+
96
+ const core = yield* createSgnsCore(n, D, counts, o, rng);
97
+ yield;
98
+ const cumulative = weights ? yield* buildCumulative(csr) : null;
99
+ const walker = createWalkEngine(csr, o, rng, cumulative);
100
+ const buf = new Uint32Array(o.walkLength);
101
+ const order = new Uint32Array(n);
102
+ const total = o.epochs * o.walksPerNode * n;
103
+ const tracker = base.createTracker(core, o.epochs, total);
104
+ const lr = o.learningRate, lrSpan = o.learningRate - o.minLearningRate;
105
+ let done = 0;
106
+
107
+ for (let epoch = 1; epoch <= o.epochs; epoch++) {
108
+ for (let r = 0; r < o.walksPerNode; r++) {
109
+ // a fresh random order of start nodes every round
110
+ for (let i = 0; i < n; i++) order[i] = i;
111
+ for (let i = n - 1; i > 0; i--) {
112
+ const j = Math.floor(randFloat(rng) * (i + 1));
113
+ const t = order[i]; order[i] = order[j]; order[j] = t;
114
+ if ((i & 0xFFFF) === 0) yield;
115
+ }
116
+ for (let i = 0; i < n; i++) {
117
+ const len = walker.walkInto(order[i], buf);
118
+ if (len > 1) core.train(buf, len, lr - lrSpan * (done / total));
119
+ done++;
120
+ tracker.tick(epoch, done);
121
+ yield;
122
+ }
123
+ }
124
+ tracker.endEpoch(epoch, done);
125
+ }
126
+ return createEmbeddings(ids, n, D, core.input);
127
+ }
128
+
129
+ return base.publicApi(resolved, {
130
+ train(cb) {
131
+ base.runAsync(cb, (next) => graph._prepare(next), trainJob);
132
+ },
133
+ trainSync() {
134
+ return base.runSync(() => graph._prepareSync(), trainJob);
135
+ }
136
+ });
137
+ }
138
+
139
+ export {
140
+ createNode2Vec,
141
+ trainingOptions
142
+ };
@@ -0,0 +1,191 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ import { buildAlias, dotAt, randFloat } from '../math.js';
6
+ // ===========================
7
+ // SGNS core — skip-gram with negative sampling (word2vec), over integer tokens
8
+ //
9
+ // the same engine trains node2vec / DeepWalk walks and any other sequences
10
+ // (item2vec sessions, playlists, ...). everything is flat typed arrays:
11
+ //
12
+ // input Float32Array(V × D) the embeddings (what you keep)
13
+ // output Float32Array(V × D) context weights (training only)
14
+ // alias prob Float32Array(V) + alias Uint32Array(V)
15
+ // O(1) negative sampling from counts^0.75. word2vec's classic
16
+ // table is 10^8 ints (400MB); the alias table is 8 bytes per token.
17
+ // keep Float32Array(V) subsampling keep-probability per token
18
+ //
19
+ // the training math follows word2vec.c (dynamic window, linear learning-rate
20
+ // decay, sigmoid lookup table, clipping at ±6) so results are comparable
21
+ // with gensim / the original node2vec.
22
+ // ===========================
23
+
24
+ const MAX_EXP = 6;
25
+ const TABLE_SIZE = 1024;
26
+ const SIGMOID = new Float64Array(TABLE_SIZE + 1);
27
+ const LOSS_POS = new Float64Array(TABLE_SIZE + 1); // −log σ(x)
28
+ for (let i = 0; i <= TABLE_SIZE; i++) {
29
+ const x = (i / TABLE_SIZE * 2 - 1) * MAX_EXP;
30
+ SIGMOID[i] = 1 / (1 + Math.exp(-x));
31
+ LOSS_POS[i] = Math.log(1 + Math.exp(-x));
32
+ }
33
+ const SCALE = TABLE_SIZE / MAX_EXP / 2;
34
+
35
+ // ---------- hot loops ----------
36
+ // written with running indices and 4-way unrolling: on V8 this is ~2× faster
37
+ // than indexing with base + d (fewer index computations / bounds checks).
38
+
39
+ // work += g · out[o..]; out[o..] += g · inp[l..]
40
+ function accumulate(work, out, o, inp, l, g, D) {
41
+ const end = D & ~3;
42
+ let d = 0, j = o, i = l;
43
+ for (; d < end; d += 4, j += 4, i += 4) {
44
+ const y0 = out[j], y1 = out[j + 1], y2 = out[j + 2], y3 = out[j + 3];
45
+ work[d] += g * y0; work[d + 1] += g * y1; work[d + 2] += g * y2; work[d + 3] += g * y3;
46
+ out[j] = y0 + g * inp[i]; out[j + 1] = y1 + g * inp[i + 1];
47
+ out[j + 2] = y2 + g * inp[i + 2]; out[j + 3] = y3 + g * inp[i + 3];
48
+ }
49
+ for (; d < D; d++, j++, i++) {
50
+ const y = out[j];
51
+ work[d] += g * y;
52
+ out[j] = y + g * inp[i];
53
+ }
54
+ }
55
+
56
+ function addInto(a, ao, b, D) {
57
+ for (let d = 0, i = ao; d < D; d++, i++) a[i] += b[d];
58
+ }
59
+
60
+ // counts: Float64Array(V) of token frequencies (exact or estimated)
61
+ // rngState: Uint32Array(1) from math.rngState — shared with the walker
62
+ // generator: setup of a large model takes long enough to need slicing
63
+ function* createSgnsCore(V, D, counts, cfg, rngState) {
64
+ const { window, negative, sample } = cfg;
65
+
66
+ const input = new Float32Array(V * D);
67
+ for (let i = 0; i < input.length; i++) {
68
+ input[i] = (randFloat(rngState) - 0.5) / D;
69
+ if ((i & 0x3FFFF) === 0x3FFFF) yield;
70
+ }
71
+
72
+ // negatives ∝ count^0.75
73
+ const pw = new Float64Array(V);
74
+ let total = 0;
75
+ for (let i = 0; i < V; i++) {
76
+ pw[i] = Math.pow(counts[i], 0.75);
77
+ total += counts[i];
78
+ if ((i & 0xFFFF) === 0xFFFF) yield;
79
+ }
80
+ const { prob, alias } = yield* buildAlias(pw);
81
+
82
+ // frequent-token subsampling (word2vec formula)
83
+ let keep = null;
84
+ if (sample > 0 && total > 0) {
85
+ keep = new Float32Array(V);
86
+ const st = sample * total;
87
+ for (let i = 0; i < V; i++) {
88
+ const c = counts[i];
89
+ keep[i] = c > 0 ? Math.min(1, (Math.sqrt(c / st) + 1) * st / c) : 1;
90
+ }
91
+ }
92
+
93
+ // one plain object with a fixed shape, read by the module-level train
94
+ // function below (see math.randFloat for why not closures)
95
+ const m = {
96
+ V, D, window, negative,
97
+ input,
98
+ output: new Float32Array(V * D),
99
+ work: new Float32Array(D),
100
+ negs: new Uint32Array(negative),
101
+ prob, alias,
102
+ keep: keep || new Float32Array(0),
103
+ useKeep: keep !== null,
104
+ sub: new Uint32Array(256),
105
+ rng: rngState,
106
+ stats: new Float64Array(2) // [loss sum, scored pairs]
107
+ };
108
+
109
+ return {
110
+ input,
111
+ train(tokens, len, alpha) { trainSequence(m, tokens, len, alpha); },
112
+ // average loss per scored pair since the last call (resets the counter)
113
+ takeLoss() {
114
+ const st = m.stats;
115
+ const l = st[1] > 0 ? st[0] / st[1] : 0;
116
+ st[0] = 0;
117
+ st[1] = 0;
118
+ return l;
119
+ }
120
+ };
121
+ }
122
+
123
+ // train on tokens[0..len) — one sentence / walk
124
+ function trainSequence(m, tokens, len, alpha) {
125
+ const { V, D, window, negative, input, output, work, prob, alias, keep, rng, stats } = m;
126
+ let seq = tokens;
127
+ if (m.useKeep) {
128
+ if (m.sub.length < len) m.sub = new Uint32Array(Math.max(len, m.sub.length * 2));
129
+ const sub = m.sub;
130
+ let k = 0;
131
+ for (let i = 0; i < len; i++) {
132
+ const t = tokens[i];
133
+ if (keep[t] >= 1 || randFloat(rng) < keep[t]) sub[k++] = t;
134
+ }
135
+ seq = sub;
136
+ len = k;
137
+ }
138
+ const negs = m.negs;
139
+ let loss = 0, pairs = 0;
140
+ for (let i = 0; i < len; i++) {
141
+ const center = seq[i];
142
+ // negatives are drawn once per center and shared by all its contexts
143
+ // (Ji et al. 2016, "pWord2Vec"): the same quality, and the K negative rows
144
+ // stay in cache for the whole window instead of K random memory reads
145
+ // per pair — the dominant cost once the model outgrows the CPU cache.
146
+ for (let s = 0; s < negative; s++) {
147
+ const r = Math.floor(randFloat(rng) * V);
148
+ negs[s] = randFloat(rng) < prob[r] ? r : alias[r];
149
+ }
150
+ const b = Math.floor(randFloat(rng) * window);
151
+ const lo = Math.max(0, i - window + b);
152
+ const hi = Math.min(len - 1, i + window - b);
153
+ for (let j = lo; j <= hi; j++) {
154
+ if (j === i) continue;
155
+ // one (context → center) update plus `negative` negatives
156
+ const l1 = seq[j] * D;
157
+ work.fill(0);
158
+ for (let s = 0; s <= negative; s++) {
159
+ let target, label;
160
+ if (s === 0) { target = center; label = 1; }
161
+ else {
162
+ target = negs[s - 1];
163
+ if (target === center) continue;
164
+ label = 0;
165
+ }
166
+ const l2 = target * D;
167
+ const f = dotAt(input, l1, output, l2, D);
168
+ let g;
169
+ // signed score: positive pairs want f → +∞, negatives f → −∞
170
+ const z = label ? f : -f;
171
+ if (z > MAX_EXP) { g = 0; }
172
+ else if (z < -MAX_EXP) {
173
+ g = (label ? 1 : -1) * alpha;
174
+ loss -= z;
175
+ } else {
176
+ g = (label - SIGMOID[((f + MAX_EXP) * SCALE) | 0]) * alpha;
177
+ loss += LOSS_POS[((z + MAX_EXP) * SCALE) | 0];
178
+ }
179
+ pairs++;
180
+ if (g !== 0) accumulate(work, output, l2, input, l1, g, D);
181
+ }
182
+ addInto(input, l1, work, D);
183
+ }
184
+ }
185
+ stats[0] += loss;
186
+ stats[1] += pairs;
187
+ }
188
+
189
+ export {
190
+ createSgnsCore
191
+ };
@@ -0,0 +1,128 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // createSkipGram(options) — embeddings for ANY sequences of ids
7
+ //
8
+ // the generic engine under node2vec, for data that is already sequences:
9
+ // item2vec items viewed / bought in the same session
10
+ // playlists songs played one after another
11
+ // walks your own random walks (createWalker) or paths from your DB
12
+ //
13
+ // train(sequences, cb) / trainSync(sequences) → embeddings
14
+ // sequences: an array of arrays (or typed arrays) of ids
15
+ //
16
+ // unlike node2vec, token frequencies are counted exactly (one pass over the
17
+ // sequences). minCount drops rare ids (they get no vector).
18
+ // ===========================
19
+
20
+ import { rngState } from '../math.js';
21
+ import { ERR, createError } from '../errors.js';
22
+ import { checkOptions, intOption, checkId } from '../validate.js';
23
+ import { createIdMap } from './idmap.js';
24
+ import { createSgnsCore } from './sgns.js';
25
+ import { createEmbeddings } from './embeddings.js';
26
+ import { createTrainerBase } from './trainer.js';
27
+ import { trainingOptions } from './node2vec.js';
28
+
29
+ const OPTIONS = [
30
+ 'dimensions', 'window', 'negative', 'epochs', 'learningRate', 'minLearningRate',
31
+ 'sample', 'minCount', 'seed'
32
+ ];
33
+
34
+ function createSkipGram(options) {
35
+ const opts = checkOptions(options, OPTIONS, 'createSkipGram');
36
+ const resolved = Object.freeze({
37
+ ...trainingOptions({ window: 5, epochs: 5, ...opts }),
38
+ minCount: intOption(opts, 'minCount', 1, 1, 1e9)
39
+ });
40
+ const base = createTrainerBase();
41
+
42
+ function* trainJob(sequences) {
43
+ if (!Array.isArray(sequences)) {
44
+ throw createError(ERR.INVALID_ARGUMENT, 'train: sequences must be an array of arrays of ids');
45
+ }
46
+ const o = resolved;
47
+ const D = o.dimensions;
48
+ const rng = rngState(o.seed);
49
+
50
+ // pass 1: vocabulary + exact counts
51
+ const seen = createIdMap(0);
52
+ let counts = new Float64Array(1024);
53
+ let tokens = 0;
54
+ let maxLen = 0;
55
+ for (let s = 0; s < sequences.length; s++) {
56
+ const seq = sequences[s];
57
+ if (!seq || typeof seq.length !== 'number') {
58
+ throw createError(ERR.INVALID_ARGUMENT, 'train: sequences[' + s + '] must be an array of ids');
59
+ }
60
+ for (let i = 0; i < seq.length; i++) {
61
+ checkId(seq[i], 'sequences[' + s + '][' + i + ']');
62
+ const t = seen.getOrAdd(seq[i]);
63
+ if (t >= counts.length) {
64
+ const c = new Float64Array(counts.length * 2);
65
+ c.set(counts);
66
+ counts = c;
67
+ }
68
+ counts[t]++;
69
+ }
70
+ tokens += seq.length;
71
+ if (seq.length > maxLen) maxLen = seq.length;
72
+ if ((s & 255) === 255) yield;
73
+ }
74
+
75
+ // drop rare ids (keeps first-seen order)
76
+ let vocab = seen, remap = null, V = seen.size;
77
+ if (o.minCount > 1) {
78
+ vocab = createIdMap(0);
79
+ remap = new Int32Array(seen.size);
80
+ const kept = [];
81
+ for (let t = 0; t < seen.size; t++) {
82
+ if (counts[t] >= o.minCount) {
83
+ remap[t] = vocab.getOrAdd(seen.idOf(t));
84
+ kept.push(counts[t]);
85
+ } else {
86
+ remap[t] = -1;
87
+ }
88
+ }
89
+ V = vocab.size;
90
+ counts = Float64Array.from(kept);
91
+ tokens = 0;
92
+ for (let t = 0; t < V; t++) tokens += counts[t];
93
+ }
94
+ yield;
95
+
96
+ const core = yield* createSgnsCore(V, D, counts.subarray(0, V), o, rng);
97
+ const buf = new Uint32Array(Math.max(1, maxLen));
98
+ const total = o.epochs * tokens;
99
+ const tracker = base.createTracker(core, o.epochs, total);
100
+ const lr = o.learningRate, lrSpan = o.learningRate - o.minLearningRate;
101
+ let done = 0;
102
+
103
+ for (let epoch = 1; epoch <= o.epochs; epoch++) {
104
+ for (let s = 0; s < sequences.length; s++) {
105
+ const seq = sequences[s];
106
+ let len = 0;
107
+ const m = Math.min(seq.length, buf.length); // sequences must not change during training
108
+ for (let i = 0; i < m; i++) {
109
+ let t = seen.get(seq[i]);
110
+ if (remap) t = remap[t];
111
+ if (t >= 0) buf[len++] = t;
112
+ }
113
+ if (len > 1) core.train(buf, len, lr - lrSpan * (done / total));
114
+ done += len;
115
+ tracker.tick(epoch, done);
116
+ yield;
117
+ }
118
+ tracker.endEpoch(epoch, done);
119
+ }
120
+ return createEmbeddings(vocab, V, D, core.input);
121
+ }
122
+
123
+ return base.publicApi(resolved, base.inputMethods((sequences) => sequences, trainJob));
124
+ }
125
+
126
+ export {
127
+ createSkipGram
128
+ };
@@ -0,0 +1,147 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // shared plumbing for every trainer (node2vec, skip-gram, ALS, BPR):
7
+ // - publicApi / inputMethods: the public object they all return
8
+ // - one training at a time per trainer (BUSY otherwise)
9
+ // - cancel(): the running job stops at the next unit and its callback
10
+ // receives a CANCELLED error
11
+ // - events:
12
+ // 'progress' { phase: 'train', epoch, epochs, done, total, loss }
13
+ // at most every ~200ms, plus once at the end
14
+ // 'epoch' { epoch, epochs, loss } after every epoch
15
+ // loss = average −log-likelihood per scored pair since the last event;
16
+ // it should go down. listeners run synchronously; keep them cheap.
17
+ // ===========================
18
+
19
+ import { ERR, createError } from '../errors.js';
20
+ import { createEmitter, requireCallback, runJobSliced, runJobSync, now, defer } from '../async.js';
21
+
22
+ const PROGRESS_MS = 200;
23
+
24
+ function createTrainerBase() {
25
+ const events = createEmitter();
26
+ let running = false;
27
+ let cancelRequested = false;
28
+
29
+ // tracker handed to a job: call tick() after every unit of work
30
+ function createTracker(core, epochs, total) {
31
+ let last = now();
32
+ let epochLossSum = 0, epochLossN = 0;
33
+ return {
34
+ tick(epoch, done) {
35
+ if (cancelRequested) throw createError(ERR.CANCELLED, 'training was cancelled');
36
+ const t = now();
37
+ if (t - last >= PROGRESS_MS) {
38
+ last = t;
39
+ const loss = core.takeLoss();
40
+ epochLossSum += loss; epochLossN++;
41
+ events.emit('progress', { phase: 'train', epoch, epochs, done, total, loss });
42
+ }
43
+ },
44
+ endEpoch(epoch, done) {
45
+ const loss = core.takeLoss();
46
+ epochLossSum += loss; epochLossN++;
47
+ const avg = epochLossSum / epochLossN;
48
+ epochLossSum = 0; epochLossN = 0;
49
+ events.emit('progress', { phase: 'train', epoch, epochs, done, total, loss });
50
+ events.emit('epoch', { epoch, epochs, loss: avg });
51
+ }
52
+ };
53
+ }
54
+
55
+ function busyError() {
56
+ return createError(ERR.BUSY, 'train: this trainer is already training');
57
+ }
58
+
59
+ // prepare(cb) obtains the input asynchronously, then makeJob(input) is run
60
+ // time-sliced
61
+ function runAsync(cb, prepare, makeJob) {
62
+ requireCallback(cb, 'train');
63
+ if (running) {
64
+ const err = busyError();
65
+ return void defer(() => cb(err));
66
+ }
67
+ running = true;
68
+ cancelRequested = false;
69
+ prepare((err, input) => {
70
+ if (err) { running = false; return cb(err); }
71
+ runJobSliced(() => makeJob(input), (err2, result) => {
72
+ running = false;
73
+ cancelRequested = false;
74
+ if (err2) cb(err2);
75
+ else cb(null, result);
76
+ });
77
+ });
78
+ }
79
+
80
+ function runSync(prepareSync, makeJob) {
81
+ if (running) throw busyError();
82
+ running = true;
83
+ cancelRequested = false;
84
+ try {
85
+ return runJobSync(makeJob(prepareSync()));
86
+ } finally {
87
+ running = false;
88
+ cancelRequested = false;
89
+ }
90
+ }
91
+
92
+ function cancel() {
93
+ if (running) cancelRequested = true;
94
+ }
95
+
96
+ // train(input, cb) / trainSync(input) for trainers that take their data
97
+ // as an argument: read(input) checks it (and copies it if needed) when
98
+ // train is called — so the caller may reuse its arrays right away — and
99
+ // its errors reach the callback asynchronously, like any other
100
+ function inputMethods(read, makeJob) {
101
+ return {
102
+ train(input, cb) {
103
+ runAsync(cb, (next) => {
104
+ let data;
105
+ try {
106
+ data = read(input);
107
+ } catch (err) {
108
+ return void defer(() => next(err));
109
+ }
110
+ next(null, data);
111
+ }, makeJob);
112
+ },
113
+ trainSync(input) {
114
+ return runSync(() => read(input), makeJob);
115
+ }
116
+ };
117
+ }
118
+
119
+ // the public trainer object: train / trainSync from the caller, plus
120
+ // what every trainer has
121
+ function publicApi(resolved, methods) {
122
+ return {
123
+ train: methods.train,
124
+ trainSync: methods.trainSync,
125
+ cancel,
126
+ on: events.on,
127
+ off: events.off,
128
+ get training() { return running; },
129
+ get options() { return resolved; }
130
+ };
131
+ }
132
+
133
+ return {
134
+ events,
135
+ createTracker,
136
+ runAsync,
137
+ runSync,
138
+ cancel,
139
+ inputMethods,
140
+ publicApi,
141
+ get training() { return running; }
142
+ };
143
+ }
144
+
145
+ export {
146
+ createTrainerBase
147
+ };