Benchmarks: paired A/B runs, sweeps, resource usage

- A/B with betterbench ab between two deployments of the same model, with verdict, confidence
  interval and caveats.
- Sweeps vary one or two deployment settings, deploy, benchmark and remove each variant, and
  compare them in one table.
- Every run records CPU, RAM, VRAM, GPU utilization and power.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-13 10:04:40 +02:00
1 parent 9e167a44f6
commit b623b16a6d
37 files changed
+4314 -214

No files matched your search

+120 -45
View File
@@ -2,7 +2,7 @@
// measure each other).
import { type ChildProcess, execFile, spawn } from "node:child_process";
import { access, mkdir } from "node:fs/promises";
import { access, mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
@@ -11,12 +11,25 @@ import { db } from "@/lib/db/client";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import { abSummary } from "./ab-summary";
import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { errorCauses } from "./log-causes";
import { ResourceSampler } from "./resources";
import { docker, workerImage } from "./runtimes";
type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] };
type Current = {
runId: string;
kind: "run" | "ab";
deploymentIds: string[];
child: ChildProcess;
sampler: ResourceSampler | null;
maxPairs: number | null;
cancelled: boolean;
lost: string | null;
secrets: string[];
};
let current: Current | null = null;
let starting = false;
@@ -114,36 +127,61 @@ async function summarize(results: string): Promise<BenchmarkSummary> {
return JSON.parse(stdout) as BenchmarkSummary;
}
type Target = { id: string; containerId: string; containerName: string; engine: "llama.cpp" | "vllm"; accelerator: string };
async function target(deploymentId: string | null): Promise<Target | null> {
if (!deploymentId) return null;
const [d] = await db()
.select({ state: deployments.state, containerId: deployments.containerId, containerName: deployments.containerName, engine: runtimes.engine, accelerator: runtimes.accelerator })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(eq(deployments.id, deploymentId));
if (!d || d.state !== "running" || !d.containerName || !d.containerId) return null;
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
}
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
async function start(run: typeof benchmarkRuns.$inferSelect) {
const fail = (error: string) => finish(run.id, { state: "failed", error });
const [d] = run.deploymentId
? await db()
.select({ state: deployments.state, containerName: deployments.containerName, engine: runtimes.engine })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(eq(deployments.id, run.deploymentId))
: [];
if (!d || d.state !== "running" || !d.containerName) return fail("The deployment isn't running anymore.");
const a = await target(run.deploymentId);
if (!a) return fail(run.kind === "ab" ? "Deployment A isn't running anymore." : "The deployment isn't running anymore.");
const b = run.kind === "ab" ? await target(run.deploymentBId) : null;
if (run.kind === "ab" && !b) return fail("Deployment B isn't running anymore.");
const dir = runDir(run.id);
await mkdir(dir, { recursive: true });
const keys = run.snapshot.options.requireApiKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const needsKey = run.snapshot.options.requireApiKey || run.snapshotB?.options.requireApiKey;
// One key works for both: BETTERBENCH_API_KEY fills in every missing key flag.
const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const s = run.snapshot;
const args = runArgs({
endpoint: `http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1`,
model: s.repoId,
out: join(dir, RESULTS_FILE),
settings: run.settings,
maxModelLen: s.options.contextSize ?? null,
notes: {
deployment: s.deploymentName,
runtime: s.runtimeName,
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...(run.label ? { label: run.label } : {}),
},
});
const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
const args =
run.kind === "ab" && b
? abArgs({
endpointA: endpoint(a),
endpointB: endpoint(b),
model: s.repoId,
out: join(dir, AB_FILE),
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
maxPairs,
notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}) },
})
: runArgs({
endpoint: endpoint(a),
model: s.repoId,
out: join(dir, RESULTS_FILE),
settings: run.settings,
maxModelLen: s.options.contextSize ?? null,
notes: {
deployment: s.deploymentName,
runtime: s.runtimeName,
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...(run.label ? { label: run.label } : {}),
},
});
// Only what BetterBench needs: no HF_TOKEN or other worker secrets.
const env: Record<string, string | undefined> = {
PATH: process.env.PATH,
@@ -156,20 +194,48 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}),
};
addLog(run.id, "system", `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`);
addLog(
run.id,
"system",
run.kind === "ab"
? `Paired A/B: ${s.deploymentName} (A) vs ${run.snapshotB?.deploymentName} (B), ${s.repoId}, with BetterBench`
: `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`,
);
addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
// Resource use of the server(s) under test; GPUs when any side runs on NVIDIA.
const c = docker();
const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia";
const sampler = c
? new ResourceSampler(
c,
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
nvidia ? workerImage() : null,
)
: null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const cur: Current = { runId: run.id, deploymentId: run.deploymentId, child, cancelled: false, lost: null, secrets: keys };
const cur: Current = {
runId: run.id,
kind: run.kind,
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
sampler,
maxPairs: run.kind === "ab" ? maxPairs : null,
cancelled: false,
lost: null,
secrets: keys,
};
current = cur;
child.stdout.on("data", (b: Buffer) => chunk(run.id, "stdout", b, keys));
child.stderr.on("data", (b: Buffer) => chunk(run.id, "stderr", b, keys));
child.stdout.on("data", (buf: Buffer) => chunk(run.id, "stdout", buf, keys));
child.stderr.on("data", (buf: Buffer) => chunk(run.id, "stderr", buf, keys));
child.on("error", (err: NodeJS.ErrnoException) => {
addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`);
});
child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err)));
log.info(`benchmark ${run.id}: started for ${s.deploymentName}`);
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
@@ -179,26 +245,33 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
const dir = runDir(id);
const results = join(dir, RESULTS_FILE);
const hasReport = await exists(join(dir, REPORT_FILE));
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", hasReport });
await finish(id, { state: "cancelled", hasReport, resources });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, hasReport });
await finish(id, { state: "failed", error: cur.lost, hasReport, resources });
} else if (code === 0 && (await exists(results))) {
try {
const summary = { ...(await summarize(results)), quick: false };
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
summary.quick = !!run?.settings.quick;
addLog(id, "system", "Done.");
await finish(id, { state: "completed", summary, hasReport });
if (cur.kind === "ab") {
const ab = abSummary(await readFile(results, "utf8"), cur.maxPairs);
addLog(id, "system", `Done: ${ab.decode_tps.verdict} (${ab.pairs} pairs).`);
await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, resources, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." });
} else {
const summary = { ...(await summarize(results)), quick: false };
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
summary.quick = !!run?.settings.quick;
addLog(id, "system", "Done.");
await finish(id, { state: "completed", summary, hasReport, resources });
}
} catch (err) {
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport, resources });
}
} else {
const lines = tails.get(id) ?? [];
@@ -209,6 +282,7 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
state: "failed",
error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
hasReport,
resources,
});
}
tails.delete(id);
@@ -233,11 +307,12 @@ export async function tickBenchmarks(): Promise<void> {
stop(cur);
return;
}
if (cur.deploymentId) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId));
for (const depId of cur.deploymentIds) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId));
if (!d || d.state !== "running") {
cur.lost = "The deployment stopped during the run.";
cur.lost = cur.deploymentIds.length > 1 ? "A deployment of the A/B stopped during the run." : "The deployment stopped during the run.";
stop(cur);
break;
}
}
return;