Benchmarks with BetterBench, launch80-style reports and publishing, GPU support

- Benchmarks: BetterBench 0.6.1 (pinned by checksum) runs against a running
  deployment, one at a time; quick/full/custom passes, phase selection, live
  step and output, cancel, run again, compare runs side by side.
- Report page after launch80's bench.betterbench.v1: headline tiles,
  "Read these first" caveats (quick, sample gate, max_tokens truncation,
  batched streams, failures, skipped depths, prefix-cache hits), charts, full
  tables with daggered under-sampled cells, method text. All figures come from
  BetterBench's own report functions.
- Publish to launch80 as a double opt-in: L80 dry run builds the exact payload
  for inspection, an explicit confirmation publishes that file (L80 CLI 0.4.0
  pinned by checksum, L80_TOKEN worker-only). Endpoint and host never leave.
- GPUs: runtime accelerator (CPU, NVIDIA, /dev/dri, ROCm) with presets for the
  official CUDA/Vulkan/Intel/ROCm builds; NVIDIA GPUs probed via nvidia-smi in
  a short-lived container; per-deployment GPU picking, -ngl, split mode,
  tensor split, MoE offload, vLLM tensor parallel and GPU memory share.
- llama.cpp --cache-ram option (1 GiB for new deployments) and a memory
  estimate that counts it and the KV cache: the 8 GiB default made containers
  thrash at their memory limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-10 20:54:38 +02:00
1 parent f0b4adda63
commit 9e167a44f6
61 files changed
+9898 -194

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
// Runs BetterBench against running deployments, one benchmark at a time (two at once would
// measure each other).
import { type ChildProcess, execFile, spawn } from "node:child_process";
import { access, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
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 { sanitizeLine } from "./job-log";
import { log } from "./log";
import { errorCauses } from "./log-causes";
type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] };
let current: Current | null = null;
let starting = false;
const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = [];
const partial = new Map<string, string>();
const tails = new Map<string, string[]>();
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
function addLog(runId: string, stream: LogStream, line: string, secrets: string[] = []) {
const clean = sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...secrets]).slice(0, 4000);
pending.push({ runId, stream, line: clean, ts: new Date() });
const tail = tails.get(runId) ?? [];
tail.push(clean);
if (tail.length > 400) tail.shift();
tails.set(runId, tail);
}
/** Split a stream into lines (keeps the unfinished rest per run and stream). */
function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets: string[]) {
const key = `${runId}:${stream}`;
const parts = ((partial.get(key) ?? "") + data.toString("utf8")).split(/\r?\n|\r/);
partial.set(key, parts.pop() ?? "");
for (const p of parts) {
if (!p.trim()) continue;
addLog(runId, stream, p, secrets);
const step = stepOf(p);
if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
}
}
/** BetterBench's progress lines ("[single] chat: …", "[prefill] depth ~2000 tok: …") as a short step label. */
export function stepOf(line: string): string | null {
const m = line.match(/^\[(single|prefill|concurrency)\]\s*([^:]*)/);
if (!m) return null;
const what = m[2].trim();
const name = m[1] === "single" ? "Generation" : m[1] === "prefill" ? "Prompt processing" : "Parallel requests";
return what ? `${name}: ${what}` : name;
}
export async function flushBenchmarkLogs(): Promise<void> {
if (pending.length === 0) return;
const batch = pending.splice(0, pending.length);
for (let i = 0; i < batch.length; i += 500) await db().insert(benchmarkLogs).values(batch.slice(i, i + 500));
}
async function finish(runId: string, set: Partial<typeof benchmarkRuns.$inferInsert>) {
await db()
.update(benchmarkRuns)
.set({ finishedAt: new Date(), ...set })
.where(eq(benchmarkRuns.id, runId));
}
/** Runs left "running" by a previous worker can't be resumed. */
export async function recoverBenchmarks(): Promise<void> {
const res = await db()
.update(benchmarkRuns)
.set({ state: "failed", error: "Interrupted: the worker restarted during the run.", finishedAt: new Date() })
.where(eq(benchmarkRuns.state, "running"))
.returning({ id: benchmarkRuns.id });
if (res.length) log.info(`marked ${res.length} interrupted benchmark(s) as failed`);
}
async function exists(path: string) {
return access(path).then(
() => true,
() => false,
);
}
/** Completed runs whose stored summary predates SUMMARY_VERSION: recompute from results.json. */
export async function refreshSummaries(): Promise<void> {
const rows = await db()
.select({ id: benchmarkRuns.id, summary: benchmarkRuns.summary, settings: benchmarkRuns.settings })
.from(benchmarkRuns)
.where(eq(benchmarkRuns.state, "completed"));
let n = 0;
for (const r of rows) {
if (r.summary?.v === SUMMARY_VERSION) continue;
const results = join(runDir(r.id), RESULTS_FILE);
if (!(await exists(results))) continue;
try {
const summary = { ...(await summarize(results)), quick: !!r.settings.quick };
await db().update(benchmarkRuns).set({ summary }).where(eq(benchmarkRuns.id, r.id));
n++;
} catch (err) {
log.warn(`benchmark ${r.id}: summary refresh failed: ${message(err)}`);
}
}
if (n) log.info(`refreshed ${n} benchmark summar${n === 1 ? "y" : "ies"}`);
}
async function summarize(results: string): Promise<BenchmarkSummary> {
const { stdout } = await promisify(execFile)(betterbenchPython(), ["-c", SUMMARY_SCRIPT, results], { timeout: 120_000, maxBuffer: 16 * 2 ** 20 });
return JSON.parse(stdout) as BenchmarkSummary;
}
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 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 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 } : {}),
},
});
// Only what BetterBench needs: no HF_TOKEN or other worker secrets.
const env: Record<string, string | undefined> = {
PATH: process.env.PATH,
HOME: process.env.HOME,
LANG: "C.UTF-8",
PYTHONUNBUFFERED: "1",
NO_COLOR: "1",
BETTERBENCH_HOME: dir,
BETTERBENCH_NO_UPDATE_CHECK: "1",
...(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", `$ betterbench ${args.join(" ")}`, keys);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
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 };
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.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}`);
}
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}`);
}
if (current === cur) current = null;
const dir = runDir(id);
const results = join(dir, RESULTS_FILE);
const hasReport = await exists(join(dir, REPORT_FILE));
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", hasReport });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, hasReport });
} 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 });
} catch (err) {
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
}
} else {
const lines = tails.get(id) ?? [];
const causes = errorCauses(lines);
const why = signal ? `stopped by ${signal}` : `exit code ${code ?? "?"}`;
const last = lines.slice(-12).join("\n");
await finish(id, {
state: "failed",
error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
hasReport,
});
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost ? "failed (deployment gone)" : code === 0 ? "completed" : "failed"}`);
}
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();
}
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
export async function tickBenchmarks(): Promise<void> {
if (starting) return;
if (current) {
const cur = current;
const [run] = await db().select({ cancel: benchmarkRuns.cancelRequestedAt }).from(benchmarkRuns).where(eq(benchmarkRuns.id, cur.runId));
if (!run || run.cancel) {
cur.cancelled = true;
stop(cur);
return;
}
if (cur.deploymentId) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId));
if (!d || d.state !== "running") {
cur.lost = "The deployment stopped during the run.";
stop(cur);
}
}
return;
}
starting = true;
try {
const next = await db().query.benchmarkRuns.findFirst({ where: eq(benchmarkRuns.state, "queued"), orderBy: asc(benchmarkRuns.createdAt) });
if (next) await start(next).catch((err) => finish(next.id, { state: "failed", error: `Could not start: ${message(err)}` }));
} finally {
starting = false;
}
}
/** Worker shutdown: a run can't continue in another process. */
export async function stopBenchmarks(): Promise<void> {
const cur = current;
if (!cur) return;
cur.lost = "Interrupted: the worker stopped during the run.";
stop(cur);
const deadline = Date.now() + 5_000;
while (current === cur && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
}