A deterministic quality eval as a run type next to BetterBench: tool calling (12 requests), coding (8 Python functions checked by unit tests in a locked-down sandbox container) and long-context retrieval (needle at 3 depths in 3 lengths up to the context). Versioned eval set in src/evals/v1, score stored per run, shown on the run page, in compare views, the benchmark list and sweep tables (optional eval per variant); API kind "eval", quality in run/sweep/compare answers; skill updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
716bd8f2f0
commit
6b67c653b5
33 files changed
+3822
-79
No files matched your search
+105
-15
@@ -11,7 +11,22 @@ import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchma
|
||||
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
|
||||
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema";
|
||||
import {
|
||||
apiKeys,
|
||||
type BenchmarkKind,
|
||||
benchmarkLogs,
|
||||
benchmarkRuns,
|
||||
type BenchmarkSummary,
|
||||
deployments,
|
||||
type LogStream,
|
||||
QUALITY_SECTIONS,
|
||||
type QualityResult,
|
||||
type QualitySection,
|
||||
type RunMeta,
|
||||
runtimes,
|
||||
type SystemSummary,
|
||||
} from "@/lib/db/schema";
|
||||
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
|
||||
import { ENGINE_PORT } from "@/lib/deploy-command";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { abSummary } from "./ab-summary";
|
||||
@@ -21,13 +36,16 @@ import { log } from "./log";
|
||||
import { normalizePciAddress } from "./hardware";
|
||||
import { errorCauses } from "./log-causes";
|
||||
import { type GpuTargets, ResourceSampler } from "./resources";
|
||||
import { runQualityEval } from "./quality";
|
||||
import { docker, workerImage } from "./runtimes";
|
||||
|
||||
type Current = {
|
||||
runId: string;
|
||||
kind: "run" | "ab";
|
||||
kind: BenchmarkKind;
|
||||
deploymentIds: string[];
|
||||
child: ChildProcess;
|
||||
/** BetterBench (runs, A/B); null for a quality eval, which runs in-process and stops via `abort`. */
|
||||
child: ChildProcess | null;
|
||||
abort: AbortController | null;
|
||||
sampler: ResourceSampler | null;
|
||||
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
|
||||
meta: RunMeta | null;
|
||||
@@ -204,6 +222,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
const setup = await runSetup([a.id, b?.id ?? null]);
|
||||
const [meta, metaB] = setup.metas;
|
||||
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
|
||||
if (run.kind === "eval") return startEval(run, a, keys, meta, setup.system);
|
||||
const args =
|
||||
run.kind === "ab" && b
|
||||
? abArgs({
|
||||
@@ -278,6 +297,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
kind: run.kind,
|
||||
deploymentIds: [a.id, ...(b ? [b.id] : [])],
|
||||
child,
|
||||
abort: null,
|
||||
sampler,
|
||||
meta,
|
||||
metaB,
|
||||
@@ -296,13 +316,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
|
||||
}
|
||||
|
||||
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
|
||||
const id = cur.runId;
|
||||
for (const stream of ["stdout", "stderr"] as const) {
|
||||
const rest = partial.get(`${id}:${stream}`);
|
||||
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
|
||||
partial.delete(`${id}:${stream}`);
|
||||
}
|
||||
/** Stop the resource sampler; record the PCIe links seen under load in the run's meta. */
|
||||
async function stopSampling(cur: Current) {
|
||||
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
|
||||
if (current === cur) current = null;
|
||||
if (resources?.links) {
|
||||
@@ -310,9 +325,82 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
await db()
|
||||
.update(benchmarkRuns)
|
||||
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
|
||||
.where(eq(benchmarkRuns.id, id))
|
||||
.catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`));
|
||||
.where(eq(benchmarkRuns.id, cur.runId))
|
||||
.catch((err) => log.warn(`benchmark ${cur.runId}: link update failed: ${message(err)}`));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
/** Kaname's quality eval: in-process against the deployment, coding answers in the sandbox. */
|
||||
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys: string[], meta: RunMeta | null, system: SystemSummary) {
|
||||
const s = run.snapshot;
|
||||
const sections = run.settings.evalSections?.length ? run.settings.evalSections : [...QUALITY_SECTIONS];
|
||||
const dep = await db().query.deployments.findFirst({ columns: { engineInfo: true, options: true }, where: eq(deployments.id, a.id) });
|
||||
const contextTokens = dep?.engineInfo?.contextSize ?? dep?.options.contextSize ?? s.options.contextSize ?? null;
|
||||
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${s.deploymentName} (${s.repoId} on ${s.runtimeName}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
|
||||
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, system }).where(eq(benchmarkRuns.id, run.id));
|
||||
|
||||
const c = docker();
|
||||
const sampler = c ? new ResourceSampler(c, [{ side: "a" as const, containerId: a.containerId }], await gpuTargets([meta, null])) : null;
|
||||
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
|
||||
const cur: Current = {
|
||||
runId: run.id,
|
||||
kind: "eval",
|
||||
deploymentIds: [a.id],
|
||||
child: null,
|
||||
abort: new AbortController(),
|
||||
sampler,
|
||||
meta,
|
||||
metaB: null,
|
||||
maxPairs: null,
|
||||
cancelled: false,
|
||||
lost: null,
|
||||
secrets: keys,
|
||||
};
|
||||
current = cur;
|
||||
log.info(`benchmark ${run.id}: quality eval started for ${s.deploymentName}`);
|
||||
const onLine = (line: string) => {
|
||||
addLog(run.id, "stdout", line, keys);
|
||||
const m = line.match(/^(tools|coding|retrieval): starting$/);
|
||||
if (m) void db().update(benchmarkRuns).set({ phase: `Quality: ${SECTION_LABEL[m[1] as QualitySection]}` }).where(eq(benchmarkRuns.id, run.id)).then(() => {}, () => {});
|
||||
};
|
||||
runQualityEval(
|
||||
{ base: `http://${a.containerName}:${ENGINE_PORT[a.engine]}`, model: s.repoId, engine: a.engine, apiKey: keys[0] ?? null, contextTokens },
|
||||
{ sections, signal: cur.abort!.signal, log: onLine, docker: c, sandboxImage: workerImage() },
|
||||
).then(
|
||||
(q) => doneEval(cur, q, null),
|
||||
(err) => doneEval(cur, null, err),
|
||||
);
|
||||
}
|
||||
|
||||
async function doneEval(cur: Current, quality: QualityResult | null, err: unknown) {
|
||||
const id = cur.runId;
|
||||
const resources = await stopSampling(cur);
|
||||
if (cur.cancelled) {
|
||||
addLog(id, "system", "Cancelled.");
|
||||
await finish(id, { state: "cancelled", quality, resources });
|
||||
} else if (cur.lost) {
|
||||
addLog(id, "system", cur.lost);
|
||||
await finish(id, { state: "failed", error: cur.lost, quality, resources });
|
||||
} else if (err || !quality) {
|
||||
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}`, resources });
|
||||
} else {
|
||||
addLog(id, "system", `Done: score ${quality.score ?? "–"} (${quality.sections.map((x) => `${x.section} ${x.unsupported ? "n/a" : `${x.passed}/${x.total}`}`).join(", ")}).`);
|
||||
await finish(id, { state: "completed", quality, resources });
|
||||
}
|
||||
tails.delete(id);
|
||||
await flushBenchmarkLogs().catch(() => {});
|
||||
log.info(`benchmark ${id}: quality eval ${cur.cancelled ? "cancelled" : cur.lost || err ? "failed" : `done, score ${quality?.score}`}`);
|
||||
}
|
||||
|
||||
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
|
||||
const id = cur.runId;
|
||||
for (const stream of ["stdout", "stderr"] as const) {
|
||||
const rest = partial.get(`${id}:${stream}`);
|
||||
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
|
||||
partial.delete(`${id}:${stream}`);
|
||||
}
|
||||
const resources = await stopSampling(cur);
|
||||
const dir = runDir(id);
|
||||
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
|
||||
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
|
||||
@@ -357,9 +445,11 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
}
|
||||
|
||||
function stop(cur: Current) {
|
||||
if (cur.child.exitCode !== null) return;
|
||||
cur.child.kill("SIGTERM");
|
||||
setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref();
|
||||
const child = cur.child;
|
||||
if (!child) return void cur.abort?.abort();
|
||||
if (child.exitCode !== null) return;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 10_000).unref();
|
||||
}
|
||||
|
||||
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// The quality eval against a fake OpenAI-compatible server: requests, scoring, unsupported sections,
|
||||
// cancelling. (The code sandbox needs Docker; here coding counts as unsupported.)
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { EVAL_SET } from "@/lib/quality";
|
||||
import { runQualityEval } from "./quality";
|
||||
|
||||
type Body = { messages: { content: string }[]; tools?: unknown[]; temperature?: number; seed?: number; chat_template_kwargs?: { enable_thinking?: boolean } };
|
||||
let server: Server;
|
||||
let base = "";
|
||||
let refuseTools = false;
|
||||
const seen: Body[] = [];
|
||||
|
||||
before(async () => {
|
||||
server = createServer((req, res) => {
|
||||
let raw = "";
|
||||
req.on("data", (c) => (raw += c));
|
||||
req.on("end", () => {
|
||||
const body = JSON.parse(raw || "{}") as Body & { content?: string };
|
||||
const json = (status: number, v: unknown) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(v));
|
||||
};
|
||||
if (req.url === "/tokenize") return json(200, { tokens: new Array(Math.ceil((body.content ?? "").length / 4)).fill(1) });
|
||||
if (req.url !== "/v1/chat/completions") return json(404, {});
|
||||
seen.push(body);
|
||||
const prompt = body.messages[0].content;
|
||||
if (body.tools) {
|
||||
if (refuseTools) return json(400, { error: { message: "tools param requires --jinja flag" } });
|
||||
const item = EVAL_SET.tools.items.find((i) => i.prompt === prompt)!;
|
||||
// Half right: every other item calls the wrong function.
|
||||
const idx = EVAL_SET.tools.items.indexOf(item);
|
||||
const args = Object.fromEntries(Object.entries(item.expect.args).map(([k, v]) => [k, typeof v === "object" ? ("contains" in v ? v.contains : "oneOf" in v ? v.oneOf[0] : "17 * 23") : v]));
|
||||
const wrong = item.expect.name === "set_timer" ? "get_weather" : "set_timer";
|
||||
const name = idx % 2 === 0 ? item.expect.name : wrong;
|
||||
return json(200, { choices: [{ message: { content: null, tool_calls: [{ function: { name, arguments: JSON.stringify(args) } }] } }] });
|
||||
}
|
||||
const code = prompt.match(/vault is (\d{6})/)?.[1];
|
||||
// Finds the needle in the first two thirds of the text only.
|
||||
const found = code && prompt.indexOf(code) / prompt.length < 0.66;
|
||||
return json(200, { choices: [{ message: { content: found ? `The code is ${code}.` : "I couldn't find it." } }] });
|
||||
});
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
after(() => server.close());
|
||||
|
||||
const target = () => ({ base, model: "test/model", engine: "llama.cpp" as const, apiKey: null, contextTokens: 4096 });
|
||||
const opts = (o: Partial<Parameters<typeof runQualityEval>[1]> = {}) => ({
|
||||
sections: ["tools", "coding", "retrieval"] as const as ("tools" | "coding" | "retrieval")[],
|
||||
signal: new AbortController().signal,
|
||||
log: () => {},
|
||||
docker: null,
|
||||
sandboxImage: null,
|
||||
...o,
|
||||
});
|
||||
|
||||
describe("quality eval run", () => {
|
||||
it("scores tool calls and retrieval, greedy with a fixed seed and thinking off", async () => {
|
||||
seen.length = 0;
|
||||
const q = await runQualityEval(target(), opts());
|
||||
const by = Object.fromEntries(q.sections.map((s) => [s.section, s]));
|
||||
assert.equal(by.tools.passed, 6);
|
||||
assert.equal(by.tools.total, 12);
|
||||
assert.match(by.coding.unsupported!, /sandbox/);
|
||||
assert.equal(by.retrieval.total, 9);
|
||||
assert.equal(by.retrieval.passed, 6, "positions 10 % and 50 % found, 90 % not");
|
||||
assert.equal(q.score, 58.3, "mean of 50 % and 66.7 %; coding doesn't count");
|
||||
assert.equal(q.evalSet, "kaname-eval-1");
|
||||
assert.ok(seen.every((b) => b.temperature === 0 && b.seed === 1 && b.chat_template_kwargs?.enable_thinking === false));
|
||||
assert.equal(q.items.filter((i) => i.section === "tools" && !i.pass)[0].detail, "called set_timer, expected convert_currency");
|
||||
});
|
||||
|
||||
it("marks tool calling unsupported when the server refuses tools", async () => {
|
||||
refuseTools = true;
|
||||
try {
|
||||
const q = await runQualityEval(target(), opts({ sections: ["tools"] }));
|
||||
assert.match(q.sections[0].unsupported!, /refused tool calls: .*--jinja/);
|
||||
assert.equal(q.score, null);
|
||||
} finally {
|
||||
refuseTools = false;
|
||||
}
|
||||
});
|
||||
|
||||
it("can't plan retrieval without a context length", async () => {
|
||||
const q = await runQualityEval({ ...target(), contextTokens: null }, opts({ sections: ["retrieval"] }));
|
||||
assert.match(q.sections[0].unsupported!, /context length is unknown/);
|
||||
});
|
||||
|
||||
it("stops early when cancelled", async () => {
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
const q = await runQualityEval(target(), opts({ signal: ac.signal }));
|
||||
assert.equal(q.sections.length, 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
// Runs the quality eval (src/lib/quality.ts) against a running deployment: greedy decoding with a
|
||||
// fixed seed, thinking turned off where the chat template supports it, scoring that doesn't depend
|
||||
// on judgement. Coding answers run with their unit tests in a throwaway container from Kaname's own
|
||||
// image: no network, read-only, unprivileged user, all capabilities dropped, small limits.
|
||||
|
||||
import type { QualityResult, QualitySection, RuntimeEngine } from "@/lib/db/schema";
|
||||
import {
|
||||
buildHaystack,
|
||||
EVAL_SEED,
|
||||
EVAL_SET,
|
||||
EVAL_SET_VERSION,
|
||||
extractCode,
|
||||
retrievalCases,
|
||||
scoreNeedle,
|
||||
scoreToolCall,
|
||||
summarize,
|
||||
testProgram,
|
||||
type ToolCall,
|
||||
toolDefs,
|
||||
} from "@/lib/quality";
|
||||
import type { DockerClient } from "./docker/client";
|
||||
|
||||
export type EvalTarget = {
|
||||
/** http://<container>:<port> */
|
||||
base: string;
|
||||
model: string;
|
||||
engine: RuntimeEngine;
|
||||
apiKey: string | null;
|
||||
/** Context per request (llama.cpp: per slot), for the retrieval lengths. */
|
||||
contextTokens: number | null;
|
||||
};
|
||||
|
||||
export type EvalOptions = {
|
||||
sections: QualitySection[];
|
||||
signal: AbortSignal;
|
||||
log: (line: string) => void;
|
||||
docker: DockerClient | null;
|
||||
/** Image for the coding sandbox (Kaname's own, it has Python); null: coding can't run. */
|
||||
sandboxImage: string | null;
|
||||
};
|
||||
|
||||
const TEMPERATURE = 0;
|
||||
const THINKING = false;
|
||||
|
||||
class HttpError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function post<T>(t: EvalTarget, path: string, body: unknown, signal: AbortSignal, timeoutMs: number): Promise<T> {
|
||||
const res = await fetch(`${t.base}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...(t.apiKey ? { Authorization: `Bearer ${t.apiKey}` } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new HttpError(res.status, text.slice(0, 300));
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
type ChatMessage = { content?: string | null; tool_calls?: { function?: { name?: string; arguments?: string } }[] };
|
||||
|
||||
/** One greedy chat completion; thinking off (Qwen3-style templates read enable_thinking, others ignore it). */
|
||||
async function chat(t: EvalTarget, messages: { role: string; content: string }[], extra: Record<string, unknown>, signal: AbortSignal, timeoutMs = 300_000) {
|
||||
const r = await post<{ choices?: { message?: ChatMessage }[] }>(
|
||||
t,
|
||||
"/v1/chat/completions",
|
||||
{ model: t.model, messages, temperature: TEMPERATURE, seed: EVAL_SEED, chat_template_kwargs: { enable_thinking: THINKING }, ...extra },
|
||||
signal,
|
||||
timeoutMs,
|
||||
);
|
||||
return r.choices?.[0]?.message ?? {};
|
||||
}
|
||||
|
||||
type Section = QualityResult["sections"][number];
|
||||
type Item = QualityResult["items"][number];
|
||||
|
||||
async function toolsSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
|
||||
let passed = 0;
|
||||
const all = EVAL_SET.tools.items;
|
||||
for (const item of all) {
|
||||
if (o.signal.aborted) break;
|
||||
try {
|
||||
const m = await chat(t, [{ role: "user", content: item.prompt }], { tools: toolDefs(item), tool_choice: "auto", max_tokens: 512 }, o.signal);
|
||||
const calls: ToolCall[] = (m.tool_calls ?? []).map((c) => ({ name: c.function?.name ?? "", arguments: c.function?.arguments ?? "" }));
|
||||
const r = scoreToolCall(calls, item.expect);
|
||||
if (r.pass) passed++;
|
||||
items.push({ section: "tools", id: item.id, pass: r.pass, detail: r.detail });
|
||||
o.log(`tools ${item.id}: ${r.pass ? "pass" : `fail (${r.detail})`}`);
|
||||
} catch (err) {
|
||||
// The server can't do tool calls at all (e.g. no tool-call parser configured): the section
|
||||
// doesn't count instead of scoring 0.
|
||||
if (err instanceof HttpError && err.status >= 400 && err.status < 500 && items.every((x) => x.section !== "tools")) {
|
||||
o.log(`tools: the server refused tool calls (${err.status}): ${err.message}`);
|
||||
return { section: "tools", passed: 0, total: 0, unsupported: `the server refused tool calls: ${err.message.slice(0, 200)}` };
|
||||
}
|
||||
if (o.signal.aborted) break;
|
||||
items.push({ section: "tools", id: item.id, pass: false, detail: err instanceof Error ? err.message.slice(0, 200) : String(err) });
|
||||
o.log(`tools ${item.id}: error ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
return { section: "tools", passed, total: all.length };
|
||||
}
|
||||
|
||||
/** Run a program in the sandbox; ok when it exits 0 and printed the marker. */
|
||||
async function runPython(c: DockerClient, image: string, program: string, signal: AbortSignal): Promise<{ ok: boolean; output: string }> {
|
||||
const runner = "import base64,os;exec(compile(base64.b64decode(os.environ['KANAME_CODE']).decode(),'solution','exec'),{'__name__':'__main__'})";
|
||||
const created = await c.createContainer(`kaname-eval-sandbox-${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`, {
|
||||
Image: image,
|
||||
User: "65534:65534",
|
||||
Entrypoint: ["python3", "-I", "-c", runner],
|
||||
Cmd: [],
|
||||
Env: [`KANAME_CODE=${Buffer.from(program).toString("base64")}`, "PYTHONDONTWRITEBYTECODE=1"],
|
||||
NetworkDisabled: true,
|
||||
Labels: { "kaname.managed": "true", "kaname.probe": "eval-sandbox" },
|
||||
HostConfig: {
|
||||
NetworkMode: "none",
|
||||
ReadonlyRootfs: true,
|
||||
Tmpfs: { "/tmp": "rw,noexec,nosuid,size=16m" },
|
||||
CapDrop: ["ALL"],
|
||||
SecurityOpt: ["no-new-privileges"],
|
||||
Memory: 256 * 2 ** 20,
|
||||
MemorySwap: 256 * 2 ** 20,
|
||||
NanoCpus: 1e9,
|
||||
PidsLimit: 64,
|
||||
Privileged: false,
|
||||
AutoRemove: false,
|
||||
},
|
||||
});
|
||||
const lines: string[] = [];
|
||||
try {
|
||||
await c.startContainer(created.Id);
|
||||
await c
|
||||
.followLogs(created.Id, (_s, line) => lines.length < 200 && lines.push(line), { tail: "all", signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]) })
|
||||
.catch(() => {});
|
||||
const st = await c.containerState(created.Id);
|
||||
if (st?.Running) {
|
||||
await c.stopContainer(created.Id, 0).catch(() => {});
|
||||
return { ok: false, output: "timed out (15 s)" };
|
||||
}
|
||||
return { ok: st?.ExitCode === 0 && lines.some((l) => l.includes("KANAME-OK")), output: lines.slice(-6).join("\n") };
|
||||
} finally {
|
||||
await c.removeContainer(created.Id).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function codingSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
|
||||
if (!o.docker || !o.sandboxImage) return { section: "coding", passed: 0, total: 0, unsupported: "no Docker access for the code sandbox" };
|
||||
let passed = 0;
|
||||
const all = EVAL_SET.coding.items;
|
||||
for (const item of all) {
|
||||
if (o.signal.aborted) break;
|
||||
let pass = false;
|
||||
let detail: string;
|
||||
try {
|
||||
const m = await chat(t, [{ role: "user", content: `${EVAL_SET.coding.instructions}\n\n${item.prompt}` }], { max_tokens: 1024 }, o.signal);
|
||||
const code = extractCode(m.content ?? "");
|
||||
if (!code) detail = "no code block in the answer";
|
||||
else {
|
||||
const r = await runPython(o.docker, o.sandboxImage, testProgram(code, item.tests), o.signal);
|
||||
pass = r.ok;
|
||||
detail = r.ok ? "tests pass" : `tests fail: ${r.output.split("\n").slice(-2).join(" ").slice(0, 200)}`;
|
||||
}
|
||||
} catch (err) {
|
||||
if (o.signal.aborted) break;
|
||||
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
|
||||
}
|
||||
if (pass) passed++;
|
||||
items.push({ section: "coding", id: item.id, pass, detail });
|
||||
o.log(`coding ${item.id}: ${pass ? "pass" : `fail (${detail})`}`);
|
||||
}
|
||||
return { section: "coding", passed, total: all.length };
|
||||
}
|
||||
|
||||
/** Characters per token of the filler text, by the server's own tokenizer (4 if it can't tell). */
|
||||
async function charsPerToken(t: EvalTarget, signal: AbortSignal): Promise<number> {
|
||||
const sample = EVAL_SET.retrieval.filler.join(" ");
|
||||
try {
|
||||
const r =
|
||||
t.engine === "llama.cpp"
|
||||
? await post<{ tokens?: unknown[] }>(t, "/tokenize", { content: sample }, signal, 30_000)
|
||||
: await post<{ count?: number; tokens?: unknown[] }>(t, "/tokenize", { model: t.model, prompt: sample }, signal, 30_000);
|
||||
const n = (r as { count?: number }).count ?? r.tokens?.length ?? 0;
|
||||
return n > 0 ? sample.length / n : 4;
|
||||
} catch {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
async function retrievalSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
|
||||
if (!t.contextTokens) return { section: "retrieval", passed: 0, total: 0, unsupported: "the context length is unknown" };
|
||||
const cases = retrievalCases(t.contextTokens);
|
||||
if (cases.length === 0) return { section: "retrieval", passed: 0, total: 0, unsupported: `context of ${t.contextTokens} tokens is too short` };
|
||||
const cpt = await charsPerToken(t, o.signal);
|
||||
let passed = 0;
|
||||
for (const c of cases) {
|
||||
if (o.signal.aborted) break;
|
||||
let pass = false;
|
||||
let detail: string;
|
||||
try {
|
||||
const m = await chat(t, [{ role: "user", content: buildHaystack(c, cpt) }], { max_tokens: 32 }, o.signal, 900_000);
|
||||
({ pass, detail } = scoreNeedle(m.content ?? "", c));
|
||||
} catch (err) {
|
||||
if (o.signal.aborted) break;
|
||||
detail = err instanceof Error ? err.message.slice(0, 200) : String(err);
|
||||
}
|
||||
if (pass) passed++;
|
||||
items.push({ section: "retrieval", id: c.id, pass, detail });
|
||||
o.log(`retrieval ${c.id}: ${pass ? "pass" : `fail (${detail})`}`);
|
||||
}
|
||||
return { section: "retrieval", passed, total: cases.length };
|
||||
}
|
||||
|
||||
const RUNNERS: Record<QualitySection, (t: EvalTarget, o: EvalOptions, items: Item[]) => Promise<Omit<Section, "score" | "seconds">>> = {
|
||||
tools: toolsSection,
|
||||
coding: codingSection,
|
||||
retrieval: retrievalSection,
|
||||
};
|
||||
|
||||
/** The whole eval (or the chosen sections), in order; stops early when the signal aborts. */
|
||||
export async function runQualityEval(t: EvalTarget, o: EvalOptions): Promise<QualityResult> {
|
||||
const items: Item[] = [];
|
||||
const sections: Section[] = [];
|
||||
for (const s of o.sections) {
|
||||
if (o.signal.aborted) break;
|
||||
const t0 = Date.now();
|
||||
o.log(`${s}: starting`);
|
||||
const r = await RUNNERS[s](t, o, items);
|
||||
sections.push({ ...r, score: null, seconds: Math.round((Date.now() - t0) / 1000) });
|
||||
}
|
||||
return {
|
||||
evalSet: EVAL_SET_VERSION,
|
||||
...summarize(sections),
|
||||
items,
|
||||
config: { temperature: TEMPERATURE, seed: EVAL_SEED, thinking: THINKING, contextTokens: t.contextTokens },
|
||||
};
|
||||
}
|
||||
+32
-7
@@ -51,20 +51,21 @@ async function advance(sweep: Sweep): Promise<void> {
|
||||
const timedOut = overTime(sweep.startedAt, sweep.timeLimitS);
|
||||
if (sweep.cancelRequestedAt || timedOut) {
|
||||
for (const v of variants) {
|
||||
if (v.state === "benchmarking" && v.runId) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, v.runId));
|
||||
if (v.state === "deploying" || v.state === "benchmarking") await removeDeployment(v.deploymentId);
|
||||
const open = v.state === "evaluating" ? v.evalRunId : v.state === "benchmarking" ? v.runId : null;
|
||||
if (open) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, open));
|
||||
if (v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating") await removeDeployment(v.deploymentId);
|
||||
}
|
||||
await save(sweep.id, {
|
||||
state: timedOut ? "failed" : "cancelled",
|
||||
...(timedOut ? { error: `Stopped: the sweep exceeded the time limit for agent sweeps (${Math.round((sweep.timeLimitS ?? 0) / 60)} min).` } : {}),
|
||||
finishedAt: new Date(),
|
||||
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)),
|
||||
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating" ? { ...v, state: "skipped" as const } : v)),
|
||||
});
|
||||
log.info(`sweep ${sweep.id}: ${timedOut ? "stopped at its time limit" : "cancelled"}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking");
|
||||
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating");
|
||||
if (i < 0) {
|
||||
const ok = variants.filter((v) => v.state === "done").length;
|
||||
await save(sweep.id, { state: ok > 0 ? "completed" : "failed", finishedAt: new Date(), error: ok > 0 ? null : "No variant could be benchmarked." });
|
||||
@@ -127,14 +128,38 @@ async function advance(sweep: Sweep): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
// benchmarking
|
||||
const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.runId) }) : null;
|
||||
// benchmarking, then (sweeps with quality) evaluating
|
||||
const runId = v.state === "evaluating" ? v.evalRunId : v.runId;
|
||||
const run = runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, runId) }) : null;
|
||||
if (!run) {
|
||||
await put(i, { state: "failed", error: "The variant's run disappeared." });
|
||||
return removeDeployment(v.deploymentId);
|
||||
}
|
||||
if (run.state === "queued" || run.state === "running") return;
|
||||
await put(i, run.state === "completed" ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
|
||||
if (run.state === "completed" && v.state === "benchmarking" && sweep.settings.quality) {
|
||||
const snap = await deploymentSnapshot(v.deploymentId!);
|
||||
if (snap) {
|
||||
const [ev] = await db()
|
||||
.insert(benchmarkRuns)
|
||||
.values({
|
||||
kind: "eval",
|
||||
deploymentId: snap.id,
|
||||
modelId: snap.modelId,
|
||||
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label} · quality`.slice(0, 120),
|
||||
settings: { quick: false, passes: null, warmup: null, phases: [], evalSections: [] },
|
||||
snapshot: snap.snapshot,
|
||||
sweepId: sweep.id,
|
||||
requestedByTokenId: sweep.requestedByTokenId,
|
||||
requestedBy: sweep.requestedBy,
|
||||
timeLimitS: sweep.runTimeLimitS,
|
||||
})
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
return void (await put(i, { state: "evaluating", evalRunId: ev.id }));
|
||||
}
|
||||
}
|
||||
const ok = run.state === "completed" || (v.state === "evaluating" && !!v.runId);
|
||||
// A failed eval doesn't undo the speed result; it shows on the eval run.
|
||||
await put(i, ok ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
|
||||
await removeDeployment(v.deploymentId);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user