@modusensus/dsh-mneme 0.5.2 → 0.5.3

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/lib/reranker.js CHANGED
@@ -1,218 +1,218 @@
1
- import os from "node:os";
2
- import path from "node:path";
3
-
4
- // Cross-encoder re-ranker for dsh-mneme recall candidates. Uses
5
- // bge-reranker-base through transformers.js: tries the native `rerank` task
6
- // first, then the sequence-classification head (sigmoid on the logit delta),
7
- // and finally feature-extraction over concatenated query+passage (cosine).
8
- // Every strategy funnels into scorePair(query, passage) so tests can inject a
9
- // fake scorer and never download a model. Failures throw — the caller degrades
10
- // back to the original candidate order.
11
- function hashString(s) {
12
- let h = 5381;
13
- for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
14
- return h.toString(16);
15
- }
16
-
17
- /** Same provider#hash fingerprint convention as the embedders. */
18
- function modelHash(model) {
19
- return `${model}#${hashString(model)}`;
20
- }
21
-
22
- /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
- async function defaultPipelineLoader(task, model, options) {
24
- const { env, pipeline } = await import("@huggingface/transformers");
25
- // issue #13: mirror cache_dir onto env.cacheDir so the tokenizer pre-check
26
- // resolves locally too (same fix as local-embedder.js).
27
- if (options?.cache_dir) env.cacheDir = options.cache_dir;
28
- return pipeline(task, model, options);
29
- }
30
-
31
- /** Flatten a transformers.js Tensor [batch, seq, dim] into number[][] rows. */
32
- function tensorToRows(tensor) {
33
- const { data, dims } = tensor;
34
- const dim = dims[dims.length - 1] || 0;
35
- const rows = [];
36
- for (let i = 0; i < data.length; i += dim) rows.push(Array.from(data.subarray(i, i + dim)));
37
- if (rows.length === 0 && dim > 0) rows.push(Array.from(data));
38
- return rows;
39
- }
40
-
41
- function cosine(a, b) {
42
- let dot = 0;
43
- let na = 0;
44
- let nb = 0;
45
- for (let i = 0; i < a.length; i++) {
46
- dot += a[i] * b[i];
47
- na += a[i] * a[i];
48
- nb += b[i] * b[i];
49
- }
50
- if (na === 0 || nb === 0) return 0;
51
- return dot / Math.sqrt(na * nb);
52
- }
53
-
54
- function clamp01(x) {
55
- return Math.max(0, Math.min(1, x));
56
- }
57
-
58
- // Pipeline strategies, best to worst. `rerank` is unsupported by the bundled
59
- // transformers.js (v4.2.0) and rejects cheaply before any model download, so
60
- // the cascade normally lands on the classification head.
61
- const STRATEGIES = [
62
- ["rerank", "rerank"],
63
- ["text-classification", "tc"],
64
- ["feature-extraction", "fe"]
65
- ];
66
-
67
- export class LocalReranker {
68
- constructor(opts = {}) {
69
- this.model = opts.model || "Xenova/bge-reranker-base";
70
- this.batchSize = opts.batchSize || 8;
71
- this.maxCandidates = opts.maxCandidates || 30;
72
- this.scoreThreshold = opts.scoreThreshold ?? 0.1;
73
- this.device = opts.device || "cpu";
74
- this.cacheDir =
75
- String(opts.cacheDir ?? "").trim() ||
76
- path.join(os.homedir(), ".dsh", "mneme", "models");
77
- this.logger = opts.logger ?? null;
78
- this.engineFactory = opts.engineFactory || defaultPipelineLoader;
79
- // Injectable seam: async (query, passage) => number. When set, init()
80
- // skips model loading entirely so tests never hit the network.
81
- this.scorePair = opts.scorePair ?? null;
82
- this.pipeline = null;
83
- this._batchScorer = null;
84
- this._queryVec = null;
85
- this._queryKey = null;
86
- }
87
-
88
- /** Load the model; throws when no strategy can be bound. */
89
- async init() {
90
- if (this.scorePair) return this;
91
- let lastErr = null;
92
- for (const [task, strategy] of STRATEGIES) {
93
- try {
94
- this.pipeline = await this.engineFactory(task, this.model, this._engineOptions());
95
- this._bindBatchScorer(strategy);
96
- this.logger?.info?.(
97
- `[dsh-mneme] local reranker ready: ${this.model} (strategy=${strategy}, device=${this.device})`
98
- );
99
- return this;
100
- } catch (err) {
101
- lastErr = err;
102
- this.logger?.warn?.(
103
- `[dsh-mneme] reranker task "${task}" unavailable for ${this.model}: ${String(err?.message ?? err)}`
104
- );
105
- }
106
- }
107
- throw new Error(`LocalReranker failed to load ${this.model}: ${String(lastErr?.message ?? lastErr)}`);
108
- }
109
-
110
- _engineOptions() {
111
- const options = { device: this.device };
112
- if (this.cacheDir) options.cache_dir = this.cacheDir;
113
- return options;
114
- }
115
-
116
- /** Bind a batch scorer for the chosen strategy. */
117
- _bindBatchScorer(strategy) {
118
- if (strategy === "rerank") {
119
- // Native cross-encoder task (transformers.js >= 4.6): { query, documents }
120
- // returns one score per document.
121
- this._batchScorer = async (query, passages) => {
122
- const out = await this.pipeline({ query, documents: passages });
123
- if (!Array.isArray(out)) throw new Error("rerank pipeline returned unexpected output");
124
- return out.map((r) => clamp01(typeof r?.score === "number" ? r.score : 0));
125
- };
126
- } else if (strategy === "tc") {
127
- // Classification head: tokenize (query, passage) pairs, score with
128
- // sigmoid(l1 - l0) so relevance lands in [0, 1].
129
- this._batchScorer = async (query, passages) => {
130
- const { tokenizer, model } = this.pipeline;
131
- const inputs = tokenizer(passages.map(() => query), {
132
- text_pair: passages,
133
- padding: true,
134
- truncation: true
135
- });
136
- const logits = await model(inputs).then((o) => o.logits);
137
- const dims = logits.dims;
138
- const cols = dims[dims.length - 1] || 2;
139
- const rows = [];
140
- for (let i = 0; i < dims[0]; i++) {
141
- const base = i * cols;
142
- const l0 = logits.data[base];
143
- const l1 = cols > 1 ? logits.data[base + 1] : l0;
144
- // sigmoid(l1 - l0) == softmax probability of the positive class.
145
- rows.push(clamp01(1 / (1 + Math.exp(l0 - l1))));
146
- }
147
- return rows;
148
- };
149
- } else {
150
- // Feature extraction: mean-pool the concatenated pair and compare with
151
- // the query embedding via cosine. Degraded but model-agnostic.
152
- // The query vector is cached per query string, so a new query always
153
- // recomputes it instead of reusing a stale vector from the previous call.
154
- this._queryVec = null;
155
- this._queryKey = null;
156
- this._batchScorer = async (query, passages) => {
157
- if (this._queryKey !== query) {
158
- const t = await this.pipeline([query], { pooling: "mean", normalize: true });
159
- this._queryVec = tensorToRows(t)[0];
160
- this._queryKey = query;
161
- }
162
- const t = await this.pipeline(passages.map((p) => `${query}\n${p}`), {
163
- pooling: "mean",
164
- normalize: true
165
- });
166
- return tensorToRows(t).map((v) => clamp01(cosine(this._queryVec, v)));
167
- };
168
- }
169
- }
170
-
171
- /** Score one batch of passages; injected scorePair scores pair by pair. */
172
- async _scores(query, passages) {
173
- if (this._batchScorer) return this._batchScorer(query, passages);
174
- return Promise.all(passages.map((p) => (p ? this.scorePair(query, p) : 0)));
175
- }
176
-
177
- /**
178
- * Re-rank recall candidates. Returns [{ id, score }] filtered by
179
- * scoreThreshold and sorted by descending score. Throws on engine failure —
180
- * the caller degrades to the original candidate order.
181
- */
182
- async rerank(query, candidates) {
183
- if (!Array.isArray(candidates)) throw new TypeError("rerank expects an array of candidates");
184
- const list = candidates.slice(0, this.maxCandidates);
185
- if (!list.length) return [];
186
- const q = String(query ?? "");
187
- const results = [];
188
- for (let i = 0; i < list.length; i += this.batchSize) {
189
- const chunk = list.slice(i, i + this.batchSize);
190
- const passages = chunk.map((c) => [c.title, c.content].filter(Boolean).join("\n"));
191
- const scores = await this._scores(q, passages);
192
- if (!Array.isArray(scores) || scores.length !== chunk.length) {
193
- throw new Error("reranker scorer returned mismatched scores");
194
- }
195
- for (let j = 0; j < chunk.length; j++) {
196
- results.push({ id: chunk[j].id, score: clamp01(Number(scores[j]) || 0) });
197
- }
198
- }
199
- return results
200
- .filter((r) => r.score >= this.scoreThreshold)
201
- .sort((a, b) => b.score - a.score);
202
- }
203
-
204
- get modelHash() {
205
- return modelHash(this.model);
206
- }
207
-
208
- dispose() {
209
- try {
210
- this.pipeline?.dispose?.();
211
- } catch {
212
- // best-effort: some engines free resources on GC
213
- }
214
- this.pipeline = null;
215
- this._queryVec = null;
216
- this._queryKey = null;
217
- }
218
- }
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+
4
+ // Cross-encoder re-ranker for dsh-mneme recall candidates. Uses
5
+ // bge-reranker-base through transformers.js: tries the native `rerank` task
6
+ // first, then the sequence-classification head (sigmoid on the logit delta),
7
+ // and finally feature-extraction over concatenated query+passage (cosine).
8
+ // Every strategy funnels into scorePair(query, passage) so tests can inject a
9
+ // fake scorer and never download a model. Failures throw — the caller degrades
10
+ // back to the original candidate order.
11
+ function hashString(s) {
12
+ let h = 5381;
13
+ for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0;
14
+ return h.toString(16);
15
+ }
16
+
17
+ /** Same provider#hash fingerprint convention as the embedders. */
18
+ function modelHash(model) {
19
+ return `${model}#${hashString(model)}`;
20
+ }
21
+
22
+ /** Lazy default pipeline factory: dynamic import keeps module load cheap. */
23
+ async function defaultPipelineLoader(task, model, options) {
24
+ const { env, pipeline } = await import("@huggingface/transformers");
25
+ // issue #13: mirror cache_dir onto env.cacheDir so the tokenizer pre-check
26
+ // resolves locally too (same fix as local-embedder.js).
27
+ if (options?.cache_dir) env.cacheDir = options.cache_dir;
28
+ return pipeline(task, model, options);
29
+ }
30
+
31
+ /** Flatten a transformers.js Tensor [batch, seq, dim] into number[][] rows. */
32
+ function tensorToRows(tensor) {
33
+ const { data, dims } = tensor;
34
+ const dim = dims[dims.length - 1] || 0;
35
+ const rows = [];
36
+ for (let i = 0; i < data.length; i += dim) rows.push(Array.from(data.subarray(i, i + dim)));
37
+ if (rows.length === 0 && dim > 0) rows.push(Array.from(data));
38
+ return rows;
39
+ }
40
+
41
+ function cosine(a, b) {
42
+ let dot = 0;
43
+ let na = 0;
44
+ let nb = 0;
45
+ for (let i = 0; i < a.length; i++) {
46
+ dot += a[i] * b[i];
47
+ na += a[i] * a[i];
48
+ nb += b[i] * b[i];
49
+ }
50
+ if (na === 0 || nb === 0) return 0;
51
+ return dot / Math.sqrt(na * nb);
52
+ }
53
+
54
+ function clamp01(x) {
55
+ return Math.max(0, Math.min(1, x));
56
+ }
57
+
58
+ // Pipeline strategies, best to worst. `rerank` is unsupported by the bundled
59
+ // transformers.js (v4.2.0) and rejects cheaply before any model download, so
60
+ // the cascade normally lands on the classification head.
61
+ const STRATEGIES = [
62
+ ["rerank", "rerank"],
63
+ ["text-classification", "tc"],
64
+ ["feature-extraction", "fe"]
65
+ ];
66
+
67
+ export class LocalReranker {
68
+ constructor(opts = {}) {
69
+ this.model = opts.model || "Xenova/bge-reranker-base";
70
+ this.batchSize = opts.batchSize || 8;
71
+ this.maxCandidates = opts.maxCandidates || 30;
72
+ this.scoreThreshold = opts.scoreThreshold ?? 0.1;
73
+ this.device = opts.device || "cpu";
74
+ this.cacheDir =
75
+ String(opts.cacheDir ?? "").trim() ||
76
+ path.join(os.homedir(), ".dsh", "mneme", "models");
77
+ this.logger = opts.logger ?? null;
78
+ this.engineFactory = opts.engineFactory || defaultPipelineLoader;
79
+ // Injectable seam: async (query, passage) => number. When set, init()
80
+ // skips model loading entirely so tests never hit the network.
81
+ this.scorePair = opts.scorePair ?? null;
82
+ this.pipeline = null;
83
+ this._batchScorer = null;
84
+ this._queryVec = null;
85
+ this._queryKey = null;
86
+ }
87
+
88
+ /** Load the model; throws when no strategy can be bound. */
89
+ async init() {
90
+ if (this.scorePair) return this;
91
+ let lastErr = null;
92
+ for (const [task, strategy] of STRATEGIES) {
93
+ try {
94
+ this.pipeline = await this.engineFactory(task, this.model, this._engineOptions());
95
+ this._bindBatchScorer(strategy);
96
+ this.logger?.info?.(
97
+ `[dsh-mneme] local reranker ready: ${this.model} (strategy=${strategy}, device=${this.device})`
98
+ );
99
+ return this;
100
+ } catch (err) {
101
+ lastErr = err;
102
+ this.logger?.warn?.(
103
+ `[dsh-mneme] reranker task "${task}" unavailable for ${this.model}: ${String(err?.message ?? err)}`
104
+ );
105
+ }
106
+ }
107
+ throw new Error(`LocalReranker failed to load ${this.model}: ${String(lastErr?.message ?? lastErr)}`);
108
+ }
109
+
110
+ _engineOptions() {
111
+ const options = { device: this.device };
112
+ if (this.cacheDir) options.cache_dir = this.cacheDir;
113
+ return options;
114
+ }
115
+
116
+ /** Bind a batch scorer for the chosen strategy. */
117
+ _bindBatchScorer(strategy) {
118
+ if (strategy === "rerank") {
119
+ // Native cross-encoder task (transformers.js >= 4.6): { query, documents }
120
+ // returns one score per document.
121
+ this._batchScorer = async (query, passages) => {
122
+ const out = await this.pipeline({ query, documents: passages });
123
+ if (!Array.isArray(out)) throw new Error("rerank pipeline returned unexpected output");
124
+ return out.map((r) => clamp01(typeof r?.score === "number" ? r.score : 0));
125
+ };
126
+ } else if (strategy === "tc") {
127
+ // Classification head: tokenize (query, passage) pairs, score with
128
+ // sigmoid(l1 - l0) so relevance lands in [0, 1].
129
+ this._batchScorer = async (query, passages) => {
130
+ const { tokenizer, model } = this.pipeline;
131
+ const inputs = tokenizer(passages.map(() => query), {
132
+ text_pair: passages,
133
+ padding: true,
134
+ truncation: true
135
+ });
136
+ const logits = await model(inputs).then((o) => o.logits);
137
+ const dims = logits.dims;
138
+ const cols = dims[dims.length - 1] || 2;
139
+ const rows = [];
140
+ for (let i = 0; i < dims[0]; i++) {
141
+ const base = i * cols;
142
+ const l0 = logits.data[base];
143
+ const l1 = cols > 1 ? logits.data[base + 1] : l0;
144
+ // sigmoid(l1 - l0) == softmax probability of the positive class.
145
+ rows.push(clamp01(1 / (1 + Math.exp(l0 - l1))));
146
+ }
147
+ return rows;
148
+ };
149
+ } else {
150
+ // Feature extraction: mean-pool the concatenated pair and compare with
151
+ // the query embedding via cosine. Degraded but model-agnostic.
152
+ // The query vector is cached per query string, so a new query always
153
+ // recomputes it instead of reusing a stale vector from the previous call.
154
+ this._queryVec = null;
155
+ this._queryKey = null;
156
+ this._batchScorer = async (query, passages) => {
157
+ if (this._queryKey !== query) {
158
+ const t = await this.pipeline([query], { pooling: "mean", normalize: true });
159
+ this._queryVec = tensorToRows(t)[0];
160
+ this._queryKey = query;
161
+ }
162
+ const t = await this.pipeline(passages.map((p) => `${query}\n${p}`), {
163
+ pooling: "mean",
164
+ normalize: true
165
+ });
166
+ return tensorToRows(t).map((v) => clamp01(cosine(this._queryVec, v)));
167
+ };
168
+ }
169
+ }
170
+
171
+ /** Score one batch of passages; injected scorePair scores pair by pair. */
172
+ async _scores(query, passages) {
173
+ if (this._batchScorer) return this._batchScorer(query, passages);
174
+ return Promise.all(passages.map((p) => (p ? this.scorePair(query, p) : 0)));
175
+ }
176
+
177
+ /**
178
+ * Re-rank recall candidates. Returns [{ id, score }] filtered by
179
+ * scoreThreshold and sorted by descending score. Throws on engine failure —
180
+ * the caller degrades to the original candidate order.
181
+ */
182
+ async rerank(query, candidates) {
183
+ if (!Array.isArray(candidates)) throw new TypeError("rerank expects an array of candidates");
184
+ const list = candidates.slice(0, this.maxCandidates);
185
+ if (!list.length) return [];
186
+ const q = String(query ?? "");
187
+ const results = [];
188
+ for (let i = 0; i < list.length; i += this.batchSize) {
189
+ const chunk = list.slice(i, i + this.batchSize);
190
+ const passages = chunk.map((c) => [c.title, c.content].filter(Boolean).join("\n"));
191
+ const scores = await this._scores(q, passages);
192
+ if (!Array.isArray(scores) || scores.length !== chunk.length) {
193
+ throw new Error("reranker scorer returned mismatched scores");
194
+ }
195
+ for (let j = 0; j < chunk.length; j++) {
196
+ results.push({ id: chunk[j].id, score: clamp01(Number(scores[j]) || 0) });
197
+ }
198
+ }
199
+ return results
200
+ .filter((r) => r.score >= this.scoreThreshold)
201
+ .sort((a, b) => b.score - a.score);
202
+ }
203
+
204
+ get modelHash() {
205
+ return modelHash(this.model);
206
+ }
207
+
208
+ dispose() {
209
+ try {
210
+ this.pipeline?.dispose?.();
211
+ } catch {
212
+ // best-effort: some engines free resources on GC
213
+ }
214
+ this.pipeline = null;
215
+ this._queryVec = null;
216
+ this._queryKey = null;
217
+ }
218
+ }