@claude-flow/cli 3.10.25 → 3.10.27
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@claude-flow/cli",
|
|
3
|
-
"version": "3.10.
|
|
3
|
+
"version": "3.10.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
|
|
6
6
|
"main": "dist/src/index.js",
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// beir-bootstrap-significance.mjs — paired bootstrap significance test for
|
|
3
|
+
// BEIR retrieval results (ADR-086).
|
|
4
|
+
//
|
|
5
|
+
// Given a run JSON with per-query nDCG@10 and a baseline mean nDCG@10,
|
|
6
|
+
// estimates whether our result is significantly above the baseline.
|
|
7
|
+
//
|
|
8
|
+
// Method: paired bootstrap — resample N=10000 with replacement from our
|
|
9
|
+
// per-query nDCG scores, compute mean each time, take 2.5%-97.5% percentile
|
|
10
|
+
// for 95% CI. Compare baseline to our CI: if baseline < CI lower bound,
|
|
11
|
+
// the difference is significant at p < 0.05.
|
|
12
|
+
//
|
|
13
|
+
// For a paired test against ANOTHER per-query run (e.g. our pure-BM25 vs
|
|
14
|
+
// our BGE-base), resample paired DIFFERENCES instead. Pass --paired
|
|
15
|
+
// path/to/baseline-run.json.
|
|
16
|
+
//
|
|
17
|
+
// Usage:
|
|
18
|
+
// node scripts/beir-bootstrap-significance.mjs <run-json-path>
|
|
19
|
+
// node scripts/beir-bootstrap-significance.mjs <ours> --paired <baseline>
|
|
20
|
+
//
|
|
21
|
+
// Example:
|
|
22
|
+
// node scripts/beir-bootstrap-significance.mjs \
|
|
23
|
+
// docs/benchmarks/runs/beir-nfcorpus-bge-latest.json
|
|
24
|
+
|
|
25
|
+
import { readFileSync } from 'node:fs';
|
|
26
|
+
import { performance } from 'node:perf_hooks';
|
|
27
|
+
|
|
28
|
+
const args = process.argv.slice(2);
|
|
29
|
+
if (args.length === 0) {
|
|
30
|
+
console.error('Usage: node beir-bootstrap-significance.mjs <run-json> [--paired <baseline-run-json>]');
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
const RUN_PATH = args[0];
|
|
34
|
+
const PAIRED_IDX = args.indexOf('--paired');
|
|
35
|
+
const PAIRED_PATH = PAIRED_IDX > 0 ? args[PAIRED_IDX + 1] : null;
|
|
36
|
+
const ITERATIONS = Number(process.env.BOOTSTRAP_ITERATIONS) || 10000;
|
|
37
|
+
|
|
38
|
+
// Deterministic PRNG (Mulberry32) — so re-runs are reproducible.
|
|
39
|
+
const SEED = Number(process.env.BOOTSTRAP_SEED) || 42;
|
|
40
|
+
function mulberry32(a) {
|
|
41
|
+
return function () {
|
|
42
|
+
a |= 0; a = (a + 0x6D2B79F5) | 0;
|
|
43
|
+
let t = a;
|
|
44
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
45
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
46
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function mean(arr) { let s = 0; for (const v of arr) s += v; return s / arr.length; }
|
|
51
|
+
|
|
52
|
+
function percentile(sortedArr, p) {
|
|
53
|
+
const idx = Math.max(0, Math.min(sortedArr.length - 1, Math.floor(p * sortedArr.length)));
|
|
54
|
+
return sortedArr[idx];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function pointEstimate(scores) {
|
|
58
|
+
return {
|
|
59
|
+
mean: mean(scores),
|
|
60
|
+
n: scores.length,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function bootstrapCI(scores, iterations, rng, percentiles = [0.025, 0.975]) {
|
|
65
|
+
const means = new Float64Array(iterations);
|
|
66
|
+
const n = scores.length;
|
|
67
|
+
for (let i = 0; i < iterations; i++) {
|
|
68
|
+
let s = 0;
|
|
69
|
+
for (let j = 0; j < n; j++) s += scores[Math.floor(rng() * n)];
|
|
70
|
+
means[i] = s / n;
|
|
71
|
+
}
|
|
72
|
+
const sorted = Array.from(means).sort((a, b) => a - b);
|
|
73
|
+
return {
|
|
74
|
+
point: mean(scores),
|
|
75
|
+
lower: percentile(sorted, percentiles[0]),
|
|
76
|
+
upper: percentile(sorted, percentiles[1]),
|
|
77
|
+
p_value_vs_baseline_zero: null,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Paired bootstrap: compare our per-query scores to a baseline's per-query
|
|
82
|
+
// scores. Resample (idx) and average paired differences. The 95% CI on the
|
|
83
|
+
// mean difference tells us if it's significantly non-zero.
|
|
84
|
+
function pairedBootstrap(oursByQid, baselineByQid, iterations, rng) {
|
|
85
|
+
const sharedIds = [...oursByQid.keys()].filter((id) => baselineByQid.has(id));
|
|
86
|
+
const diffs = sharedIds.map((id) => oursByQid.get(id) - baselineByQid.get(id));
|
|
87
|
+
const n = diffs.length;
|
|
88
|
+
const means = new Float64Array(iterations);
|
|
89
|
+
for (let i = 0; i < iterations; i++) {
|
|
90
|
+
let s = 0;
|
|
91
|
+
for (let j = 0; j < n; j++) s += diffs[Math.floor(rng() * n)];
|
|
92
|
+
means[i] = s / n;
|
|
93
|
+
}
|
|
94
|
+
const sorted = Array.from(means).sort((a, b) => a - b);
|
|
95
|
+
// One-sided p ≈ fraction of resamples where mean diff ≤ 0
|
|
96
|
+
let negCount = 0;
|
|
97
|
+
for (const m of means) if (m <= 0) negCount++;
|
|
98
|
+
return {
|
|
99
|
+
n_paired: n,
|
|
100
|
+
point_diff: mean(diffs),
|
|
101
|
+
lower_95: percentile(sorted, 0.025),
|
|
102
|
+
upper_95: percentile(sorted, 0.975),
|
|
103
|
+
p_one_sided: negCount / iterations,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function loadRun(path) {
|
|
108
|
+
const data = JSON.parse(readFileSync(path, 'utf-8'));
|
|
109
|
+
if (!data.perQuery || !Array.isArray(data.perQuery)) {
|
|
110
|
+
console.error(`Run JSON at ${path} has no perQuery array — re-run the bench with the updated harness.`);
|
|
111
|
+
process.exit(2);
|
|
112
|
+
}
|
|
113
|
+
return data;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const ours = loadRun(RUN_PATH);
|
|
117
|
+
console.log(`# BEIR significance test (ADR-086)`);
|
|
118
|
+
console.log(`Run: ${RUN_PATH}`);
|
|
119
|
+
console.log(`Dataset: ${ours.dataset ?? '?'} Model: ${ours.model ?? '?'} Queries: ${ours.perQuery.length}`);
|
|
120
|
+
console.log(`Bootstrap: ${ITERATIONS} iterations, seed=${SEED}`);
|
|
121
|
+
|
|
122
|
+
const rng = mulberry32(SEED);
|
|
123
|
+
const ourScores = ours.perQuery.map((q) => q.ndcg10);
|
|
124
|
+
|
|
125
|
+
const t0 = performance.now();
|
|
126
|
+
const oursCI = bootstrapCI(ourScores, ITERATIONS, rng);
|
|
127
|
+
console.log(`\n=== Our nDCG@10 (1-sample bootstrap CI) ===`);
|
|
128
|
+
console.log(` point: ${oursCI.point.toFixed(4)}`);
|
|
129
|
+
console.log(` 95% CI: [${oursCI.lower.toFixed(4)}, ${oursCI.upper.toFixed(4)}]`);
|
|
130
|
+
|
|
131
|
+
if (ours.baselines) {
|
|
132
|
+
console.log(`\n=== vs each published baseline (CI overlap) ===`);
|
|
133
|
+
for (const [name, score] of Object.entries(ours.baselines)) {
|
|
134
|
+
const ciDiff = oursCI.point - score;
|
|
135
|
+
const lowerDiff = oursCI.lower - score;
|
|
136
|
+
const upperDiff = oursCI.upper - score;
|
|
137
|
+
const direction = ciDiff > 0 ? '↑ above' : '↓ below';
|
|
138
|
+
const sig = (lowerDiff > 0 && upperDiff > 0) ? 'p<0.05 (95% CI excludes baseline)'
|
|
139
|
+
: (lowerDiff < 0 && upperDiff < 0) ? 'p<0.05 (95% CI below baseline)'
|
|
140
|
+
: 'n.s. (95% CI overlaps baseline)';
|
|
141
|
+
console.log(` ${score.toFixed(3)} ${name.padEnd(28)} Δ=${ciDiff >= 0 ? '+' : ''}${ciDiff.toFixed(4)} ${direction} [${sig}]`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (PAIRED_PATH) {
|
|
146
|
+
const baseline = loadRun(PAIRED_PATH);
|
|
147
|
+
console.log(`\n=== Paired bootstrap vs ${PAIRED_PATH} ===`);
|
|
148
|
+
const oursByQid = new Map(ours.perQuery.map((q) => [q.qid, q.ndcg10]));
|
|
149
|
+
const baseByQid = new Map(baseline.perQuery.map((q) => [q.qid, q.ndcg10]));
|
|
150
|
+
const rng2 = mulberry32(SEED + 1);
|
|
151
|
+
const paired = pairedBootstrap(oursByQid, baseByQid, ITERATIONS, rng2);
|
|
152
|
+
console.log(` paired queries: ${paired.n_paired}`);
|
|
153
|
+
console.log(` Δ (ours - baseline): ${paired.point_diff >= 0 ? '+' : ''}${paired.point_diff.toFixed(4)}`);
|
|
154
|
+
console.log(` 95% CI: [${paired.lower_95.toFixed(4)}, ${paired.upper_95.toFixed(4)}]`);
|
|
155
|
+
console.log(` one-sided p (Δ ≤ 0): ${paired.p_one_sided.toFixed(4)}`);
|
|
156
|
+
const sig = paired.lower_95 > 0 ? 'SIGNIFICANT improvement (p<0.025 one-sided)' :
|
|
157
|
+
paired.upper_95 < 0 ? 'SIGNIFICANT regression (p<0.025 one-sided)' :
|
|
158
|
+
'NOT SIGNIFICANT — CI overlaps zero';
|
|
159
|
+
console.log(` verdict: ${sig}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
console.log(`\nBootstrap took ${((performance.now() - t0) / 1000).toFixed(1)}s.`);
|
package/scripts/run-beir-bge.mjs
CHANGED
|
@@ -26,7 +26,10 @@ const RUFLO_ROOT = resolve(SCRIPT_DIR, '../../../..');
|
|
|
26
26
|
const RUNS_DIR = join(RUFLO_ROOT, 'docs', 'benchmarks', 'runs');
|
|
27
27
|
|
|
28
28
|
const DATA_DIR = process.env.BEIR_DATA_DIR || '/tmp/beir-nfcorpus/nfcorpus';
|
|
29
|
-
|
|
29
|
+
// BUG-FIX (ADR-087): CACHE_DIR was hardcoded to /tmp/beir-nfcorpus/bge-cache,
|
|
30
|
+
// which made the SciFact run silently overwrite the NFCorpus cache. Now
|
|
31
|
+
// derived from DATA_DIR — each dataset gets its own cache directory.
|
|
32
|
+
const CACHE_DIR = join(dirname(DATA_DIR), 'bge-cache');
|
|
30
33
|
const BGE_MODEL = process.env.BGE_MODEL || 'Xenova/bge-base-en-v1.5';
|
|
31
34
|
const SKIP_INGEST = process.env.SKIP_INGEST === '1';
|
|
32
35
|
const MAX_QUERIES = Number(process.env.MAX_QUERIES) || 0;
|
|
@@ -218,25 +221,26 @@ async function main() {
|
|
|
218
221
|
|
|
219
222
|
console.log(`\nRunning ${evalQueryIds.length} queries...`);
|
|
220
223
|
let nSum = 0, mSum = 0, r10Sum = 0, r100Sum = 0, n = 0;
|
|
224
|
+
// ADR-086 — save per-query metrics for paired bootstrap significance testing.
|
|
225
|
+
const perQuery = [];
|
|
221
226
|
const tQ = performance.now();
|
|
222
227
|
for (const qid of evalQueryIds) {
|
|
223
228
|
const qtext = queriesById.get(qid);
|
|
224
229
|
if (!qtext) continue;
|
|
225
|
-
// BGE
|
|
226
|
-
// but only for v1.5 *en-icl* variants. v1.5 (non-icl) works without it.
|
|
230
|
+
// BGE v1.5 non-icl works without the query prefix.
|
|
227
231
|
const qEmb = await emb.embed(qtext);
|
|
228
|
-
// Score every doc, sort.
|
|
229
232
|
const scores = new Array(docEmbeds.length);
|
|
230
233
|
for (let i = 0; i < docEmbeds.length; i++) scores[i] = { id: docIds[i], score: cosine(qEmb, docEmbeds[i]) };
|
|
231
234
|
scores.sort((a, b) => b.score - a.score);
|
|
232
235
|
const top100 = scores.slice(0, 100).map((s) => s.id);
|
|
233
236
|
|
|
234
237
|
const qmap = qrels.get(qid);
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
n++;
|
|
238
|
+
const qNdcg = ndcg(top100, qmap, 10);
|
|
239
|
+
const qMrr = mrr(top100, qmap, 10);
|
|
240
|
+
const qR10 = recall(top100, qmap, 10);
|
|
241
|
+
const qR100 = recall(top100, qmap, 100);
|
|
242
|
+
nSum += qNdcg; mSum += qMrr; r10Sum += qR10; r100Sum += qR100; n++;
|
|
243
|
+
perQuery.push({ qid, ndcg10: qNdcg, mrr10: qMrr, recall10: qR10, recall100: qR100 });
|
|
240
244
|
if (n % 50 === 0) {
|
|
241
245
|
const elapsed = (performance.now() - tQ) / 1000;
|
|
242
246
|
console.log(` ${n}/${evalQueryIds.length} in ${elapsed.toFixed(0)}s running nDCG@10=${(nSum / n).toFixed(4)}`);
|
|
@@ -276,6 +280,7 @@ async function main() {
|
|
|
276
280
|
queries: n,
|
|
277
281
|
corpusSize: corpus.length,
|
|
278
282
|
metrics: { ndcg10, mrr10, recall10, recall100, avgQueryLatencyMs: queryMs / n },
|
|
283
|
+
perQuery, // ADR-086: per-query metrics for paired bootstrap significance testing
|
|
279
284
|
baselines: BASELINES_NDCG10,
|
|
280
285
|
ourRank,
|
|
281
286
|
leaderboardLength: ranking.length,
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// run-beir-hybrid.mjs — BM25 + dense (BGE) + RRF fusion + optional
|
|
3
|
+
// cross-encoder rerank, evaluated on BEIR (ADR-087).
|
|
4
|
+
//
|
|
5
|
+
// Pipeline:
|
|
6
|
+
// 1. BM25 over corpus (multi-field BM25 from hybrid-retrieval.ts)
|
|
7
|
+
// 2. Dense cosine over BGE-base embeddings (cached from run-beir-bge.mjs)
|
|
8
|
+
// 3. RRF fusion: score = sum over systems of 1/(k + rank) (k=60)
|
|
9
|
+
// 4. Optional cross-encoder rerank of fused top-100 → top-10
|
|
10
|
+
//
|
|
11
|
+
// Reuses the .f32 doc-embedding cache from run-beir-bge.mjs — must run
|
|
12
|
+
// that first to populate the cache.
|
|
13
|
+
//
|
|
14
|
+
// Usage:
|
|
15
|
+
// cd /tmp/beir-nfcorpus
|
|
16
|
+
// node /path/to/scripts/run-beir-hybrid.mjs # RRF only
|
|
17
|
+
// RERANK=1 node /path/to/scripts/run-beir-hybrid.mjs # + cross-encoder rerank
|
|
18
|
+
// RRF_K=60 node /path/to/scripts/run-beir-hybrid.mjs # tune RRF k
|
|
19
|
+
//
|
|
20
|
+
// ADR-087.
|
|
21
|
+
|
|
22
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { dirname, join, resolve } from 'node:path';
|
|
25
|
+
import { performance } from 'node:perf_hooks';
|
|
26
|
+
|
|
27
|
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
28
|
+
const CLI_ROOT = resolve(SCRIPT_DIR, '..');
|
|
29
|
+
const RUFLO_ROOT = resolve(SCRIPT_DIR, '../../../..');
|
|
30
|
+
const RUNS_DIR = join(RUFLO_ROOT, 'docs', 'benchmarks', 'runs');
|
|
31
|
+
|
|
32
|
+
const DATA_DIR = process.env.BEIR_DATA_DIR || '/tmp/beir-nfcorpus/nfcorpus';
|
|
33
|
+
const BGE_MODEL = process.env.BGE_MODEL || 'Xenova/bge-base-en-v1.5';
|
|
34
|
+
const CACHE_DIR = join(process.env.CACHE_BASE_DIR || dirname(DATA_DIR), 'bge-cache');
|
|
35
|
+
const RRF_K = Number(process.env.RRF_K) || 60;
|
|
36
|
+
const RERANK = process.env.RERANK === '1';
|
|
37
|
+
const RERANK_TOP_K = Number(process.env.RERANK_TOP_K) || 100;
|
|
38
|
+
const MAX_QUERIES = Number(process.env.MAX_QUERIES) || 0;
|
|
39
|
+
|
|
40
|
+
// Same baselines table as run-beir-bge.mjs.
|
|
41
|
+
const BASELINES_BY_DATASET = {
|
|
42
|
+
nfcorpus: { 'BM25 (Lucene)': 0.325, 'DocT5query': 0.328, 'TAS-B': 0.319, 'GenQ': 0.319, 'ColBERT': 0.305, 'Contriever': 0.328, 'GTR-XL': 0.343, 'SPLADE++': 0.347, 'BGE-large-v1.5 (pub)': 0.380, 'SBERT msmarco': 0.272 },
|
|
43
|
+
scifact: { 'BM25 (Lucene)': 0.679, 'DocT5query': 0.675, 'TAS-B': 0.643, 'GenQ': 0.644, 'ColBERT': 0.671, 'Contriever': 0.677, 'GTR-XL': 0.662, 'SPLADE++': 0.704, 'BGE-large-v1.5 (pub)': 0.722, 'SBERT msmarco': 0.555 },
|
|
44
|
+
};
|
|
45
|
+
function detectDataset(path) {
|
|
46
|
+
const p = path.toLowerCase();
|
|
47
|
+
for (const ds of Object.keys(BASELINES_BY_DATASET)) if (p.includes(ds)) return ds;
|
|
48
|
+
return 'nfcorpus';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function dcg(rels, k) { let s = 0; for (let i = 0; i < Math.min(rels.length, k); i++) s += (Math.pow(2, rels[i]) - 1) / Math.log2(i + 2); return s; }
|
|
52
|
+
function ndcg(retrieved, qrels, k) { const rels = retrieved.slice(0, k).map((id) => qrels.get(id) ?? 0); const ideal = [...qrels.values()].sort((a, b) => b - a).slice(0, k); const idcg = dcg(ideal, k); return idcg > 0 ? dcg(rels, k) / idcg : 0; }
|
|
53
|
+
function mrr(retrieved, qrels, k) { for (let i = 0; i < Math.min(retrieved.length, k); i++) if ((qrels.get(retrieved[i]) ?? 0) > 0) return 1 / (i + 1); return 0; }
|
|
54
|
+
function recall(retrieved, qrels, k) { const tot = [...qrels.values()].filter((v) => v > 0).length; if (tot === 0) return 0; let h = 0; for (let i = 0; i < Math.min(retrieved.length, k); i++) if ((qrels.get(retrieved[i]) ?? 0) > 0) h++; return h / tot; }
|
|
55
|
+
function cosine(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; }
|
|
56
|
+
|
|
57
|
+
function loadJsonl(path) { return readFileSync(path, 'utf-8').split('\n').filter(Boolean).map((l) => JSON.parse(l)); }
|
|
58
|
+
function loadQrels(path) { const q = new Map(); const lines = readFileSync(path, 'utf-8').split('\n'); for (let i = 1; i < lines.length; i++) { if (!lines[i].trim()) continue; const [qid, did, score] = lines[i].split('\t'); if (!q.has(qid)) q.set(qid, new Map()); q.get(qid).set(did, Number(score)); } return q; }
|
|
59
|
+
|
|
60
|
+
function cachePath(suffix) { const safe = BGE_MODEL.replace(/\//g, '_'); return join(CACHE_DIR, `${safe}.${suffix}`); }
|
|
61
|
+
function loadEmbeddings(dim) {
|
|
62
|
+
if (!existsSync(cachePath('ids')) || !existsSync(cachePath('f32'))) return null;
|
|
63
|
+
const ids = readFileSync(cachePath('ids'), 'utf-8').split('\n').filter(Boolean);
|
|
64
|
+
const raw = readFileSync(cachePath('f32'));
|
|
65
|
+
const buf = new Float32Array(raw.buffer, raw.byteOffset, raw.length / 4);
|
|
66
|
+
const embeds = [];
|
|
67
|
+
for (let i = 0; i < ids.length; i++) embeds.push(buf.slice(i * dim, (i + 1) * dim));
|
|
68
|
+
return { ids, embeds };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function main() {
|
|
72
|
+
const dataset = detectDataset(DATA_DIR);
|
|
73
|
+
const BASELINES_NDCG10 = BASELINES_BY_DATASET[dataset];
|
|
74
|
+
console.log(`# BEIR ${dataset} — hybrid RRF${RERANK ? ' + cross-encoder rerank' : ''} (ADR-087)`);
|
|
75
|
+
console.log(`Data: ${DATA_DIR}`);
|
|
76
|
+
console.log(`Dense: ${BGE_MODEL}`);
|
|
77
|
+
console.log(`RRF k: ${RRF_K}${RERANK ? `, rerank top-${RERANK_TOP_K}` : ''}`);
|
|
78
|
+
|
|
79
|
+
const corpus = loadJsonl(join(DATA_DIR, 'corpus.jsonl'));
|
|
80
|
+
const queries = loadJsonl(join(DATA_DIR, 'queries.jsonl'));
|
|
81
|
+
const qrels = loadQrels(join(DATA_DIR, 'qrels/test.tsv'));
|
|
82
|
+
console.log(`Corpus: ${corpus.length} docs · Test qrels: ${qrels.size}`);
|
|
83
|
+
|
|
84
|
+
// BGE embeddings — must be pre-cached from run-beir-bge.mjs.
|
|
85
|
+
const bge = await import(join(CLI_ROOT, 'dist/src/memory/bge-embedder.js'));
|
|
86
|
+
const emb = await bge.getBgeEmbedder(BGE_MODEL);
|
|
87
|
+
if (!emb) { console.error('BGE failed:', bge.getBgeStatus()); process.exit(1); }
|
|
88
|
+
const dim = emb.dim();
|
|
89
|
+
const cached = loadEmbeddings(dim);
|
|
90
|
+
if (!cached) { console.error(`No cached BGE embeddings at ${cachePath('f32')}. Run run-beir-bge.mjs first.`); process.exit(2); }
|
|
91
|
+
const docIds = cached.ids;
|
|
92
|
+
const docEmbeds = cached.embeds;
|
|
93
|
+
console.log(`Loaded ${docIds.length} cached BGE embeddings`);
|
|
94
|
+
|
|
95
|
+
// BM25 setup — multi-field over (title, text) per doc.
|
|
96
|
+
const { tokenize, buildCorpusStats, multiFieldBM25 } = await import(join(CLI_ROOT, 'dist/src/memory/hybrid-retrieval.js'));
|
|
97
|
+
const titleDocs = corpus.map((d) => tokenize(d.title || ''));
|
|
98
|
+
const textDocs = corpus.map((d) => tokenize(d.text || ''));
|
|
99
|
+
const titleStats = buildCorpusStats(titleDocs);
|
|
100
|
+
const textStats = buildCorpusStats(textDocs);
|
|
101
|
+
const SUBJECT_WEIGHT = Number(process.env.SUBJECT_WEIGHT ?? 1.0); // titles in BEIR are short, neutral weight is fine
|
|
102
|
+
const BODY_WEIGHT = Number(process.env.BODY_WEIGHT ?? 1.0);
|
|
103
|
+
console.log(`BM25: multi-field (title sw=${SUBJECT_WEIGHT}, text bw=${BODY_WEIGHT})`);
|
|
104
|
+
|
|
105
|
+
// Optional cross-encoder reranker.
|
|
106
|
+
let crossEncoder = null;
|
|
107
|
+
if (RERANK) {
|
|
108
|
+
const ce = await import(join(CLI_ROOT, 'dist/src/memory/cross-encoder-rerank.js'));
|
|
109
|
+
const ceFn = await ce.getCrossEncoder('Xenova/ms-marco-MiniLM-L-6-v2');
|
|
110
|
+
if (!ceFn) { console.error('Cross-encoder failed to load:', ce.getCrossEncoderStatus()); process.exit(3); }
|
|
111
|
+
crossEncoder = ceFn;
|
|
112
|
+
console.log('Cross-encoder loaded: Xenova/ms-marco-MiniLM-L-6-v2');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const queriesById = new Map(queries.map((q) => [q._id, q.text]));
|
|
116
|
+
const evalQueryIds = MAX_QUERIES ? [...qrels.keys()].slice(0, MAX_QUERIES) : [...qrels.keys()];
|
|
117
|
+
|
|
118
|
+
// Build doc id → corpus index lookup (BM25 returns indices, dense returns ids).
|
|
119
|
+
const idToIdx = new Map(docIds.map((id, i) => [id, i]));
|
|
120
|
+
// Need a reverse map too: corpus index → doc id (for BM25 over corpus order).
|
|
121
|
+
const corpusIdToIdx = new Map(corpus.map((d, i) => [d._id, i]));
|
|
122
|
+
const corpusIdxToId = corpus.map((d) => d._id);
|
|
123
|
+
|
|
124
|
+
console.log(`\nRunning ${evalQueryIds.length} queries...`);
|
|
125
|
+
let nSum = 0, mSum = 0, r10Sum = 0, r100Sum = 0, n = 0;
|
|
126
|
+
const perQuery = [];
|
|
127
|
+
const tQ = performance.now();
|
|
128
|
+
|
|
129
|
+
for (const qid of evalQueryIds) {
|
|
130
|
+
const qtext = queriesById.get(qid);
|
|
131
|
+
if (!qtext) continue;
|
|
132
|
+
|
|
133
|
+
// §1 — dense BGE retrieval
|
|
134
|
+
const qEmb = await emb.embed(qtext);
|
|
135
|
+
const denseScored = new Array(docEmbeds.length);
|
|
136
|
+
for (let i = 0; i < docEmbeds.length; i++) denseScored[i] = { id: docIds[i], score: cosine(qEmb, docEmbeds[i]) };
|
|
137
|
+
denseScored.sort((a, b) => b.score - a.score);
|
|
138
|
+
|
|
139
|
+
// §2 — BM25 retrieval (over corpus order, then map to docIds)
|
|
140
|
+
const qTokens = tokenize(qtext);
|
|
141
|
+
const bm25Scored = new Array(corpus.length);
|
|
142
|
+
for (let i = 0; i < corpus.length; i++) {
|
|
143
|
+
const s = multiFieldBM25(qTokens, titleDocs[i], textDocs[i], titleStats, textStats, SUBJECT_WEIGHT, BODY_WEIGHT);
|
|
144
|
+
bm25Scored[i] = { id: corpusIdxToId[i], score: s };
|
|
145
|
+
}
|
|
146
|
+
bm25Scored.sort((a, b) => b.score - a.score);
|
|
147
|
+
|
|
148
|
+
// §3 — RRF fusion: score = sum over systems of 1/(k + rank).
|
|
149
|
+
// Only need top ~200 from each for stable RRF; cap at top-500 per system.
|
|
150
|
+
const TOP_PER_SYSTEM = 500;
|
|
151
|
+
const rrfScores = new Map();
|
|
152
|
+
for (let r = 0; r < Math.min(TOP_PER_SYSTEM, denseScored.length); r++) {
|
|
153
|
+
const id = denseScored[r].id;
|
|
154
|
+
rrfScores.set(id, (rrfScores.get(id) || 0) + 1 / (RRF_K + r + 1));
|
|
155
|
+
}
|
|
156
|
+
for (let r = 0; r < Math.min(TOP_PER_SYSTEM, bm25Scored.length); r++) {
|
|
157
|
+
const id = bm25Scored[r].id;
|
|
158
|
+
// Skip if this doc has 0 BM25 score (no token overlap) — true random docs would otherwise leak in
|
|
159
|
+
if (bm25Scored[r].score === 0) break;
|
|
160
|
+
rrfScores.set(id, (rrfScores.get(id) || 0) + 1 / (RRF_K + r + 1));
|
|
161
|
+
}
|
|
162
|
+
const fused = [...rrfScores.entries()]
|
|
163
|
+
.map(([id, score]) => ({ id, score }))
|
|
164
|
+
.sort((a, b) => b.score - a.score)
|
|
165
|
+
.slice(0, RERANK ? RERANK_TOP_K : 100);
|
|
166
|
+
|
|
167
|
+
let final = fused;
|
|
168
|
+
|
|
169
|
+
// §4 — optional cross-encoder rerank.
|
|
170
|
+
if (crossEncoder && fused.length > 0) {
|
|
171
|
+
const docsForRerank = fused.map(({ id }) => {
|
|
172
|
+
const ci = corpusIdToIdx.get(id);
|
|
173
|
+
const d = corpus[ci];
|
|
174
|
+
return `${d.title || ''} ${d.text || ''}`.slice(0, 4096);
|
|
175
|
+
});
|
|
176
|
+
const ceScores = await crossEncoder.scoreBatch(qtext, docsForRerank);
|
|
177
|
+
final = fused
|
|
178
|
+
.map((f, i) => ({ id: f.id, score: ceScores[i], rrf: f.score }))
|
|
179
|
+
.sort((a, b) => b.score - a.score);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const top100 = final.slice(0, 100).map((s) => s.id);
|
|
183
|
+
const qmap = qrels.get(qid);
|
|
184
|
+
const qNdcg = ndcg(top100, qmap, 10);
|
|
185
|
+
const qMrr = mrr(top100, qmap, 10);
|
|
186
|
+
const qR10 = recall(top100, qmap, 10);
|
|
187
|
+
const qR100 = recall(top100, qmap, 100);
|
|
188
|
+
nSum += qNdcg; mSum += qMrr; r10Sum += qR10; r100Sum += qR100; n++;
|
|
189
|
+
perQuery.push({ qid, ndcg10: qNdcg, mrr10: qMrr, recall10: qR10, recall100: qR100 });
|
|
190
|
+
if (n % 50 === 0) {
|
|
191
|
+
const elapsed = (performance.now() - tQ) / 1000;
|
|
192
|
+
console.log(` ${n}/${evalQueryIds.length} in ${elapsed.toFixed(0)}s running nDCG@10=${(nSum / n).toFixed(4)}`);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const queryMs = performance.now() - tQ;
|
|
196
|
+
|
|
197
|
+
const ndcg10 = nSum / n;
|
|
198
|
+
const mrr10 = mSum / n;
|
|
199
|
+
const recall10 = r10Sum / n;
|
|
200
|
+
const recall100 = r100Sum / n;
|
|
201
|
+
|
|
202
|
+
console.log(`\n=== Results (N=${n}, ${dataset}, BM25+BGE-base RRF k=${RRF_K}${RERANK ? ' + CE rerank' : ''}) ===`);
|
|
203
|
+
console.log(` nDCG@10: ${ndcg10.toFixed(4)}`);
|
|
204
|
+
console.log(` MRR@10: ${mrr10.toFixed(4)}`);
|
|
205
|
+
console.log(` Recall@10: ${recall10.toFixed(4)}`);
|
|
206
|
+
console.log(` Recall@100: ${recall100.toFixed(4)}`);
|
|
207
|
+
console.log(` Avg query latency: ${(queryMs / n).toFixed(0)}ms`);
|
|
208
|
+
|
|
209
|
+
const ourLabel = `ruflo + BM25+BGE-base RRF${RERANK ? '+CE' : ''}`;
|
|
210
|
+
const ranking = [
|
|
211
|
+
...Object.entries(BASELINES_NDCG10).map(([name, score]) => ({ name, score, ours: false })),
|
|
212
|
+
{ name: ourLabel, score: ndcg10, ours: true },
|
|
213
|
+
].sort((a, b) => b.score - a.score);
|
|
214
|
+
console.log(`\n=== vs ${dataset} listed baselines ===`);
|
|
215
|
+
for (const r of ranking) console.log(` ${r.score.toFixed(3)} ${r.name}${r.ours ? ' ← us' : ''}`);
|
|
216
|
+
const ourRank = ranking.findIndex((r) => r.ours) + 1;
|
|
217
|
+
console.log(`\n Our rank: ${ourRank} / ${ranking.length}`);
|
|
218
|
+
|
|
219
|
+
const summary = {
|
|
220
|
+
runAt: new Date().toISOString(),
|
|
221
|
+
benchmark: `beir-${dataset}-hybrid${RERANK ? '-rerank' : ''}`,
|
|
222
|
+
dataset,
|
|
223
|
+
pipeline: `BM25+BGE RRF${RERANK ? '+CE-rerank' : ''}`,
|
|
224
|
+
bgeModel: BGE_MODEL,
|
|
225
|
+
rrfK: RRF_K,
|
|
226
|
+
rerank: RERANK,
|
|
227
|
+
queries: n,
|
|
228
|
+
corpusSize: corpus.length,
|
|
229
|
+
metrics: { ndcg10, mrr10, recall10, recall100, avgQueryLatencyMs: queryMs / n },
|
|
230
|
+
perQuery,
|
|
231
|
+
baselines: BASELINES_NDCG10,
|
|
232
|
+
ourRank,
|
|
233
|
+
leaderboardLength: ranking.length,
|
|
234
|
+
};
|
|
235
|
+
mkdirSync(RUNS_DIR, { recursive: true });
|
|
236
|
+
const stamp = summary.runAt.replace(/[:.]/g, '-');
|
|
237
|
+
const suffix = RERANK ? 'hybrid-rerank' : 'hybrid-rrf';
|
|
238
|
+
writeFileSync(join(RUNS_DIR, `beir-${dataset}-${suffix}-${stamp}.json`), JSON.stringify(summary, null, 2));
|
|
239
|
+
writeFileSync(join(RUNS_DIR, `beir-${dataset}-${suffix}-latest.json`), JSON.stringify(summary, null, 2));
|
|
240
|
+
console.log(`\nWrote ${join(RUNS_DIR, `beir-${dataset}-${suffix}-${stamp}.json`)}`);
|
|
241
|
+
process.exit(0);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
main().catch((err) => { console.error(err); process.exit(1); });
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// run-beir-rrf-ablation.mjs — RRF weight/k ablation matrix on a single
|
|
3
|
+
// BEIR dataset (ADR-087).
|
|
4
|
+
//
|
|
5
|
+
// Pre-requisite: BGE doc embeddings cached at <dataset>/bge-cache/
|
|
6
|
+
// (run scripts/run-beir-bge.mjs first).
|
|
7
|
+
//
|
|
8
|
+
// Reports:
|
|
9
|
+
// - Fixed default: k=60, equal weights (the headline number we ship)
|
|
10
|
+
// - Ablations: k=30/60/120 × weights (0.8/1.0, 1.0/1.0, 1.2/0.8 dense/bm25)
|
|
11
|
+
// - Bootstrap 95% CI on the fixed-default config only
|
|
12
|
+
//
|
|
13
|
+
// Usage:
|
|
14
|
+
// cd /tmp/beir-nfcorpus
|
|
15
|
+
// node /path/to/scripts/run-beir-rrf-ablation.mjs
|
|
16
|
+
// cd /tmp/beir-scifact
|
|
17
|
+
// BEIR_DATA_DIR=/tmp/beir-scifact/scifact node /path/to/scripts/run-beir-rrf-ablation.mjs
|
|
18
|
+
|
|
19
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { dirname, join, resolve } from 'node:path';
|
|
22
|
+
import { performance } from 'node:perf_hooks';
|
|
23
|
+
|
|
24
|
+
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
|
|
25
|
+
const CLI_ROOT = resolve(SCRIPT_DIR, '..');
|
|
26
|
+
const RUFLO_ROOT = resolve(SCRIPT_DIR, '../../../..');
|
|
27
|
+
const RUNS_DIR = join(RUFLO_ROOT, 'docs', 'benchmarks', 'runs');
|
|
28
|
+
|
|
29
|
+
const DATA_DIR = process.env.BEIR_DATA_DIR || '/tmp/beir-nfcorpus/nfcorpus';
|
|
30
|
+
const BGE_MODEL = process.env.BGE_MODEL || 'Xenova/bge-base-en-v1.5';
|
|
31
|
+
const CACHE_DIR = join(dirname(DATA_DIR), 'bge-cache');
|
|
32
|
+
|
|
33
|
+
const BASELINES = {
|
|
34
|
+
nfcorpus: { 'BM25': 0.325, 'BGE-large-pub': 0.380, 'SPLADE++': 0.347 },
|
|
35
|
+
scifact: { 'BM25': 0.679, 'BGE-large-pub': 0.722, 'SPLADE++': 0.704 },
|
|
36
|
+
};
|
|
37
|
+
function detectDataset(p) { const x = p.toLowerCase(); return Object.keys(BASELINES).find(d => x.includes(d)) || 'nfcorpus'; }
|
|
38
|
+
const DATASET = detectDataset(DATA_DIR);
|
|
39
|
+
|
|
40
|
+
function dcg(rels, k) { let s = 0; for (let i = 0; i < Math.min(rels.length, k); i++) s += (Math.pow(2, rels[i]) - 1) / Math.log2(i + 2); return s; }
|
|
41
|
+
function ndcg(retrieved, qrels, k) { const rels = retrieved.slice(0, k).map((id) => qrels.get(id) ?? 0); const ideal = [...qrels.values()].sort((a, b) => b - a).slice(0, k); const idcg = dcg(ideal, k); return idcg > 0 ? dcg(rels, k) / idcg : 0; }
|
|
42
|
+
function recall(retrieved, qrels, k) { const tot = [...qrels.values()].filter((v) => v > 0).length; if (tot === 0) return 0; let h = 0; for (let i = 0; i < Math.min(retrieved.length, k); i++) if ((qrels.get(retrieved[i]) ?? 0) > 0) h++; return h / tot; }
|
|
43
|
+
function cosine(a, b) { let s = 0; for (let i = 0; i < a.length; i++) s += a[i] * b[i]; return s; }
|
|
44
|
+
|
|
45
|
+
function loadJsonl(p) { return readFileSync(p, 'utf-8').split('\n').filter(Boolean).map((l) => JSON.parse(l)); }
|
|
46
|
+
function loadQrels(p) { const q = new Map(); const lines = readFileSync(p, 'utf-8').split('\n'); for (let i = 1; i < lines.length; i++) { if (!lines[i].trim()) continue; const [qid, did, s] = lines[i].split('\t'); if (!q.has(qid)) q.set(qid, new Map()); q.get(qid).set(did, Number(s)); } return q; }
|
|
47
|
+
|
|
48
|
+
function cachePath(s) { const safe = BGE_MODEL.replace(/\//g, '_'); return join(CACHE_DIR, `${safe}.${s}`); }
|
|
49
|
+
function loadEmbeddings(dim) {
|
|
50
|
+
if (!existsSync(cachePath('ids')) || !existsSync(cachePath('f32'))) return null;
|
|
51
|
+
const ids = readFileSync(cachePath('ids'), 'utf-8').split('\n').filter(Boolean);
|
|
52
|
+
const raw = readFileSync(cachePath('f32'));
|
|
53
|
+
const buf = new Float32Array(raw.buffer, raw.byteOffset, raw.length / 4);
|
|
54
|
+
return { ids, embeds: ids.map((_, i) => buf.slice(i * dim, (i + 1) * dim)) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// RRF — pure function per the original Cormack/Clarke/Buettcher 2009 paper.
|
|
58
|
+
// `rankings` is an array of [{id, score}, ...] sorted descending by score.
|
|
59
|
+
// `weights` is per-system weight (default 1.0 each).
|
|
60
|
+
function rrfFuse(rankings, k = 60, weights) {
|
|
61
|
+
const scores = new Map();
|
|
62
|
+
rankings.forEach((ranking, sIdx) => {
|
|
63
|
+
const w = weights?.[sIdx] ?? 1;
|
|
64
|
+
ranking.forEach((doc, rankIdx) => {
|
|
65
|
+
const rank = rankIdx + 1;
|
|
66
|
+
scores.set(doc.id, (scores.get(doc.id) ?? 0) + w / (k + rank));
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
return [...scores.entries()].map(([id, score]) => ({ id, score })).sort((a, b) => b.score - a.score);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Mulberry32 PRNG for deterministic bootstrap.
|
|
73
|
+
function mulberry32(a) { return function () { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
|
|
74
|
+
function bootstrapCI(scores, iter = 10000, rng = mulberry32(42)) {
|
|
75
|
+
const n = scores.length; const means = new Float64Array(iter);
|
|
76
|
+
for (let i = 0; i < iter; i++) { let s = 0; for (let j = 0; j < n; j++) s += scores[Math.floor(rng() * n)]; means[i] = s / n; }
|
|
77
|
+
const sorted = Array.from(means).sort((a, b) => a - b);
|
|
78
|
+
const lo = sorted[Math.floor(0.025 * iter)]; const hi = sorted[Math.floor(0.975 * iter)];
|
|
79
|
+
return { mean: scores.reduce((s, v) => s + v, 0) / n, lo, hi };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function main() {
|
|
83
|
+
console.log(`# RRF ablation on BEIR ${DATASET} (ADR-087)`);
|
|
84
|
+
console.log(`Data: ${DATA_DIR}\nDense: ${BGE_MODEL}\n`);
|
|
85
|
+
|
|
86
|
+
const corpus = loadJsonl(join(DATA_DIR, 'corpus.jsonl'));
|
|
87
|
+
const queries = loadJsonl(join(DATA_DIR, 'queries.jsonl'));
|
|
88
|
+
const qrels = loadQrels(join(DATA_DIR, 'qrels/test.tsv'));
|
|
89
|
+
console.log(`Corpus: ${corpus.length} · queries: ${queries.length} · test qrels: ${qrels.size}`);
|
|
90
|
+
|
|
91
|
+
// Dense
|
|
92
|
+
const bge = await import(join(CLI_ROOT, 'dist/src/memory/bge-embedder.js'));
|
|
93
|
+
const emb = await bge.getBgeEmbedder(BGE_MODEL);
|
|
94
|
+
if (!emb) { console.error('BGE failed'); process.exit(1); }
|
|
95
|
+
const cached = loadEmbeddings(emb.dim());
|
|
96
|
+
if (!cached) { console.error(`No cached embeddings at ${cachePath('f32')}. Run run-beir-bge.mjs first.`); process.exit(2); }
|
|
97
|
+
const { ids: docIds, embeds: docEmbeds } = cached;
|
|
98
|
+
|
|
99
|
+
// BM25
|
|
100
|
+
const { tokenize, buildCorpusStats, multiFieldBM25 } = await import(join(CLI_ROOT, 'dist/src/memory/hybrid-retrieval.js'));
|
|
101
|
+
const titleDocs = corpus.map((d) => tokenize(d.title || ''));
|
|
102
|
+
const textDocs = corpus.map((d) => tokenize(d.text || ''));
|
|
103
|
+
const titleStats = buildCorpusStats(titleDocs);
|
|
104
|
+
const textStats = buildCorpusStats(textDocs);
|
|
105
|
+
const corpusIdxToId = corpus.map((d) => d._id);
|
|
106
|
+
|
|
107
|
+
// Pre-compute per-query rankings for both systems ONCE, so the ablation
|
|
108
|
+
// matrix below just permutes RRF k/weights, not the underlying retrievals.
|
|
109
|
+
const queriesById = new Map(queries.map((q) => [q._id, q.text]));
|
|
110
|
+
const evalQids = [...qrels.keys()];
|
|
111
|
+
|
|
112
|
+
console.log(`Pre-computing dense + BM25 rankings for ${evalQids.length} queries...`);
|
|
113
|
+
const cached_dense = new Map();
|
|
114
|
+
const cached_bm25 = new Map();
|
|
115
|
+
const TOP_K_RETRIEVE = 1000; // enough for stable RRF
|
|
116
|
+
const tPre = performance.now();
|
|
117
|
+
for (const qid of evalQids) {
|
|
118
|
+
const qtext = queriesById.get(qid);
|
|
119
|
+
if (!qtext) continue;
|
|
120
|
+
// Dense
|
|
121
|
+
const qEmb = await emb.embed(qtext);
|
|
122
|
+
const dense = docIds.map((id, i) => ({ id, score: cosine(qEmb, docEmbeds[i]) })).sort((a, b) => b.score - a.score).slice(0, TOP_K_RETRIEVE);
|
|
123
|
+
cached_dense.set(qid, dense);
|
|
124
|
+
// BM25
|
|
125
|
+
const qTokens = tokenize(qtext);
|
|
126
|
+
const bm25 = corpus.map((d, i) => ({ id: corpusIdxToId[i], score: multiFieldBM25(qTokens, titleDocs[i], textDocs[i], titleStats, textStats, 1, 1) })).filter((d) => d.score > 0).sort((a, b) => b.score - a.score).slice(0, TOP_K_RETRIEVE);
|
|
127
|
+
cached_bm25.set(qid, bm25);
|
|
128
|
+
}
|
|
129
|
+
console.log(`Pre-compute done in ${((performance.now() - tPre) / 1000).toFixed(0)}s.\n`);
|
|
130
|
+
|
|
131
|
+
// ----- ABLATION GRID -----
|
|
132
|
+
// FIXED-DEFAULT first (the ship claim). Other variants reported as exploratory.
|
|
133
|
+
const CONFIGS = [
|
|
134
|
+
// The headline configurations — defaults fixed before viewing results.
|
|
135
|
+
{ name: 'dense only', rrf: false, weights: null, kVal: null },
|
|
136
|
+
{ name: 'BM25 only', rrf: false, weights: null, kVal: null, bm25Only: true },
|
|
137
|
+
{ name: 'RRF k=60 equal (default)', rrf: true, weights: [1.0, 1.0], kVal: 60 },
|
|
138
|
+
// Exploratory — disclose as tuned variants, not default.
|
|
139
|
+
{ name: 'RRF k=30 equal', rrf: true, weights: [1.0, 1.0], kVal: 30 },
|
|
140
|
+
{ name: 'RRF k=120 equal', rrf: true, weights: [1.0, 1.0], kVal: 120 },
|
|
141
|
+
{ name: 'RRF k=60 dense=1.2,bm25=0.8', rrf: true, weights: [1.2, 0.8], kVal: 60 },
|
|
142
|
+
{ name: 'RRF k=60 dense=0.8,bm25=1.2', rrf: true, weights: [0.8, 1.2], kVal: 60 },
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
function scoreConfig(cfg) {
|
|
146
|
+
let nSum = 0, r10Sum = 0, r100Sum = 0, n = 0;
|
|
147
|
+
const perQuery = [];
|
|
148
|
+
for (const qid of evalQids) {
|
|
149
|
+
const dense = cached_dense.get(qid);
|
|
150
|
+
const bm25 = cached_bm25.get(qid);
|
|
151
|
+
if (!dense) continue;
|
|
152
|
+
let top100;
|
|
153
|
+
if (!cfg.rrf) {
|
|
154
|
+
if (cfg.bm25Only) top100 = (bm25 || []).slice(0, 100).map((d) => d.id);
|
|
155
|
+
else top100 = dense.slice(0, 100).map((d) => d.id);
|
|
156
|
+
} else {
|
|
157
|
+
const fused = rrfFuse([dense, bm25 || []], cfg.kVal, cfg.weights);
|
|
158
|
+
top100 = fused.slice(0, 100).map((d) => d.id);
|
|
159
|
+
}
|
|
160
|
+
const qmap = qrels.get(qid);
|
|
161
|
+
const ndcg10 = ndcg(top100, qmap, 10);
|
|
162
|
+
nSum += ndcg10;
|
|
163
|
+
r10Sum += recall(top100, qmap, 10);
|
|
164
|
+
r100Sum += recall(top100, qmap, 100);
|
|
165
|
+
n++;
|
|
166
|
+
perQuery.push({ qid, ndcg10 });
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
name: cfg.name,
|
|
170
|
+
ndcg10: nSum / n,
|
|
171
|
+
recall10: r10Sum / n,
|
|
172
|
+
recall100: r100Sum / n,
|
|
173
|
+
n,
|
|
174
|
+
perQuery,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
console.log('Config | nDCG@10 R@10 R@100 95% CI');
|
|
179
|
+
console.log('--------------------------------------|---------------------------------');
|
|
180
|
+
const results = [];
|
|
181
|
+
let defaultResult = null;
|
|
182
|
+
for (const cfg of CONFIGS) {
|
|
183
|
+
const r = scoreConfig(cfg);
|
|
184
|
+
const ci = bootstrapCI(r.perQuery.map((q) => q.ndcg10));
|
|
185
|
+
const ciStr = `[${ci.lo.toFixed(3)}, ${ci.hi.toFixed(3)}]`;
|
|
186
|
+
console.log(`${cfg.name.padEnd(38)} | ${r.ndcg10.toFixed(4)} ${r.recall10.toFixed(3)} ${r.recall100.toFixed(3)} ${ciStr}`);
|
|
187
|
+
results.push({ ...r, ci, cfg });
|
|
188
|
+
if (cfg.name.includes('default')) defaultResult = { ...r, ci, cfg };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
console.log('\n=== Ship claim (fixed default, k=60, equal weights) ===');
|
|
192
|
+
console.log(`Dataset: ${DATASET}`);
|
|
193
|
+
console.log(`nDCG@10: ${defaultResult.ndcg10.toFixed(4)} 95% CI ${`[${defaultResult.ci.lo.toFixed(4)}, ${defaultResult.ci.hi.toFixed(4)}]`}`);
|
|
194
|
+
for (const [name, score] of Object.entries(BASELINES[DATASET])) {
|
|
195
|
+
const delta = defaultResult.ndcg10 - score;
|
|
196
|
+
const inCi = score >= defaultResult.ci.lo && score <= defaultResult.ci.hi;
|
|
197
|
+
const sig = inCi ? 'n.s.' : (delta > 0 ? 'p<0.05 WIN' : 'p<0.05 LOSS');
|
|
198
|
+
console.log(` vs ${name.padEnd(15)} Δ=${(delta >= 0 ? '+' : '') + delta.toFixed(4)} ${sig}`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Save
|
|
202
|
+
const summary = {
|
|
203
|
+
runAt: new Date().toISOString(),
|
|
204
|
+
benchmark: `beir-${DATASET}-rrf-ablation`,
|
|
205
|
+
dataset: DATASET,
|
|
206
|
+
bgeModel: BGE_MODEL,
|
|
207
|
+
queries: defaultResult.n,
|
|
208
|
+
corpusSize: corpus.length,
|
|
209
|
+
fixedDefault: { name: defaultResult.cfg.name, metrics: { ndcg10: defaultResult.ndcg10, recall10: defaultResult.recall10, recall100: defaultResult.recall100 }, ci: defaultResult.ci, perQuery: defaultResult.perQuery },
|
|
210
|
+
ablation: results.map((r) => ({ name: r.cfg.name, ndcg10: r.ndcg10, recall10: r.recall10, recall100: r.recall100, ci: r.ci })),
|
|
211
|
+
baselines: BASELINES[DATASET],
|
|
212
|
+
};
|
|
213
|
+
mkdirSync(RUNS_DIR, { recursive: true });
|
|
214
|
+
const stamp = summary.runAt.replace(/[:.]/g, '-');
|
|
215
|
+
writeFileSync(join(RUNS_DIR, `beir-${DATASET}-rrf-ablation-${stamp}.json`), JSON.stringify(summary, null, 2));
|
|
216
|
+
writeFileSync(join(RUNS_DIR, `beir-${DATASET}-rrf-ablation-latest.json`), JSON.stringify(summary, null, 2));
|
|
217
|
+
console.log(`\nWrote ${join(RUNS_DIR, `beir-${DATASET}-rrf-ablation-${stamp}.json`)}`);
|
|
218
|
+
process.exit(0);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
main().catch((err) => { console.error(err); process.exit(1); });
|