Elffuss BraidHub

kikocis/utopia public

608af2bf35c5 · 15.2 KiBRawPermalink
1#!/usr/bin/env node
2// 类型消解的测量台:**每一组一个新库**。
3//
4// 存在的理由是一次踩过的坑:连着三轮在同一个库上调检索,而那个库带着前几轮的
5// 改类结果——容易的实体早已精化,拒绝理由里写着 "already correctly typed as
6// pharmacy"。后两轮的数字跟第一轮根本不可比,我却拿它们当依据改了两次代码。
7//
8// 一组 = 新建知识库 → 灌固定语料 → 可选导入本体 → 跑类型消解 → 对标准答案打分。
9// 语料与标准答案都在库里(scripts/bench/),所以任何人重跑得到同一批数字。
10//
11// 用法:
12// node scripts/bench/run.mjs --corpus pharma --label seeds-only
13// node scripts/bench/run.mjs --corpus pharma --ontology /tmp/schemaorg.ttl --label schemaorg
14//
15// 环境变量:BENCH_BASE(默认 http://localhost:18080)、BENCH_EMAIL / BENCH_PASSWORD、
16// BENCH_PSQL(默认 docker exec … psql;本体段字符数要直接查库)。
17
18import fs from "node:fs";
19import path from "node:path";
20import { execFileSync } from "node:child_process";
21import { fileURLToPath } from "node:url";
22
23const HERE = path.dirname(fileURLToPath(import.meta.url));
24const BASE = process.env.BENCH_BASE || "http://localhost:18080";
25const EMAIL = process.env.BENCH_EMAIL || "bench@test.local";
26const PASSWORD = process.env.BENCH_PASSWORD || "benchbench123";
27
28// 实测 4.0 字符 ≈ 1 token(377,735↔81,855、396,716↔99,041,两次都是 4.0)。
29//
30// 抽取提示词的真实 token 数拿不到——它在 LLM 客户端里,穿出来要改一路签名。
31// 本体段字符数与它稳定成比例,而这里要量的正是"本体规模",够用且不动客户端。
32const CHARS_PER_TOKEN = 4.0;
33// 「没动过」的样子。0009 删掉内置类之后,本体装不下的实体就停在 `type_id IS NULL`,
34// 取数时写成 `-`——**它才是判断"本不该改的有没有被改"的基准**。
35//
36// 从前这里是九个内置类名(concept/person/organization…)。那套种子已经不存在,
37// 留着它会让每一个未分类实体都被判成"被改动过",wronglyChanged 直接虚高。
38const UNTOUCHED = "-";
39
40const args = Object.fromEntries(
41 process.argv.slice(2).reduce((acc, cur, i, arr) => {
42 if (cur.startsWith("--")) acc.push([cur.slice(2), arr[i + 1]]);
43 return acc;
44 }, []),
45);
46const corpusName = args.corpus || "pharma";
47const label = args.label || corpusName;
48
49let cookie = "";
50async function api(method, url, body, isForm) {
51 const init = { method, headers: {} };
52 if (cookie) init.headers.cookie = cookie;
53 if (isForm) init.body = body;
54 else if (body !== undefined) {
55 init.headers["content-type"] = "application/json";
56 init.body = JSON.stringify(body);
57 }
58 const r = await fetch(BASE + url, init);
59 for (const c of r.headers.getSetCookie?.() ?? []) cookie = c.split(";")[0];
60 const text = await r.text();
61 if (!r.ok) throw new Error(method + " " + url + " -> " + r.status + " " + text.slice(0, 200));
62 return text ? JSON.parse(text) : null;
63}
64
65function psql(sql) {
66 const cmd =
67 process.env.BENCH_PSQL ||
68 "docker exec -e PGPASSWORD=utopia landscapebi-db-1 psql -U utopia -d utopia -tAc";
69 const parts = cmd.split(" ");
70 return execFileSync(parts[0], [...parts.slice(1), sql], { encoding: "utf8" }).trim();
71}
72const num = (sql) => Number(psql(sql) || 0);
73
74const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
75/// **卡住才算超时,慢不算。**
76///
77/// 从前这里是「总时长上限 15 分钟」,于是 348 块的语料每次都在文档抽完之前
78/// 被判死——三组都这样,结果 JSON 一份也没拿到,而服务端其实一直跑得好好的
79///(任务在服务端排队,驱动脚本死掉不影响它们)。台子把跑成功的组报成失败,
80/// 比不报还坏。
81///
82/// 而这个上限没法拍一个数:单块要一分钟,20 块的语料三分钟跑完,348 块要
83/// 七十五分钟,一个总时长上限伺候不了两边。所以改成看**进展**——
84/// `fn` 每次回报一个进度值,只要它在动就把闹钟往后推。
85///
86/// `fn` 返回 true 表示完成;返回数字表示"还没完成,当前进度是这个"。
87async function until(fn, everyMs, stallMs) {
88 const stall = stallMs || 900000;
89 let deadline = Date.now() + stall;
90 let last = null;
91 for (;;) {
92 const r = await fn();
93 if (r === true) return;
94 if (typeof r === "number" && r !== last) {
95 last = r;
96 deadline = Date.now() + stall;
97 }
98 if (Date.now() > deadline) {
99 throw new Error(`等超时:${Math.round(stall / 60000)} 分钟没有任何进展`);
100 }
101 await sleep(everyMs || 5000);
102 }
103}
104
105async function main() {
106 const corpus = JSON.parse(
107 fs.readFileSync(path.join(HERE, "corpora", corpusName + ".json"), "utf8"),
108 );
109 // 答案键是**可选的**。有些语料不是准确性基准:holmes 那份是 demo 空镜与
110 // 实体消解夹具,模型早就读过它,量类型准确性量到的是记忆而不是这条流水线。
111 // 没有答案键就只报规模、耗时与图的形状,不打分——比编一份假答案诚实
112 const truthPath = path.join(HERE, "truth", corpusName + ".json");
113 const truth = fs.existsSync(truthPath)
114 ? JSON.parse(fs.readFileSync(truthPath, "utf8")).expect
115 : null;
116
117 try {
118 await api("POST", "/api/v1/auth/register", {
119 email: EMAIL,
120 display_name: "bench",
121 password: PASSWORD,
122 });
123 } catch {
124 // 已经注册过,走登录
125 }
126 await api("POST", "/api/v1/auth/login", { email: EMAIL, password: PASSWORD });
127 psql("UPDATE users SET is_admin=TRUE WHERE email='" + EMAIL + "'");
128 await api("POST", "/api/v1/auth/login", { email: EMAIL, password: PASSWORD });
129
130 const ws = (await api("GET", "/api/v1/workspaces"))[0].id;
131 // **每组一个新库**:这一条是整个脚本存在的理由,别为了省几分钟去复用
132 const stamp = new Date().toISOString().replace(/[:.]/g, "-");
133 const kb = (
134 await api("POST", "/api/v1/workspaces/" + ws + "/kbs", {
135 name: "bench " + label + " " + stamp,
136 })
137 ).id;
138 // **自动扩本体默认关掉**:它会在测量中途改本体,那样两组比的就不是同一件事了。
139 //
140 // 但关掉它也就意味着**冷启动从来没被量过**——新建的库只有 10 个默认关系,
141 // 产品的答案是抽取完自动补本体(bootstrap_ontology,列默认值 true),
142 // 而这里一律 FALSE,于是台子报出来的 related_to 占比一直是「机制被关掉之后」
143 // 的数字。拿它去说产品冷启动有多糟,是拿自己的开关当结论。
144 //
145 // 所以给它一个开关。开着跑量的是**产品的实际行为**,关着跑量的是**单一变量**,
146 // 两者都要,别只留一个。
147 const autoExtend = "auto-extend" in args;
148 if (!autoExtend) {
149 psql("UPDATE knowledge_bases SET auto_extend_ontology=FALSE WHERE id='" + kb + "'");
150 }
151 await sleep(6000);
152
153 // **导入与灌语料的先后次序,量的是两件不同的事。**
154 //
155 // 先灌后导(默认):抽取只看得见种子本体,大本体只作用于事后消解。
156 // 先导后灌(--ontology-first):抽取当场就看得见大本体,量的是提示词。
157 //
158 // 这条曾经害我得出一个错结论:默认次序下报了 108k 的本体段,就说"108k 的
159 // 提示词吃掉了 5 个实体"——而那一组抽取时提示词里只有 9 个种子类,两组的
160 // 抽取输入根本一样,25 vs 18 是跑次方差。所以下面两处 ontology_size 都记,
161 // 各自标明是什么时候量的。
162 const ontologyFirst = "ontology-first" in args;
163
164 async function importOntology() {
165 if (!args.ontology) return 0;
166 const t1 = Date.now();
167 const form = new FormData();
168 form.append(
169 "file",
170 new Blob([fs.readFileSync(args.ontology)]),
171 path.basename(args.ontology),
172 );
173 await api("POST", "/api/v1/kbs/" + kb + "/ontology/imports", form, true);
174 // 类向量建完才谈得上检索。关系那一半有后台任务补,类型消解用不到。
175 //
176 // 一千个类的冷启动要几分钟到几十分钟——跟别的库的补齐任务抢同一个嵌入
177 // 并发信号量。所以放宽到 40 分钟,并把剩余数打到 stderr:静默地等二十
178 // 分钟,分不清是在跑还是卡死了。
179 await until(
180 async () => {
181 // **两份向量都要等**(0050)。只等 `embedding` 的话,label 那份还没补完
182 // 就开跑,短说法那一路一条都检索不到——测出来的是个半成品,而且看不出来
183 const left = num(
184 "SELECT count(*) FILTER (WHERE embedding IS NULL)" +
185 " + count(*) FILTER (WHERE label_embedding IS NULL)" +
186 " FROM entity_types WHERE kb_id='" +
187 kb +
188 "'",
189 );
190 if (left) process.stderr.write(" 类向量还差 " + left + "\n");
191 // 返回剩余数当进度:它在减就说明没卡住(until 看的是"有没有动")
192 return left === 0 ? true : left;
193 },
194 10000,
195 2400000,
196 );
197 return Date.now() - t1;
198 }
199
200 const sizeNow = () => {
201 const c = num(
202 "SELECT coalesce(sum(length('- '||key||coalesce(': '||nullif(description,''),''))+1),0)" +
203 " FROM entity_types WHERE kb_id='" +
204 kb +
205 "'",
206 );
207 const r = num(
208 "SELECT coalesce(sum(length('- '||key||' (x)'||coalesce(': '||nullif(description,''),''))+1),0)" +
209 " FROM relation_types WHERE kb_id='" +
210 kb +
211 "' AND kind<>'attribute'",
212 );
213 const a = num(
214 "SELECT coalesce(sum((length('- '||r.key||' (text)'||coalesce(': '||nullif(r.description,''),''))+1)" +
215 " * greatest(1,(SELECT count(*) FROM relation_type_domains d WHERE d.relation_type_id=r.id))),0)" +
216 " FROM relation_types r WHERE r.kb_id='" +
217 kb +
218 "' AND r.kind='attribute'",
219 );
220 return {
221 classes: num("SELECT count(*) FROM entity_types WHERE kb_id='" + kb + "'"),
222 relations: num(
223 "SELECT count(*) FROM relation_types WHERE kb_id='" + kb + "' AND kind<>'attribute'",
224 ),
225 attributes: num(
226 "SELECT count(*) FROM relation_types WHERE kb_id='" + kb + "' AND kind='attribute'",
227 ),
228 prompt_chars: c + r + a,
229 prompt_tokens_est: Math.round((c + r + a) / CHARS_PER_TOKEN),
230 };
231 };
232
233 let importMs = 0;
234 if (ontologyFirst) importMs = await importOntology();
235
236 // **抽取当时本体有多大**——这一份才是提示词看到的那个规模。
237 //
238 // 先摸一次本体:种子类是**惰性建**的(第一次读本体或抽取时才落库),
239 // 不先摸就量到导入进来那些、漏掉 9 个种子。第一版就漏了,表现是
240 // 抽取时 24 类、消解时 32 类,看着像中途有人改了本体
241 await api("GET", "/api/v1/kbs/" + kb + "/ontology");
242 const atExtraction = sizeNow();
243
244 const t0 = Date.now();
245 for (const [filename, content] of corpus.docs) {
246 await api("POST", "/api/v1/kbs/" + kb + "/ingest", { filename, content });
247 }
248 // 进度按**块**数,不按文档数。文档数是个很粗的刻度:一篇 73 块的文档要跑
249 // 一个多小时,期间文档数一动不动,看着就像卡死了
250 await until(async () => {
251 const done = num(
252 "SELECT count(*) FROM documents WHERE kb_id='" + kb + "' AND graph_status='done'",
253 );
254 if (done >= corpus.docs.length) return true;
255 const chunks = num(
256 "SELECT count(*) FROM chunks WHERE kb_id='" + kb + "' AND extracted_at IS NOT NULL",
257 );
258 process.stderr.write(` 抽取 ${chunks} 块 / ${done} 篇完成\n`);
259 return chunks;
260 }, 15000);
261 const extractMs = Date.now() - t0;
262
263 if (!ontologyFirst) importMs = await importOntology();
264
265 // 消解时本体有多大(先灌后导时它跟抽取当时不同)
266 const atResolution = sizeNow();
267
268 const t2 = Date.now();
269 const outcome = await api("POST", "/api/v1/kbs/" + kb + "/ontology/type-resolution");
270 const resolveMs = Date.now() - t2;
271
272 // 打分。**待人工的按"没改"算**——它确实还没改,算成命中就是把人的活记在机器账上。
273 //
274 // **LEFT JOIN,且没有类时写 `-`**(0009)。内连接会让未分类实体整个不出现,
275 // 于是它们被算进 absent——"抽取压根没抽出来"——而实际是抽出来了、只是没定类。
276 // 两种失败的修法完全不同,混在一栏里这张表就白做了。
277 const rows = psql(
278 "SELECT e.canonical_name || '|' || coalesce(t.key, '-') FROM entities e" +
279 " LEFT JOIN entity_types t ON t.id=e.type_id" +
280 " WHERE e.kb_id='" +
281 kb +
282 "' AND e.merged_into IS NULL",
283 )
284 .split("\n")
285 .filter(Boolean)
286 .map((l) => {
287 const i = l.lastIndexOf("|");
288 return [l.slice(0, i), l.slice(i + 1)];
289 });
290
291 let hit = 0;
292 let miss = 0;
293 let correctlyLeft = 0;
294 let wronglyChanged = 0;
295 let absent = 0;
296 const notes = [];
297 for (const [frag, accept] of Object.entries(truth ?? {})) {
298 // 按片段匹配而不是全等:抽取给的名字每次略有出入
299 //("星云科技" / "星云科技(上海)有限公司"),全等会把这种变化算成失败
300 const found = rows.filter(([name]) => name.includes(frag));
301 if (found.length === 0) {
302 absent += 1;
303 continue;
304 }
305 const keys = found.map((r) => r[1]);
306 if (accept.length === 0) {
307 // 本体里没有对得上的类:正确行为是**不动**,动了才算错
308 if (keys.some((k) => k !== UNTOUCHED)) {
309 wronglyChanged += 1;
310 notes.push(frag + ":本不该改,却成了 " + keys.join("/"));
311 } else correctlyLeft += 1;
312 } else if (keys.some((k) => accept.includes(k))) {
313 hit += 1;
314 } else {
315 miss += 1;
316 notes.push(frag + ":期望 " + accept.join("|") + ",实得 " + keys.join("/"));
317 }
318 }
319
320 console.log(
321 JSON.stringify(
322 {
323 label,
324 corpus: corpusName,
325 ontology: args.ontology ? path.basename(args.ontology) : null,
326 kb_id: kb,
327 order: ontologyFirst ? "ontology-first" : "documents-first",
328 // 开关写进结果里而不是靠人记得——上一个没写进去的前提(本体规模是
329 // 什么时候量的)已经害我得出过一个错结论
330 auto_extend_ontology: autoExtend,
331 // **两份,各自标明什么时候量的。** 只报一份就会被读成"抽取用的提示词
332 // 有这么大",而先灌后导时抽取根本没见过它——这个误读已经发生过一次
333 ontology_at_extraction: atExtraction,
334 ontology_at_resolution: atResolution,
335 graph: {
336 entities: num(
337 "SELECT count(*) FROM entities WHERE kb_id='" +
338 kb +
339 "' AND merged_into IS NULL",
340 ),
341 facts: num(
342 "SELECT count(*) FROM facts WHERE kb_id='" +
343 kb +
344 "' AND invalidated_at IS NULL",
345 ),
346 },
347 resolution: {
348 retyped: outcome.retyped,
349 for_review: outcome.for_review.length,
350 left_alone: outcome.left_alone.length,
351 },
352 score: truth
353 ? { hit, miss, correctlyLeft, wronglyChanged, absent, notes }
354 : "无答案键,不打分",
355 ms: { extract: extractMs, import: importMs, resolve: resolveMs },
356 },
357 null,
358 2,
359 ),
360 );
361}
362
363main().catch((e) => {
364 console.error(e);
365 process.exit(1);
366});