dsh-eval 0.4.0 → 0.5.1
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/README.md +214 -13
- package/README.zh.md +99 -10
- package/lib/agreement.js +46 -0
- package/lib/argv.js +66 -0
- package/lib/atomic-write.js +38 -0
- package/lib/benchmark.js +116 -19
- package/lib/calibration.js +90 -0
- package/lib/command.js +202 -10
- package/lib/compare.js +310 -31
- package/lib/dashboard.js +260 -0
- package/lib/digest.js +118 -0
- package/lib/export.js +50 -0
- package/lib/gate.js +293 -0
- package/lib/import.js +17 -6
- package/lib/index.js +174 -12
- package/lib/judge.js +30 -7
- package/lib/leaderboard.js +222 -0
- package/lib/precision.js +50 -0
- package/lib/rejudge.js +107 -0
- package/lib/reliability.js +107 -0
- package/lib/report.js +285 -11
- package/lib/runner.js +189 -33
- package/lib/safe-regex.js +74 -0
- package/lib/segments.js +15 -0
- package/lib/stats.js +63 -0
- package/lib/trace.js +19 -2
- package/lib/types/agreement.d.ts +33 -0
- package/lib/types/argv.d.ts +19 -0
- package/lib/types/atomic-write.d.ts +15 -0
- package/lib/types/benchmark.d.ts +9 -2
- package/lib/types/calibration.d.ts +45 -0
- package/lib/types/command.d.ts +58 -0
- package/lib/types/compare.d.ts +82 -2
- package/lib/types/dashboard.d.ts +24 -0
- package/lib/types/digest.d.ts +38 -0
- package/lib/types/export.d.ts +17 -0
- package/lib/types/gate.d.ts +87 -0
- package/lib/types/index.d.ts +8 -4
- package/lib/types/judge.d.ts +4 -1
- package/lib/types/leaderboard.d.ts +70 -0
- package/lib/types/precision.d.ts +44 -0
- package/lib/types/rejudge.d.ts +22 -0
- package/lib/types/reliability.d.ts +85 -0
- package/lib/types/report.d.ts +18 -5
- package/lib/types/runner.d.ts +8 -1
- package/lib/types/safe-regex.d.ts +24 -0
- package/lib/types/segments.d.ts +12 -0
- package/lib/types/stats.d.ts +56 -0
- package/lib/types/trace.d.ts +7 -0
- package/lib/types/types.d.ts +55 -6
- package/lib/types/validate.d.ts +57 -0
- package/lib/validate.js +155 -0
- package/package.json +2 -2
- package/src/agreement.ts +60 -0
- package/src/argv.ts +63 -0
- package/src/atomic-write.ts +38 -0
- package/src/benchmark.ts +139 -13
- package/src/calibration.ts +113 -0
- package/src/command.ts +297 -10
- package/src/compare.ts +392 -37
- package/src/dashboard.ts +287 -0
- package/src/digest.ts +144 -0
- package/src/export.ts +57 -0
- package/src/gate.ts +383 -0
- package/src/import.ts +18 -6
- package/src/index.ts +192 -12
- package/src/judge.ts +30 -6
- package/src/leaderboard.ts +272 -0
- package/src/precision.ts +85 -0
- package/src/rejudge.ts +112 -0
- package/src/reliability.ts +166 -0
- package/src/report.ts +303 -11
- package/src/runner.ts +182 -35
- package/src/safe-regex.ts +79 -0
- package/src/segments.ts +16 -0
- package/src/stats.ts +104 -0
- package/src/trace.ts +19 -2
- package/src/types.ts +56 -6
- package/src/validate.ts +177 -0
package/src/agreement.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Judge / script agreement for dsh-eval.
|
|
3
|
+
*
|
|
4
|
+
* A scripted check and an LLM judge are two independent views of the same
|
|
5
|
+
* trial. Observed agreement alone is misleading when one view almost always
|
|
6
|
+
* passes, so we also report Cohen's kappa, which subtracts the agreement
|
|
7
|
+
* expected from the two marginals. The judge signal used here is
|
|
8
|
+
* "no hallucination flagged", paired with scripted `taskSuccess`.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-eval/agreement
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { EvalRun } from './types.ts'
|
|
14
|
+
|
|
15
|
+
/** Agreement statistics over trials carrying both signals. */
|
|
16
|
+
export interface AgreementSummary {
|
|
17
|
+
/** Number of trials with a boolean scripted result and a boolean judge verdict. */
|
|
18
|
+
pairs: number
|
|
19
|
+
/** Number of trials where the two signals matched. */
|
|
20
|
+
agreements: number
|
|
21
|
+
/** Observed agreement, agreements / pairs. */
|
|
22
|
+
rate: number
|
|
23
|
+
/** Cohen's kappa: agreement beyond chance; can be negative. */
|
|
24
|
+
kappa: number
|
|
25
|
+
/** Trials where the judge flagged no hallucination. */
|
|
26
|
+
judgePassed: number
|
|
27
|
+
/** Trials where the scripted task check passed. */
|
|
28
|
+
scriptPassed: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Compute judge/script agreement for a run.
|
|
33
|
+
* @param run - a persisted run record.
|
|
34
|
+
* @returns the summary, or null when no trial carries both signals.
|
|
35
|
+
*/
|
|
36
|
+
export function computeAgreement(run: EvalRun): AgreementSummary | null {
|
|
37
|
+
let pairs = 0
|
|
38
|
+
let agreements = 0
|
|
39
|
+
let judgePassed = 0
|
|
40
|
+
let scriptPassed = 0
|
|
41
|
+
for (const result of run.cases) {
|
|
42
|
+
const script = result.grade?.taskSuccess
|
|
43
|
+
const judge = result.judge?.hallucination
|
|
44
|
+
if (script === undefined || script === null || judge === undefined || judge === null) continue
|
|
45
|
+
pairs += 1
|
|
46
|
+
const judgePass = !judge
|
|
47
|
+
if (judgePass) judgePassed += 1
|
|
48
|
+
if (script) scriptPassed += 1
|
|
49
|
+
if (judgePass === script) agreements += 1
|
|
50
|
+
}
|
|
51
|
+
if (pairs === 0) return null
|
|
52
|
+
const rate = agreements / pairs
|
|
53
|
+
const judgeRate = judgePassed / pairs
|
|
54
|
+
const scriptRate = scriptPassed / pairs
|
|
55
|
+
const chance = judgeRate * scriptRate + (1 - judgeRate) * (1 - scriptRate)
|
|
56
|
+
// A degenerate marginal (everyone passes) leaves kappa undefined at 0/0;
|
|
57
|
+
// in that case perfect observed agreement is the only sensible answer.
|
|
58
|
+
const kappa = 1 - chance < Number.EPSILON ? rate : (rate - chance) / (1 - chance)
|
|
59
|
+
return { pairs, agreements, rate, kappa, judgePassed, scriptPassed }
|
|
60
|
+
}
|
package/src/argv.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small, dependency-free command-line splitter shared by the CLI `--dsh`
|
|
3
|
+
* override and benchmark check commands.
|
|
4
|
+
*
|
|
5
|
+
* Whitespace-only splitting silently breaks paths with spaces and quoted
|
|
6
|
+
* arguments: `node "my script.mjs" --flag "a b"` used to become five argv
|
|
7
|
+
* entries. This parser supports single/double quotes, backslash escapes and
|
|
8
|
+
* escaped whitespace, without pretending to be a full POSIX shell (redirection
|
|
9
|
+
* and pipes stay the job of explicit opt-in `checkShell`).
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-eval/argv
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Split a command string into argv tokens.
|
|
16
|
+
* @param value - the command line as written by the user.
|
|
17
|
+
* @returns argv tokens with quotes and escapes removed.
|
|
18
|
+
* @throws on an unterminated quote, which is a typo rather than an empty command.
|
|
19
|
+
*/
|
|
20
|
+
export function splitArgv(value: string): string[] {
|
|
21
|
+
const tokens: string[] = []
|
|
22
|
+
let token = ''
|
|
23
|
+
let started = false
|
|
24
|
+
let quote: '"' | "'" | undefined
|
|
25
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
26
|
+
const char = value[index]!
|
|
27
|
+
if (quote !== undefined) {
|
|
28
|
+
if (char === quote) {
|
|
29
|
+
quote = undefined
|
|
30
|
+
} else if (char === '\\' && quote === '"' && index + 1 < value.length) {
|
|
31
|
+
token += value[index + 1]!
|
|
32
|
+
index += 1
|
|
33
|
+
} else {
|
|
34
|
+
token += char
|
|
35
|
+
}
|
|
36
|
+
continue
|
|
37
|
+
}
|
|
38
|
+
if (char === '"' || char === "'") {
|
|
39
|
+
quote = char
|
|
40
|
+
started = true
|
|
41
|
+
continue
|
|
42
|
+
}
|
|
43
|
+
if (char === '\\' && index + 1 < value.length && /\s/u.test(value[index + 1]!)) {
|
|
44
|
+
token += value[index + 1]!
|
|
45
|
+
started = true
|
|
46
|
+
index += 1
|
|
47
|
+
continue
|
|
48
|
+
}
|
|
49
|
+
if (/\s/u.test(char)) {
|
|
50
|
+
if (started) {
|
|
51
|
+
tokens.push(token)
|
|
52
|
+
token = ''
|
|
53
|
+
started = false
|
|
54
|
+
}
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
token += char
|
|
58
|
+
started = true
|
|
59
|
+
}
|
|
60
|
+
if (quote !== undefined) throw new Error('unterminated quote in command')
|
|
61
|
+
if (started) tokens.push(token)
|
|
62
|
+
return tokens
|
|
63
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash-safe text output shared by every file-writing CLI command.
|
|
3
|
+
*
|
|
4
|
+
* Writing directly to the destination can leave a truncated file that looks
|
|
5
|
+
* loadable after a crash or a full disk. Staging beside the target and
|
|
6
|
+
* renaming keeps readers on either the old or the new complete document.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-eval/atomic-write
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomUUID } from 'node:crypto'
|
|
12
|
+
import { chmod, mkdir, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
|
13
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Write UTF-8 text atomically, creating parent directories as needed.
|
|
17
|
+
* @param path - destination path.
|
|
18
|
+
* @param text - complete file contents.
|
|
19
|
+
*/
|
|
20
|
+
export async function writeTextAtomic(path: string, text: string): Promise<void> {
|
|
21
|
+
const absolute = resolve(path)
|
|
22
|
+
// Replace the real target, not the symlink: an `--out` alias must stay valid.
|
|
23
|
+
const destination = await realpath(absolute).catch(() => absolute)
|
|
24
|
+
const directory = dirname(destination)
|
|
25
|
+
await mkdir(directory, { recursive: true })
|
|
26
|
+
const temp = join(directory, `.${basename(destination)}.${process.pid}.${randomUUID()}.tmp`)
|
|
27
|
+
const existing = await stat(destination).catch(() => null)
|
|
28
|
+
try {
|
|
29
|
+
await writeFile(temp, text, 'utf8')
|
|
30
|
+
// Preserve an existing file's permission bits across the rename.
|
|
31
|
+
if (existing !== null) await chmod(temp, existing.mode)
|
|
32
|
+
await rename(temp, destination)
|
|
33
|
+
} catch (error) {
|
|
34
|
+
/* v8 ignore next -- cleanup of a failed staged write is best-effort. */
|
|
35
|
+
await unlink(temp).catch(() => {})
|
|
36
|
+
throw error
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/benchmark.ts
CHANGED
|
@@ -6,10 +6,12 @@
|
|
|
6
6
|
* @module dsh-eval/benchmark
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { readFile } from 'node:fs/promises'
|
|
10
|
-
import { dirname, isAbsolute, resolve } from 'node:path'
|
|
9
|
+
import { readFile, realpath } from 'node:fs/promises'
|
|
10
|
+
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
|
|
11
11
|
import { load } from 'js-yaml'
|
|
12
12
|
import { z } from 'zod'
|
|
13
|
+
import { hashBenchmarkInputs } from './digest.ts'
|
|
14
|
+
import { caseSegment } from './segments.ts'
|
|
13
15
|
import type { Benchmark, BenchmarkCase } from './types.ts'
|
|
14
16
|
|
|
15
17
|
const judgeSchema = z.object({
|
|
@@ -30,17 +32,54 @@ const pricingSchema = z.object({
|
|
|
30
32
|
outputUsdPerMTokens: z.number().nonnegative(),
|
|
31
33
|
}).strict()
|
|
32
34
|
|
|
35
|
+
/** A non-empty string that the runtime can compile as a Unicode regular expression. */
|
|
36
|
+
function regexSchema(message: string) {
|
|
37
|
+
return z.string().min(1).refine((value) => {
|
|
38
|
+
try {
|
|
39
|
+
new RegExp(value, 'u')
|
|
40
|
+
return true
|
|
41
|
+
} catch {
|
|
42
|
+
return false
|
|
43
|
+
}
|
|
44
|
+
}, { message })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const toolRegexSchema = regexSchema('toolRegex is not a valid regular expression')
|
|
48
|
+
const answerRegexSchema = regexSchema('answerRegex is not a valid regular expression')
|
|
49
|
+
|
|
33
50
|
const benchmarkCaseSchema = z.object({
|
|
34
51
|
id: z.string().min(1),
|
|
35
52
|
prompt: z.string().min(1).optional(),
|
|
36
53
|
promptFile: z.string().min(1).optional(),
|
|
37
54
|
workspace: z.string().min(1).optional(),
|
|
55
|
+
timeoutMs: z.number().int().positive().optional(),
|
|
38
56
|
expected: z.object({
|
|
39
57
|
tool: z.string().min(1).optional(),
|
|
58
|
+
tools: z.array(z.string().min(1)).min(1).readonly().optional(),
|
|
59
|
+
toolAnyOf: z.array(z.string().min(1)).min(1).readonly().optional(),
|
|
60
|
+
toolRegex: toolRegexSchema.optional(),
|
|
61
|
+
toolNot: z.array(z.string().min(1)).min(1).readonly().optional(),
|
|
40
62
|
check: z.string().min(1).optional(),
|
|
63
|
+
checkArgv: z.array(z.string().min(1)).min(1).readonly().optional(),
|
|
64
|
+
checkShell: z.string().min(1).optional(),
|
|
65
|
+
answer: z.string().min(1).optional(),
|
|
66
|
+
answerRegex: answerRegexSchema.optional(),
|
|
41
67
|
}).strict().refine(
|
|
42
|
-
expectation => expectation.tool !== undefined || expectation.
|
|
43
|
-
|
|
68
|
+
expectation => expectation.tool !== undefined || expectation.tools !== undefined
|
|
69
|
+
|| expectation.toolAnyOf !== undefined || expectation.toolRegex !== undefined
|
|
70
|
+
|| expectation.toolNot !== undefined || expectation.check !== undefined
|
|
71
|
+
|| expectation.checkArgv !== undefined || expectation.checkShell !== undefined
|
|
72
|
+
|| expectation.answer !== undefined || expectation.answerRegex !== undefined,
|
|
73
|
+
{
|
|
74
|
+
message: 'expected needs at least one of tool, tools, toolAnyOf, toolRegex, toolNot, check, checkArgv, checkShell, answer or answerRegex',
|
|
75
|
+
},
|
|
76
|
+
).refine(
|
|
77
|
+
(expectation) => {
|
|
78
|
+
const commands = [expectation.check, expectation.checkArgv, expectation.checkShell]
|
|
79
|
+
.filter(value => value !== undefined)
|
|
80
|
+
return commands.length <= 1
|
|
81
|
+
},
|
|
82
|
+
{ message: 'expected accepts at most one of check, checkArgv or checkShell' },
|
|
44
83
|
).optional(),
|
|
45
84
|
}).strict().refine(
|
|
46
85
|
caseValue => (caseValue.prompt === undefined) !== (caseValue.promptFile === undefined),
|
|
@@ -55,12 +94,31 @@ const benchmarkSchema = z.object({
|
|
|
55
94
|
trials: z.number().int().positive().default(1),
|
|
56
95
|
concurrency: z.number().int().positive().default(1),
|
|
57
96
|
timeoutMs: z.number().int().positive().default(600_000),
|
|
97
|
+
allowExternalPaths: z.boolean().default(false),
|
|
58
98
|
seed: z.number().int().default(0),
|
|
59
99
|
cases: z.array(benchmarkCaseSchema).min(1),
|
|
60
100
|
pricing: z.record(z.string().min(1), pricingSchema).optional(),
|
|
61
101
|
judge: judgeSchema.optional(),
|
|
62
102
|
replay: replaySchema.optional(),
|
|
63
|
-
}).strict()
|
|
103
|
+
}).strict().superRefine((parsed, ctx) => {
|
|
104
|
+
// Every trial's private directory is `<caseSegment(id)>-<trial>`. Distinct
|
|
105
|
+
// ids that normalize to one segment (or a plain duplicate) would otherwise
|
|
106
|
+
// share a workspace and DSH_HOME, leaking session logs and metrics across
|
|
107
|
+
// cases. Compare case-insensitively so Windows' case-folding FS is safe too.
|
|
108
|
+
const seen = new Set<string>()
|
|
109
|
+
parsed.cases.forEach((caseValue, index) => {
|
|
110
|
+
const key = caseSegment(caseValue.id).toLowerCase()
|
|
111
|
+
if (seen.has(key)) {
|
|
112
|
+
ctx.addIssue({
|
|
113
|
+
code: 'custom',
|
|
114
|
+
path: ['cases', index, 'id'],
|
|
115
|
+
message: `case id "${caseValue.id}" collides with an earlier case after directory normalization`,
|
|
116
|
+
})
|
|
117
|
+
} else {
|
|
118
|
+
seen.add(key)
|
|
119
|
+
}
|
|
120
|
+
})
|
|
121
|
+
})
|
|
64
122
|
|
|
65
123
|
/**
|
|
66
124
|
* Resolve one parsed case's prompt and workspace against the benchmark
|
|
@@ -70,23 +128,66 @@ const benchmarkSchema = z.object({
|
|
|
70
128
|
* @param baseDir - absolute directory the benchmark file lives in.
|
|
71
129
|
* @returns the resolved runtime case.
|
|
72
130
|
*/
|
|
131
|
+
/**
|
|
132
|
+
* Resolve a referenced path without letting a third-party benchmark read
|
|
133
|
+
* outside its directory. The override is caller-supplied (CLI/API), never
|
|
134
|
+
* taken from the document itself.
|
|
135
|
+
*/
|
|
136
|
+
async function resolveInputPath(
|
|
137
|
+
value: string,
|
|
138
|
+
baseDir: string,
|
|
139
|
+
allowExternal: boolean,
|
|
140
|
+
field: string,
|
|
141
|
+
): Promise<string> {
|
|
142
|
+
const resolved = resolve(baseDir, value)
|
|
143
|
+
if (allowExternal) return resolved
|
|
144
|
+
const rel = relative(baseDir, resolved)
|
|
145
|
+
if (isAbsolute(value) || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
146
|
+
throw new Error(`${field} "${value}" escapes the benchmark directory`)
|
|
147
|
+
}
|
|
148
|
+
// Compare real paths so a symlink inside the directory cannot point at a
|
|
149
|
+
// file outside it. A missing path is left for readFile() to report.
|
|
150
|
+
let real: string
|
|
151
|
+
try {
|
|
152
|
+
real = await realpath(resolved)
|
|
153
|
+
} catch {
|
|
154
|
+
return resolved
|
|
155
|
+
}
|
|
156
|
+
const realRoot = await realpath(baseDir)
|
|
157
|
+
const realRel = relative(realRoot, real)
|
|
158
|
+
if (realRel === '..' || realRel.startsWith(`..${sep}`) || isAbsolute(realRel)) {
|
|
159
|
+
throw new Error(`${field} "${value}" escapes the benchmark directory`)
|
|
160
|
+
}
|
|
161
|
+
return resolved
|
|
162
|
+
}
|
|
163
|
+
|
|
73
164
|
async function resolveCase(
|
|
74
165
|
parsed: z.infer<typeof benchmarkCaseSchema>,
|
|
75
166
|
baseDir: string,
|
|
167
|
+
allowExternalPaths: boolean,
|
|
76
168
|
): Promise<BenchmarkCase> {
|
|
77
169
|
const prompt = parsed.prompt
|
|
78
|
-
?? await readFile(
|
|
170
|
+
?? await readFile(await resolveInputPath(parsed.promptFile as string, baseDir, allowExternalPaths, 'promptFile'), 'utf8')
|
|
79
171
|
return {
|
|
80
172
|
id: parsed.id,
|
|
81
173
|
prompt,
|
|
174
|
+
...(parsed.timeoutMs !== undefined ? { timeoutMs: parsed.timeoutMs } : {}),
|
|
82
175
|
...(parsed.workspace !== undefined
|
|
83
|
-
? { workspace:
|
|
176
|
+
? { workspace: await resolveInputPath(parsed.workspace, baseDir, allowExternalPaths, 'workspace') }
|
|
84
177
|
: {}),
|
|
85
178
|
...(parsed.expected !== undefined
|
|
86
179
|
? {
|
|
87
180
|
expected: {
|
|
88
181
|
...(parsed.expected.tool !== undefined ? { tool: parsed.expected.tool } : {}),
|
|
182
|
+
...(parsed.expected.tools !== undefined ? { tools: parsed.expected.tools } : {}),
|
|
183
|
+
...(parsed.expected.toolAnyOf !== undefined ? { toolAnyOf: parsed.expected.toolAnyOf } : {}),
|
|
184
|
+
...(parsed.expected.toolRegex !== undefined ? { toolRegex: parsed.expected.toolRegex } : {}),
|
|
185
|
+
...(parsed.expected.toolNot !== undefined ? { toolNot: parsed.expected.toolNot } : {}),
|
|
89
186
|
...(parsed.expected.check !== undefined ? { check: parsed.expected.check } : {}),
|
|
187
|
+
...(parsed.expected.checkArgv !== undefined ? { checkArgv: parsed.expected.checkArgv } : {}),
|
|
188
|
+
...(parsed.expected.checkShell !== undefined ? { checkShell: parsed.expected.checkShell } : {}),
|
|
189
|
+
...(parsed.expected.answer !== undefined ? { answer: parsed.expected.answer } : {}),
|
|
190
|
+
...(parsed.expected.answerRegex !== undefined ? { answerRegex: parsed.expected.answerRegex } : {}),
|
|
90
191
|
},
|
|
91
192
|
}
|
|
92
193
|
: {}),
|
|
@@ -99,24 +200,40 @@ async function resolveCase(
|
|
|
99
200
|
* @param baseDir - absolute directory used to resolve prompt and workspace paths.
|
|
100
201
|
* @returns the validated benchmark.
|
|
101
202
|
*/
|
|
102
|
-
|
|
203
|
+
/** Trusted caller options; the benchmark document itself cannot set these. */
|
|
204
|
+
export interface BenchmarkLoadOptions {
|
|
205
|
+
/** Permit referenced paths outside the benchmark directory. */
|
|
206
|
+
allowExternalPaths?: boolean
|
|
207
|
+
/** Output artifacts to omit from the provenance digest. */
|
|
208
|
+
excludeFromDigest?: readonly string[]
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function parseBenchmark(
|
|
212
|
+
text: string,
|
|
213
|
+
baseDir: string,
|
|
214
|
+
options: BenchmarkLoadOptions = {},
|
|
215
|
+
): Promise<Benchmark> {
|
|
103
216
|
const value = load(text)
|
|
104
217
|
if (typeof value !== 'object' || value === null) {
|
|
105
218
|
throw new Error('benchmark document must be a YAML mapping')
|
|
106
219
|
}
|
|
107
220
|
const parsed = benchmarkSchema.parse(value)
|
|
221
|
+
// `allowExternalPaths` in YAML is accepted for backward compatibility but
|
|
222
|
+
// ignored: only the operator running the CLI/API may widen the boundary.
|
|
223
|
+
const allowExternalPaths = options.allowExternalPaths === true
|
|
108
224
|
const cases: BenchmarkCase[] = []
|
|
109
225
|
for (const caseValue of parsed.cases) {
|
|
110
|
-
cases.push(await resolveCase(caseValue, baseDir))
|
|
226
|
+
cases.push(await resolveCase(caseValue, baseDir, allowExternalPaths))
|
|
111
227
|
}
|
|
112
228
|
const pricing = parsed.pricing
|
|
113
229
|
const judge = parsed.judge
|
|
114
230
|
const replay = parsed.replay
|
|
115
|
-
|
|
231
|
+
const benchmark: Benchmark = {
|
|
116
232
|
name: parsed.name,
|
|
117
233
|
model: parsed.model,
|
|
118
234
|
profile: parsed.profile,
|
|
119
235
|
command: parsed.command,
|
|
236
|
+
allowExternalPaths,
|
|
120
237
|
trials: parsed.trials,
|
|
121
238
|
concurrency: parsed.concurrency,
|
|
122
239
|
timeoutMs: parsed.timeoutMs,
|
|
@@ -127,10 +244,16 @@ export async function parseBenchmark(text: string, baseDir: string): Promise<Ben
|
|
|
127
244
|
? { judge: { provider: judge.provider, model: judge.model ?? parsed.model, ...(judge.rubric !== undefined ? { rubric: judge.rubric } : {}), maxScore: judge.maxScore } }
|
|
128
245
|
: {}),
|
|
129
246
|
...(replay !== undefined
|
|
130
|
-
? { replay: { dir:
|
|
247
|
+
? { replay: { dir: await resolveInputPath(replay.dir, baseDir, allowExternalPaths, 'replay.dir') } }
|
|
131
248
|
: {}),
|
|
132
249
|
baseDir,
|
|
133
250
|
}
|
|
251
|
+
return {
|
|
252
|
+
...benchmark,
|
|
253
|
+
sourceSha256: await hashBenchmarkInputs(text, benchmark, {
|
|
254
|
+
...(options.excludeFromDigest === undefined ? {} : { excludePaths: options.excludeFromDigest }),
|
|
255
|
+
}),
|
|
256
|
+
}
|
|
134
257
|
}
|
|
135
258
|
|
|
136
259
|
/**
|
|
@@ -138,7 +261,10 @@ export async function parseBenchmark(text: string, baseDir: string): Promise<Ben
|
|
|
138
261
|
* @param path - path to the benchmark YAML file.
|
|
139
262
|
* @returns the validated benchmark.
|
|
140
263
|
*/
|
|
141
|
-
export async function loadBenchmark(
|
|
264
|
+
export async function loadBenchmark(
|
|
265
|
+
path: string,
|
|
266
|
+
options: BenchmarkLoadOptions = {},
|
|
267
|
+
): Promise<Benchmark> {
|
|
142
268
|
const absolute = resolve(path)
|
|
143
|
-
return parseBenchmark(await readFile(absolute, 'utf8'), dirname(absolute))
|
|
269
|
+
return parseBenchmark(await readFile(absolute, 'utf8'), dirname(absolute), options)
|
|
144
270
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Judge calibration diagnostics for dsh-eval.
|
|
3
|
+
*
|
|
4
|
+
* Agreement and kappa say whether the judge and the scripted check reach the
|
|
5
|
+
* same verdict, but a judge can be perfectly calibrated on an all-pass run and
|
|
6
|
+
* still useless for ranking. This module also measures how well the judge's
|
|
7
|
+
* numeric score separates scripted passes from failures, and surfaces the
|
|
8
|
+
* concrete cases where the two views disagree so a rubric can be improved.
|
|
9
|
+
* A normalized score >= 0.5 counts as a judge pass; the hallucination flag is
|
|
10
|
+
* only a fallback for trials whose score is missing, so the disagreement list
|
|
11
|
+
* can explain the score-based separation and ranking figures.
|
|
12
|
+
*
|
|
13
|
+
* @module dsh-eval/calibration
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { EvalRun } from './types.ts'
|
|
17
|
+
|
|
18
|
+
/** A case x trial where the judge and the scripted check disagree. */
|
|
19
|
+
export interface CalibrationDisagreement {
|
|
20
|
+
caseId: string
|
|
21
|
+
trial: number
|
|
22
|
+
scriptPassed: boolean
|
|
23
|
+
score: number | null
|
|
24
|
+
hallucination: boolean | null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Calibration statistics over trials carrying both signals. */
|
|
28
|
+
export interface CalibrationSummary {
|
|
29
|
+
pairs: number
|
|
30
|
+
/** Mean normalized judge score on scripted passes, or null when none. */
|
|
31
|
+
passedMean: number | null
|
|
32
|
+
/** Mean normalized judge score on scripted failures, or null when none. */
|
|
33
|
+
failedMean: number | null
|
|
34
|
+
/** passedMean - failedMean; positive means the judge ranks passes higher. */
|
|
35
|
+
separation: number | null
|
|
36
|
+
/** P(random pass scores above random fail), ties count as half. Null when one side is empty. */
|
|
37
|
+
rankingAccuracy: number | null
|
|
38
|
+
/** Mean squared error of normalized score against the scripted verdict; lower is better. */
|
|
39
|
+
brier: number | null
|
|
40
|
+
/** Up to five disagreements, ordered by case id and trial. */
|
|
41
|
+
disagreements: readonly CalibrationDisagreement[]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Normalize a judge score to 0..1 using its run's maxScore when available. */
|
|
45
|
+
function normalizedScore(score: number | null | undefined, maxScore: number | undefined): number | null {
|
|
46
|
+
if (score === null || score === undefined || !Number.isFinite(score)) return null
|
|
47
|
+
if (maxScore === undefined || maxScore <= 0) return null
|
|
48
|
+
return Math.max(0, Math.min(1, score / maxScore))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Compute judge calibration for a run.
|
|
53
|
+
* @param run - a persisted run record.
|
|
54
|
+
* @returns the summary, or null when no trial has both a scripted result and a usable judge verdict.
|
|
55
|
+
*/
|
|
56
|
+
export function computeCalibration(run: EvalRun): CalibrationSummary | null {
|
|
57
|
+
const maxScore = run.judge?.maxScore
|
|
58
|
+
const passed: number[] = []
|
|
59
|
+
const failed: number[] = []
|
|
60
|
+
const disagreements: CalibrationDisagreement[] = []
|
|
61
|
+
let withBoth = 0
|
|
62
|
+
let brierSum = 0
|
|
63
|
+
let brierCount = 0
|
|
64
|
+
for (const result of run.cases) {
|
|
65
|
+
const script = result.grade?.taskSuccess
|
|
66
|
+
const judge = result.judge
|
|
67
|
+
if (script === undefined || script === null || judge === undefined) continue
|
|
68
|
+
const score = normalizedScore(judge.finalAnswerScore, maxScore)
|
|
69
|
+
const hallucination = judge.hallucination ?? null
|
|
70
|
+
// A verdict with neither signal is ungraded, not evidence of agreement.
|
|
71
|
+
if (score === null && hallucination === null) continue
|
|
72
|
+
withBoth += 1
|
|
73
|
+
if (score !== null) {
|
|
74
|
+
if (script) passed.push(score)
|
|
75
|
+
else failed.push(score)
|
|
76
|
+
const error = score - (script ? 1 : 0)
|
|
77
|
+
brierSum += error * error
|
|
78
|
+
brierCount += 1
|
|
79
|
+
}
|
|
80
|
+
// The score drives calibration; the hallucination flag is a fallback.
|
|
81
|
+
const judgePass = score !== null ? score >= 0.5 : !hallucination
|
|
82
|
+
if (judgePass !== script) {
|
|
83
|
+
disagreements.push({
|
|
84
|
+
caseId: result.caseId, trial: result.trial, scriptPassed: script,
|
|
85
|
+
score: judge.finalAnswerScore ?? null, hallucination,
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
disagreements.sort((a, b) => a.caseId.localeCompare(b.caseId) || a.trial - b.trial)
|
|
90
|
+
disagreements.length = Math.min(disagreements.length, 5)
|
|
91
|
+
if (withBoth === 0) return null
|
|
92
|
+
const mean = (values: readonly number[]): number | null =>
|
|
93
|
+
values.length === 0 ? null : values.reduce((sum, value) => sum + value, 0) / values.length
|
|
94
|
+
const passedMean = mean(passed)
|
|
95
|
+
const failedMean = mean(failed)
|
|
96
|
+
let rankingAccuracy: number | null = null
|
|
97
|
+
if (passed.length > 0 && failed.length > 0) {
|
|
98
|
+
let wins = 0
|
|
99
|
+
for (const high of passed) {
|
|
100
|
+
for (const low of failed) wins += high > low ? 1 : high === low ? 0.5 : 0
|
|
101
|
+
}
|
|
102
|
+
rankingAccuracy = wins / (passed.length * failed.length)
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
pairs: withBoth,
|
|
106
|
+
passedMean,
|
|
107
|
+
failedMean,
|
|
108
|
+
separation: passedMean === null || failedMean === null ? null : passedMean - failedMean,
|
|
109
|
+
rankingAccuracy,
|
|
110
|
+
brier: brierCount === 0 ? null : brierSum / brierCount,
|
|
111
|
+
disagreements,
|
|
112
|
+
}
|
|
113
|
+
}
|