@claude-flow/cli 3.10.26 → 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",
|
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;
|
|
@@ -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); });
|