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

+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));
}