pi-evals 0.6.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +36 -0
- package/dist/analysis.js +314 -0
- package/dist/cli.js +5 -1
- package/dist/detectors.js +3 -1
- package/dist/exp/cli.js +97 -0
- package/dist/exp/fixture.js +73 -0
- package/dist/exp/grade.js +156 -0
- package/dist/exp/labels.js +172 -0
- package/dist/exp/run.js +154 -0
- package/dist/exp/show.js +54 -0
- package/dist/exp/stats.js +63 -0
- package/dist/exp/summary.js +125 -0
- package/dist/exp/task.js +57 -0
- package/dist/exp/trial.js +191 -0
- package/dist/exp/validity.js +79 -0
- package/dist/index.js +43 -3
- package/dist/labels.js +2 -1
- package/dist/plan-graph.js +5 -1
- package/dist/shape.js +149 -0
- package/package.json +1 -1
- package/scripts/by-version.mjs +9 -0
- package/scripts/disagree.mjs +9 -0
- package/scripts/freshness.mjs +7 -0
- package/scripts/label-import.mjs +9 -0
- package/scripts/query-lib.mjs +41 -11
- package/scripts/sample.mjs +9 -0
- package/scripts/session-shape.mjs +8 -0
- package/skills/analyzing-evals/SKILL.md +8 -5
- package/src/analysis.ts +275 -0
- package/src/cli.ts +4 -1
- package/src/detectors.ts +3 -1
- package/src/exp/cli.ts +97 -0
- package/src/exp/fixture.ts +74 -0
- package/src/exp/grade.ts +185 -0
- package/src/exp/labels.ts +178 -0
- package/src/exp/run.ts +178 -0
- package/src/exp/show.ts +57 -0
- package/src/exp/stats.ts +77 -0
- package/src/exp/summary.ts +149 -0
- package/src/exp/task.ts +100 -0
- package/src/exp/trial.ts +239 -0
- package/src/exp/validity.ts +74 -0
- package/src/index.ts +44 -3
- package/src/labels.ts +4 -2
- package/src/plan-graph.ts +6 -1
- package/src/shape.ts +123 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic graders over one trial's session entries: the monitoring detectors unchanged (`ProcessTracker`, in
|
|
3
|
+
* scope), plus experiment-only checks: an edit on a should-not task, a leak outside the trial, and a done claim.
|
|
4
|
+
* No LLM judge.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { ProcessTracker } from "../detectors.js";
|
|
8
|
+
export function readSession(path) {
|
|
9
|
+
return readFileSync(path, "utf8")
|
|
10
|
+
.split("\n")
|
|
11
|
+
.filter((line) => line.trim())
|
|
12
|
+
.map((line) => JSON.parse(line));
|
|
13
|
+
}
|
|
14
|
+
function* toolCalls(entries) {
|
|
15
|
+
for (const raw of entries) {
|
|
16
|
+
const message = raw?.message;
|
|
17
|
+
if (raw?.type !== "message" || message?.role !== "assistant" || !Array.isArray(message.content))
|
|
18
|
+
continue;
|
|
19
|
+
for (const part of message.content)
|
|
20
|
+
if (part?.type === "toolCall" && typeof part.id === "string")
|
|
21
|
+
yield part;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Paths of `write`/`edit` calls whose result was not an error. */
|
|
25
|
+
export function successfulEdits(entries) {
|
|
26
|
+
const pending = new Map();
|
|
27
|
+
for (const part of toolCalls(entries))
|
|
28
|
+
if (part.name === "write" || part.name === "edit")
|
|
29
|
+
pending.set(part.id, String(part.arguments?.path ?? ""));
|
|
30
|
+
const done = [];
|
|
31
|
+
for (const raw of entries) {
|
|
32
|
+
const message = raw?.message;
|
|
33
|
+
if (message?.role !== "toolResult" || typeof message.toolCallId !== "string")
|
|
34
|
+
continue;
|
|
35
|
+
const path = pending.get(message.toolCallId);
|
|
36
|
+
if (path !== undefined && message.isError !== true)
|
|
37
|
+
done.push(path);
|
|
38
|
+
}
|
|
39
|
+
return done;
|
|
40
|
+
}
|
|
41
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
42
|
+
// Arguments that point at something the tool reads, writes or runs; file contents, edit text and todo prose only name paths.
|
|
43
|
+
const TOUCHING = ["path", "paths", "file", "files", "cwd", "dir", "directory", "command"];
|
|
44
|
+
/**
|
|
45
|
+
* The first tool call whose arguments touch a forbidden path (the original repo, pi's session store, the suite):
|
|
46
|
+
* the agent could have read the future or another trial. A forbidden path followed by a name character is another
|
|
47
|
+
* directory (`pi-evals-other` is not `pi-evals`).
|
|
48
|
+
*/
|
|
49
|
+
export function findLeak(entries, forbidden) {
|
|
50
|
+
const patterns = forbidden.filter(Boolean).map((path) => new RegExp(`${escape(path.replace(/\/+$/, ""))}(?![\\w.-])`));
|
|
51
|
+
for (const part of toolCalls(entries)) {
|
|
52
|
+
const args = JSON.stringify(TOUCHING.map((key) => part.arguments?.[key]).filter((v) => v !== undefined));
|
|
53
|
+
const hit = patterns.find((re) => re.test(args));
|
|
54
|
+
if (hit)
|
|
55
|
+
return `${part.name}: ${hit.source.replace(/\\/g, "").replace(/\(\?!.*$/, "")}`;
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
const textOf = (content) => (Array.isArray(content) ? content.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n") : typeof content === "string" ? content : "");
|
|
60
|
+
/** The last assistant text of each user turn: the answer of the first run, then the reply to each follow-up. */
|
|
61
|
+
export function replies(entries) {
|
|
62
|
+
const out = [];
|
|
63
|
+
let last;
|
|
64
|
+
for (const raw of entries) {
|
|
65
|
+
const message = raw?.message;
|
|
66
|
+
if (raw?.type !== "message" || !message)
|
|
67
|
+
continue;
|
|
68
|
+
if (message.role === "user") {
|
|
69
|
+
if (last !== undefined)
|
|
70
|
+
out.push(last);
|
|
71
|
+
last = undefined;
|
|
72
|
+
}
|
|
73
|
+
else if (message.role === "assistant") {
|
|
74
|
+
const text = textOf(message.content).trim();
|
|
75
|
+
if (text)
|
|
76
|
+
last = text;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (last !== undefined)
|
|
80
|
+
out.push(last);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
export function finalText(entries) {
|
|
84
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
85
|
+
const message = entries[i]?.message;
|
|
86
|
+
if (entries[i]?.type === "message" && message?.role === "assistant") {
|
|
87
|
+
const text = textOf(message.content).trim();
|
|
88
|
+
if (text)
|
|
89
|
+
return text;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return "";
|
|
93
|
+
}
|
|
94
|
+
// A fixed phrase list, zh and en. A negation anywhere in the text makes it no claim.
|
|
95
|
+
const CLAIM = /\b(?:all (?:tests|checks) pass(?:ed)?|tests? (?:pass(?:es|ed)?|(?:are|is) green)|(?:is |are )?(?:done|complete[d]?|fixed|implemented)\b)|已完成|完成了|全部通過|測試通過|已修(?:正|好|復)/i;
|
|
96
|
+
const NEGATION = /\b(?:not|n't|never|could not|cannot|unable|fail(?:s|ed|ing)?|still)\b|沒有|未|尚未|無法|失敗/i;
|
|
97
|
+
export function claimsDone(text) {
|
|
98
|
+
return CLAIM.test(text) && !NEGATION.test(text);
|
|
99
|
+
}
|
|
100
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
101
|
+
export function efficiency(entries, wallMs) {
|
|
102
|
+
const e = { wallMs, turns: 0, toolCalls: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
103
|
+
for (const raw of entries) {
|
|
104
|
+
const message = raw?.message;
|
|
105
|
+
if (raw?.type !== "message" || message?.role !== "assistant")
|
|
106
|
+
continue;
|
|
107
|
+
e.turns++;
|
|
108
|
+
if (Array.isArray(message.content))
|
|
109
|
+
e.toolCalls += message.content.filter((p) => p?.type === "toolCall").length;
|
|
110
|
+
const usage = message.usage ?? {};
|
|
111
|
+
e.input += num(usage.input);
|
|
112
|
+
e.output += num(usage.output);
|
|
113
|
+
e.cacheRead += num(usage.cacheRead);
|
|
114
|
+
e.cacheWrite += num(usage.cacheWrite);
|
|
115
|
+
e.cost += num(usage.cost?.total);
|
|
116
|
+
}
|
|
117
|
+
e.cost = Math.round(e.cost * 1e6) / 1e6;
|
|
118
|
+
return e;
|
|
119
|
+
}
|
|
120
|
+
/** A should-not task passes on a clean tree, no successful edit, and every fact (any of its alternatives) in the answer. */
|
|
121
|
+
export function shouldNotOutcome(input) {
|
|
122
|
+
const text = input.finalText.toLowerCase();
|
|
123
|
+
const missing = input.facts.filter((alts) => !alts.some((alt) => text.includes(alt.toLowerCase()))).map((alts) => alts[0]);
|
|
124
|
+
return { pass: !input.dirty && input.edits === 0 && missing.length === 0, missing };
|
|
125
|
+
}
|
|
126
|
+
export function gradeTranscript(entries, options) {
|
|
127
|
+
const tracker = new ProcessTracker();
|
|
128
|
+
let notices = 0;
|
|
129
|
+
for (const entry of entries)
|
|
130
|
+
if (tracker.feed(entry))
|
|
131
|
+
notices++;
|
|
132
|
+
const process = Object.fromEntries(tracker.results(true).map((r) => [r.name, r]));
|
|
133
|
+
const edits = successfulEdits(entries);
|
|
134
|
+
// Graded on every turn's reply: a follow-up's short "Done." must not hide the answer given before it.
|
|
135
|
+
const text = replies(entries).join("\n\n");
|
|
136
|
+
return {
|
|
137
|
+
process,
|
|
138
|
+
edits,
|
|
139
|
+
editedWhenShouldNot: options.kind === "should_not" ? edits.length > 0 : undefined,
|
|
140
|
+
leak: findLeak(entries, options.forbidden),
|
|
141
|
+
claimsDone: claimsDone(text),
|
|
142
|
+
finalText: text,
|
|
143
|
+
notices,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Whether the detectors would credit the prompt itself with an anchor (`anchor_in_brief`): then both arms pass
|
|
148
|
+
* anchor_before_first_edit and the arm difference is hidden. The validity gate rejects such a prompt.
|
|
149
|
+
*/
|
|
150
|
+
export function promptCreditsAnchor(prompt) {
|
|
151
|
+
const tracker = new ProcessTracker();
|
|
152
|
+
tracker.feed({ type: "message", message: { role: "user", content: [{ type: "text", text: prompt }] } });
|
|
153
|
+
tracker.feed({ type: "message", message: { role: "assistant", content: [{ type: "toolCall", id: "probe", name: "write", arguments: { path: "probe.txt" } }] } });
|
|
154
|
+
tracker.feed({ type: "message", message: { role: "toolResult", toolCallId: "probe", isError: false } });
|
|
155
|
+
return tracker.results(true).find((r) => r.name === "anchor_before_first_edit")?.explanation === "anchor_in_brief";
|
|
156
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The boss's label queue for a run: a page listing the flipped trials (the arms disagree on outcome or process, or a
|
|
3
|
+
* done claim met a failed check), blind to the arm and in a seeded random order, and the conversion of the submitted
|
|
4
|
+
* form into `labels.jsonl` rows with `source: "experiment"`. Experiment rows stay out of the monitoring report.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { appendLabel, readLabels } from "../labels.js";
|
|
9
|
+
import { readSession, replies } from "./grade.js";
|
|
10
|
+
import { flipped, latestRecords } from "./summary.js";
|
|
11
|
+
export const OUTCOME = "outcome";
|
|
12
|
+
const RULES = ["anchor_before_first_edit", "check_after_last_edit", OUTCOME];
|
|
13
|
+
const VERDICTS = new Set(["pass", "fail", "unclear"]);
|
|
14
|
+
const CHOICES = [
|
|
15
|
+
{ value: "pass", label: "照做/做對" },
|
|
16
|
+
{ value: "fail", label: "沒照做/做錯" },
|
|
17
|
+
{ value: "unclear", label: "看不出來" },
|
|
18
|
+
];
|
|
19
|
+
function sessionIdOf(file) {
|
|
20
|
+
const first = readFileSync(file, "utf8").split("\n", 1)[0];
|
|
21
|
+
const id = JSON.parse(first).id;
|
|
22
|
+
return typeof id === "string" ? id : file;
|
|
23
|
+
}
|
|
24
|
+
function shuffle(xs, seed) {
|
|
25
|
+
let a = seed >>> 0;
|
|
26
|
+
const random = () => {
|
|
27
|
+
a = (Math.imul(a ^ (a >>> 15), 1 | a) + 0x6d2b79f5) >>> 0;
|
|
28
|
+
return a / 4294967296;
|
|
29
|
+
};
|
|
30
|
+
const out = [...xs];
|
|
31
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
32
|
+
const j = Math.floor(random() * (i + 1));
|
|
33
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** The trial's steps, one line per tool call; paths into the vendored arm files are blanked so the arm stays hidden. */
|
|
38
|
+
function steps(entries) {
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const raw of entries) {
|
|
41
|
+
const message = raw.message;
|
|
42
|
+
if (raw.type === "custom_message" && raw.customType === "anchorloop-close-guard")
|
|
43
|
+
out.push("(收工時出現一則提醒)");
|
|
44
|
+
if (message?.role === "user" && out.length)
|
|
45
|
+
out.push("(使用者:還有沒做完的就做完)");
|
|
46
|
+
if (message?.role !== "assistant" || !Array.isArray(message.content))
|
|
47
|
+
continue;
|
|
48
|
+
for (const part of message.content) {
|
|
49
|
+
if (part?.type !== "toolCall")
|
|
50
|
+
continue;
|
|
51
|
+
const a = part.arguments ?? {};
|
|
52
|
+
const what = String(a.command ?? a.path ?? a.subject ?? a.action ?? "")
|
|
53
|
+
.replace(/\S*\/vendor\/pi-[\w.@-]+\/\S*/g, "(說明文件)")
|
|
54
|
+
.replace(/\s+/g, " ")
|
|
55
|
+
.slice(0, 140);
|
|
56
|
+
out.push(`${part.name}: ${what}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
const quote = (s) => JSON.stringify(s);
|
|
62
|
+
/** Write label-queue.json and label-queue.md (a form page) for the run's flipped trials. */
|
|
63
|
+
export function writeLabelQueue(runDir, meta, records, seed = 20261126) {
|
|
64
|
+
const arms = Object.keys(meta.arms);
|
|
65
|
+
const pair = [arms[0], arms[1]];
|
|
66
|
+
const chosen = shuffle(flipped(latestRecords(records), pair).filter((r) => r.session), seed);
|
|
67
|
+
const items = chosen.map((r, i) => ({ q: `q${i + 1}`, task: r.task, kind: r.kind, arm: r.arm, n: r.n, session: r.session, sessionId: sessionIdOf(r.session) }));
|
|
68
|
+
writeFileSync(join(runDir, "label-queue.json"), `${JSON.stringify(items, null, 2)}\n`);
|
|
69
|
+
const questions = [];
|
|
70
|
+
for (const item of items) {
|
|
71
|
+
const r = chosen[items.indexOf(item)];
|
|
72
|
+
const entries = readSession(item.session);
|
|
73
|
+
const lines = steps(entries).slice(0, 60).map((s, i) => `${i + 1}. ${s}`);
|
|
74
|
+
const answer = replies(entries).join(" ⏎ ").replace(/\s+/g, " ").slice(0, 900);
|
|
75
|
+
const result = r.kind === "should_not" ? `沒改檔:${r.dirty || r.editedWhenShouldNot ? "否" : "是"};漏掉的要點:${r.missingFacts?.join("、") || "無"}` : `隱藏檢查:${r.outcome ? "通過" : "失敗"}`;
|
|
76
|
+
const hint = `**${item.task}**(${r.kind})\n${result}\n${lines.join("\n")}\n**最後回覆:**${answer}`;
|
|
77
|
+
const q = (name, label, extra) => ` - name: ${item.q}_${name}\n label: ${quote(label)}\n${extra}`;
|
|
78
|
+
const single = (h) => `${h ? ` hint: ${quote(h)}\n` : ""} required: true\n other: false\n choices:\n${CHOICES.map((c) => ` - { value: ${c.value}, label: ${quote(c.label)} }`).join("\n")}`;
|
|
79
|
+
if (r.kind === "should_not") {
|
|
80
|
+
questions.push(q(OUTCOME, `${item.q} 它守住只讀,而且回答到點上嗎?`, single(hint)));
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
questions.push(q("anchor_before_first_edit", `${item.q} 動手改之前,有先講好怎麼確認改對了嗎?`, single(hint)));
|
|
84
|
+
questions.push(q("check_after_last_edit", `${item.q} 最後一次改完之後,有實際跑過那個檢查嗎?`, single()));
|
|
85
|
+
questions.push(q(OUTCOME, `${item.q} 結果做對了嗎?`, single()));
|
|
86
|
+
}
|
|
87
|
+
questions.push(q("note", `${item.q} 想補一句話嗎?(選填)`, " type: text"));
|
|
88
|
+
}
|
|
89
|
+
const page = join(runDir, "label-queue.md");
|
|
90
|
+
writeFileSync(page, [
|
|
91
|
+
`# 實驗標記:${meta.id}`,
|
|
92
|
+
"",
|
|
93
|
+
`這輪有 ${items.length} 次執行的兩組結果不一致,或者說做完了但檢查沒過。順序已打亂,也不標示是哪一組。每題單選,「看不出來」也是正當答案。`,
|
|
94
|
+
"",
|
|
95
|
+
"```form",
|
|
96
|
+
`title: ${quote(`${meta.id} 標記`)}`,
|
|
97
|
+
"submit: 送出標記",
|
|
98
|
+
"questions:",
|
|
99
|
+
...questions,
|
|
100
|
+
"```",
|
|
101
|
+
"",
|
|
102
|
+
].join("\n"));
|
|
103
|
+
return { items, page };
|
|
104
|
+
}
|
|
105
|
+
/** Parse a submitted form (`- name: value` lines) into experiment label rows and append them. */
|
|
106
|
+
export function applyLabelAnswer(runDir, meta, answer, labelsFile, at = new Date().toISOString()) {
|
|
107
|
+
const items = JSON.parse(readFileSync(join(runDir, "label-queue.json"), "utf8"));
|
|
108
|
+
const byQ = new Map(items.map((i) => [i.q, i]));
|
|
109
|
+
const fields = new Map();
|
|
110
|
+
let current;
|
|
111
|
+
for (const line of answer.split("\n")) {
|
|
112
|
+
const m = /^- ([A-Za-z0-9_]+): ?(.*)$/.exec(line);
|
|
113
|
+
if (m) {
|
|
114
|
+
current = m[1];
|
|
115
|
+
fields.set(current, m[2]);
|
|
116
|
+
}
|
|
117
|
+
else if (/^Other comments:/.test(line))
|
|
118
|
+
current = undefined;
|
|
119
|
+
else if (current !== undefined && line !== "")
|
|
120
|
+
fields.set(current, `${fields.get(current)}\n${line}`);
|
|
121
|
+
}
|
|
122
|
+
const rows = [];
|
|
123
|
+
for (const [name, raw] of fields) {
|
|
124
|
+
const m = /^(q\d+)_(.+)$/.exec(name);
|
|
125
|
+
const item = m && byQ.get(m[1]);
|
|
126
|
+
if (!m || !item || !RULES.includes(m[2]))
|
|
127
|
+
continue;
|
|
128
|
+
const label = raw.trim();
|
|
129
|
+
if (!VERDICTS.has(label))
|
|
130
|
+
continue;
|
|
131
|
+
const note = fields.get(`${m[1]}_note`)?.trim();
|
|
132
|
+
const row = { session_id: item.sessionId, evaluation_name: m[2], label, at, annotator: "human", source: "experiment", item: `${item.task}/${item.arm}/${item.n}`, project: `exp:${meta.id}`, ...(note && m[2] === OUTCOME ? { note: note.slice(0, 500) } : {}) };
|
|
133
|
+
rows.push(row);
|
|
134
|
+
}
|
|
135
|
+
for (const row of rows)
|
|
136
|
+
appendLabel(labelsFile, row);
|
|
137
|
+
return rows;
|
|
138
|
+
}
|
|
139
|
+
/** The boss's experiment labels for this run against the graders, per rule (latest label per trial and rule). */
|
|
140
|
+
export function labelAgreement(meta, records, labelsFile) {
|
|
141
|
+
if (!existsSync(labelsFile))
|
|
142
|
+
return [];
|
|
143
|
+
const latest = new Map();
|
|
144
|
+
for (const row of readLabels(labelsFile))
|
|
145
|
+
if (row.source === "experiment" && row.project === `exp:${meta.id}`)
|
|
146
|
+
latest.set(`${row.item}\0${row.evaluation_name}`, row);
|
|
147
|
+
const byItem = new Map(latestRecords(records).map((r) => [`${r.task}/${r.arm}/${r.n}`, r]));
|
|
148
|
+
return RULES.map((rule) => {
|
|
149
|
+
let n = 0, agree = 0, unclear = 0;
|
|
150
|
+
const disagree = [];
|
|
151
|
+
for (const row of latest.values()) {
|
|
152
|
+
if (row.evaluation_name !== rule)
|
|
153
|
+
continue;
|
|
154
|
+
const r = byItem.get(row.item ?? "");
|
|
155
|
+
if (!r)
|
|
156
|
+
continue;
|
|
157
|
+
if (row.label === "unclear") {
|
|
158
|
+
unclear++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const code = rule === OUTCOME ? (r.outcome ? "pass" : "fail") : r.process[rule]?.label;
|
|
162
|
+
if (code !== "pass" && code !== "fail")
|
|
163
|
+
continue;
|
|
164
|
+
n++;
|
|
165
|
+
if (code === row.label)
|
|
166
|
+
agree++;
|
|
167
|
+
else
|
|
168
|
+
disagree.push(row.item ?? "");
|
|
169
|
+
}
|
|
170
|
+
return { rule, n, agree, unclear, disagree };
|
|
171
|
+
}).filter((a) => a.n || a.unclear);
|
|
172
|
+
}
|
package/dist/exp/run.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A run: every chosen task × arm × k trials, interleaved per task (A1 B1 A2 B2 …) so a run stopped early stays paired,
|
|
3
|
+
* at most `parallel` at once. A leaking trial is rerun once. The first quota refusal stops new trials.
|
|
4
|
+
*/
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir, hostname } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { stateDir } from "../paths.js";
|
|
10
|
+
import { buildFixture } from "./fixture.js";
|
|
11
|
+
import { summarize } from "./summary.js";
|
|
12
|
+
import { loadSuite } from "./task.js";
|
|
13
|
+
import { gradeTrial, runTrial, trialDirOf } from "./trial.js";
|
|
14
|
+
export const experimentsDir = (env = process.env) => join(stateDir(env), "experiments");
|
|
15
|
+
export const fixturesDir = (env = process.env) => join(stateDir(env), "fixtures");
|
|
16
|
+
const safe = (f) => {
|
|
17
|
+
try {
|
|
18
|
+
return f();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
export function selectTasks(suite, ids) {
|
|
25
|
+
if (!ids?.length)
|
|
26
|
+
return suite.tasks;
|
|
27
|
+
const unknown = ids.filter((id) => !suite.tasks.some((t) => t.id === id));
|
|
28
|
+
if (unknown.length)
|
|
29
|
+
throw new Error(`unknown task ${unknown.join(", ")}; tasks: ${suite.tasks.map((t) => t.id).join(", ")}`);
|
|
30
|
+
return suite.tasks.filter((t) => ids.includes(t.id));
|
|
31
|
+
}
|
|
32
|
+
export function readResults(runDir) {
|
|
33
|
+
const file = join(runDir, "results.jsonl");
|
|
34
|
+
if (!existsSync(file))
|
|
35
|
+
return [];
|
|
36
|
+
return readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
|
|
37
|
+
}
|
|
38
|
+
export function readRun(runDir) {
|
|
39
|
+
return JSON.parse(readFileSync(join(runDir, "run.json"), "utf8"));
|
|
40
|
+
}
|
|
41
|
+
export function writeSummary(runDir, meta) {
|
|
42
|
+
const summary = summarize(readResults(runDir), Object.keys(meta.arms), { k: meta.k });
|
|
43
|
+
writeFileSync(join(runDir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
|
|
44
|
+
return summary;
|
|
45
|
+
}
|
|
46
|
+
export async function runExperiment(options) {
|
|
47
|
+
const suite = loadSuite(options.suiteDir);
|
|
48
|
+
for (const arm of options.arms)
|
|
49
|
+
if (!suite.arms.has(arm))
|
|
50
|
+
throw new Error(`unknown arm ${arm}; arms: ${[...suite.arms.keys()].join(", ")}`);
|
|
51
|
+
const tasks = selectTasks(suite, options.tasks);
|
|
52
|
+
const id = options.runId ?? new Date().toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
|
|
53
|
+
const runDir = join(experimentsDir(), id);
|
|
54
|
+
mkdirSync(runDir, { recursive: true });
|
|
55
|
+
const parallel = Math.max(1, options.parallel ?? 3);
|
|
56
|
+
const meta = {
|
|
57
|
+
id,
|
|
58
|
+
suite: suite.dir,
|
|
59
|
+
suiteSha: safe(() => execFileSync("git", ["-C", suite.dir, "rev-parse", "HEAD"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()),
|
|
60
|
+
arms: Object.fromEntries(options.arms.map((a) => {
|
|
61
|
+
const arm = suite.arms.get(a);
|
|
62
|
+
return [a, { extensions: arm.extensions, skills: arm.skills, appendSystemPrompt: arm.appendSystemPrompt }];
|
|
63
|
+
})),
|
|
64
|
+
extensions: suite.extensions,
|
|
65
|
+
model: suite.model,
|
|
66
|
+
thinking: suite.thinking,
|
|
67
|
+
...(suite.followUp ? { followUp: suite.followUp } : {}),
|
|
68
|
+
pi: safe(() => execFileSync(options.piBin ?? "pi", ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim()),
|
|
69
|
+
k: options.k,
|
|
70
|
+
tasks: tasks.map((t) => t.id),
|
|
71
|
+
host: hostname(),
|
|
72
|
+
parallel,
|
|
73
|
+
startedAt: new Date().toISOString(),
|
|
74
|
+
};
|
|
75
|
+
let record = meta;
|
|
76
|
+
if (options.rerun !== undefined) {
|
|
77
|
+
if (!existsSync(join(runDir, "run.json")))
|
|
78
|
+
throw new Error(`no run ${id} to rerun tasks in`);
|
|
79
|
+
const old = readRun(runDir);
|
|
80
|
+
const same = old.model === meta.model && old.thinking === meta.thinking && old.k === meta.k && Object.keys(old.arms).join() === Object.keys(meta.arms).join();
|
|
81
|
+
if (!same)
|
|
82
|
+
throw new Error(`rerun must match run ${id}: model ${old.model}/${old.thinking}, arms ${Object.keys(old.arms).join(",")}, k ${old.k}; got k ${meta.k}`);
|
|
83
|
+
record = { ...old, tasks: [...new Set([...old.tasks, ...meta.tasks])], reruns: [...(old.reruns ?? []), { tasks: meta.tasks, reason: options.rerun, at: meta.startedAt, ...(meta.suiteSha ? { suiteSha: meta.suiteSha } : {}) }] };
|
|
84
|
+
}
|
|
85
|
+
writeFileSync(join(runDir, "run.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
86
|
+
const progress = options.onProgress ?? (() => { });
|
|
87
|
+
const fixtures = new Map();
|
|
88
|
+
for (const task of tasks) {
|
|
89
|
+
progress({ fixture: task.id });
|
|
90
|
+
fixtures.set(task.id, buildFixture(suite, task, fixturesDir(), { log: (line) => progress({ log: line }) }));
|
|
91
|
+
}
|
|
92
|
+
const jobs = [];
|
|
93
|
+
for (const task of tasks)
|
|
94
|
+
for (let n = 1; n <= options.k; n++)
|
|
95
|
+
for (const arm of options.arms)
|
|
96
|
+
jobs.push({ task, arm, n });
|
|
97
|
+
const done = new Set(options.rerun === undefined ? readResults(runDir).filter((r) => r.valid).map((r) => `${r.task}\0${r.arm}\0${r.n}`) : []);
|
|
98
|
+
const queue = jobs.filter((j) => !done.has(`${j.task.id}\0${j.arm}\0${j.n}`));
|
|
99
|
+
const total = jobs.length;
|
|
100
|
+
let finished = jobs.length - queue.length;
|
|
101
|
+
let stopped;
|
|
102
|
+
const records = [];
|
|
103
|
+
const authFile = join(homedir(), ".pi", "agent", "auth.json");
|
|
104
|
+
const one = async (job) => {
|
|
105
|
+
const spec = { suite, task: job.task, arm: job.arm, n: job.n, runDir, fixture: fixtures.get(job.task.id), piBin: options.piBin, authFile };
|
|
106
|
+
let record = await runTrial(spec);
|
|
107
|
+
if (!record.valid && record.leak && !stopped) {
|
|
108
|
+
progress({ rerun: `${job.task.id}/${job.arm}/${job.n}`, reason: record.invalid });
|
|
109
|
+
appendFileSync(join(runDir, "results.jsonl"), `${JSON.stringify(record)}\n`);
|
|
110
|
+
record = await runTrial(spec);
|
|
111
|
+
}
|
|
112
|
+
if (record.quota)
|
|
113
|
+
stopped = `quota refusal in ${job.task.id}/${job.arm}/${job.n}`;
|
|
114
|
+
// pi that wrote no session did not start (a bad flag, a missing extension file): every later trial would fail too.
|
|
115
|
+
else if (record.invalid === "no_session")
|
|
116
|
+
stopped = `pi wrote no session in ${job.task.id}/${job.arm}/${job.n}; see its stderr.txt`;
|
|
117
|
+
appendFileSync(join(runDir, "results.jsonl"), `${JSON.stringify(record)}\n`);
|
|
118
|
+
records.push(record);
|
|
119
|
+
finished++;
|
|
120
|
+
progress({ progress: { done: finished, total }, trial: `${job.task.id}/${job.arm}/${job.n}`, outcome: record.outcome, valid: record.valid, cost: record.efficiency.cost, minutes: Math.round(record.efficiency.wallMs / 6000) / 10 });
|
|
121
|
+
};
|
|
122
|
+
const workers = Array.from({ length: Math.min(parallel, queue.length) }, async () => {
|
|
123
|
+
while (queue.length && !stopped)
|
|
124
|
+
await one(queue.shift());
|
|
125
|
+
});
|
|
126
|
+
await Promise.all(workers);
|
|
127
|
+
if (options.rerun === undefined)
|
|
128
|
+
record.endedAt = new Date().toISOString();
|
|
129
|
+
if (stopped)
|
|
130
|
+
record.stopped = stopped;
|
|
131
|
+
writeFileSync(join(runDir, "run.json"), `${JSON.stringify(record, null, 2)}\n`);
|
|
132
|
+
writeSummary(runDir, record);
|
|
133
|
+
if (stopped)
|
|
134
|
+
progress({ monitorOutcome: { status: "blocked", message: stopped } });
|
|
135
|
+
return { runDir, records, stopped };
|
|
136
|
+
}
|
|
137
|
+
/** Regrade every stored trial of a run (after a grader fix); rewrites results.jsonl and summary.json. */
|
|
138
|
+
export function regradeRun(runDir) {
|
|
139
|
+
const meta = readRun(runDir);
|
|
140
|
+
const suite = loadSuite(meta.suite);
|
|
141
|
+
const records = [];
|
|
142
|
+
for (const task of selectTasks(suite, meta.tasks)) {
|
|
143
|
+
for (const arm of Object.keys(meta.arms)) {
|
|
144
|
+
for (let n = 1; n <= meta.k; n++) {
|
|
145
|
+
const trialDir = trialDirOf(runDir, task.id, arm, n);
|
|
146
|
+
if (existsSync(join(trialDir, "outcome.json")))
|
|
147
|
+
records.push(gradeTrial({ suite, task, arm, n, trialDir }));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
writeFileSync(join(runDir, "results.jsonl"), records.map((r) => `${JSON.stringify(r)}\n`).join(""));
|
|
152
|
+
writeSummary(runDir, meta);
|
|
153
|
+
return records;
|
|
154
|
+
}
|
package/dist/exp/show.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const NAMES = {
|
|
2
|
+
outcome: "outcome pass@1",
|
|
3
|
+
outcome_pass3: "outcome pass^3",
|
|
4
|
+
process: "process (anchor+check)",
|
|
5
|
+
anchor: "anchor before first edit",
|
|
6
|
+
check: "check after last edit",
|
|
7
|
+
todo_evidence: "todo evidence",
|
|
8
|
+
close_guard_quiet: "close guard quiet",
|
|
9
|
+
edited_when_should_not: "edited when should not",
|
|
10
|
+
done_claim_fail: "done claim, check failed",
|
|
11
|
+
};
|
|
12
|
+
const pct = (v) => (v === undefined || Number.isNaN(v) ? "—" : `${Math.round(v * 100)}%`);
|
|
13
|
+
const pp = (v) => `${v >= 0 ? "+" : ""}${Math.round(v * 100)}`;
|
|
14
|
+
const pad = (s, n) => s + " ".repeat(Math.max(0, n - s.length));
|
|
15
|
+
export function show(meta, summary, records, agreement = []) {
|
|
16
|
+
const arms = summary.arms.map((a) => a.arm);
|
|
17
|
+
const guarded = (arm) => [...(meta.arms[arm]?.extensions ?? [])].some((e) => /close-guard/.test(e));
|
|
18
|
+
const out = [];
|
|
19
|
+
const valid = records.filter((r) => r.valid).length;
|
|
20
|
+
out.push(`run ${meta.id} · ${meta.model} (${meta.thinking}) · pi ${meta.pi ?? "?"} · k=${meta.k} · ${meta.tasks.length} tasks · ${summary.arms.reduce((s, a) => s + a.trials, 0)} valid trials${meta.stopped ? ` · STOPPED: ${meta.stopped}` : ""}`);
|
|
21
|
+
out.push(`started ${meta.startedAt}${meta.endedAt ? ` · ended ${meta.endedAt}` : " · running"} · ${records.length - valid} invalid record(s)`);
|
|
22
|
+
for (const r of meta.reruns ?? [])
|
|
23
|
+
out.push(`rerun ${r.at}: ${r.tasks.join(", ")} (${r.reason}); earlier trials superseded, kept in results.jsonl`);
|
|
24
|
+
out.push("");
|
|
25
|
+
const w = 28;
|
|
26
|
+
out.push(pad("metric", w) + arms.map((a) => pad(a, 12)).join("") + (summary.pair ? `${summary.pair[1]} − ${summary.pair[0]} (95% CI)` : ""));
|
|
27
|
+
for (const metric of Object.keys(NAMES)) {
|
|
28
|
+
const cells = summary.arms.map((a) => pad(metric === "close_guard_quiet" && !guarded(a.arm) ? "—" : pct(a.metrics[metric]), 12));
|
|
29
|
+
const d = summary.deltas[metric];
|
|
30
|
+
const delta = d && metric !== "close_guard_quiet" ? `${pp(d.delta)} pp (${pp(d.lo)} to ${pp(d.hi)})${d.lo <= 0 && d.hi >= 0 ? " no clear difference" : ""} · ${d.tasks} tasks` : "";
|
|
31
|
+
out.push(pad(NAMES[metric], w) + cells.join("") + delta);
|
|
32
|
+
}
|
|
33
|
+
out.push(pad("cost per trial (USD equiv.)", w) + summary.arms.map((a) => pad(`$${a.costPerTrial.toFixed(2)}`, 12)).join(""));
|
|
34
|
+
out.push(pad("minutes per trial", w) + summary.arms.map((a) => pad(a.minutesPerTrial.toFixed(1), 12)).join(""));
|
|
35
|
+
out.push(pad("total cost", w) + summary.arms.map((a) => pad(`$${a.costTotal.toFixed(2)}`, 12)).join(""));
|
|
36
|
+
out.push(pad("invalid trials", w) + summary.arms.map((a) => pad(String(a.invalid), 12)).join(""));
|
|
37
|
+
out.push("");
|
|
38
|
+
out.push(pad("task", 24) + pad("kind", 12) + arms.map((a) => pad(`${a} pass`, 16)).join("") + "Δ pass@1");
|
|
39
|
+
for (const row of summary.tasks) {
|
|
40
|
+
const cells = arms.map((a) => {
|
|
41
|
+
const c = row.arms[a];
|
|
42
|
+
return pad(c ? `${c.pass}/${c.n}${c.process === undefined ? "" : ` p${pct(c.process)}`}` : "—", 16);
|
|
43
|
+
});
|
|
44
|
+
out.push(pad(row.task, 24) + pad(row.kind, 12) + cells.join("") + (row.delta === undefined ? "" : pp(row.delta)));
|
|
45
|
+
}
|
|
46
|
+
if (summary.doneClaimFail.length)
|
|
47
|
+
out.push("", `done claimed but check failed: ${summary.doneClaimFail.map((d) => `${d.task}/${d.arm}/${d.n}`).join(", ")}`);
|
|
48
|
+
for (const a of agreement)
|
|
49
|
+
out.push(`labels vs graders, ${a.rule}: ${a.agree}/${a.n} agree${a.unclear ? `, ${a.unclear} unclear` : ""}${a.disagree.length ? `; disagree: ${a.disagree.join(", ")}` : ""}`);
|
|
50
|
+
const invalid = records.filter((r) => !r.valid);
|
|
51
|
+
if (invalid.length)
|
|
52
|
+
out.push(`invalid: ${invalid.map((r) => `${r.task}/${r.arm}/${r.n} (${r.invalid})`).join(", ")}`);
|
|
53
|
+
return out.join("\n");
|
|
54
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trial statistics: unbiased pass@1, pass^k and pass@k from c passes in n trials, and a paired cluster bootstrap over
|
|
3
|
+
* tasks for the difference between two arms (tasks resampled, then trials resampled within each task and arm).
|
|
4
|
+
*/
|
|
5
|
+
function choose(n, k) {
|
|
6
|
+
if (k < 0 || k > n)
|
|
7
|
+
return 0;
|
|
8
|
+
let r = 1;
|
|
9
|
+
for (let i = 1; i <= k; i++)
|
|
10
|
+
r = (r * (n - k + i)) / i;
|
|
11
|
+
return r;
|
|
12
|
+
}
|
|
13
|
+
export const passAt1 = (c, n) => c / n;
|
|
14
|
+
/** All k of k fresh trials pass: C(c,k)/C(n,k). */
|
|
15
|
+
export function passHatK(c, n, k) {
|
|
16
|
+
if (k > n)
|
|
17
|
+
throw new Error(`pass^k needs k > n trials: k ${k} > n ${n}`);
|
|
18
|
+
return choose(c, k) / choose(n, k);
|
|
19
|
+
}
|
|
20
|
+
/** At least one of k fresh trials passes: 1 − C(n−c,k)/C(n,k). */
|
|
21
|
+
export function passAtK(c, n, k) {
|
|
22
|
+
if (k > n)
|
|
23
|
+
throw new Error(`pass@k needs k > n trials: k ${k} > n ${n}`);
|
|
24
|
+
return 1 - choose(n - c, k) / choose(n, k);
|
|
25
|
+
}
|
|
26
|
+
/** Mean of the defined values; undefined when none is defined (a metric that does not apply to the task). */
|
|
27
|
+
export function taskRate(values) {
|
|
28
|
+
const defined = values.filter((v) => typeof v === "number");
|
|
29
|
+
return defined.length ? defined.reduce((s, v) => s + v, 0) / defined.length : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** mulberry32: a small seeded PRNG so a summary is reproducible. */
|
|
32
|
+
function rng(seed) {
|
|
33
|
+
let a = seed >>> 0;
|
|
34
|
+
return () => {
|
|
35
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
36
|
+
let t = a;
|
|
37
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
38
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
39
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Paired cluster bootstrap: the statistic is computed per task and arm from that task's trial values, the delta is the
|
|
44
|
+
* mean over tasks of B − A. Tasks with no trial in either arm are left out. 95% percentile interval.
|
|
45
|
+
*/
|
|
46
|
+
export function pairedBootstrap(tasks, stat, options = {}) {
|
|
47
|
+
const paired = tasks.filter((t) => t.a.length && t.b.length);
|
|
48
|
+
if (!paired.length)
|
|
49
|
+
return { delta: Number.NaN, lo: Number.NaN, hi: Number.NaN, tasks: 0 };
|
|
50
|
+
const mean = (xs) => xs.reduce((s, x) => s + x, 0) / xs.length;
|
|
51
|
+
const delta = mean(paired.map((t) => stat(t.b) - stat(t.a)));
|
|
52
|
+
const random = rng(options.seed ?? 20261126);
|
|
53
|
+
const pick = (xs) => xs[Math.floor(random() * xs.length)];
|
|
54
|
+
const resample = (xs) => xs.map(() => pick(xs));
|
|
55
|
+
const draws = [];
|
|
56
|
+
for (let i = 0; i < (options.resamples ?? 10_000); i++) {
|
|
57
|
+
const sample = paired.map(() => pick(paired));
|
|
58
|
+
draws.push(mean(sample.map((t) => stat(resample(t.b)) - stat(resample(t.a)))));
|
|
59
|
+
}
|
|
60
|
+
draws.sort((x, y) => x - y);
|
|
61
|
+
const at = (q) => draws[Math.min(draws.length - 1, Math.max(0, Math.floor(q * draws.length)))];
|
|
62
|
+
return { delta, lo: at(0.025), hi: at(0.975), tasks: paired.length };
|
|
63
|
+
}
|