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

+13
View File
@@ -8,6 +8,19 @@ step 1 (Hugging Face downloader) is released as a minor version.
### Added
- **Paired A/B benchmarks** (`betterbench ab`): from a deployment's Benchmark card, pick another
running deployment of the same model as B. The same prompts go to both, alternating, with greedy
decoding, until the difference is known to ±the target precision (default 1 %, at most 200
pairs). The report shows the verdict (faster/slower/no measurable difference), the confidence
interval, both sides, what differs between them and the caveats, after launch80's rules.
- **Sweeps**: vary one or two settings of a deployment (context size, KV cache type, quant file,
threads, parallel slots, batch sizes, flash attention, prompt cache, GPU layers, CPU limit; vLLM:
dtype, max sequences, KV cache, GPU memory share), up to 16 variants. Kaname deploys each variant
in turn, benchmarks it, removes it again, and shows all of them side by side (chart and table,
best values in bold), with a link to compare the runs in detail. Compare now takes up to 16 runs.
- **Resource usage in every run**: CPU (cores, average and peak), RAM (average and peak against the
container limit) from Docker, and per GPU VRAM, utilization and power from nvidia-smi, sampled
every 2 s while the benchmark runs. Shown on the report, the A/B report and the sweep table.
- **Benchmarks** (new main menu entry) with [BetterBench](https://github.com/GGZ14/BetterBench)
(Apache-2.0, the benchmark behind launch80.com), built into the image (v0.6.1, archive pinned by
checksum).
+23
View File
@@ -0,0 +1,23 @@
CREATE TABLE `benchmark_sweeps` (
`id` text PRIMARY KEY NOT NULL,
`label` text,
`base_deployment_id` text,
`base` text NOT NULL,
`params` text NOT NULL,
`settings` text NOT NULL,
`variants` text NOT NULL,
`state` text DEFAULT 'queued' NOT NULL,
`cancel_requested_at` integer,
`started_at` integer,
`finished_at` integer,
`error` text,
`created_at` integer NOT NULL
);
--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `kind` text DEFAULT 'run' NOT NULL;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `deployment_b_id` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `snapshot_b` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `ab` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `resources` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `sweep_id` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `sweep_id` text;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -113,6 +113,13 @@
"when": 1791657884019,
"tag": "0015_benchmark_publications",
"breakpoints": true
},
{
"idx": 16,
"version": "6",
"when": 1791658947930,
"tag": "0016_ab_resources_sweeps",
"breakpoints": true
}
]
}
+185
View File
@@ -0,0 +1,185 @@
import { TriangleAlertIcon } from "lucide-react";
import { BenchmarkResources } from "@/components/benchmark-resources";
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "@/lib/ab-report";
import { CONFIG_ROWS } from "@/lib/benchmark-view";
import type { PairedResult } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../benchmark-list";
const sign = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
/** The difference with its 95% interval on a %-axis: zero line, the ±target band, the interval and the point. */
function IntervalChart({ r, target }: { r: PairedResult; target: number }) {
const reach = Math.max(Math.abs(r.ci_low_pct), Math.abs(r.ci_high_pct), target) * 1.25 || 1;
const pos = (v: number) => `${((v + reach) / (2 * reach)) * 100}%`;
const ticks = [-reach, -reach / 2, 0, reach / 2, reach].map((t) => Math.round(t * 10) / 10);
return (
<div className="flex flex-col gap-1" role="img" aria-label={`Difference ${sign(r.pct_diff)}, 95% interval ${sign(r.ci_low_pct)} to ${sign(r.ci_high_pct)}`}>
<div className="relative h-12">
{/* ±target band: differences inside it are smaller than the precision asked for */}
<div className="absolute inset-y-2 bg-muted" style={{ left: pos(-target), width: `calc(${pos(target)} - ${pos(-target)})` }} />
<div className="absolute inset-y-0 w-px bg-foreground/50" style={{ left: pos(0) }} />
<div
className={cn("absolute top-1/2 h-2 -translate-y-1/2 rounded-full", r.significant ? "bg-series" : "bg-foreground/40")}
style={{ left: pos(r.ci_low_pct), width: `calc(${pos(r.ci_high_pct)} - ${pos(r.ci_low_pct)})` }}
/>
<div
className={cn("absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2 ring-card", r.significant ? "bg-series" : "bg-foreground/60")}
style={{ left: pos(r.pct_diff) }}
/>
</div>
<div className="relative h-4 text-[11px] text-muted-foreground tabular-nums">
{ticks.map((t) => (
<span key={t} className="absolute -translate-x-1/2" style={{ left: pos(t) }}>
{t > 0 ? "+" : ""}
{t}%
</span>
))}
</div>
<p className="text-[11px] text-muted-foreground">
Dot: B&apos;s difference from A. Bar: the 95% interval. Grey band: ±{target}%, the precision asked for. B is better to the {r.higher_is_better ? "right" : "left"}.
</p>
</div>
);
}
function Side({ label, name, value, unit }: { label: string; name: string; value: number; unit: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-lg font-semibold">
{value.toFixed(unit === "ms" ? 2 : 1)} <span className="text-sm font-normal text-muted-foreground">{unit}</span>
</span>
<span className="truncate text-[11px] text-muted-foreground" title={name}>
{name}
</span>
</div>
);
}
export function AbReport({ run }: { run: ListRow }) {
const ab = run.ab;
const a = run.snapshot;
const b = run.snapshotB;
if (!ab || !b) return null;
const d = ab.decode_tps;
const g = ab.gap_median;
const caveats = abCaveats(ab);
const rows = CONFIG_ROWS.map((row) => ({ row, va: row.value(a), vb: row.value(b) })).filter((x) => x.va != null || x.vb != null);
const differs = rows.filter((x) => x.va !== x.vb);
const same = rows.filter((x) => x.va === x.vb);
return (
<article className="flex flex-col gap-8 rounded-2xl bg-card px-5 py-6 ring-1 ring-foreground/10 sm:px-8 sm:py-8">
<header className="flex flex-col gap-3">
<span className="font-mono text-[11px] tracking-wider text-muted-foreground uppercase">
BetterBench {ab.betterbenchVersion} · paired A/B · {ab.pairs} pairs
</span>
<h2 className="text-2xl font-semibold tracking-tight">{run.label ?? `${a.deploymentName} vs ${b.deploymentName}`}</h2>
<p className="max-w-3xl text-sm leading-relaxed">{abSummaryText(ab, a.deploymentName, b.deploymentName)}</p>
</header>
<section className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Decode throughput</span>
<span className={cn("text-3xl font-semibold", d.significant ? "" : "text-muted-foreground")}>{abHeadline(d)}</span>
<span className="text-sm text-muted-foreground">
{sign(d.pct_diff)} · 95% CI {sign(d.ci_low_pct)} to {sign(d.ci_high_pct)} · {d.significant ? "significant" : "within noise"}
</span>
<IntervalChart r={d} target={ab.target_mde_pct} />
</div>
<div className="flex flex-col gap-3">
<span className="text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g.batched ? "Stream-update gap" : "Token-to-token smoothness"}</span>
<span className={cn("text-3xl font-semibold", g.significant ? "" : "text-muted-foreground")}>{abHeadline(g)}</span>
<span className="text-sm text-muted-foreground">
{sign(g.pct_diff)} · 95% CI {sign(g.ci_low_pct)} to {sign(g.ci_high_pct)} · lower is better
</span>
<IntervalChart r={g} target={ab.target_mde_pct} />
</div>
</section>
<div className="grid gap-2 sm:grid-cols-4">
<Side label="A · decode, mean" name={a.deploymentName} value={d.mean_a} unit="t/s" />
<Side label="B · decode, mean" name={b.deploymentName} value={d.mean_b} unit="t/s" />
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Pairs</span>
<span className="text-lg font-semibold">{ab.pairs}</span>
<span className="text-[11px] text-muted-foreground">
±{halfWidth(d).toFixed(2)}% reached · target ±{ab.target_mde_pct}%
</span>
</div>
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">Paired CV</span>
<span className="text-lg font-semibold">{(ab.paired_cv * 100).toFixed(2)}%</span>
<span className="text-[11px] text-muted-foreground">~{ab.pairs_needed_for_mde} pairs for ±{ab.target_mde_pct}%</span>
</div>
</div>
{caveats.length > 0 && (
<div className="flex gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
<div className="flex flex-col gap-1.5">
<span className="font-medium text-amber-800 dark:text-amber-200">Read these first</span>
{caveats.map((x) => (
<p key={x} className="text-foreground/80">
{x}
</p>
))}
</div>
</div>
)}
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">What differs</h3>
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
<table className="w-full text-xs">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="px-3 py-2 font-medium" />
<th className="px-3 py-2 font-medium">A · {a.deploymentName}</th>
<th className="px-3 py-2 font-medium">B · {b.deploymentName}</th>
</tr>
</thead>
<tbody>
{differs.length === 0 && (
<tr>
<td colSpan={3} className="px-3 py-2 text-muted-foreground">
Same settings on both sides (a null A/B: it shows how much noise the setup has).
</td>
</tr>
)}
{differs.map(({ row, va, vb }) => (
<tr key={row.key} className="border-b bg-amber-500/5 last:border-0">
<td className="px-3 py-1.5 font-medium">{row.label}</td>
<td className="px-3 py-1.5 font-mono break-all">{va ?? <span className="text-muted-foreground">default</span>}</td>
<td className="px-3 py-1.5 font-mono break-all">{vb ?? <span className="text-muted-foreground">default</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
{same.length > 0 && <p className="text-xs text-muted-foreground">Same on both: {same.map((x) => `${x.row.label.toLowerCase()} ${x.va}`).join(" · ")}.</p>}
</section>
{run.resources && (
<section className="flex flex-col gap-3">
<h3 className="text-base font-semibold">Resources</h3>
<BenchmarkResources stats={run.resources} names={{ a: a.deploymentName, b: b.deploymentName }} />
</section>
)}
<section className="flex flex-col gap-2">
<h3 className="text-base font-semibold">Method</h3>
<div className="flex max-w-3xl flex-col gap-2 text-sm text-muted-foreground">
{abMethod(ab).map((p) => (
<p key={p}>{p}</p>
))}
</div>
</section>
<footer className="border-t pt-4 text-xs text-muted-foreground">
Generated by Kaname from a BetterBench {ab.betterbenchVersion} paired A/B{ab.corpusVersion ? ` on corpus v${ab.corpusVersion}` : ""}. Every figure is BetterBench&apos;s own.
</footer>
</article>
);
}
@@ -1,6 +1,13 @@
"use client";
import { DownloadIcon, ExternalLinkIcon, RotateCcwIcon, SquareIcon, Trash2Icon, TriangleAlertIcon } from "lucide-react";
import {
DownloadIcon,
ExternalLinkIcon,
RotateCcwIcon,
SquareIcon,
Trash2Icon,
TriangleAlertIcon,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
@@ -27,15 +34,23 @@ import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
import type { ListRow } from "../benchmark-list";
import { cancelBenchmark, deleteBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
import { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
function duration(a: string | null, b: string | null, now: number) {
if (!a) return null;
const s = Math.max(0, ((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000);
const s = Math.max(
0,
((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000,
);
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
return h ? `${h} h ${m} min` : m ? `${m} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`;
return h
? `${h} h ${m} min`
: m
? `${m} min ${Math.round(s % 60)} s`
: `${Math.round(s)} s`;
}
export function BenchmarkDetail({ initial }: { initial: ListRow }) {
@@ -49,7 +64,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
if (!active) return;
const t = setInterval(async () => {
setNow(Date.now());
const res = await fetch(`/api/benchmarks/${r.id}`, { cache: "no-store" }).catch(() => null);
const res = await fetch(`/api/benchmarks/${r.id}`, {
cache: "no-store",
}).catch(() => null);
if (res?.ok) setR(await res.json());
}, 2_000);
return () => clearInterval(t);
@@ -60,10 +77,18 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const res = await fetch("/api/benchmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ deploymentId: r.deploymentId, label: r.label, ...r.settings }),
body: JSON.stringify({
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
label: r.label,
...r.settings,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
if (!res.ok)
return toast.error(
json.error?.message ?? `Could not start (${res.status})`,
);
router.push(`/benchmarks/${json.id}`);
}
@@ -77,12 +102,28 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
<CardContent className="flex flex-wrap items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold">{r.label ?? s.deploymentName}</h1>
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
<h1 className="text-xl font-semibold">
{r.label ??
(r.kind === "ab"
? `${s.deploymentName} vs ${r.snapshotB?.deploymentName}`
: s.deploymentName)}
</h1>
{r.kind === "ab" && (
<span className="rounded-md border px-1.5 text-xs text-muted-foreground">
A/B
</span>
)}
<BenchmarkStateBadge
state={r.state}
cancelling={!!r.cancelRequestedAt}
/>
</div>
<p className="text-sm text-muted-foreground">
{r.deploymentId ? (
<Link href={`/deployments/${r.deploymentId}`} className="hover:underline">
<Link
href={`/deployments/${r.deploymentId}`}
className="hover:underline"
>
{s.deploymentName}
</Link>
) : (
@@ -97,33 +138,85 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
s.repoId
)}{" "}
· {s.runtimeName}
{r.kind === "ab" && r.snapshotB && (
<>
{" "}
· B:{" "}
{r.deploymentBId ? (
<Link
href={`/deployments/${r.deploymentBId}`}
className="hover:underline"
>
{r.snapshotB.deploymentName}
</Link>
) : (
r.snapshotB.deploymentName
)}
</>
)}
{r.sweepId && (
<>
{" "}
·{" "}
<Link
href={`/benchmarks/sweeps/${r.sweepId}`}
className="hover:underline"
>
part of a sweep
</Link>
</>
)}
</p>
<p className="text-xs text-muted-foreground">
BetterBench · {describeSettings(r.settings)} · created <LocalTime value={r.createdAt} />
{took && ` · ${r.state === "running" ? "running for" : "took"} ${took}`}
BetterBench ·{" "}
{r.kind === "ab"
? `paired A/B, target ±${r.settings.mdePct ?? 1}%, up to ${r.settings.maxPairs ?? 200} pairs`
: describeSettings(r.settings)}{" "}
· created <LocalTime value={r.createdAt} />
{took &&
` · ${r.state === "running" ? "running for" : "took"} ${took}`}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{r.hasReport && (
<a href={`/api/benchmarks/${r.id}/report`} target="_blank" rel="noreferrer" className={buttonVariants({ variant: "outline" })}>
<a
href={`/api/benchmarks/${r.id}/report`}
target="_blank"
rel="noreferrer"
className={buttonVariants({ variant: "outline" })}
>
<ExternalLinkIcon />
Full report
</a>
)}
{r.state === "completed" && (
<a href={`/api/benchmarks/${r.id}/results`} className={buttonVariants({ variant: "outline" })}>
<a
href={`/api/benchmarks/${r.id}/results`}
className={buttonVariants({ variant: "outline" })}
>
<DownloadIcon />
results.json
{r.kind === "ab" ? "ab.json" : "results.json"}
</a>
)}
{active ? (
<Button variant="outline" disabled={!!r.cancelRequestedAt} onClick={async () => (await cancelBenchmark(r.id)) && router.refresh()}>
<Button
variant="outline"
disabled={!!r.cancelRequestedAt}
onClick={async () =>
(await cancelBenchmark(r.id)) && router.refresh()
}
>
<SquareIcon />
Cancel
</Button>
) : (
r.deploymentId && (
<Button variant="outline" onClick={again} title="Queue a new run with the same settings (the deployment must be running)">
r.deploymentId &&
!r.sweepId && (
<Button
variant="outline"
onClick={again}
title="Queue a new run with the same settings (the deployment must be running)"
>
<RotateCcwIcon />
Run again
</Button>
@@ -131,7 +224,13 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
)}
<AlertDialog>
<AlertDialogTrigger
render={<Button variant="outline" disabled={r.state === "running"} className="text-destructive hover:bg-destructive/10 hover:text-destructive" />}
render={
<Button
variant="outline"
disabled={r.state === "running"}
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
/>
}
>
<Trash2Icon />
Delete
@@ -139,7 +238,9 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this benchmark?</AlertDialogTitle>
<AlertDialogDescription>Its numbers, log, results.json and HTML report are removed.</AlertDialogDescription>
<AlertDialogDescription>
Its numbers, log, results.json and HTML report are removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
@@ -164,21 +265,37 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
{r.error && (
<div className="flex gap-3 rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm">
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0 text-destructive" />
<pre className="min-w-0 flex-1 font-sans break-words whitespace-pre-wrap">{r.error}</pre>
<pre className="min-w-0 flex-1 font-sans break-words whitespace-pre-wrap">
{r.error}
</pre>
</div>
)}
{r.state === "queued" && <p className="text-sm text-muted-foreground">Waiting: benchmarks run one at a time.</p>}
{r.state === "running" && r.phase && <p className="text-sm text-muted-foreground">Now: {r.phase}</p>}
{r.state === "queued" && (
<p className="text-sm text-muted-foreground">
Waiting: benchmarks run one at a time.
</p>
)}
{r.state === "running" && r.phase && (
<p className="text-sm text-muted-foreground">Now: {r.phase}</p>
)}
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_340px]">
<div className="flex min-w-0 flex-col gap-4">
<BenchmarkReport run={r} />
<LiveLog url={`/api/benchmarks/${r.id}/logs`} title="BetterBench output" live={active} />
{r.kind === "ab" ? <AbReport run={r} /> : <BenchmarkReport run={r} />}
<LiveLog
url={`/api/benchmarks/${r.id}/logs`}
title="BetterBench output"
live={active}
/>
</div>
<aside className="flex flex-col gap-4">
{r.state === "completed" && r.summary && (
<PublishCard runId={r.id} defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`} defaultSummary={reportSummary(r)} />
{r.kind === "run" && r.state === "completed" && r.summary && (
<PublishCard
runId={r.id}
defaultTitle={r.label ?? `${s.repoId} ${weightsLabel(s)}`}
defaultSummary={reportSummary(r)}
/>
)}
<Card size="sm">
<CardHeader>
@@ -190,41 +307,52 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
maxLength={120}
placeholder="e.g. q8_0 KV cache"
onChange={(e) => setLabel(e.target.value)}
onBlur={async () => label !== (r.label ?? "") && (await renameBenchmark(r.id, label || null)) && setR({ ...r, label: label.trim() || null })}
onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
onBlur={async () =>
label !== (r.label ?? "") &&
(await renameBenchmark(r.id, label || null)) &&
setR({ ...r, label: label.trim() || null })
}
onKeyDown={(e) =>
e.key === "Enter" && (e.target as HTMLInputElement).blur()
}
/>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
{CONFIG_ROWS.map((row) => {
const v = row.value(s);
return v == null ? null : (
<div key={row.key} className="contents">
<dt className="text-muted-foreground">{row.label}</dt>
<dd className="min-w-0 font-mono break-all">{v}</dd>
</div>
);
})}
</dl>
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between text-xs text-muted-foreground">
Command
<CopyButton value={s.command} label="Copy command" />
{r.kind === "run" && (
<Card size="sm">
<CardHeader>
<CardTitle>Settings measured</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-xs">
{CONFIG_ROWS.map((row) => {
const v = row.value(s);
return v == null ? null : (
<div key={row.key} className="contents">
<dt className="text-muted-foreground">{row.label}</dt>
<dd className="min-w-0 font-mono break-all">{v}</dd>
</div>
);
})}
</dl>
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between text-xs text-muted-foreground">
Command
<CopyButton value={s.command} label="Copy command" />
</div>
<pre className="rounded-md bg-muted/60 px-2 py-1.5 font-mono text-[11px] break-all whitespace-pre-wrap">
{s.command}
</pre>
</div>
<pre className="rounded-md bg-muted/60 px-2 py-1.5 font-mono text-[11px] break-all whitespace-pre-wrap">{s.command}</pre>
</div>
{sum && (
<p className="text-[11px] text-muted-foreground">
BetterBench {sum.betterbenchVersion} · corpus v{sum.corpusVersion} · phases: {sum.phases.join(", ") || "–"}
</p>
)}
</CardContent>
</Card>
{sum && (
<p className="text-[11px] text-muted-foreground">
BetterBench {sum.betterbenchVersion} · corpus v
{sum.corpusVersion} · phases: {sum.phases.join(", ") || "–"}
</p>
)}
</CardContent>
</Card>
)}
</aside>
</div>
</div>
@@ -2,6 +2,7 @@
import { TriangleAlertIcon } from "lucide-react";
import { BarChart } from "@/components/bar-chart";
import { BenchmarkResources } from "@/components/benchmark-resources";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report";
import { configChips } from "@/lib/benchmark-view";
@@ -199,6 +200,12 @@ export function BenchmarkReport({ run }: { run: ListRow }) {
</Section>
)}
{run.resources && (
<Section title="Resources" intro="What the server used while BetterBench measured it.">
<BenchmarkResources stats={run.resources} />
</Section>
)}
<Section title="Full numbers">
{sum.single.length > 0 && (
<div className="overflow-x-auto rounded-lg ring-1 ring-foreground/10">
+1 -1
View File
@@ -20,7 +20,7 @@ export type ListRow = Omit<BenchmarkRow, "createdAt" | "startedAt" | "finishedAt
cancelRequestedAt: string | null;
};
const MAX_COMPARE = 6;
const MAX_COMPARE = 16;
const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
/** All runs with their headline numbers; polls while something is queued or running. */
+1 -1
View File
@@ -39,7 +39,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
String(ids ?? "")
.split(",")
.filter(Boolean)
.slice(0, 6),
.slice(0, 16),
);
if (runs.length < 2) {
return (
@@ -0,0 +1,13 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getSweep } from "@/lib/sweeps";
import { SweepDetail } from "./sweep-detail";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Sweep · Benchmarks" };
export default async function SweepPage({ params }: PageProps<"/benchmarks/sweeps/[id]">) {
const data = await getSweep((await params).id);
if (!data) notFound();
return <SweepDetail initial={JSON.parse(JSON.stringify(data))} />;
}
@@ -0,0 +1,234 @@
"use client";
import { GitCompareIcon, Grid3x3Icon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { BarChart } from "@/components/bar-chart";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, SweepVariant } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
type Sweep = typeof benchmarkSweeps.$inferSelect;
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null };
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
pending: "Waiting",
deploying: "Deploying",
benchmarking: "Benchmarking",
done: "Done",
failed: "Failed",
skipped: "Skipped",
};
type Row = {
v: SweepVariant;
run: Run | null;
decode: number | null;
ttft: number | null;
prefill: number | null;
peak: number | null;
cpu: number | null;
ram: number | null;
vram: number | null;
};
function rowsOf(data: SweepData): Row[] {
return data.sweep.variants.map((v) => {
const run = data.runs.find((r) => r.id === v.runId) ?? null;
const h = headline(run?.summary ?? null);
const c = run?.resources?.containers.find((x) => x.side === "a");
const g = run?.resources?.gpus ?? [];
return {
v,
run,
decode: h.decode,
ttft: h.ttftMs,
prefill: h.prefill?.tps ?? null,
peak: h.peak?.tps ?? null,
cpu: c?.cpuAvg ?? null,
ram: c?.memPeakBytes ?? null,
vram: g.length ? g.reduce((s, x) => s + x.vramPeakMb, 0) : null,
};
});
}
/** Best value per column (higher or lower is better), to set it in bold. */
function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
if (vals.length < 2) return null;
return higher ? Math.max(...vals) : Math.min(...vals);
}
export function SweepDetail({ initial }: { initial: SweepData }) {
const router = useRouter();
const [data, setData] = useState(initial);
const [busy, setBusy] = useState(false);
const { sweep } = data;
const active = sweep.state === "queued" || sweep.state === "running";
useEffect(() => {
if (!active) return;
const t = setInterval(async () => {
const res = await fetch(`/api/sweeps/${sweep.id}`, { cache: "no-store" }).catch(() => null);
if (res?.ok) setData(await res.json());
}, 3_000);
return () => clearInterval(t);
}, [sweep.id, active]);
async function act(path: string, method: string, done: () => void) {
setBusy(true);
try {
const res = await fetch(path, { method });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Failed (${res.status})`);
done();
} finally {
setBusy(false);
}
}
const rows = rowsOf(data);
const finished = rows.filter((r) => r.decode != null);
const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
const bestOf = {
decode: best(rows, "decode", true),
ttft: best(rows, "ttft", false),
prefill: best(rows, "prefill", true),
peak: best(rows, "peak", true),
cpu: best(rows, "cpu", false),
ram: best(rows, "ram", false),
vram: best(rows, "vram", false),
};
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
);
const done = rows.filter((r) => r.v.state === "done" || r.v.state === "failed" || r.v.state === "skipped").length;
return (
<div className="flex flex-col gap-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="flex flex-col gap-1">
<h1 className="flex items-center gap-2 text-xl font-semibold">
<Grid3x3Icon className="size-5 text-muted-foreground" />
{sweep.label ?? `Sweep of ${sweep.base.name}`}
</h1>
<p className="text-sm text-muted-foreground">
{sweep.params.map((p) => p.key).join(" × ")} · {rows.length} variants · {describeSettings(sweep.settings)} ·{" "}
{sweep.baseDeploymentId ? (
<Link href={`/deployments/${sweep.baseDeploymentId}`} className="underline">
{sweep.base.name}
</Link>
) : (
sweep.base.name
)}
</p>
</div>
<div className="flex items-center gap-2">
<BenchmarkStateBadge state={sweep.state} cancelling={!!sweep.cancelRequestedAt && active} />
{runIds.length >= 2 && (
<Link href={`/benchmarks/compare?ids=${runIds.join(",")}`} className={buttonVariants({ variant: "outline", size: "sm" })}>
<GitCompareIcon />
Compare in detail
</Link>
)}
{active ? (
<Button variant="outline" size="sm" disabled={busy || !!sweep.cancelRequestedAt} onClick={() => act(`/api/sweeps/${sweep.id}/cancel`, "POST", () => router.refresh())}>
<SquareIcon />
Cancel
</Button>
) : (
<Button variant="outline" size="sm" disabled={busy} onClick={() => act(`/api/sweeps/${sweep.id}`, "DELETE", () => router.push("/benchmarks"))}>
<Trash2Icon />
Delete
</Button>
)}
</div>
</div>
{active && (
<p className="text-sm text-muted-foreground">
{done} of {rows.length} variants finished. Each variant is deployed, benchmarked and removed again, one after another.
</p>
)}
{sweep.error && <p className="text-sm text-destructive">{sweep.error}</p>}
{finished.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Generation speed by variant</CardTitle>
<CardDescription>Single-stream decode, tokens per second (BetterBench combined score). Higher is better.</CardDescription>
</CardHeader>
<CardContent>
<BarChart
axisLabel="Decode t/s"
rows={finished.map((r) => ({
label: r.v.label,
value: r.decode,
valueLabel: r.decode!.toFixed(1),
details: [r.ttft != null ? `TTFT ${r.ttft.toFixed(0)} ms` : "", r.ram != null ? `Peak RAM ${formatBytes(r.ram)}` : ""].filter(Boolean),
}))}
/>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Variants</CardTitle>
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
</CardHeader>
<CardContent className="overflow-x-auto px-0">
<table className="w-full text-sm">
<thead className="text-xs text-muted-foreground">
<tr className="border-b">
<th className="px-3 py-2 text-left font-medium">Variant</th>
<th className="px-3 py-2 text-left font-medium">State</th>
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
<th className="px-3 py-2 text-right font-medium">Peak t/s</th>
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.v.index} className="border-b last:border-0">
<td className="px-3 py-2 font-mono text-xs">
{r.v.runId ? (
<Link href={`/benchmarks/${r.v.runId}`} className="underline-offset-2 hover:underline">
{r.v.label}
</Link>
) : (
r.v.label
)}
</td>
<td className="px-3 py-2 text-xs text-muted-foreground" title={r.v.error ?? r.run?.error ?? undefined}>
{VARIANT_STATE[r.v.state]}
{r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
{(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
</td>
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
{cell(r.peak, bestOf.peak, (x) => x.toFixed(1))}
{cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
{cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
{cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
</tr>
))}
</tbody>
</table>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,36 @@
import type { Metadata } from "next";
import { listDeployableModels, listDeployments } from "@/lib/deployments";
import { SweepForm, type SweepBase } from "./sweep-form";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "New sweep" };
export default async function NewSweepPage({ searchParams }: PageProps<"/benchmarks/sweeps/new">) {
const { deployment } = await searchParams;
const [deployments, models] = await Promise.all([listDeployments(), listDeployableModels()]);
const bases: SweepBase[] = deployments
.filter((d) => !d.sweepId)
.map((d) => ({
id: d.id,
name: d.name,
engine: d.engine,
accelerator: d.accelerator,
repoId: d.repoId,
options: d.options,
cpus: d.cpus,
memoryMb: d.memoryMb,
ggufFiles: models.find((m) => m.id === d.modelId)?.candidates.gguf.map((g) => g.path) ?? [],
}));
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-semibold">New sweep</h1>
<p className="max-w-3xl text-sm text-muted-foreground">
Vary one or two settings of a deployment. Kaname deploys each variant in turn, benchmarks it with BetterBench, removes it again and compares all of them,
including the resources each one used.
</p>
</div>
<SweepForm bases={bases} initialBaseId={typeof deployment === "string" ? deployment : undefined} />
</div>
);
}
@@ -0,0 +1,248 @@
"use client";
import { Grid3x3Icon, PlusIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { BenchmarkPhase, DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
import { quantGroup } from "@/lib/selection";
import { expandSweep, MAX_SWEEP_VARIANTS, splitValues, SweepError, sweepKeysFor } from "@/lib/sweep";
export type SweepBase = {
id: string;
name: string;
engine: RuntimeEngine;
accelerator: RuntimeAccelerator;
repoId: string;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
ggufFiles: string[];
};
const PHASES: { id: BenchmarkPhase; label: string }[] = [
{ id: "decode", label: "Generation" },
{ id: "prefill", label: "Prompt processing" },
{ id: "concurrency", label: "Parallel requests" },
];
/** The base's current value of a sweep key, shown as a hint. */
function currentValue(base: SweepBase, key: string): string {
const o = base.options;
const v: Record<string, unknown> = {
contextSize: o.contextSize,
modelFile: o.modelFile,
kvCache: o.cacheTypeK ?? "f16",
threads: o.threads ?? "auto",
parallel: o.parallel ?? "auto",
batchSize: o.batchSize ?? "default",
ubatchSize: o.ubatchSize ?? "default",
flashAttn: o.flashAttn ?? "auto",
cacheRamMb: o.cacheRamMb ?? "8192 (default)",
gpuLayers: o.gpuLayers ?? "auto",
dtype: o.dtype ?? "runtime default",
maxNumSeqs: o.maxNumSeqs ?? "default",
kvCacheGb: o.kvCacheGb ?? "runtime default",
gpuMemoryUtilization: o.gpuMemoryUtilization ?? "0.9",
cpus: base.cpus ?? "no limit",
};
return String(v[key] ?? "");
}
type Param = { key: string; text: string; files: string[] };
export function SweepForm({ bases, initialBaseId }: { bases: SweepBase[]; initialBaseId?: string }) {
const router = useRouter();
const [baseId, setBaseId] = useState(initialBaseId && bases.some((b) => b.id === initialBaseId) ? initialBaseId : (bases[0]?.id ?? ""));
const base = bases.find((b) => b.id === baseId) ?? null;
const keys = base ? sweepKeysFor(base.engine, base.accelerator) : [];
const [params, setParams] = useState<Param[]>([{ key: "contextSize", text: "", files: [] }]);
const [label, setLabel] = useState("");
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [busy, setBusy] = useState(false);
const values = (p: Param) => (p.key === "modelFile" ? p.files : splitValues(p.text));
let preview: { variants: ReturnType<typeof expandSweep> | null; error: string | null } = { variants: null, error: null };
if (base) {
try {
preview = { variants: expandSweep(params.map((p) => ({ key: p.key, values: values(p) })), base.engine, base.accelerator, { modelFiles: base.ggufFiles }), error: null };
} catch (err) {
preview = { variants: null, error: err instanceof SweepError ? err.message : String(err) };
}
}
const setParam = (i: number, patch: Partial<Param>) => setParams((ps) => ps.map((p, j) => (j === i ? { ...p, ...patch } : p)));
async function submit() {
if (!base || !preview.variants) return;
setBusy(true);
try {
const res = await fetch("/api/sweeps", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
baseDeploymentId: base.id,
label: label.trim() || null,
params: params.map((p) => ({ key: p.key, values: values(p) })),
quick: mode === "quick",
passes: mode === "custom" ? Number(passes) || 10 : null,
phases: phases.length === PHASES.length ? [] : phases,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
router.push(`/benchmarks/sweeps/${json.id}`);
} finally {
setBusy(false);
}
}
if (bases.length === 0) return <p className="text-sm text-muted-foreground">Create a deployment first; a sweep varies its settings.</p>;
return (
<div className="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="flex flex-col gap-4">
<Card>
<CardHeader>
<CardTitle>Base deployment</CardTitle>
<CardDescription>Every variant starts from its settings. It doesn&apos;t need to be running.</CardDescription>
</CardHeader>
<CardContent>
<NativeSelect value={baseId} onChange={(e) => setBaseId(e.target.value)} aria-label="Base deployment">
{bases.map((b) => (
<option key={b.id} value={b.id}>
{b.name} · {b.repoId}
</option>
))}
</NativeSelect>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>What to vary</CardTitle>
<CardDescription>One or two settings; every combination becomes a variant (up to {MAX_SWEEP_VARIANTS}).</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{base &&
params.map((p, i) => {
const def = keys.find((k) => k.key === p.key);
return (
<div key={i} className="flex flex-col gap-2 rounded-lg border px-3 py-3">
<div className="flex items-center gap-2">
<NativeSelect value={p.key} onChange={(e) => setParam(i, { key: e.target.value, text: "", files: [] })} aria-label={`Setting ${i + 1}`}>
{keys
.filter((k) => k.key === p.key || !params.some((q) => q.key === k.key))
.map((k) => (
<option key={k.key} value={k.key}>
{k.label}
</option>
))}
</NativeSelect>
{params.length > 1 && (
<Button variant="ghost" size="icon-sm" aria-label="Remove setting" onClick={() => setParams((ps) => ps.filter((_, j) => j !== i))}>
<XIcon />
</Button>
)}
</div>
{p.key === "modelFile" ? (
<div className="flex flex-col gap-1">
{base.ggufFiles.map((f) => (
<label key={f} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={p.files.includes(f)} onCheckedChange={(v) => setParam(i, { files: v ? [...p.files, f] : p.files.filter((x) => x !== f) })} />
<span className="font-mono text-xs">{quantGroup(f) ?? f}</span>
</label>
))}
{base.ggufFiles.length < 2 && <p className="text-xs text-muted-foreground">Only one GGUF file is downloaded; download more quants to compare them.</p>}
</div>
) : (
<Input value={p.text} onChange={(e) => setParam(i, { text: e.target.value })} placeholder={def?.hint} aria-label="Values" className="font-mono text-sm" />
)}
<p className="text-xs text-muted-foreground">Base value: {currentValue(base, p.key)}</p>
</div>
);
})}
{params.length < 2 && base && (
<Button
variant="outline"
size="sm"
className="self-start"
onClick={() => setParams((ps) => [...ps, { key: keys.find((k) => !ps.some((q) => q.key === k.key))?.key ?? "threads", text: "", files: [] }])}
>
<PlusIcon />
Vary a second setting
</Button>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Benchmark per variant</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && <Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes" />}
</div>
<div className="flex flex-wrap gap-4">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-center gap-2 text-sm">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} />
{p.label}
</label>
))}
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="sw-label">Label</Label>
<Input id="sw-label" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={80} placeholder="e.g. context vs KV cache (optional)" />
</div>
</CardContent>
</Card>
</div>
<Card className="lg:sticky lg:top-4">
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<Grid3x3Icon className="size-4 text-muted-foreground" />
{preview.variants ? `${preview.variants.length} variants` : "Variants"}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
{preview.error ? (
<p className="text-xs text-muted-foreground">{preview.error}</p>
) : (
<ol className="flex flex-col gap-1">
{preview.variants?.map((v) => (
<li key={v.index} className="flex gap-2 text-xs">
<span className="w-5 text-right text-muted-foreground tabular-nums">{v.index + 1}</span>
<span className="font-mono">{v.label}</span>
</li>
))}
</ol>
)}
<p className="text-xs text-muted-foreground">
Variants run one after another, each in its own temporary deployment{base?.memoryMb ? " (memory limit: the base's, raised where a variant needs more)" : ""}.
{mode !== "quick" && " Full runs on a CPU can take hours per variant."}
</p>
<Button onClick={submit} disabled={!preview.variants || busy || phases.length === 0}>
<Grid3x3Icon />
Start sweep
</Button>
</CardContent>
</Card>
</div>
);
}
+165 -50
View File
@@ -1,18 +1,20 @@
"use client";
import { GaugeIcon } from "lucide-react";
import { GaugeIcon, GitCompareArrowsIcon, Grid3x3Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button } from "@/components/ui/button";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select";
import { abHeadline } from "@/lib/ab-report";
import { headline } from "@/lib/benchmark-view";
import type { BenchmarkPhase } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
import type { ListRow } from "../../benchmarks/benchmark-list";
const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
@@ -21,15 +23,23 @@ const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
{ id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
];
/** Start a BetterBench run against this deployment and list its recent runs. */
export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId: string; running: boolean; initial: ListRow[] }) {
type Mode = "run" | "ab" | "sweep";
type Peer = { id: string; name: string; state: string; modelId: string };
/** Benchmark this deployment: a single run, a paired A/B against another one, or a sweep. */
export function BenchmarkCard({ deploymentId, modelId, running, initial }: { deploymentId: string; modelId: string; running: boolean; initial: ListRow[] }) {
const router = useRouter();
const [tab, setTab] = useState<Mode>("run");
const [mode, setMode] = useState("quick");
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [label, setLabel] = useState("");
const [busy, setBusy] = useState(false);
const [runs, setRuns] = useState(initial);
const [peers, setPeers] = useState<Peer[] | null>(null);
const [peerId, setPeerId] = useState("");
const [mde, setMde] = useState("1");
const [maxPairs, setMaxPairs] = useState("200");
const active = runs.some((r) => r.state === "queued" || r.state === "running");
useEffect(() => {
@@ -43,21 +53,27 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId
return () => clearInterval(t);
}, [deploymentId, active]);
async function start() {
// Other deployments of the same model (A/B partners).
useEffect(() => {
if (tab !== "ab") return;
let stop = false;
void fetch("/api/deployments", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : []))
.then((rows: Peer[]) => {
if (stop) return;
const list = rows.filter((p) => p.modelId === modelId && p.id !== deploymentId);
setPeers(list);
setPeerId((cur) => cur || list.find((p) => p.state === "running")?.id || "");
});
return () => {
stop = true;
};
}, [tab, modelId, deploymentId]);
async function start(body: Record<string, unknown>) {
setBusy(true);
try {
const res = await fetch("/api/benchmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
deploymentId,
label: label.trim() || null,
quick: mode === "quick",
passes: mode === "custom" ? Number(passes) || 10 : null,
// All three selected means "everything" (BetterBench's default).
phases: phases.length === PHASES.length ? [] : phases,
}),
});
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, ...body }) });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
router.push(`/benchmarks/${json.id}`);
@@ -66,6 +82,13 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId
}
}
const peer = peers?.find((p) => p.id === peerId);
const TABS: { id: Mode; label: string; icon: typeof GaugeIcon }[] = [
{ id: "run", label: "Run", icon: GaugeIcon },
{ id: "ab", label: "A/B", icon: GitCompareArrowsIcon },
{ id: "sweep", label: "Sweep", icon: Grid3x3Icon },
];
return (
<Card size="sm">
<CardHeader>
@@ -75,39 +98,128 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3 text-sm">
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && (
<Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
)}
</div>
<div className="flex flex-col gap-1.5">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-start gap-2">
<Checkbox
checked={phases.includes(p.id)}
onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))}
className="mt-0.5"
/>
<span className="flex flex-col">
<span>{p.label}</span>
<span className="text-xs text-muted-foreground">{p.hint}</span>
</span>
</label>
<div className="inline-flex self-start rounded-lg bg-muted p-1" role="tablist">
{TABS.map((t) => (
<button
key={t.id}
type="button"
role="tab"
aria-selected={tab === t.id}
onClick={() => setTab(t.id)}
className={cn("flex items-center gap-1 rounded-md px-2.5 py-1 text-xs", tab === t.id ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground")}
>
<t.icon className="size-3.5" />
{t.label}
</button>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button onClick={start} disabled={!running || busy || phases.length === 0}>
<GaugeIcon />
Run benchmark
</Button>
<p className="text-xs text-muted-foreground">
{running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
</p>
{tab === "run" && (
<>
<div className="grid grid-cols-[1fr_auto] items-center gap-2">
<NativeSelect value={mode} onChange={(e) => setMode(e.target.value)} aria-label="Run length">
<option value="quick">Quick: 5 passes (smoke test)</option>
<option value="full">Full: 20 passes (comparable)</option>
<option value="custom">Custom number of passes</option>
</NativeSelect>
{mode === "custom" && (
<Input value={passes} onChange={(e) => setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
)}
</div>
<div className="flex flex-col gap-1.5">
{PHASES.map((p) => (
<label key={p.id} className="flex cursor-pointer items-start gap-2">
<Checkbox checked={phases.includes(p.id)} onCheckedChange={(v) => setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))} className="mt-0.5" />
<span className="flex flex-col">
<span>{p.label}</span>
<span className="text-xs text-muted-foreground">{p.hint}</span>
</span>
</label>
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Button
onClick={() =>
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
}
disabled={!running || busy || phases.length === 0}
>
<GaugeIcon />
Run benchmark
</Button>
<p className="text-xs text-muted-foreground">
{running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
</p>
</>
)}
{tab === "ab" && (
<>
<p className="text-xs text-muted-foreground">
Paired A/B: the same prompts go to this deployment (A) and another one of the same model (B), alternating, until the difference is known to ±the target. Both
must be running and fit in memory together.
</p>
{peers === null ? (
<p className="text-xs text-muted-foreground">Loading…</p>
) : peers.length === 0 ? (
<p className="text-xs text-muted-foreground">
No other deployment of this model. Create one with the setting you want to compare (e.g. a different KV cache type), or run a sweep.
</p>
) : (
<>
<NativeSelect value={peerId} onChange={(e) => setPeerId(e.target.value)} aria-label="Deployment B">
<option value="">Choose B…</option>
{peers.map((p) => (
<option key={p.id} value={p.id}>
{p.name} {p.state !== "running" ? `(${p.state})` : ""}
</option>
))}
</NativeSelect>
{peer && peer.state !== "running" && (
<p className="text-xs text-amber-700 dark:text-amber-300">
{peer.name} isn&apos;t running.{" "}
<Link href={`/deployments/${peer.id}`} className="underline">
Start it
</Link>{" "}
first.
</p>
)}
<div className="grid grid-cols-2 gap-2">
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Target precision (±%)</span>
<Input value={mde} onChange={(e) => setMde(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" />
</label>
<label className="flex flex-col gap-1 text-xs">
<span className="text-muted-foreground">Max pairs</span>
<Input value={maxPairs} onChange={(e) => setMaxPairs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</label>
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
<Button
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
disabled={!running || busy || !peer || peer.state !== "running"}
>
<GitCompareArrowsIcon />
Start A/B
</Button>
</>
)}
{!running && <p className="text-xs text-muted-foreground">Start this deployment (A) first.</p>}
</>
)}
{tab === "sweep" && (
<>
<p className="text-xs text-muted-foreground">
Vary one or two settings (context size, KV cache type, threads, quant, GPU layers, …). Kaname deploys each variant in turn, benchmarks it, removes it again, and
compares all of them. This deployment doesn&apos;t need to run.
</p>
<Link href={`/benchmarks/sweeps/new?deployment=${deploymentId}`} className={buttonVariants()}>
<Grid3x3Icon />
Set up a sweep
</Link>
</>
)}
{runs.length > 0 && (
<div className="flex flex-col gap-1 border-t pt-3">
@@ -115,9 +227,12 @@ export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId
const h = headline(r.summary);
return (
<Link key={r.id} href={`/benchmarks/${r.id}`} className="flex items-center justify-between gap-2 rounded-md px-1.5 py-1 hover:bg-muted">
<span className="min-w-0 truncate">{r.label ?? new Date(r.createdAt).toLocaleString()}</span>
<span className="min-w-0 truncate">
{r.kind === "ab" && <span className="mr-1 rounded border px-1 text-[10px] text-muted-foreground">A/B</span>}
{r.label ?? new Date(r.createdAt).toLocaleString()}
</span>
<span className="flex shrink-0 items-center gap-2 text-xs text-muted-foreground tabular-nums">
{h.decode != null && `${h.decode.toFixed(1)} t/s`}
{r.kind === "ab" ? r.ab && abHeadline(r.ab.decode_tps) : h.decode != null && `${h.decode.toFixed(1)} t/s`}
<BenchmarkStateBadge state={r.state} cancelling={!!r.cancelRequestedAt} />
</span>
</Link>
@@ -194,7 +194,7 @@ export function DeploymentDetail({ initial, benchmarks }: { initial: Deployment;
<div className="flex flex-col gap-4">
<Chat id={d.id} running={d.state === "running"} />
<BenchmarkCard deploymentId={d.id} running={d.state === "running"} initial={benchmarks} />
<BenchmarkCard deploymentId={d.id} modelId={d.modelId} running={d.state === "running"} initial={benchmarks} />
<Card size="sm">
<CardHeader>
<CardTitle>Endpoint</CardTitle>
+8 -4
View File
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { AB_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { getBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
@@ -11,15 +11,19 @@ export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/benchmarks/[id]/results">>(async (_req, { params }) => {
const run = await getBenchmark((await params).id);
if (!run) return apiError(404, "not_found", "Benchmark not found.");
const raw = await readFile(join(runDir(run.id), RESULTS_FILE), "utf8").catch(() => null);
const ab = run.kind === "ab";
const raw = await readFile(join(runDir(run.id), ab ? AB_FILE : RESULTS_FILE), "utf8").catch(() => null);
if (!raw) return apiError(404, "not_found", "This run has no results file.");
// Like launch80's L80 CLI: the endpoint URL and host name never leave the machine.
const data = JSON.parse(raw) as { env?: Record<string, unknown> };
const data = JSON.parse(raw) as { env?: Record<string, unknown>; endpoint_a?: unknown; endpoint_b?: unknown };
if (data.env) {
delete data.env.endpoint;
delete data.env.endpoint_b;
delete data.env.host;
}
delete data.endpoint_a;
delete data.endpoint_b;
const json = JSON.stringify(data, null, 2);
const name = `betterbench-${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
const name = `betterbench-${ab ? "ab-" : ""}${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
});
+14
View File
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { cancelSweep, SweepRequestError } from "@/lib/sweeps";
export const POST = withAuth<RouteContext<"/api/sweeps/[id]/cancel">>(async (_req, { params }) => {
try {
await cancelSweep((await params).id);
return new NextResponse(null, { status: 202 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { deleteSweep, getSweep, SweepRequestError } from "@/lib/sweeps";
export const dynamic = "force-dynamic";
export const GET = withAuth<RouteContext<"/api/sweeps/[id]">>(async (_req, { params }) => {
const s = await getSweep((await params).id);
return s ? NextResponse.json(s) : apiError(404, "not_found", "Sweep not found.");
});
export const DELETE = withAuth<RouteContext<"/api/sweeps/[id]">>(async (_req, { params }) => {
try {
await deleteSweep((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+18
View File
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createSweep, listSweeps, SweepBody, SweepRequestError } from "@/lib/sweeps";
export const dynamic = "force-dynamic";
export const GET = withAuth(async () => NextResponse.json(await listSweeps()));
/** Queue a sweep: one or two settings varied over a base deployment, one benchmark per variant. */
export const POST = withAuth(async (req) => {
try {
return NextResponse.json(await createSweep(SweepBody.parse(await req.json())), { status: 201 });
} catch (err) {
if (err instanceof SweepRequestError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+58
View File
@@ -0,0 +1,58 @@
import type { ResourceStats } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1));
function Cell({ label, value, note }: { label: string; value: string; note?: string }) {
return (
<div className="flex flex-col gap-0.5 rounded-lg bg-muted/50 px-3 py-2">
<span className="text-[11px] tracking-wide text-muted-foreground uppercase">{label}</span>
<span className="text-lg font-semibold">{value}</span>
{note && <span className="text-[11px] text-muted-foreground">{note}</span>}
</div>
);
}
/** Resource use sampled during a run: per deployment (A/B: both sides) and per GPU. */
export function BenchmarkResources({ stats, names }: { stats: ResourceStats; names?: { a: string; b?: string } }) {
if (stats.samples === 0 && stats.gpus.length === 0) return <p className="text-sm text-muted-foreground">No resource samples were recorded.</p>;
const multi = stats.containers.length > 1;
return (
<div className="flex flex-col gap-3">
{stats.containers.map((c) => (
<div key={c.side} className="flex flex-col gap-1.5">
{multi && <span className="text-xs font-medium">{c.side === "a" ? `A · ${names?.a ?? ""}` : `B · ${names?.b ?? ""}`}</span>}
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="CPU, average" value={`${cores(c.cpuAvg)} cores`} note={`peak ${cores(c.cpuPeak)} cores`} />
<Cell
label="RAM, peak"
value={c.memPeakBytes != null ? formatBytes(c.memPeakBytes) : "—"}
note={`average ${c.memAvgBytes != null ? formatBytes(c.memAvgBytes) : "—"}${c.memLimitBytes ? ` · limit ${formatBytes(c.memLimitBytes)}` : ""}`}
/>
{c.memPeakBytes != null && c.memLimitBytes ? (
<Cell label="Of the limit" value={`${Math.round((c.memPeakBytes / c.memLimitBytes) * 100)}%`} note="peak RAM ÷ memory limit" />
) : (
<Cell label="Of the limit" value="—" note="no memory limit set" />
)}
</div>
</div>
))}
{stats.gpus.map((g) => (
<div key={g.index} className="flex flex-col gap-1.5">
<span className="text-xs font-medium">
GPU {g.index} · {g.name}
</span>
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="VRAM, peak" value={formatBytes(g.vramPeakMb * 2 ** 20)} note={`of ${formatBytes(g.vramTotalMb * 2 ** 20)} · average ${formatBytes(g.vramAvgMb * 2 ** 20)}`} />
<Cell label="Utilization" value={`${Math.round(g.utilAvg)}%`} note={`average · peak ${Math.round(g.utilPeak)}%`} />
<Cell label="Power" value={g.powerAvgW != null ? `${Math.round(g.powerAvgW)} W` : "—"} note={g.powerPeakW != null ? `average · peak ${Math.round(g.powerPeakW)} W` : undefined} />
</div>
</div>
))}
<p className="text-[11px] text-muted-foreground">
Sampled every ~2 s over {stats.seconds} s ({stats.samples} samples). RAM is the container&apos;s usage without page cache, like <code>docker stats</code>; GPU
figures are for the whole GPU, so other work on it counts too.
</p>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { abCaveats, abHeadline, abMethod, abSummaryText, halfWidth } from "./ab-report";
import type { AbSummary, PairedResult } from "./db/schema";
const r = (p: Partial<PairedResult>): PairedResult => ({
metric: "decode_tps",
n_pairs: 12,
mean_a: 115,
mean_b: 120,
mean_diff: 5,
pct_diff: 4.37,
ci_low_pct: 3.24,
ci_high_pct: 5.5,
conf: 0.95,
significant: true,
verdict: "B is 4.37% faster — SIGNIFICANT",
higher_is_better: true,
...p,
});
const ab: AbSummary = {
pairs: 12,
decode_tps: r({}),
gap_median: { ...r({ metric: "update_gap_median_ms", pct_diff: -4.6, ci_low_pct: -5.8, ci_high_pct: -3.4, higher_is_better: false }), batched: false },
paired_cv: 0.0178,
pairs_needed_for_mde: 7,
target_mde_pct: 2,
conf: 0.95,
maxPairs: 24,
raw: { a_tps: [], b_tps: [] },
betterbenchVersion: "0.6.1",
corpusVersion: "1.0",
timestamp: null,
config: { greedy: true, temperature: 0.7, warmup: 3, unique_nonce: true, ab_min_pairs: 12 },
};
describe("A/B report text", () => {
it("states the result as BetterBench does", () => {
assert.equal(abHeadline(ab.decode_tps), "B is 4.37% faster");
assert.equal(abHeadline(ab.gap_median), "B is 4.60% faster");
assert.equal(abHeadline(r({ significant: false, pct_diff: 0.3 })), "No measurable difference");
assert.equal(abHeadline(r({ pct_diff: -2 })), "B is 2.00% slower");
assert.ok(Math.abs(halfWidth(ab.decode_tps) - 1.13) < 1e-9);
assert.equal(abSummaryText(ab, "4 threads", "8 threads"), "8 threads (B) against 4 threads (A), 12 interleaved pairs: decode +4.37% (95% CI +3.24% to +5.50%), significant.");
});
it("flags imprecise and inconclusive results", () => {
assert.deepEqual(abCaveats(ab), []);
const wide = { ...ab, pairs: 24, decode_tps: r({ ci_low_pct: -1, ci_high_pct: 5, significant: false }), pairs_needed_for_mde: 90 };
const c = abCaveats(wide);
assert.match(c[0], /±3\.00%, wider than the 2% target: the run stopped at the 24-pair limit first\. About 90 pairs/);
assert.match(c[1], /can't be told apart/);
assert.match(abMethod(ab).join(" "), /narrower than ±2% \(after at least 12 pairs\), or after 24 pairs/);
});
});
+43
View File
@@ -0,0 +1,43 @@
// Text for a paired A/B report (betterbench ab). Every figure is one BetterBench reported. Pure.
import type { AbSummary, PairedResult } from "@/lib/db/schema";
export const halfWidth = (r: PairedResult) => (r.ci_high_pct - r.ci_low_pct) / 2;
const pct = (v: number) => `${v > 0 ? "+" : ""}${v.toFixed(2)}%`;
/** "B is 4.37% faster" / "No measurable difference" — the headline, from BetterBench's verdict. */
export function abHeadline(r: PairedResult): string {
if (!r.significant) return "No measurable difference";
const better = r.higher_is_better ? r.pct_diff > 0 : r.pct_diff < 0;
return `B is ${Math.abs(r.pct_diff).toFixed(2)}% ${better ? "faster" : "slower"}`;
}
export function abCaveats(ab: AbSummary): string[] {
const out: string[] = [];
const min = ab.config.ab_min_pairs ?? 12;
const hw = halfWidth(ab.decode_tps);
if (ab.pairs < min) out.push(`Only ${ab.pairs} pairs survived (BetterBench's minimum is ${min}); a pair counts only when both calls succeed. Treat the result as indicative.`);
if (hw > ab.target_mde_pct) {
out.push(
`The 95% interval is ±${hw.toFixed(2)}%, wider than the ${ab.target_mde_pct}% target: the run ${ab.maxPairs && ab.pairs >= ab.maxPairs ? `stopped at the ${ab.maxPairs}-pair limit` : "ended"} first. About ${ab.pairs_needed_for_mde} pairs would be needed; differences smaller than ±${hw.toFixed(1)}% can't be told apart here.`,
);
}
if (!ab.decode_tps.significant) out.push("The interval includes zero: A and B can't be told apart at this precision. That is a result, not a failure.");
if (ab.gap_median.batched) out.push("At least one side streamed several tokens per update (speculative or batched decoding), so smoothness is compared as the stream-update gap, not per-token latency.");
return out;
}
export function abMethod(ab: AbSummary): string[] {
const c = ab.config;
return [
`Paired A/B with BetterBench ${ab.betterbenchVersion}${ab.corpusVersion ? `, corpus v${ab.corpusVersion}` : ""}: the same prompt goes to A and B back to back, the order alternating every pair, so drift (heat, caches, background load) hits both sides equally.`,
`${c.greedy ? "Greedy decoding (identical token counts on both sides)" : `Sampled decoding${c.temperature != null ? `, temperature ${c.temperature}` : ""}`}, ${c.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (a unique nonce per pair)"}${c.warmup != null ? `, ${c.warmup} warmup pairs` : ""}.`,
`It stops once the ${Math.round(ab.conf * 100)}% confidence interval of the decode difference is narrower than ±${ab.target_mde_pct}% (after at least ${c.ab_min_pairs ?? 12} pairs)${ab.maxPairs ? `, or after ${ab.maxPairs} pairs` : ""}. The interval is a paired t-interval on the per-pair differences; a difference is significant when it excludes zero.`,
`Decode is tokens per second per request (higher is better); smoothness is the median gap between streamed updates in ms (lower is better). Paired CV ${(ab.paired_cv * 100).toFixed(2)}%: how much the per-pair difference varies.`,
];
}
export function abSummaryText(ab: AbSummary, a: string, b: string): string {
const d = ab.decode_tps;
return `${b} (B) against ${a} (A), ${ab.pairs} interleaved pairs: decode ${pct(d.pct_diff)} (95% CI ${pct(d.ci_low_pct)} to ${pct(d.ci_high_pct)}), ${d.significant ? "significant" : "within noise"}.`;
}
+1
View File
@@ -21,3 +21,4 @@ export function runDir(runId: string): string {
export const RESULTS_FILE = "results.json";
export const REPORT_FILE = "results.html";
export const AB_FILE = "ab.json";
+62
View File
@@ -0,0 +1,62 @@
// What a benchmark run records about the deployment it measures. Shared by the web app and the worker
// (sweeps create runs there), so no "server-only" here.
import { and, eq, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */
async function hostFacts(uuids: string[] | null, nvidia: boolean) {
const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
const h = ws?.docker;
const gpus = h?.gpus ?? [];
return {
gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [],
host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null },
};
}
/** The deployment as it is now; null when it doesn't exist (or is being deleted). */
export async function deploymentSnapshot(deploymentId: string): Promise<{ id: string; modelId: string; state: string; snapshot: BenchmarkSnapshot } | null> {
const [d] = await db()
.select({
id: deployments.id,
name: deployments.name,
state: deployments.state,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
command: deployments.command,
imageId: deployments.imageId,
modelId: deployments.modelId,
repoId: models.repoId,
runtimeName: runtimes.name,
engine: runtimes.engine,
accelerator: runtimes.accelerator,
image: runtimes.image,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(and(eq(deployments.id, deploymentId), isNull(deployments.deleteRequestedAt)));
if (!d) return null;
return {
id: d.id,
modelId: d.modelId,
state: d.state,
snapshot: {
deploymentName: d.name,
repoId: d.repoId,
runtimeName: d.runtimeName,
engine: d.engine,
accelerator: d.accelerator,
...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")),
image: d.image,
imageId: d.imageId,
options: d.options,
cpus: d.cpus,
memoryMb: d.memoryMb,
command: [d.image, ...(d.command ?? [])].join(" "),
},
};
}
+49 -55
View File
@@ -1,10 +1,11 @@
import "server-only";
import { rm } from "node:fs/promises";
import { and, asc, desc, eq, gt, inArray, isNull } from "drizzle-orm";
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm";
import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns } from "@/lib/db/schema";
export class BenchmarkError extends Error {
constructor(
@@ -24,68 +25,55 @@ export const BenchmarkBody = z.object({
warmup: z.number().int().min(0).max(50).nullable().optional(),
/** Empty: all phases. */
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
/** A/B: the second deployment (B), the target minimum detectable effect in % and the pair ceiling. */
deploymentBId: z.string().min(1).nullable().optional(),
mdePct: z.number().min(0.1).max(50).nullable().optional(),
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
/** Set by sweeps. */
sweepId: z.string().nullable().optional(),
});
export type BenchmarkInput = z.infer<typeof BenchmarkBody>;
/** Names of the GPUs a deployment uses (all detected ones when none are picked). */
async function hostFacts(uuids: string[] | null, nvidia: boolean) {
const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
const h = ws?.docker;
const gpus = h?.gpus ?? [];
return {
gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [],
host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null },
};
/** A running deployment as it is now: what a run measures and records. */
async function snapshotOf(deploymentId: string, role: string) {
const d = await deploymentSnapshot(deploymentId);
if (!d) throw new BenchmarkError("not_found", `${role} not found.`, 404);
if (d.state !== "running") throw new BenchmarkError("invalid", `Start ${role.toLowerCase()} first; benchmarks run against a running server.`, 409);
return d;
}
/** Queue a run against a running deployment; the worker runs one benchmark at a time. */
/**
* Queue a run against a running deployment, or a paired A/B between two running deployments of the
* same model (BetterBench sends one model name to both). The worker runs one benchmark at a time.
*/
export async function createBenchmark(input: BenchmarkInput) {
const [d] = await db()
.select({
id: deployments.id,
name: deployments.name,
state: deployments.state,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
command: deployments.command,
imageId: deployments.imageId,
modelId: deployments.modelId,
repoId: models.repoId,
runtimeName: runtimes.name,
engine: runtimes.engine,
accelerator: runtimes.accelerator,
image: runtimes.image,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(and(eq(deployments.id, input.deploymentId), isNull(deployments.deleteRequestedAt)));
if (!d) throw new BenchmarkError("not_found", "Deployment not found.", 404);
if (d.state !== "running") throw new BenchmarkError("invalid", "Start the deployment first; benchmarks run against a running server.", 409);
const snapshot: BenchmarkSnapshot = {
deploymentName: d.name,
repoId: d.repoId,
runtimeName: d.runtimeName,
engine: d.engine,
accelerator: d.accelerator,
...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")),
image: d.image,
imageId: d.imageId,
options: d.options,
cpus: d.cpus,
memoryMb: d.memoryMb,
command: [d.image, ...(d.command ?? [])].join(" "),
};
const ab = !!input.deploymentBId;
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
if (b) {
if (b.id === a.id) throw new BenchmarkError("invalid", "Pick two different deployments for an A/B.", 400);
if (b.snapshot.repoId !== a.snapshot.repoId) {
throw new BenchmarkError("invalid", "An A/B compares two deployments of the same model (BetterBench requests one model name from both).", 400);
}
}
const [row] = await db()
.insert(benchmarkRuns)
.values({
deploymentId: d.id,
modelId: d.modelId,
kind: ab ? "ab" : "run",
deploymentId: a.id,
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: input.warmup ?? null, phases: input.phases },
snapshot,
settings: {
quick: input.quick,
passes: input.passes ?? null,
warmup: input.warmup ?? null,
phases: input.phases,
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
},
snapshot: a.snapshot,
snapshotB: b?.snapshot ?? null,
sweepId: input.sweepId ?? null,
})
.returning({ id: benchmarkRuns.id });
return row;
@@ -107,6 +95,12 @@ const listColumns = {
error: benchmarkRuns.error,
summary: benchmarkRuns.summary,
hasReport: benchmarkRuns.hasReport,
kind: benchmarkRuns.kind,
deploymentBId: benchmarkRuns.deploymentBId,
snapshotB: benchmarkRuns.snapshotB,
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
sweepId: benchmarkRuns.sweepId,
createdAt: benchmarkRuns.createdAt,
};
@@ -118,7 +112,7 @@ export async function listBenchmarks(filter: { deploymentId?: string; modelId?:
.from(benchmarkRuns)
.where(
and(
filter.deploymentId ? eq(benchmarkRuns.deploymentId, filter.deploymentId) : undefined,
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
),
)
+105
View File
@@ -525,6 +525,8 @@ export const deployments = sqliteTable("deployments", {
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -572,6 +574,61 @@ export type BenchmarkSettings = {
passes: number | null;
warmup: number | null;
phases: BenchmarkPhase[];
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
mdePct?: number | null;
maxPairs?: number | null;
};
export const BENCHMARK_KINDS = ["run", "ab"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
export type PairedResult = {
metric: string;
n_pairs: number;
mean_a: number;
mean_b: number;
mean_diff: number;
pct_diff: number;
ci_low_pct: number;
ci_high_pct: number;
conf: number;
significant: boolean;
verdict: string;
higher_is_better: boolean;
};
/** `betterbench ab` result without the endpoints (raw per-pair series kept for the chart). */
export type AbSummary = {
pairs: number;
decode_tps: PairedResult;
gap_median: PairedResult & { batched: boolean };
paired_cv: number;
pairs_needed_for_mde: number;
target_mde_pct: number;
conf: number;
maxPairs: number | null;
raw: { a_tps: number[]; b_tps: number[] };
betterbenchVersion: string;
corpusVersion: string;
timestamp: string | null;
config: { greedy?: boolean | null; temperature?: number | null; warmup?: number | null; unique_nonce?: boolean | null; ab_min_pairs?: number | null };
};
/** Resource use sampled during a run (every ~2 s), per deployment and per GPU. */
export type ResourceStats = {
samples: number;
seconds: number;
containers: {
side: "a" | "b";
cpuAvg: number | null;
cpuPeak: number | null;
memAvgBytes: number | null;
memPeakBytes: number | null;
memLimitBytes: number | null;
}[];
/** Whole-GPU figures (nvidia-smi), not per process. */
gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[];
};
/** The deployment as it was when the run started, so results stay comparable after edits. */
@@ -701,6 +758,14 @@ export const benchmarkRuns = sqliteTable(
summary: text("summary", { mode: "json" }).$type<BenchmarkSummary>(),
/** Files under BENCHMARKS_DIR/<id>/: results.json and results.html. */
hasReport: integer("has_report", { mode: "boolean" }).notNull().default(false),
kind: text("kind", { enum: BENCHMARK_KINDS }).notNull().default("run"),
/** A/B: the second deployment (B); `deploymentId` is A. */
deploymentBId: text("deployment_b_id"),
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
@@ -753,3 +818,43 @@ export const benchmarkPublications = sqliteTable(
},
(t) => [index("benchmark_publications_run_idx").on(t.runId)],
);
// ---------------------------------------------------------------------------
// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant
// ---------------------------------------------------------------------------
export const SWEEP_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
export type SweepState = (typeof SWEEP_STATES)[number];
/** A setting a sweep varies; values are strings as entered (parsed per key). */
export type SweepParam = { key: string; values: string[] };
export type SweepVariant = {
index: number;
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
overrides: Record<string, unknown>;
label: string;
state: "pending" | "deploying" | "benchmarking" | "done" | "failed" | "skipped";
deploymentId?: string | null;
runId?: string | null;
error?: string | null;
};
export const benchmarkSweeps = sqliteTable("benchmark_sweeps", {
id: id(),
label: text("label"),
/** The deployment the variants are copied from (may be deleted later; `base` keeps it). */
baseDeploymentId: text("base_deployment_id"),
base: text("base", { mode: "json" })
.$type<{ name: string; runtimeId: string; modelId: string; options: DeploymentOptions; cpus: number | null; memoryMb: number | null }>()
.notNull(),
params: text("params", { mode: "json" }).$type<SweepParam[]>().notNull(),
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
variants: text("variants", { mode: "json" }).$type<SweepVariant[]>().notNull(),
state: text("state", { enum: SWEEP_STATES }).notNull().default("queued"),
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
error: text("error"),
createdAt: createdAt(),
});
+1
View File
@@ -228,6 +228,7 @@ const listColumns = {
runtimeName: runtimes.name,
runtimeImage: runtimes.image,
accelerator: runtimes.accelerator,
sweepId: deployments.sweepId,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
+47
View File
@@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { applyOverrides, expandSweep, splitValues, SweepError, sweepKeysFor } from "./sweep";
describe("sweeps", () => {
it("expands two settings into a cartesian product with labels", () => {
const v = expandSweep(
[
{ key: "contextSize", values: ["4096", "8192"] },
{ key: "kvCache", values: ["f16", "q8_0"] },
],
"llama.cpp",
"cpu",
);
assert.equal(v.length, 4);
assert.deepEqual(v[0], { index: 0, overrides: { contextSize: 4096, cacheTypeK: null, cacheTypeV: null }, label: "ctx 4096 · KV f16" });
assert.deepEqual(v[3].overrides, { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" });
});
it("rejects bad values, keys and sizes", () => {
assert.throws(() => expandSweep([{ key: "contextSize", values: ["big", "8192"] }], "llama.cpp", "cpu"), SweepError);
assert.throws(() => expandSweep([{ key: "gpuLayers", values: ["10", "20"] }], "llama.cpp", "cpu"), /can't be varied/);
assert.throws(() => expandSweep([{ key: "dtype", values: ["float32", "bfloat16"] }], "llama.cpp", "cpu"), /can't be varied/);
assert.throws(() => expandSweep([{ key: "threads", values: ["4"] }], "llama.cpp", "cpu"), /at least two variants/);
assert.throws(
() =>
expandSweep(
[
{ key: "threads", values: ["1", "2", "3", "4", "5"] },
{ key: "parallel", values: ["1", "2", "3", "4"] },
],
"llama.cpp",
"cpu",
),
/20 variants/,
);
assert.throws(() => expandSweep([{ key: "modelFile", values: ["a.gguf", "x.gguf"] }], "llama.cpp", "cpu", { modelFiles: ["a.gguf", "b.gguf"] }), /x\.gguf/);
});
it("offers GPU keys only on GPU runtimes and applies overrides", () => {
assert.ok(sweepKeysFor("llama.cpp", "nvidia").some((d) => d.key === "gpuLayers"));
assert.ok(!sweepKeysFor("vllm", "nvidia").some((d) => d.key === "kvCacheGb"));
assert.deepEqual(splitValues("4096, 8192 8192;16384"), ["4096", "8192", "16384"]);
const r = applyOverrides({ options: { modelFile: "m.gguf", contextSize: 4096, threads: 4, extraArgs: [] }, cpus: 4 }, { threads: 8, cpus: 8 });
assert.deepEqual(r, { options: { modelFile: "m.gguf", contextSize: 4096, threads: 8, extraArgs: [] }, cpus: 8 });
});
});
+101
View File
@@ -0,0 +1,101 @@
// Benchmark sweeps: which settings can vary, how their values parse, and the variant list (the
// cartesian product of up to two settings). Pure; shared by the form, the API and the worker.
import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine, SweepParam } from "@/lib/db/schema";
export const MAX_SWEEP_VARIANTS = 16;
export const MAX_SWEEP_PARAMS = 2;
/** Overrides for one variant: deployment options plus the container's CPU limit. */
export type VariantOverrides = Partial<DeploymentOptions> & { cpus?: number | null };
type Def = {
key: string;
label: string;
/** Which runtimes it applies to. */
engines: RuntimeEngine[];
gpuOnly?: boolean;
cpuOnly?: boolean;
/** Example values for the form. */
hint: string;
parse: (v: string) => VariantOverrides | null;
/** Short form for labels, e.g. "ctx 8192". */
short: (v: string) => string;
};
const int = (min: number, max: number) => (v: string) => {
const n = Number(v);
return Number.isInteger(n) && n >= min && n <= max ? n : null;
};
const num = (min: number, max: number) => (v: string) => {
const n = Number(v);
return Number.isFinite(n) && n >= min && n <= max ? n : null;
};
const oneOf = <T extends string>(...xs: T[]) => (v: string) => (xs.includes(v as T) ? (v as T) : null);
const wrap = <T>(f: (v: string) => T | null, to: (x: T) => VariantOverrides) => (v: string) => {
const x = f(v.trim());
return x == null ? null : to(x);
};
export const SWEEP_KEYS: Def[] = [
{ key: "contextSize", label: "Context size", engines: ["llama.cpp", "vllm"], hint: "4096, 8192, 16384", parse: wrap(int(128, 1_048_576), (x) => ({ contextSize: x })), short: (v) => `ctx ${v}` },
{ key: "modelFile", label: "Model file (quant)", engines: ["llama.cpp"], hint: "pick downloaded GGUF files", parse: (v) => (v.trim() ? { modelFile: v.trim() } : null), short: (v) => v.replace(/\.gguf$/i, "").split(/[/-]/).slice(-1)[0] },
{ key: "kvCache", label: "KV cache type (K and V)", engines: ["llama.cpp"], hint: "f16, q8_0, q4_0", parse: wrap(oneOf("f16", "q8_0", "q4_0"), (x) => ({ cacheTypeK: x === "f16" ? null : x, cacheTypeV: x === "f16" ? null : x })), short: (v) => `KV ${v}` },
{ key: "threads", label: "Threads", engines: ["llama.cpp"], hint: "4, 8, 16", parse: wrap(int(1, 1024), (x) => ({ threads: x })), short: (v) => `${v} threads` },
{ key: "parallel", label: "Parallel slots", engines: ["llama.cpp"], hint: "1, 2, 4", parse: wrap(int(1, 256), (x) => ({ parallel: x })), short: (v) => `np ${v}` },
{ key: "batchSize", label: "Batch size", engines: ["llama.cpp"], hint: "512, 1024, 2048", parse: wrap(int(1, 65_536), (x) => ({ batchSize: x })), short: (v) => `b ${v}` },
{ key: "ubatchSize", label: "Micro-batch size", engines: ["llama.cpp"], hint: "128, 256, 512", parse: wrap(int(1, 65_536), (x) => ({ ubatchSize: x })), short: (v) => `ub ${v}` },
{ key: "flashAttn", label: "Flash attention", engines: ["llama.cpp"], hint: "on, off", parse: wrap(oneOf("auto", "on", "off"), (x) => ({ flashAttn: x })), short: (v) => `fa ${v}` },
{ key: "cacheRamMb", label: "Prompt cache in RAM (MiB)", engines: ["llama.cpp"], hint: "0, 1024, 8192", parse: wrap(int(-1, 1_048_576), (x) => ({ cacheRamMb: x })), short: (v) => `cram ${v}` },
{ key: "gpuLayers", label: "GPU layers", engines: ["llama.cpp"], gpuOnly: true, hint: "auto, 20, all", parse: (v) => (/^(auto|all|\d{1,4})$/.test(v.trim()) ? { gpuLayers: v.trim() } : null), short: (v) => `ngl ${v}` },
{ key: "dtype", label: "Data type", engines: ["vllm"], hint: "bfloat16, float32", parse: wrap(oneOf("auto", "bfloat16", "float16", "float32"), (x) => ({ dtype: x })), short: (v) => v },
{ key: "maxNumSeqs", label: "Max sequences", engines: ["vllm"], hint: "8, 16, 32", parse: wrap(int(1, 1024), (x) => ({ maxNumSeqs: x })), short: (v) => `seqs ${v}` },
{ key: "kvCacheGb", label: "KV cache (GiB)", engines: ["vllm"], cpuOnly: true, hint: "1, 2, 4", parse: wrap(num(0.25, 1024), (x) => ({ kvCacheGb: x })), short: (v) => `KV ${v} GiB` },
{ key: "gpuMemoryUtilization", label: "GPU memory share", engines: ["vllm"], gpuOnly: true, hint: "0.8, 0.9", parse: wrap(num(0.05, 1), (x) => ({ gpuMemoryUtilization: x })), short: (v) => `gmu ${v}` },
{ key: "cpus", label: "CPU limit (cores)", engines: ["llama.cpp", "vllm"], hint: "2, 4, 8", parse: wrap(num(0.1, 1024), (x) => ({ cpus: x })), short: (v) => `${v} cores` },
];
export function sweepKeysFor(engine: RuntimeEngine, accelerator: RuntimeAccelerator): Def[] {
const gpu = accelerator !== "cpu";
return SWEEP_KEYS.filter((d) => d.engines.includes(engine) && !(d.gpuOnly && !gpu) && !(d.cpuOnly && gpu));
}
/** "4096, 8192 16384" → ["4096", "8192", "16384"] (deduplicated, order kept). */
export function splitValues(text: string): string[] {
return [...new Set(text.split(/[\s,;]+/).map((v) => v.trim()).filter(Boolean))];
}
export class SweepError extends Error {}
export type Variant = { index: number; overrides: VariantOverrides; label: string };
/** Validate the parameters and expand them into variants (cartesian product). Throws SweepError. */
export function expandSweep(params: SweepParam[], engine: RuntimeEngine, accelerator: RuntimeAccelerator, opts: { modelFiles?: string[] } = {}): Variant[] {
if (params.length === 0 || params.length > MAX_SWEEP_PARAMS) throw new SweepError(`Vary one or two settings.`);
const allowed = sweepKeysFor(engine, accelerator);
if (new Set(params.map((p) => p.key)).size !== params.length) throw new SweepError("Each setting can only be varied once.");
const axes = params.map((p) => {
const def = allowed.find((d) => d.key === p.key);
if (!def) throw new SweepError(`"${p.key}" can't be varied for this runtime.`);
const values = [...new Set(p.values.map((v) => v.trim()).filter(Boolean))];
if (values.length < 1) throw new SweepError(`Give at least one value for ${def.label}.`);
return values.map((v) => {
const o = def.parse(v);
if (!o) throw new SweepError(`"${v}" isn't a valid value for ${def.label} (e.g. ${def.hint}).`);
if (p.key === "modelFile" && opts.modelFiles && !opts.modelFiles.includes(v)) throw new SweepError(`${v} isn't a downloaded GGUF file of this model.`);
return { o, s: def.short(v) };
});
});
const total = axes.reduce((n, a) => n * a.length, 1);
if (total < 2) throw new SweepError("A sweep needs at least two variants.");
if (total > MAX_SWEEP_VARIANTS) throw new SweepError(`That's ${total} variants; the limit is ${MAX_SWEEP_VARIANTS}.`);
let combos: { o: VariantOverrides; s: string[] }[] = [{ o: {}, s: [] }];
for (const axis of axes) combos = combos.flatMap((c) => axis.map((v) => ({ o: { ...c.o, ...v.o }, s: [...c.s, v.s] })));
return combos.map((c, index) => ({ index, overrides: c.o, label: c.s.join(" · ") }));
}
/** Apply a variant's overrides to the base deployment's options / CPU limit. */
export function applyOverrides(base: { options: DeploymentOptions; cpus: number | null }, o: VariantOverrides) {
const { cpus, ...rest } = o;
return { options: { ...base.options, ...rest } as DeploymentOptions, cpus: cpus !== undefined ? cpus : base.cpus };
}
+121
View File
@@ -0,0 +1,121 @@
import "server-only";
import { rm } from "node:fs/promises";
import { and, desc, eq, inArray } from "drizzle-orm";
import { z } from "zod";
import { runDir } from "@/lib/benchmark-paths";
import { db } from "@/lib/db/client";
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
import { modelCandidates } from "@/lib/deploy-candidates";
import { expandSweep, MAX_SWEEP_PARAMS, SweepError } from "@/lib/sweep";
export class SweepRequestError extends Error {
constructor(
public code: "invalid" | "not_found" | "busy",
message: string,
public status: number,
) {
super(message);
}
}
export const SweepBody = z.object({
baseDeploymentId: z.string().min(1),
label: z.string().trim().max(80).nullable().optional(),
params: z
.array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }))
.min(1)
.max(MAX_SWEEP_PARAMS),
quick: z.boolean().default(true),
passes: z.number().int().min(1).max(200).nullable().optional(),
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
});
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
export async function createSweep(input: z.infer<typeof SweepBody>) {
const [base] = await db()
.select({
id: deployments.id,
name: deployments.name,
runtimeId: deployments.runtimeId,
modelId: deployments.modelId,
options: deployments.options,
cpus: deployments.cpus,
memoryMb: deployments.memoryMb,
engine: runtimes.engine,
accelerator: runtimes.accelerator,
imageState: runtimes.imageState,
})
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(eq(deployments.id, input.baseDeploymentId));
if (!base) throw new SweepRequestError("not_found", "Base deployment not found.", 404);
if (base.imageState !== "present") throw new SweepRequestError("invalid", "The runtime's image isn't pulled.", 409);
const files = await db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, base.modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
const gguf = modelCandidates(files).gguf.map((g) => g.path);
let variants;
try {
variants = expandSweep(input.params, base.engine, base.accelerator, { modelFiles: gguf });
} catch (err) {
if (err instanceof SweepError) throw new SweepRequestError("invalid", err.message, 400);
throw err;
}
const [row] = await db()
.insert(benchmarkSweeps)
.values({
label: input.label || null,
baseDeploymentId: base.id,
// The variants' deployments must not publish ports or require a second copy of the base's port.
base: { name: base.name, runtimeId: base.runtimeId, modelId: base.modelId, options: base.options, cpus: base.cpus, memoryMb: base.memoryMb },
params: input.params,
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })),
})
.returning({ id: benchmarkSweeps.id });
return row;
}
export type SweepRow = typeof benchmarkSweeps.$inferSelect;
export async function listSweeps(): Promise<SweepRow[]> {
return db().select().from(benchmarkSweeps).orderBy(desc(benchmarkSweeps.createdAt));
}
export async function getSweep(id: string) {
const sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!sweep) return null;
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error })
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
return { sweep, runs };
}
export async function cancelSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ columns: { state: true }, where: eq(benchmarkSweeps.id, id) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "queued") {
await db().update(benchmarkSweeps).set({ state: "cancelled", finishedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
} else if (s.state === "running") {
await db().update(benchmarkSweeps).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
}
}
/** Delete a finished sweep with its runs (and their files). */
export async function deleteSweep(id: string) {
const s = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
if (s.state === "running" || s.state === "queued") throw new SweepRequestError("busy", "Cancel the sweep first.", 409);
const runIds = s.variants.map((v) => v.runId).filter((x): x is string => !!x);
if (runIds.length) {
await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds));
await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds));
for (const r of runIds) await rm(runDir(r), { recursive: true, force: true });
}
await db().delete(benchmarkSweeps).where(eq(benchmarkSweeps.id, id));
}
+50
View File
@@ -0,0 +1,50 @@
// `betterbench ab` output (ab.json) → Kaname's AbSummary. Keeps BetterBench's own paired_compare
// results as reported; drops the endpoints (they never leave the machine). Pure, for tests.
import type { AbSummary, PairedResult } from "@/lib/db/schema";
type AbJson = {
betterbench_version?: string;
corpus_version?: string;
config?: Record<string, unknown>;
env?: { timestamp?: string };
pairs: number;
decode_tps: PairedResult;
gap_median?: PairedResult & { batched?: boolean };
itl_median?: PairedResult;
paired_cv: number;
pairs_needed_for_mde: number;
target_mde_pct: number;
conf: number;
raw?: { a_tps?: number[]; b_tps?: number[] };
};
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
export function abSummary(raw: string, maxPairs: number | null): AbSummary {
const j = JSON.parse(raw) as AbJson;
if (!j.decode_tps || typeof j.pairs !== "number") throw new Error("not a BetterBench ab.json");
const gap = j.gap_median ?? (j.itl_median ? { ...j.itl_median, batched: false } : null);
const cfg = j.config ?? {};
return {
pairs: j.pairs,
decode_tps: j.decode_tps,
gap_median: { ...(gap as PairedResult), batched: !!(gap as { batched?: boolean } | null)?.batched },
paired_cv: j.paired_cv,
pairs_needed_for_mde: j.pairs_needed_for_mde,
target_mde_pct: j.target_mde_pct,
conf: j.conf,
maxPairs,
raw: { a_tps: j.raw?.a_tps ?? [], b_tps: j.raw?.b_tps ?? [] },
betterbenchVersion: j.betterbench_version ?? "",
corpusVersion: j.corpus_version ?? "",
timestamp: j.env?.timestamp ?? null,
config: {
greedy: typeof cfg.greedy === "boolean" ? cfg.greedy : null,
temperature: num(cfg.temperature),
warmup: num(cfg.warmup),
unique_nonce: typeof cfg.unique_nonce === "boolean" ? cfg.unique_nonce : null,
ab_min_pairs: num(cfg.ab_min_pairs),
},
};
}
+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;
+33
View File
@@ -43,6 +43,39 @@ export function runArgs(o: {
];
}
/** `betterbench ab`: interleaved paired A/B until the CI is tighter than --mde (or --max-pairs). */
export function abArgs(o: {
endpointA: string;
endpointB: string;
model: string;
out: string;
mdePct: number;
maxPairs: number;
notes: Record<string, string>;
}): string[] {
return [
"ab",
"--endpoint-a",
o.endpointA,
"--endpoint-b",
o.endpointB,
"--model",
o.model,
"--out",
o.out,
"--mde",
String(o.mdePct),
"--max-pairs",
String(o.maxPairs),
...Object.entries(o.notes).flatMap(([k, v]) => ["--note", `${k}=${v}`]),
"--no-update-check",
];
}
export { AB_FILE } from "@/lib/benchmark-paths";
export const AB_DEFAULT_MDE_PCT = 1;
export const AB_DEFAULT_MAX_PAIRS = 200;
/**
* Prints Kaname's BenchmarkSummary for a results.json, using BetterBench's own report functions
* so the numbers match its HTML report.
+2
View File
@@ -14,6 +14,7 @@ import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks";
import { reportL80Status, tickPublications } from "./publish";
import { tickSweeps } from "./sweeps";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
@@ -414,6 +415,7 @@ async function main() {
void refreshSummaries();
void reportL80Status();
timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void tickSweeps(), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
+132
View File
@@ -0,0 +1,132 @@
// Samples resource use while a benchmark runs: CPU and memory of the deployment containers (Docker
// stats, every ~2 s) and, on NVIDIA hosts, whole-GPU VRAM/utilization/power from one long-lived
// `nvidia-smi -lms` probe container. Aggregation is pure (summarizeSamples) for tests.
import type { ResourceStats } from "@/lib/db/schema";
import type { DockerClient } from "./docker/client";
import { log } from "./log";
const INTERVAL_MS = 2_000;
export type ContainerSample = { side: "a" | "b"; cpuPercent: number; memoryBytes: number; memoryLimitBytes: number };
export type GpuSample = { index: number; name: string; vramTotalMb: number; vramUsedMb: number; util: number; powerW: number | null };
const avg = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null);
const peak = (xs: number[]) => (xs.length ? Math.max(...xs) : null);
/** One CSV line of `nvidia-smi --query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw`. */
export function parseGpuLine(line: string): GpuSample | null {
const p = line.split(",").map((x) => x.trim());
if (p.length < 6 || !/^\d+$/.test(p[0])) return null;
const n = (s: string) => (Number.isFinite(Number(s)) ? Number(s) : null);
return { index: Number(p[0]), name: p[1], vramTotalMb: n(p[2]) ?? 0, vramUsedMb: n(p[3]) ?? 0, util: n(p[4]) ?? 0, powerW: n(p[5]) };
}
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number): ResourceStats {
const sides = [...new Set(containers.map((c) => c.side))].sort();
return {
samples: containers.length,
seconds: Math.round(seconds),
containers: sides.map((side) => {
const xs = containers.filter((c) => c.side === side);
// Docker reports CPU in percent of one core; keep cores.
const cpu = xs.map((x) => x.cpuPercent / 100);
const mem = xs.map((x) => x.memoryBytes);
const limit = xs.find((x) => x.memoryLimitBytes > 0)?.memoryLimitBytes ?? null;
return {
side,
cpuAvg: avg(cpu),
cpuPeak: peak(cpu),
memAvgBytes: avg(mem),
memPeakBytes: peak(mem),
// Without a limit Docker reports the host's memory; that isn't a limit.
memLimitBytes: limit,
};
}),
gpus: [...new Set(gpus.map((g) => g.index))].sort((a, b) => a - b).map((index) => {
const xs = gpus.filter((g) => g.index === index);
const power = xs.map((x) => x.powerW).filter((x): x is number => x != null);
return {
index,
name: xs[0].name,
vramTotalMb: xs[0].vramTotalMb,
vramPeakMb: peak(xs.map((x) => x.vramUsedMb)) ?? 0,
vramAvgMb: avg(xs.map((x) => x.vramUsedMb)) ?? 0,
utilAvg: avg(xs.map((x) => x.util)) ?? 0,
utilPeak: peak(xs.map((x) => x.util)) ?? 0,
powerAvgW: avg(power),
powerPeakW: peak(power),
};
}),
};
}
export class ResourceSampler {
private containerSamples: ContainerSample[] = [];
private gpuSamples: GpuSample[] = [];
private timer?: NodeJS.Timeout;
private busy = false;
private probeId: string | null = null;
private abort = new AbortController();
private started = Date.now();
constructor(
private c: DockerClient,
private targets: { side: "a" | "b"; containerId: string }[],
private gpuProbeImage: string | null,
) {}
async start(): Promise<void> {
this.started = Date.now();
this.timer = setInterval(() => void this.sample(), INTERVAL_MS);
void this.sample();
if (this.gpuProbeImage) await this.startGpuProbe(this.gpuProbeImage).catch((err) => log.warn(`GPU sampling unavailable: ${err instanceof Error ? err.message : err}`));
}
private async sample() {
if (this.busy) return;
this.busy = true;
try {
for (const t of this.targets) {
const s = await this.c.containerStats(t.containerId).catch(() => null);
if (s) this.containerSamples.push({ side: t.side, ...s });
}
} finally {
this.busy = false;
}
}
private async startGpuProbe(image: string) {
const created = await this.c.createContainer(`kaname-gpu-sampler-${Date.now().toString(36)}`, {
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: ["--query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw", "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)],
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false },
});
this.probeId = created.Id;
await this.c.startContainer(created.Id);
void this.c
.followLogs(
created.Id,
(_s, line) => {
const g = parseGpuLine(line);
if (g) this.gpuSamples.push(g);
},
{ tail: "all", signal: this.abort.signal },
)
.catch(() => {});
}
/** Stop sampling and return the aggregate (never throws). */
async stop(): Promise<ResourceStats> {
clearInterval(this.timer);
this.abort.abort();
if (this.probeId) {
await this.c.stopContainer(this.probeId, 1).catch(() => {});
await this.c.removeContainer(this.probeId).catch(() => {});
}
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000);
}
}
+5
View File
@@ -62,6 +62,10 @@ async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "networ
// --- GPUs ---------------------------------------------------------------------
const GPU_PROBE_MS = 60 * 60_000;
let ownImage: string | null = null;
/** The worker's own image (from the last host check); probe containers run from it. */
export const workerImage = () => ownImage;
let gpuCache: { at: number; gpus: HostGpu[]; error: string | null } | null = null;
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
@@ -146,6 +150,7 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
try {
const [v, i] = await Promise.all([c.version(), c.info()]);
const self = await selfDetect(c);
ownImage = self.image;
info = {
connected: true,
error: null,
+153
View File
@@ -0,0 +1,153 @@
// Runs benchmark sweeps one variant at a time: a temporary deployment with the variant's settings,
// a benchmark run against it once it is healthy, then the deployment is removed again. State lives in
// the sweep row, so a worker restart picks up where it was (an interrupted run fails its variant).
import { and, asc, eq, inArray } from "drizzle-orm";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
import { estimateMemoryMb } from "@/lib/deploy-command";
import { applyOverrides } from "@/lib/sweep";
import { log } from "./log";
let busy = false;
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
type Sweep = typeof benchmarkSweeps.$inferSelect;
async function save(id: string, set: Partial<typeof benchmarkSweeps.$inferInsert>) {
await db().update(benchmarkSweeps).set(set).where(eq(benchmarkSweeps.id, id));
}
/** Stop and remove a sweep's temporary deployment (the deployments reconciler does the work). */
async function removeDeployment(id: string | null | undefined) {
if (!id) return;
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
}
/** The variant's memory limit: the base limit, raised to the estimate when the variant needs more. */
async function memoryFor(sweep: Sweep, options: Sweep["base"]["options"], accelerator: string, engine: "llama.cpp" | "vllm"): Promise<number | null> {
if (!sweep.base.memoryMb) return null;
const files = await db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, sweep.base.modelId), eq(modelFiles.selected, true)));
const bytes =
engine === "llama.cpp"
? files.filter((f) => [options.modelFile, options.mmproj, options.draftFile].includes(f.path)).reduce((s, f) => s + f.size, 0)
: files.reduce((s, f) => s + f.size, 0);
const est = estimateMemoryMb(bytes, options.contextSize, engine, { ...options, accelerator: accelerator as never });
return Math.max(sweep.base.memoryMb, est);
}
async function advance(sweep: Sweep): Promise<void> {
const variants = [...sweep.variants];
const put = async (i: number, patch: Partial<SweepVariant>) => {
variants[i] = { ...variants[i], ...patch };
await save(sweep.id, { variants });
};
if (sweep.cancelRequestedAt) {
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);
}
await save(sweep.id, {
state: "cancelled",
finishedAt: new Date(),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)),
});
log.info(`sweep ${sweep.id}: cancelled`);
return;
}
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking");
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." });
log.info(`sweep ${sweep.id}: ${ok}/${variants.length} variants done`);
return;
}
const v = variants[i];
if (v.state === "pending") {
const rt = await db().query.runtimes.findFirst({ columns: { engine: true, accelerator: true }, where: eq(runtimes.id, sweep.base.runtimeId) });
if (!rt) return void (await put(i, { state: "failed", error: "The runtime was deleted." }));
const { options, cpus } = applyOverrides(sweep.base, v.overrides);
const memoryMb = await memoryFor(sweep, options, rt.accelerator, rt.engine);
const [row] = await db()
.insert(deployments)
.values({
name: `${sweep.base.name} · ${v.label}`.slice(0, 80),
runtimeId: sweep.base.runtimeId,
modelId: sweep.base.modelId,
options,
cpus,
memoryMb,
hostPort: null,
desiredState: "running",
sweepId: sweep.id,
})
.returning({ id: deployments.id });
await put(i, { state: "deploying", deploymentId: row.id });
log.info(`sweep ${sweep.id}: variant ${i + 1}/${variants.length} (${v.label}) deploying`);
return;
}
if (v.state === "deploying") {
const d = v.deploymentId ? await db().query.deployments.findFirst({ columns: { state: true, error: true }, where: eq(deployments.id, v.deploymentId) }) : null;
if (!d) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
if (d.state === "failed") {
await put(i, { state: "failed", error: d.error ?? "The deployment failed to start." });
return removeDeployment(v.deploymentId);
}
if (d.state !== "running") return; // still starting
const snap = await deploymentSnapshot(v.deploymentId!);
if (!snap) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
const [run] = await db()
.insert(benchmarkRuns)
.values({
kind: "run",
deploymentId: snap.id,
modelId: snap.modelId,
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label}`.slice(0, 120),
settings: sweep.settings,
snapshot: snap.snapshot,
sweepId: sweep.id,
})
.returning({ id: benchmarkRuns.id });
await put(i, { state: "benchmarking", runId: run.id });
return;
}
// benchmarking
const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.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}.` });
await removeDeployment(v.deploymentId);
}
/** Drive the running sweep (or start the oldest queued one). */
export async function tickSweeps(): Promise<void> {
if (busy) return;
busy = true;
try {
let sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.state, "running"), orderBy: asc(benchmarkSweeps.createdAt) });
if (!sweep) {
const next = await db().query.benchmarkSweeps.findFirst({ where: inArray(benchmarkSweeps.state, ["queued"]), orderBy: asc(benchmarkSweeps.createdAt) });
if (!next) return;
await save(next.id, { state: "running", startedAt: new Date() });
sweep = { ...next, state: "running" };
log.info(`sweep ${next.id}: started (${next.variants.length} variants)`);
}
await advance(sweep).catch((err) => log.error(`sweep ${sweep!.id}`, err));
} catch (err) {
log.error("sweeps", message(err));
} finally {
busy = false;
}
}