Benchmarks with BetterBench, launch80-style reports and publishing, GPU support
- Benchmarks: BetterBench 0.6.1 (pinned by checksum) runs against a running deployment, one at a time; quick/full/custom passes, phase selection, live step and output, cancel, run again, compare runs side by side. - Report page after launch80's bench.betterbench.v1: headline tiles, "Read these first" caveats (quick, sample gate, max_tokens truncation, batched streams, failures, skipped depths, prefix-cache hits), charts, full tables with daggered under-sampled cells, method text. All figures come from BetterBench's own report functions. - Publish to launch80 as a double opt-in: L80 dry run builds the exact payload for inspection, an explicit confirmation publishes that file (L80 CLI 0.4.0 pinned by checksum, L80_TOKEN worker-only). Endpoint and host never leave. - GPUs: runtime accelerator (CPU, NVIDIA, /dev/dri, ROCm) with presets for the official CUDA/Vulkan/Intel/ROCm builds; NVIDIA GPUs probed via nvidia-smi in a short-lived container; per-deployment GPU picking, -ngl, split mode, tensor split, MoE offload, vLLM tensor parallel and GPU memory share. - llama.cpp --cache-ram option (1 GiB for new deployments) and a memory estimate that counts it and the KV cache: the 8 GiB default made containers thrash at their memory limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f0b4adda63
commit
9e167a44f6
61 files changed
+9898
-194
No files matched your search
@@ -0,0 +1,23 @@
|
||||
// Where benchmark files live. Shared by the worker (writes) and the web app (serves reports).
|
||||
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
|
||||
/** BENCHMARKS_DIR, or "benchmarks" next to the SQLite file (e.g. /data/benchmarks). */
|
||||
export function benchmarksDir(): string {
|
||||
const env = coreEnv();
|
||||
if (env.BENCHMARKS_DIR) return resolve(env.BENCHMARKS_DIR);
|
||||
const db = env.DATABASE_URL.replace(/^file:/, "");
|
||||
return resolve(dirname(db), "benchmarks");
|
||||
}
|
||||
|
||||
/** Run ids are ULIDs; anything else never becomes a path. */
|
||||
const RUN_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
|
||||
export function runDir(runId: string): string {
|
||||
if (!RUN_ID_RE.test(runId)) throw new Error("invalid run id");
|
||||
return join(benchmarksDir(), runId);
|
||||
}
|
||||
|
||||
export const RESULTS_FILE = "results.json";
|
||||
export const REPORT_FILE = "results.html";
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { describeHardware, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled } from "./benchmark-report";
|
||||
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
|
||||
|
||||
const snap = {
|
||||
deploymentName: "bench test",
|
||||
repoId: "unsloth/Qwen3-0.6B-GGUF",
|
||||
runtimeName: "llama.cpp (CPU)",
|
||||
engine: "llama.cpp",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server",
|
||||
imageId: null,
|
||||
options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, extraArgs: [] },
|
||||
cpus: 4,
|
||||
memoryMb: 2640,
|
||||
command: "",
|
||||
host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
|
||||
} as BenchmarkSnapshot;
|
||||
|
||||
const summary: BenchmarkSummary = {
|
||||
v: 2,
|
||||
combined: { decode: 97.25, ttft_p50: 140, itl_low1: 48.03, update_p50: 10.1, update_p99: 17.5 },
|
||||
single: [
|
||||
{ category: "chat", runs: 5, ttft_p50: 150.3, ttft_p99: 165.5, decode_med: 102.8, decode_cv: 0.05, itl_low1: 51.1, tok_per_update: 1.01, batched: false, batched_runs: 0 },
|
||||
{ category: "code", runs: 5, ttft_p50: 135.7, ttft_p99: 165.7, decode_med: 89.1, decode_cv: 0.1, itl_low1: 40.8, tok_per_update: 1.0, batched: false, batched_runs: 0 },
|
||||
],
|
||||
prefill: [
|
||||
{ target_depth: 2000, skipped: false, pp_med: 600 },
|
||||
{ target_depth: 8000, skipped: true },
|
||||
],
|
||||
concurrency: [
|
||||
{ level: 1, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 100, ttft_p99: 200, decode_med: 95 },
|
||||
{ level: 4, ok: 46, requests: 48, aggregate_tps: 210, ttft_p50: 300, ttft_p99: 900, decode_med: 52 },
|
||||
],
|
||||
gate: [
|
||||
{ section: "single_stream", key: "chat", metric: "ttft_p99", n: 5, need: 500 },
|
||||
{ section: "concurrency", key: 4, metric: "ttft_p99", n: 46, need: 500 },
|
||||
],
|
||||
truncated: [3, 10],
|
||||
failedSingle: 0,
|
||||
phases: ["decode", "prefill", "concurrency"],
|
||||
cacheHits: 0,
|
||||
betterbenchVersion: "0.6.1",
|
||||
corpusVersion: "1.0",
|
||||
maxModelLen: 4096,
|
||||
config: { warmup: 1, runs_per_category: 5, temperature: 0.7, top_p: 0.95, top_k: 20, unique_nonce: true, weights: { code: 0.3, chat: 0 }, concurrency_requests: 48, prefill_runs: 8, prefill_warmup: 2, prefill_max_tokens: 16 },
|
||||
passes: 5,
|
||||
quick: true,
|
||||
};
|
||||
|
||||
const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
|
||||
|
||||
describe("benchmark report (launch80 conventions)", () => {
|
||||
it("describes hardware, subtitle and summary", () => {
|
||||
assert.equal(describeHardware(snap), "4 CPU cores of an AMD Ryzen 7 9850X3D");
|
||||
assert.equal(describeHardware({ ...snap, gpuNames: ["NVIDIA GeForce RTX 3080", "NVIDIA GeForce RTX 3080"] }), "2× NVIDIA GeForce RTX 3080");
|
||||
assert.equal(reportSubtitle(run), "4 CPU cores of an AMD Ryzen 7 9850X3D · 5 passes per category · temp 0.7 · quick smoke run");
|
||||
const s = reportSummary(run);
|
||||
assert.match(s, /^Quick smoke run, not a publishable measurement\. unsloth\/Qwen3-0\.6B-GGUF \(Q4_K_M, 4,096-token context\)/);
|
||||
assert.match(s, /5 measured passes per category over 2 categories\. Combined decode 97\.3 t\/s \(weighted median\), TTFT p50 140 ms, ITL 1% low 48\.0 t\/s\./);
|
||||
assert.match(s, /peaked at 210\.0 t\/s at concurrency 4\. Prefill reached 600 t\/s at ~2,000 prompt tokens\.$/);
|
||||
});
|
||||
|
||||
it("lists caveats in launch80's order", () => {
|
||||
const c = reportCaveats(run);
|
||||
assert.match(c[0], /^Quick smoke run: 5 passes per category after 1 warmup/);
|
||||
assert.match(c[1], /^Under-sampled: TTFT p99 in chat, c4 \(n ≤ 46\)\. A p99 needs 500 samples/);
|
||||
assert.match(c[2], /^3 of 10 runs stopped at max_tokens \(30%\)/);
|
||||
assert.match(c[3], /^Concurrency requests failed at level 4: 46\/48 ok/);
|
||||
assert.match(c[4], /^Prefill depths skipped: 8,000 tokens \(exceed the model context of 4,096\)/);
|
||||
assert.equal(c.length, 5);
|
||||
});
|
||||
|
||||
it("writes the method from the config and flags gated cells", () => {
|
||||
const m = reportMethod(summary).join("\n");
|
||||
assert.match(m, /Single stream: 1 warmup then 5 measured passes per category, temperature 0\.7, top_p 0\.95, top_k 20, prefix cache cold/);
|
||||
assert.match(m, /Concurrency sweep: 48 requests at levels 1, 4\./);
|
||||
assert.match(m, /weighted by category: chat 0, code 0\.3/);
|
||||
assert.ok(undersampled(summary, "single_stream", "chat", "ttft_p99"));
|
||||
assert.ok(undersampled(summary, "concurrency", 4, "ttft_p99"));
|
||||
assert.ok(!undersampled(summary, "single_stream", "code", "ttft_p99"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
// Text for a benchmark's report page, following launch80's bench.betterbench.v1 conventions
|
||||
// (L80 CLI, internal/betterbench/payload.go): every figure is one BetterBench reported, quick runs
|
||||
// say so first, under-sampled percentiles are flagged, truncated and batched runs are called out,
|
||||
// and no endpoint or host name appears. Pure, for tests.
|
||||
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
type Run = { label: string | null; snapshot: BenchmarkSnapshot; settings: BenchmarkSettings; summary: BenchmarkSummary | null };
|
||||
|
||||
export const f1 = (v: number | null | undefined) => (v == null ? "—" : v.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 }));
|
||||
export const f0 = (v: number | null | undefined) => (v == null ? "—" : Math.round(v).toLocaleString("en-US"));
|
||||
const int = (v: number) => v.toLocaleString("en-US");
|
||||
|
||||
/** launch80's quick rule: a single-stream run with ≤ 5 passes per category. */
|
||||
export function isQuick(sum: BenchmarkSummary | null): boolean {
|
||||
if (!sum) return false;
|
||||
return sum.quick || (sum.single.length > 0 && sum.passes != null && sum.passes > 0 && sum.passes <= 5);
|
||||
}
|
||||
|
||||
/** Did the server stream several tokens per update (speculative/batched decoding)? */
|
||||
export function isBatched(sum: BenchmarkSummary | null): boolean {
|
||||
return !!sum?.single.some((r) => r.batched);
|
||||
}
|
||||
|
||||
/** "RTX 3080" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
|
||||
export function describeHardware(s: BenchmarkSnapshot): string {
|
||||
if (s.gpuNames?.length) {
|
||||
const names = [...new Set(s.gpuNames)];
|
||||
return s.gpuNames.length > 1 && names.length === 1 ? `${s.gpuNames.length}× ${names[0]}` : names.join(" + ");
|
||||
}
|
||||
const cpu = s.host?.cpuModel
|
||||
?.replace(/\s+\d+-Core Processor$/i, "")
|
||||
.replace(/\(R\)|\(TM\)/g, "")
|
||||
.trim();
|
||||
if (s.cpus) return `${s.cpus} CPU core${s.cpus === 1 ? "" : "s"}${cpu ? ` of an ${cpu}` : ""}`;
|
||||
return cpu ? `an ${cpu}${s.host?.threads ? ` (${s.host.threads} threads)` : ""}` : "CPU";
|
||||
}
|
||||
|
||||
export function weightsLabel(s: BenchmarkSnapshot): string {
|
||||
return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
|
||||
}
|
||||
|
||||
/** hardware · N passes per category · temp 0.7 · quick smoke run */
|
||||
export function reportSubtitle(run: Run): string {
|
||||
const sum = run.summary;
|
||||
const parts = [describeHardware(run.snapshot)];
|
||||
if (sum?.single.length && sum.passes) parts.push(`${sum.passes} passes per category`);
|
||||
const cfg = sum?.config;
|
||||
if (cfg?.greedy) parts.push("greedy");
|
||||
else if (cfg?.temperature != null) parts.push(`temp ${cfg.temperature}`);
|
||||
if (isQuick(sum)) parts.push("quick smoke run");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
export function reportSummary(run: Run): string {
|
||||
const s = run.snapshot;
|
||||
const sum = run.summary;
|
||||
const out: string[] = [];
|
||||
if (isQuick(sum)) out.push("Quick smoke run, not a publishable measurement.");
|
||||
out.push(
|
||||
`${s.repoId} (${weightsLabel(s)}, ${int(s.options.contextSize)}-token context) on ${s.runtimeName}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
|
||||
sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
|
||||
}.`.replace(" ,", ","),
|
||||
);
|
||||
const c = sum?.combined;
|
||||
if (c) {
|
||||
const bits: string[] = [];
|
||||
if (c.decode != null) bits.push(`combined decode ${f1(c.decode)} t/s (weighted median)`);
|
||||
if (c.ttft_p50 != null) bits.push(`TTFT p50 ${f0(c.ttft_p50)} ms`);
|
||||
if (isBatched(sum) && c.update_p99 != null) bits.push(`stream-update p99 ${f1(c.update_p99)} ms`);
|
||||
else if (c.itl_low1 != null) bits.push(`ITL 1% low ${f1(c.itl_low1)} t/s`);
|
||||
if (bits.length) out.push(bits.join(", ").replace(/^./, (x) => x.toUpperCase()) + ".");
|
||||
}
|
||||
const peak = sum?.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
|
||||
if (peak) out.push(`Aggregate throughput peaked at ${f1(peak.aggregate_tps)} t/s at concurrency ${peak.level}.`);
|
||||
const pre = sum?.prefill.filter((p) => !p.skipped && p.pp_med != null) ?? [];
|
||||
const best = pre.length ? pre.reduce((a, b) => (b.pp_med! > a.pp_med! ? b : a)) : null;
|
||||
if (best) out.push(`Prefill reached ${f0(best.pp_med)} t/s at ~${int(best.target_depth)} prompt tokens.`);
|
||||
return out.join(" ");
|
||||
}
|
||||
|
||||
/** The Method section: how BetterBench measured, from the run's own config. */
|
||||
export function reportMethod(sum: BenchmarkSummary): string[] {
|
||||
const p: string[] = [];
|
||||
const cfg = sum.config ?? {};
|
||||
const cats = sum.single.map((r) => r.category);
|
||||
p.push(`BetterBench ${sum.betterbenchVersion}${sum.corpusVersion ? `, corpus v${sum.corpusVersion}` : ""}${cats.length ? ` (${cats.length} categories: ${cats.join(", ")})` : ""}.`);
|
||||
if (sum.single.length) {
|
||||
let s = `Single stream: ${cfg.warmup ?? "?"} warmup then ${cfg.runs_per_category ?? sum.passes} measured passes per category`;
|
||||
if (cfg.greedy) s += ", greedy sampling";
|
||||
else if (cfg.temperature != null) s += `, temperature ${cfg.temperature}${cfg.top_p != null ? `, top_p ${cfg.top_p}` : ""}${cfg.top_k != null ? `, top_k ${cfg.top_k}` : ""}`;
|
||||
s += cfg.unique_nonce === false ? ", prefix cache warm" : ", prefix cache cold (unique nonce per request)";
|
||||
p.push(`${s}.`);
|
||||
}
|
||||
if (sum.concurrency.length) {
|
||||
const n = cfg.concurrency_requests ?? sum.concurrency[0].requests;
|
||||
p.push(`Concurrency sweep: ${n} requests at levels ${sum.concurrency.map((c) => c.level).join(", ")}.`);
|
||||
}
|
||||
if (sum.prefill.length) {
|
||||
let s = `Prefill sweep at target depths ${sum.prefill.map((d) => d.target_depth).join(", ")} tokens`;
|
||||
if (cfg.prefill_runs) s += `, ${cfg.prefill_runs} runs after ${cfg.prefill_warmup ?? 0} warmup`;
|
||||
if (cfg.prefill_max_tokens) s += `, ${cfg.prefill_max_tokens}-token decode`;
|
||||
p.push(`${s}, cold prefix cache. Prefill throughput is prompt tokens divided by TTFT.`);
|
||||
}
|
||||
p.push(
|
||||
isBatched(sum)
|
||||
? "Units: TTFT in ms; decode and prefill throughput in tokens per second; update p50/p99 is the wall-clock gap between stream updates in ms, and tok/update how many tokens each update carried."
|
||||
: "Units: TTFT in ms; decode, ITL and prefill throughput in tokens per second; ITL columns are instantaneous tokens per second (1% low = slowest tokens, 99% high = fastest).",
|
||||
);
|
||||
const w = cfg.weights;
|
||||
if (w && Object.keys(w).length && sum.single.length) {
|
||||
const ws = sum.single.filter((r) => w[r.category] != null).map((r) => `${r.category} ${w[r.category]}`);
|
||||
if (ws.length) p.push(`Combined figures are weighted by category: ${ws.join(", ")}. Categories without a weight are excluded from the combined figures.`);
|
||||
} else if (sum.single.length > 1) {
|
||||
p.push("Combined figures weight every category equally.");
|
||||
}
|
||||
p.push("Undersampled cells (†) carry a percentile that rests on fewer samples than n · tail ≥ 5 requires; read them as roughly the worst observed, not as percentiles.");
|
||||
return p;
|
||||
}
|
||||
|
||||
const METRIC_LABEL: Record<string, string> = {
|
||||
ttft_p99: "TTFT p99",
|
||||
itl_high99: "ITL 99% high",
|
||||
update_p99: "update p99",
|
||||
pp_p99: "prefill p99",
|
||||
};
|
||||
|
||||
/** "Read these first": the same rules as launch80's buildCaveats, plus prefix-cache hits. */
|
||||
export function reportCaveats(run: Run): string[] {
|
||||
const sum = run.summary;
|
||||
if (!sum) return [];
|
||||
const out: string[] = [];
|
||||
if (isQuick(sum)) {
|
||||
out.push(`Quick smoke run: ${sum.passes ?? 5} passes per category after ${sum.config?.warmup ?? 1} warmup. Too few passes for any percentile to hold; treat every figure as indicative, not as a result.`);
|
||||
}
|
||||
const gate = sum.gate ?? [];
|
||||
if (gate.length) {
|
||||
const by = new Map<string, string[]>();
|
||||
for (const g of gate) {
|
||||
const label = `${METRIC_LABEL[g.metric] ?? g.metric}`;
|
||||
by.set(label, [...(by.get(label) ?? []), String(g.section === "prefill" ? `${int(Number(g.key))} tok` : g.section === "concurrency" ? `c${g.key}` : g.key)]);
|
||||
}
|
||||
const list = [...by].map(([m, keys]) => `${m} in ${keys.slice(0, 4).join(", ")}${keys.length > 4 ? ` +${keys.length - 4}` : ""}`).join("; ");
|
||||
const need = Math.max(...gate.map((g) => g.need));
|
||||
out.push(`Under-sampled: ${list} (n ≤ ${Math.max(...gate.map((g) => g.n))}). A p99 needs ${int(need)} samples; the daggered cells are roughly the worst observed, not percentiles.`);
|
||||
}
|
||||
const [trunc, tot] = sum.truncated ?? [0, 0];
|
||||
if (tot > 0 && trunc > 0) {
|
||||
out.push(`${trunc} of ${tot} runs stopped at max_tokens (${Math.round((trunc / tot) * 100)}%). On a thinking model a truncated run measures the thinking phase, not a complete answer.`);
|
||||
}
|
||||
const batchedRuns = sum.single.reduce((s, r) => s + (r.batched_runs ?? 0), 0);
|
||||
if (batchedRuns > 0) {
|
||||
const runs = sum.single.reduce((s, r) => s + r.runs, 0);
|
||||
out.push(`${batchedRuns} of ${runs} runs streamed several tokens per update (speculative or batched decoding), so per-token ITL is not reported; update p50/p99 and tok/update are shown instead.`);
|
||||
}
|
||||
if (sum.failedSingle) out.push(`${sum.failedSingle} single-stream request(s) failed and are excluded from every figure.`);
|
||||
const concFail = sum.concurrency.filter((c) => c.ok < c.requests).map((c) => `level ${c.level}: ${c.ok}/${c.requests} ok`);
|
||||
if (concFail.length) out.push(`Concurrency requests failed at ${concFail.join("; ")}. Aggregate throughput counts only completed requests.`);
|
||||
const skipped = sum.prefill.filter((p) => p.skipped).map((p) => int(p.target_depth));
|
||||
if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context of ${int(sum.maxModelLen ?? run.snapshot.options.contextSize)}).`);
|
||||
if (sum.cacheHits > 0) out.push(`${sum.cacheHits} request(s) were partly served from the server's prefix cache although the run asked for a cold cache; those prefill figures may be cache lookups.`);
|
||||
return out.slice(0, 8);
|
||||
}
|
||||
|
||||
/** Did this percentile cell fail the sample gate? */
|
||||
export function undersampled(sum: BenchmarkSummary, section: string, key: string | number, metric: string): boolean {
|
||||
return !!sum.gate?.some((g) => g.section === section && String(g.key) === String(key) && g.metric === metric);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { configChips, deltaPct, describeSettings, headline } from "./benchmark-view";
|
||||
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
|
||||
|
||||
const summary: BenchmarkSummary = {
|
||||
combined: { decode: 42.5, ttft_p50: 180, itl_low1: null, update_p50: null, update_p99: null },
|
||||
single: [],
|
||||
prefill: [
|
||||
{ target_depth: 2048, skipped: false, pp_med: 900 },
|
||||
{ target_depth: 8192, skipped: false, pp_med: 700 },
|
||||
{ target_depth: 65536, skipped: true },
|
||||
],
|
||||
concurrency: [
|
||||
{ level: 1, ok: 48, requests: 48, aggregate_tps: 40, ttft_p50: 100, ttft_p99: 200, decode_med: 40 },
|
||||
{ level: 4, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 300, ttft_p99: 900, decode_med: 25 },
|
||||
{ level: 8, ok: 48, requests: 48, aggregate_tps: 90, ttft_p50: 700, ttft_p99: 2000, decode_med: 12 },
|
||||
],
|
||||
phases: ["decode", "prefill", "concurrency"],
|
||||
cacheHits: 0,
|
||||
betterbenchVersion: "0.6.1",
|
||||
corpusVersion: "1.0",
|
||||
passes: 20,
|
||||
quick: false,
|
||||
};
|
||||
|
||||
describe("benchmark view", () => {
|
||||
it("picks the headline numbers", () => {
|
||||
assert.deepEqual(headline(summary), { decode: 42.5, ttftMs: 180, prefill: { tps: 700, depth: 8192 }, peak: { tps: 95, level: 4 } });
|
||||
assert.deepEqual(headline(null), { decode: null, ttftMs: null, prefill: null, peak: null });
|
||||
});
|
||||
|
||||
it("lists set options as chips", () => {
|
||||
const snap = {
|
||||
options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, threads: 8, cacheTypeK: "q8_0", extraArgs: [] },
|
||||
cpus: 8,
|
||||
memoryMb: null,
|
||||
} as unknown as BenchmarkSnapshot;
|
||||
assert.deepEqual(configChips(snap), ["Q4_K_M", "context 4096", "threads 8", "kv cache k / v q8_0 / f16", "cpu limit 8 cores"]);
|
||||
});
|
||||
|
||||
it("describes settings and deltas", () => {
|
||||
assert.equal(describeSettings({ quick: true, passes: null, warmup: null, phases: [] }), "quick, 5 passes · all phases");
|
||||
assert.equal(describeSettings({ quick: false, passes: 10, warmup: null, phases: ["decode"] }), "10 passes · decode");
|
||||
assert.equal(deltaPct(110, 100), 10);
|
||||
assert.equal(deltaPct(null, 100), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
// Display helpers for benchmark runs. Pure; shared by list, detail and compare pages.
|
||||
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
export type Headline = {
|
||||
/** Weighted single-stream decode t/s (BetterBench's combined score). */
|
||||
decode: number | null;
|
||||
ttftMs: number | null;
|
||||
/** Prefill t/s at the deepest measured depth. */
|
||||
prefill: { tps: number; depth: number } | null;
|
||||
/** Highest aggregate t/s in the concurrency sweep. */
|
||||
peak: { tps: number; level: number } | null;
|
||||
};
|
||||
|
||||
export function headline(s: BenchmarkSummary | null): Headline {
|
||||
if (!s) return { decode: null, ttftMs: null, prefill: null, peak: null };
|
||||
const pre = s.prefill.filter((p) => !p.skipped && p.pp_med != null).sort((a, b) => b.target_depth - a.target_depth)[0];
|
||||
const peak = [...s.concurrency].sort((a, b) => b.aggregate_tps - a.aggregate_tps)[0];
|
||||
return {
|
||||
decode: s.combined?.decode ?? null,
|
||||
ttftMs: s.combined?.ttft_p50 ?? null,
|
||||
prefill: pre ? { tps: pre.pp_med!, depth: pre.target_depth } : null,
|
||||
peak: peak ? { tps: peak.aggregate_tps, level: peak.level } : null,
|
||||
};
|
||||
}
|
||||
|
||||
export type ConfigRow = { key: string; label: string; value: (s: BenchmarkSnapshot) => string | null };
|
||||
|
||||
const n = (v: number | null | undefined, unit = "") => (v != null ? `${v}${unit}` : null);
|
||||
|
||||
/** Launch settings worth comparing between runs, in display order. */
|
||||
export const CONFIG_ROWS: ConfigRow[] = [
|
||||
{ key: "runtime", label: "Runtime", value: (s) => s.runtimeName },
|
||||
{ key: "image", label: "Image", value: (s) => s.image },
|
||||
{ key: "accel", label: "Runs on", value: (s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null) },
|
||||
{ key: "gpus", label: "GPUs", value: (s) => (s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
|
||||
{ key: "ngl", label: "GPU layers", value: (s) => s.options.gpuLayers ?? null },
|
||||
{ key: "sm", label: "Split mode", value: (s) => s.options.splitMode ?? null },
|
||||
{ key: "ts", label: "Tensor split", value: (s) => s.options.tensorSplit ?? null },
|
||||
{ key: "moe", label: "MoE experts in RAM", value: (s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null) },
|
||||
{ key: "tp", label: "Tensor parallel", value: (s) => n(s.options.tensorParallel) },
|
||||
{ key: "gmu", label: "GPU memory share", value: (s) => n(s.options.gpuMemoryUtilization) },
|
||||
{ key: "cram", label: "Prompt cache (MiB)", value: (s) => n(s.options.cacheRamMb) },
|
||||
{ key: "file", label: "Weights", value: (s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors") },
|
||||
{ key: "ctx", label: "Context", value: (s) => n(s.options.contextSize) },
|
||||
{ key: "threads", label: "Threads", value: (s) => n(s.options.threads) },
|
||||
{ key: "parallel", label: "Parallel slots", value: (s) => n(s.options.parallel) },
|
||||
{ key: "batch", label: "Batch / micro-batch", value: (s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null) },
|
||||
{ key: "kv", label: "KV cache K / V", value: (s) => (s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
|
||||
{ key: "fa", label: "Flash attention", value: (s) => s.options.flashAttn ?? null },
|
||||
{ key: "draft", label: "Speculative", value: (s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null) },
|
||||
{ key: "dtype", label: "Data type", value: (s) => s.options.dtype ?? null },
|
||||
{ key: "seqs", label: "Max sequences", value: (s) => n(s.options.maxNumSeqs) },
|
||||
{ key: "kvgb", label: "KV cache (GiB)", value: (s) => n(s.options.kvCacheGb) },
|
||||
{ key: "cpus", label: "CPU limit", value: (s) => n(s.cpus, " cores") },
|
||||
{ key: "mem", label: "Memory limit", value: (s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null) },
|
||||
{ key: "args", label: "Extra arguments", value: (s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null) },
|
||||
];
|
||||
|
||||
/** Short chips for a list row: the settings that are set. */
|
||||
export function configChips(s: BenchmarkSnapshot): string[] {
|
||||
const skip = new Set(["runtime", "image", "args"]);
|
||||
return CONFIG_ROWS.filter((r) => !skip.has(r.key))
|
||||
.map((r) => {
|
||||
const v = r.value(s);
|
||||
return v == null ? null : r.key === "file" ? v : `${r.label.toLowerCase()} ${v}`;
|
||||
})
|
||||
.filter((v): v is string => v != null);
|
||||
}
|
||||
|
||||
export function describeSettings(st: BenchmarkSettings): string {
|
||||
const passes = st.passes ?? (st.quick ? 5 : 20);
|
||||
const phases = st.phases.length ? st.phases.join(", ") : "all phases";
|
||||
return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
|
||||
}
|
||||
|
||||
/** Relative difference of `v` against `base` in percent (null if either is missing). */
|
||||
export function deltaPct(v: number | null | undefined, base: number | null | undefined): number | null {
|
||||
return v != null && base != null && base !== 0 ? ((v - base) / base) * 100 : null;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import "server-only";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { and, asc, desc, eq, gt, inArray, isNull } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { runDir } from "@/lib/benchmark-paths";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
|
||||
|
||||
export class BenchmarkError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export const BenchmarkBody = z.object({
|
||||
deploymentId: z.string().min(1),
|
||||
label: z.string().trim().max(120).nullable().optional(),
|
||||
quick: z.boolean().default(false),
|
||||
passes: z.number().int().min(1).max(200).nullable().optional(),
|
||||
warmup: z.number().int().min(0).max(50).nullable().optional(),
|
||||
/** Empty: all phases. */
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
});
|
||||
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 },
|
||||
};
|
||||
}
|
||||
|
||||
/** Queue a run against a running deployment; 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 [row] = await db()
|
||||
.insert(benchmarkRuns)
|
||||
.values({
|
||||
deploymentId: d.id,
|
||||
modelId: d.modelId,
|
||||
label: input.label || null,
|
||||
settings: { quick: input.quick, passes: input.passes ?? null, warmup: input.warmup ?? null, phases: input.phases },
|
||||
snapshot,
|
||||
})
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
const listColumns = {
|
||||
id: benchmarkRuns.id,
|
||||
deploymentId: benchmarkRuns.deploymentId,
|
||||
modelId: benchmarkRuns.modelId,
|
||||
tool: benchmarkRuns.tool,
|
||||
label: benchmarkRuns.label,
|
||||
settings: benchmarkRuns.settings,
|
||||
snapshot: benchmarkRuns.snapshot,
|
||||
state: benchmarkRuns.state,
|
||||
phase: benchmarkRuns.phase,
|
||||
cancelRequestedAt: benchmarkRuns.cancelRequestedAt,
|
||||
startedAt: benchmarkRuns.startedAt,
|
||||
finishedAt: benchmarkRuns.finishedAt,
|
||||
error: benchmarkRuns.error,
|
||||
summary: benchmarkRuns.summary,
|
||||
hasReport: benchmarkRuns.hasReport,
|
||||
createdAt: benchmarkRuns.createdAt,
|
||||
};
|
||||
|
||||
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
|
||||
|
||||
export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
|
||||
return db()
|
||||
.select(listColumns)
|
||||
.from(benchmarkRuns)
|
||||
.where(
|
||||
and(
|
||||
filter.deploymentId ? eq(benchmarkRuns.deploymentId, filter.deploymentId) : undefined,
|
||||
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(benchmarkRuns.createdAt));
|
||||
}
|
||||
|
||||
export async function getBenchmark(id: string) {
|
||||
const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function getBenchmarks(ids: string[]) {
|
||||
if (ids.length === 0) return [];
|
||||
const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
|
||||
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
|
||||
}
|
||||
|
||||
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
|
||||
export async function cancelBenchmark(id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state === "queued") {
|
||||
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "queued")));
|
||||
} else if (run.state === "running") {
|
||||
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateBenchmarkLabel(id: string, label: string | null) {
|
||||
const res = await db().update(benchmarkRuns).set({ label: label?.trim() || null }).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
|
||||
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
}
|
||||
|
||||
/** Deletes the run, its log and its files. Cancel a running one first. */
|
||||
export async function deleteBenchmark(id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state === "running") throw new BenchmarkError("busy", "Cancel the run before deleting it.", 409);
|
||||
await db().delete(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
|
||||
await db().delete(benchmarkRuns).where(eq(benchmarkRuns.id, id));
|
||||
await rm(runDir(id), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
export async function listBenchmarkLogs(id: string, afterId: number, tail = 500) {
|
||||
const rows =
|
||||
afterId > 0
|
||||
? await db()
|
||||
.select()
|
||||
.from(benchmarkLogs)
|
||||
.where(and(eq(benchmarkLogs.runId, id), gt(benchmarkLogs.id, afterId)))
|
||||
.orderBy(asc(benchmarkLogs.id))
|
||||
.limit(2000)
|
||||
: (await db().select().from(benchmarkLogs).where(eq(benchmarkLogs.runId, id)).orderBy(desc(benchmarkLogs.id)).limit(tail)).reverse();
|
||||
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
|
||||
}
|
||||
@@ -362,9 +362,17 @@ export type DockerHostInfo = {
|
||||
network: string | null;
|
||||
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
|
||||
modelsSource: { type: "bind" | "volume"; source: string } | null;
|
||||
/** Docker has the NVIDIA runtime / CDI devices, so GPUs can be requested. */
|
||||
nvidia?: boolean;
|
||||
/** GPUs found by a probe container (nvidia-smi); empty when none or not probed. */
|
||||
gpus?: HostGpu[];
|
||||
gpuError?: string | null;
|
||||
gpuCheckedAt?: string | null;
|
||||
checkedAt: string;
|
||||
};
|
||||
|
||||
export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -373,6 +381,13 @@ export type DockerHostInfo = {
|
||||
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
|
||||
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
|
||||
|
||||
/**
|
||||
* What the image computes on. nvidia: GPUs requested through Docker (NVIDIA Container Toolkit);
|
||||
* dri: Intel/AMD GPUs via /dev/dri (Vulkan, SYCL, XPU); rocm: AMD via /dev/kfd + /dev/dri.
|
||||
*/
|
||||
export const RUNTIME_ACCELERATORS = ["cpu", "nvidia", "dri", "rocm"] as const;
|
||||
export type RuntimeAccelerator = (typeof RUNTIME_ACCELERATORS)[number];
|
||||
|
||||
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
|
||||
export type ImageState = (typeof IMAGE_STATES)[number];
|
||||
|
||||
@@ -380,6 +395,7 @@ export const runtimes = sqliteTable("runtimes", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
|
||||
accelerator: text("accelerator", { enum: RUNTIME_ACCELERATORS }).notNull().default("cpu"),
|
||||
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
|
||||
image: text("image").notNull(),
|
||||
description: text("description"),
|
||||
@@ -451,6 +467,22 @@ export type DeploymentOptions = {
|
||||
flashAttn?: "auto" | "on" | "off" | null;
|
||||
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
|
||||
webui?: boolean | null;
|
||||
/** llama.cpp -cram: prompt cache in RAM, MiB (llama-server default 8192; 0 off, -1 unlimited). */
|
||||
cacheRamMb?: number | null;
|
||||
/** NVIDIA: GPU UUIDs to use (null: all). */
|
||||
gpus?: string[] | null;
|
||||
/** llama.cpp -ngl: "auto" (default), "all" or a number of layers. */
|
||||
gpuLayers?: string | null;
|
||||
/** llama.cpp -sm across several GPUs. */
|
||||
splitMode?: "none" | "layer" | "row" | "tensor" | null;
|
||||
/** llama.cpp -ts, e.g. "3,1". */
|
||||
tensorSplit?: string | null;
|
||||
/** llama.cpp: keep all MoE expert weights in RAM (-cmoe) or those of the first N layers (-ncmoe). */
|
||||
cpuMoe?: boolean | null;
|
||||
nCpuMoe?: number | null;
|
||||
/** vLLM --tensor-parallel-size and --gpu-memory-utilization. */
|
||||
tensorParallel?: number | null;
|
||||
gpuMemoryUtilization?: number | null;
|
||||
/** Only accept requests with one of the API keys from Settings → API keys. */
|
||||
requireApiKey?: boolean | null;
|
||||
/** vLLM */
|
||||
@@ -523,3 +555,201 @@ export const apiKeys = sqliteTable("api_keys", {
|
||||
key: text("key").notNull().unique(),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Benchmarks (BetterBench runs against a running deployment)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
|
||||
|
||||
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
|
||||
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
|
||||
|
||||
/** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */
|
||||
export type BenchmarkSettings = {
|
||||
quick: boolean;
|
||||
passes: number | null;
|
||||
warmup: number | null;
|
||||
phases: BenchmarkPhase[];
|
||||
};
|
||||
|
||||
/** The deployment as it was when the run started, so results stay comparable after edits. */
|
||||
export type BenchmarkSnapshot = {
|
||||
deploymentName: string;
|
||||
repoId: string;
|
||||
runtimeName: string;
|
||||
engine: RuntimeEngine;
|
||||
accelerator?: RuntimeAccelerator;
|
||||
/** Names of the GPUs used (NVIDIA), for comparisons. */
|
||||
gpuNames?: string[];
|
||||
/** The Docker host when the run started. */
|
||||
host?: { cpuModel: string | null; threads: number | null; memoryBytes: number | null; os: string | null };
|
||||
image: string;
|
||||
imageId: string | null;
|
||||
options: DeploymentOptions;
|
||||
cpus: number | null;
|
||||
memoryMb: number | null;
|
||||
/** Rendered command (API keys masked). */
|
||||
command: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
|
||||
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
|
||||
* or fills in a number; `null` means BetterBench didn't report it. The endpoint and host are never
|
||||
* stored. `v` 2; older summaries (no `v`) are recomputed by the worker from results.json.
|
||||
*/
|
||||
export type BenchmarkSummary = {
|
||||
v?: number;
|
||||
combined: { decode: number | null; ttft_p50: number | null; itl_low1: number | null; update_p50: number | null; update_p99: number | null } | null;
|
||||
single: {
|
||||
category: string;
|
||||
runs: number;
|
||||
tokens?: number;
|
||||
ttft_n?: number;
|
||||
gap_n?: number;
|
||||
ttft_p99_ok?: boolean;
|
||||
tail_ok?: boolean;
|
||||
ttft_p50: number | null;
|
||||
ttft_p99: number | null;
|
||||
update_p50?: number | null;
|
||||
update_p99?: number | null;
|
||||
tok_per_update: number | null;
|
||||
batched?: boolean;
|
||||
batched_runs?: number;
|
||||
decode_med: number | null;
|
||||
decode_iqr?: number | null;
|
||||
decode_cv: number | null;
|
||||
itl_low1: number | null;
|
||||
itl_med?: number | null;
|
||||
itl_high99?: number | null;
|
||||
}[];
|
||||
prefill: {
|
||||
target_depth: number;
|
||||
skipped: boolean;
|
||||
prompt_tokens_med?: number | null;
|
||||
ttft_p50?: number | null;
|
||||
pp_low1?: number | null;
|
||||
pp_med?: number | null;
|
||||
pp_p99?: number | null;
|
||||
pp_n?: number;
|
||||
pp_tail_ok?: boolean;
|
||||
}[];
|
||||
concurrency: {
|
||||
level: number;
|
||||
ok: number;
|
||||
requests: number;
|
||||
aggregate_tps: number;
|
||||
ttft_p50: number | null;
|
||||
ttft_p99: number | null;
|
||||
decode_med: number | null;
|
||||
ttft_n?: number;
|
||||
ttft_p99_ok?: boolean;
|
||||
}[];
|
||||
/** Thinking models: share of reasoning tokens and time to first answer token, where detectable. */
|
||||
reasoning?: { category: string; runs: number; known: number; answered: number; never_answered: number; reasoning_share: number | null; ttfa_p50: number | null }[];
|
||||
/** Percentiles resting on fewer samples than n · tail ≥ 5 requires (BetterBench's sample gate). */
|
||||
gate?: { section: string; key: string | number; metric: string; n: number; need: number }[];
|
||||
/** [runs stopped at max_tokens, ok runs] in the single-stream set. */
|
||||
truncated?: [number, number];
|
||||
failedSingle?: number;
|
||||
phases: string[];
|
||||
cacheHits: number;
|
||||
betterbenchVersion: string;
|
||||
corpusVersion: string;
|
||||
corpusHash?: string | null;
|
||||
timestamp?: string | null;
|
||||
maxModelLen?: number | null;
|
||||
config?: {
|
||||
warmup?: number | null;
|
||||
runs_per_category?: number | null;
|
||||
temperature?: number | null;
|
||||
top_p?: number | null;
|
||||
top_k?: number | null;
|
||||
greedy?: boolean | null;
|
||||
unique_nonce?: boolean | null;
|
||||
weights?: Record<string, number> | null;
|
||||
concurrency_levels?: number[] | null;
|
||||
concurrency_requests?: number | null;
|
||||
prefill_runs?: number | null;
|
||||
prefill_warmup?: number | null;
|
||||
prefill_max_tokens?: number | null;
|
||||
};
|
||||
passes: number | null;
|
||||
quick: boolean;
|
||||
};
|
||||
|
||||
export const benchmarkRuns = sqliteTable(
|
||||
"benchmark_runs",
|
||||
{
|
||||
id: id(),
|
||||
/** Null once the deployment is deleted; the snapshot keeps what was measured. */
|
||||
deploymentId: text("deployment_id"),
|
||||
modelId: text("model_id"),
|
||||
tool: text("tool").notNull().default("betterbench"),
|
||||
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
|
||||
snapshot: text("snapshot", { mode: "json" }).$type<BenchmarkSnapshot>().notNull(),
|
||||
/** Free-form label, e.g. "q8 KV cache". */
|
||||
label: text("label"),
|
||||
state: text("state", { enum: BENCHMARK_STATES }).notNull().default("queued"),
|
||||
phase: text("phase"),
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
startedAt: ts("started_at"),
|
||||
finishedAt: ts("finished_at"),
|
||||
error: text("error"),
|
||||
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),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
|
||||
);
|
||||
|
||||
export const benchmarkLogs = sqliteTable(
|
||||
"benchmark_logs",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
runId: text("run_id").notNull(),
|
||||
ts: integer("ts", { mode: "timestamp_ms" }).notNull(),
|
||||
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
|
||||
line: text("line").notNull(),
|
||||
},
|
||||
(t) => [index("benchmark_logs_idx").on(t.runId, t.id)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
|
||||
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
|
||||
* published / failed.
|
||||
*/
|
||||
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
|
||||
export type PublicationState = (typeof PUBLICATION_STATES)[number];
|
||||
|
||||
export const benchmarkPublications = sqliteTable(
|
||||
"benchmark_publications",
|
||||
{
|
||||
id: id(),
|
||||
runId: text("run_id").notNull(),
|
||||
state: text("state", { enum: PUBLICATION_STATES }).notNull().default("preview"),
|
||||
template: text("template").notNull().default("bench.betterbench.v1"),
|
||||
title: text("title"),
|
||||
summary: text("summary"),
|
||||
/** Size of the exact payload from the dry run; the payload itself is a file next to the run. */
|
||||
payloadBytes: integer("payload_bytes"),
|
||||
previewedAt: ts("previewed_at"),
|
||||
/** Who confirmed publishing (the second opt-in), and when. */
|
||||
confirmedBy: text("confirmed_by"),
|
||||
confirmedAt: ts("confirmed_at"),
|
||||
url: text("url"),
|
||||
guid: text("guid"),
|
||||
publishedAt: ts("published_at"),
|
||||
error: text("error"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("benchmark_publications_run_idx").on(t.runId)],
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { buildCommand, redactCommand, renderCommand } from "./deploy-command";
|
||||
import { buildCommand, estimateMemoryMb, redactCommand, renderCommand } from "./deploy-command";
|
||||
|
||||
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
|
||||
|
||||
@@ -83,4 +83,34 @@ describe("buildCommand", () => {
|
||||
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
|
||||
assert.equal(off.env.LLAMA_API_KEY, undefined);
|
||||
});
|
||||
|
||||
it("adds GPU flags only on GPU runtimes", () => {
|
||||
const model = { repoId: "a/b", localPath: "a/b" };
|
||||
const options = { modelFile: "m.gguf", contextSize: 4096, gpuLayers: "all", splitMode: "layer" as const, nCpuMoe: 8, cacheRamMb: 1024, extraArgs: [] };
|
||||
const gpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } }).args.join(" ");
|
||||
assert.match(gpu, /-cram 1024 -ngl all -sm layer -ncmoe 8 --metrics/);
|
||||
const cpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [] } }).args.join(" ");
|
||||
assert.ok(cpu.includes("-cram 1024") && !cpu.includes("-ngl") && !cpu.includes("-ncmoe"));
|
||||
const auto = buildCommand({ engine: "llama.cpp", model, options: { ...options, gpuLayers: "auto" }, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } });
|
||||
assert.ok(!auto.args.includes("-ngl"));
|
||||
|
||||
const vllm = buildCommand({
|
||||
engine: "vllm",
|
||||
model,
|
||||
options: { modelFile: "", contextSize: 4096, tensorParallel: 2, gpuMemoryUtilization: 0.85, kvCacheGb: 4, extraArgs: [] },
|
||||
runtime: { env: {}, extraArgs: [], accelerator: "nvidia" },
|
||||
});
|
||||
assert.match(vllm.args.join(" "), /--tensor-parallel-size 2 --gpu-memory-utilization 0.85/);
|
||||
assert.equal(vllm.env.VLLM_CPU_KVCACHE_SPACE, undefined);
|
||||
});
|
||||
|
||||
it("counts the prompt cache and KV cache in the llama.cpp memory estimate", () => {
|
||||
const file = 400 * 2 ** 20;
|
||||
const small = estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024 });
|
||||
const unset = estimateMemoryMb(file, 4096, "llama.cpp", {});
|
||||
assert.ok(small > 2048 && small < 3072, String(small));
|
||||
assert.equal(unset - small, 8192 - 1024);
|
||||
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }) < small);
|
||||
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, accelerator: "nvidia" }) < small);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
|
||||
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
|
||||
|
||||
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
|
||||
import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
/** Where the models folder is mounted inside every runtime container (read-only). */
|
||||
export const CONTAINER_MODELS_DIR = "/models";
|
||||
@@ -13,7 +13,8 @@ export type CommandInput = {
|
||||
engine: RuntimeEngine;
|
||||
options: DeploymentOptions;
|
||||
model: { repoId: string; localPath: string };
|
||||
runtime: { env: Record<string, string>; extraArgs: string[] };
|
||||
/** `accelerator` unset: CPU. */
|
||||
runtime: { env: Record<string, string>; extraArgs: string[]; accelerator?: RuntimeAccelerator };
|
||||
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
|
||||
apiKeys?: string[];
|
||||
};
|
||||
@@ -42,6 +43,7 @@ function withoutFlag(args: string[], flag: string): string[] {
|
||||
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
|
||||
const port = ENGINE_PORT[engine];
|
||||
const keys = o.requireApiKey ? apiKeys : [];
|
||||
const gpu = !!runtime.accelerator && runtime.accelerator !== "cpu";
|
||||
if (engine === "llama.cpp") {
|
||||
// The image's entrypoint is llama-server, so these are its arguments.
|
||||
const args = [
|
||||
@@ -62,9 +64,16 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
|
||||
...str("-ctk", o.cacheTypeK),
|
||||
...str("-ctv", o.cacheTypeV),
|
||||
...str("-fa", o.flashAttn),
|
||||
...num("-cram", o.cacheRamMb),
|
||||
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
|
||||
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
|
||||
...(o.webui === false ? ["--no-webui"] : []),
|
||||
// GPU offload (-ngl defaults to "auto", which fits layers into free VRAM).
|
||||
...(gpu ? str("-ngl", o.gpuLayers && o.gpuLayers !== "auto" ? o.gpuLayers : null) : []),
|
||||
...(gpu ? str("-sm", o.splitMode) : []),
|
||||
...(gpu ? str("-ts", o.tensorSplit) : []),
|
||||
...(gpu && o.cpuMoe ? ["-cmoe"] : []),
|
||||
...(gpu && !o.cpuMoe ? num("-ncmoe", o.nCpuMoe) : []),
|
||||
"--metrics",
|
||||
...runtime.extraArgs,
|
||||
...o.extraArgs,
|
||||
@@ -76,7 +85,7 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
|
||||
|
||||
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
|
||||
const env = { ...runtime.env };
|
||||
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
|
||||
if (!gpu && o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
|
||||
// VLLM_API_KEY holds a single key; more than one needs --api-key.
|
||||
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
|
||||
const args = [
|
||||
@@ -89,6 +98,8 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
|
||||
model.repoId,
|
||||
...num("--max-model-len", o.contextSize),
|
||||
...num("--max-num-seqs", o.maxNumSeqs),
|
||||
...(gpu ? num("--tensor-parallel-size", o.tensorParallel) : []),
|
||||
...(gpu ? num("--gpu-memory-utilization", o.gpuMemoryUtilization) : []),
|
||||
...(keys.length > 1 ? ["--api-key", ...keys] : []),
|
||||
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
|
||||
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
|
||||
@@ -112,11 +123,31 @@ export function renderCommand(image: string, cmd: ContainerCommand): string {
|
||||
}
|
||||
|
||||
/** Rough memory need: model files plus KV cache and runtime overhead. */
|
||||
export function estimateMemoryMb(fileBytes: number, contextSize: number, engine: RuntimeEngine, kvCacheGb?: number | null): number {
|
||||
/** llama-server's default --cache-ram (MiB): prompts kept in RAM for reuse. */
|
||||
export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
|
||||
|
||||
const KV_TYPE_FACTOR: Record<string, number> = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 };
|
||||
|
||||
/**
|
||||
* Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size
|
||||
* per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA.
|
||||
* Measured (llama.cpp b11429, Qwen3-0.6B Q4_K_M, ctx 4096): ~1.2 GiB without the prompt cache.
|
||||
*/
|
||||
export function estimateMemoryMb(
|
||||
fileBytes: number,
|
||||
contextSize: number,
|
||||
engine: RuntimeEngine,
|
||||
o: Pick<DeploymentOptions, "kvCacheGb" | "cacheRamMb" | "cacheTypeK" | "cacheTypeV"> & { accelerator?: RuntimeAccelerator } = {},
|
||||
): number {
|
||||
const model = fileBytes / 2 ** 20;
|
||||
const gpu = !!o.accelerator && o.accelerator !== "cpu";
|
||||
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
|
||||
if (engine === "vllm") return Math.ceil(model + (kvCacheGb ?? 4) * 1024 + 3072);
|
||||
// llama.cpp: ~ctx/8 MiB of f16 KV cache per 4k tokens for small models is too model-specific to
|
||||
// compute without the GGUF header; a margin that scales with context is a safe default.
|
||||
return Math.ceil(model * 1.1 + 512 + contextSize / 16);
|
||||
// On a GPU the weights and KV cache live in VRAM; RAM holds the processes.
|
||||
if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072);
|
||||
const perTokenKiB = 96 + 24 * Math.sqrt(model / 1024);
|
||||
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
|
||||
const kv = (contextSize * perTokenKiB * kvFactor) / 1024;
|
||||
const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb;
|
||||
// The memory-mapped model counts against the container's limit (page cache), even when offloaded.
|
||||
return Math.ceil(model + (gpu ? 0 : kv) + cache + 768);
|
||||
}
|
||||
+44
-2
@@ -37,6 +37,23 @@ export const DeploymentBody = z.object({
|
||||
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
|
||||
webui: z.boolean().nullable().optional(),
|
||||
requireApiKey: z.boolean().nullable().optional(),
|
||||
cacheRamMb: int(-1, 1_048_576).nullable().optional(),
|
||||
gpus: z.array(z.string().regex(/^GPU-[0-9a-f-]{36}$/i, "a GPU UUID")).max(64).nullable().optional(),
|
||||
gpuLayers: z
|
||||
.string()
|
||||
.regex(/^(auto|all|\d{1,4})$/, "auto, all or a number")
|
||||
.nullable()
|
||||
.optional(),
|
||||
splitMode: z.enum(["none", "layer", "row", "tensor"]).nullable().optional(),
|
||||
tensorSplit: z
|
||||
.string()
|
||||
.regex(/^\d+(\.\d+)?(,\d+(\.\d+)?)*$/, "proportions like 3,1")
|
||||
.nullable()
|
||||
.optional(),
|
||||
cpuMoe: z.boolean().nullable().optional(),
|
||||
nCpuMoe: int(0, 1000).nullable().optional(),
|
||||
tensorParallel: int(1, 64).nullable().optional(),
|
||||
gpuMemoryUtilization: z.number().min(0.05).max(1).nullable().optional(),
|
||||
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
|
||||
maxNumSeqs: int(1, 1024).nullable().optional(),
|
||||
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
|
||||
@@ -90,9 +107,33 @@ async function validate(input: DeploymentInput, selfId?: string): Promise<Deploy
|
||||
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
|
||||
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
|
||||
options.draftType = draft?.type ?? null;
|
||||
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null });
|
||||
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null, tensorParallel: null, gpuMemoryUtilization: null });
|
||||
} else {
|
||||
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null });
|
||||
Object.assign(options, {
|
||||
modelFile: "",
|
||||
mmproj: null,
|
||||
draftFile: null,
|
||||
draftType: null,
|
||||
batchSize: null,
|
||||
ubatchSize: null,
|
||||
cacheTypeK: null,
|
||||
cacheTypeV: null,
|
||||
flashAttn: null,
|
||||
webui: null,
|
||||
cacheRamMb: null,
|
||||
gpuLayers: null,
|
||||
splitMode: null,
|
||||
tensorSplit: null,
|
||||
cpuMoe: null,
|
||||
nCpuMoe: null,
|
||||
});
|
||||
}
|
||||
// GPU settings only mean something on a GPU runtime; GPU picking only on NVIDIA.
|
||||
if (runtime.accelerator === "cpu") {
|
||||
Object.assign(options, { gpus: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, tensorParallel: null, gpuMemoryUtilization: null });
|
||||
} else {
|
||||
if (runtime.accelerator !== "nvidia") options.gpus = null;
|
||||
options.kvCacheGb = null;
|
||||
}
|
||||
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
|
||||
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
|
||||
@@ -186,6 +227,7 @@ const listColumns = {
|
||||
runtimeId: deployments.runtimeId,
|
||||
runtimeName: runtimes.name,
|
||||
runtimeImage: runtimes.image,
|
||||
accelerator: runtimes.accelerator,
|
||||
engine: runtimes.engine,
|
||||
modelId: deployments.modelId,
|
||||
repoId: models.repoId,
|
||||
|
||||
@@ -30,6 +30,15 @@ const coreSchema = z.object({
|
||||
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
|
||||
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** BetterBench results and HTML reports. Default: "benchmarks" next to the SQLite database. */
|
||||
BENCHMARKS_DIR: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** The betterbench executable (the image ships one). Unset and not on PATH: benchmarks are disabled. */
|
||||
BETTERBENCH_BIN: z.preprocess(emptyToUndefined, z.string().default("betterbench")),
|
||||
/** launch80 publish token (worker only; passed to the L80 CLI via its environment, never shown or logged). */
|
||||
L80_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
L80_API_BASE: z.preprocess(emptyToUndefined, z.url().optional()),
|
||||
/** The L80 CLI (the image ships one). */
|
||||
L80_BIN: z.preprocess(emptyToUndefined, z.string().default("L80")),
|
||||
});
|
||||
|
||||
const authSchema = z.object({
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import "server-only";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { runDir } from "@/lib/benchmark-paths";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { benchmarkPublications, benchmarkRuns, settings } from "@/lib/db/schema";
|
||||
|
||||
export class PublicationError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Limits of the L80 CLI (internal/betterbench: maxTitle, maxSummary). */
|
||||
export const PreviewBody = z.object({
|
||||
title: z.string().trim().max(120).nullable().optional(),
|
||||
summary: z.string().trim().max(600).nullable().optional(),
|
||||
});
|
||||
|
||||
export type L80Status = { version: string | null; tokenSet: boolean; apiBase: string; checkedAt: string } | null;
|
||||
|
||||
export async function getL80Status(): Promise<L80Status> {
|
||||
const row = await db().query.settings.findFirst({ where: eq(settings.key, "l80.status") });
|
||||
return (row?.value as L80Status) ?? null;
|
||||
}
|
||||
|
||||
export type PublicationRow = typeof benchmarkPublications.$inferSelect;
|
||||
|
||||
export async function listPublications(runId: string): Promise<PublicationRow[]> {
|
||||
return db().select().from(benchmarkPublications).where(eq(benchmarkPublications.runId, runId)).orderBy(desc(benchmarkPublications.createdAt));
|
||||
}
|
||||
|
||||
async function getPublication(runId: string, pubId: string) {
|
||||
const p = await db().query.benchmarkPublications.findFirst({ where: and(eq(benchmarkPublications.id, pubId), eq(benchmarkPublications.runId, runId)) });
|
||||
if (!p) throw new PublicationError("not_found", "Publication not found.", 404);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Opt-in 1: build the exact payload with a dry run (nothing leaves the machine). */
|
||||
export async function requestPreview(runId: string, input: z.infer<typeof PreviewBody>) {
|
||||
const run = await db().query.benchmarkRuns.findFirst({ columns: { state: true }, where: eq(benchmarkRuns.id, runId) });
|
||||
if (!run) throw new PublicationError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state !== "completed") throw new PublicationError("invalid", "Only completed runs can be published.", 409);
|
||||
const status = await getL80Status();
|
||||
if (!status?.version) throw new PublicationError("invalid", "The L80 CLI isn't available in this installation.", 409);
|
||||
const [row] = await db()
|
||||
.insert(benchmarkPublications)
|
||||
.values({ runId, title: input.title || null, summary: input.summary || null })
|
||||
.returning({ id: benchmarkPublications.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Opt-in 2: an explicit confirmation of a previewed payload. */
|
||||
export async function confirmPublication(runId: string, pubId: string, by: string | null) {
|
||||
const p = await getPublication(runId, pubId);
|
||||
if (p.state !== "previewed") throw new PublicationError("invalid", "Only a finished preview can be published.", 409);
|
||||
const status = await getL80Status();
|
||||
if (!status?.tokenSet) throw new PublicationError("invalid", "No launch80 token is configured (L80_TOKEN).", 409);
|
||||
await db()
|
||||
.update(benchmarkPublications)
|
||||
.set({ state: "publish", confirmedBy: by, confirmedAt: new Date() })
|
||||
.where(and(eq(benchmarkPublications.id, pubId), eq(benchmarkPublications.state, "previewed")));
|
||||
}
|
||||
|
||||
/** Throw away a preview (published ones stay as a record). */
|
||||
export async function discardPublication(runId: string, pubId: string) {
|
||||
const p = await getPublication(runId, pubId);
|
||||
if (p.state === "published" || p.state === "publish") throw new PublicationError("busy", "Published pages can't be withdrawn from here; they expire after 5 days.", 409);
|
||||
await db().delete(benchmarkPublications).where(eq(benchmarkPublications.id, pubId));
|
||||
await rm(payloadFile(runId, pubId), { force: true });
|
||||
}
|
||||
|
||||
export function payloadFile(runId: string, pubId: string): string {
|
||||
// Ids come from the URL; only ULIDs become a path.
|
||||
if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(pubId)) throw new PublicationError("not_found", "Publication not found.", 404);
|
||||
return join(runDir(runId), "publications", `${pubId}.json`);
|
||||
}
|
||||
|
||||
export type PayloadPreview = {
|
||||
template: string;
|
||||
bytes: number;
|
||||
title: string | null;
|
||||
summary: string | null;
|
||||
model: string | null;
|
||||
notes: Record<string, string>;
|
||||
/** Top-level keys that will be sent, and env keys (endpoint/host must be absent). */
|
||||
keys: string[];
|
||||
envKeys: string[];
|
||||
hostRemoved: boolean;
|
||||
categories: string[];
|
||||
phases: string[];
|
||||
};
|
||||
|
||||
/** What the dry-run payload contains, read from the exact file that would be sent. */
|
||||
export async function readPayloadPreview(runId: string, pubId: string): Promise<PayloadPreview | null> {
|
||||
const p = await getPublication(runId, pubId);
|
||||
const raw = await readFile(payloadFile(runId, p.id), "utf8").catch(() => null);
|
||||
if (!raw) return null;
|
||||
const data = JSON.parse(raw) as Record<string, unknown> & {
|
||||
$template?: string;
|
||||
env?: Record<string, unknown>;
|
||||
l80?: { title?: string; summary?: string };
|
||||
single_stream?: Record<string, unknown>;
|
||||
prefill?: unknown[];
|
||||
concurrency?: unknown[];
|
||||
};
|
||||
const env = data.env ?? {};
|
||||
return {
|
||||
template: data.$template ?? p.template,
|
||||
bytes: Buffer.byteLength(raw),
|
||||
title: data.l80?.title ?? null,
|
||||
summary: data.l80?.summary ?? null,
|
||||
model: typeof env.model === "string" ? env.model : null,
|
||||
notes: (env.notes as Record<string, string>) ?? {},
|
||||
keys: Object.keys(data),
|
||||
envKeys: Object.keys(env),
|
||||
hostRemoved: !("endpoint" in env) && !("host" in env),
|
||||
categories: Object.keys(data.single_stream ?? {}),
|
||||
phases: [data.single_stream ? "decode" : null, data.prefill?.length ? "prefill" : null, data.concurrency?.length ? "concurrency" : null].filter(Boolean) as string[],
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,21 @@
|
||||
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
|
||||
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
export const ACCELERATOR_LABEL: Record<RuntimeAccelerator, string> = {
|
||||
cpu: "CPU",
|
||||
nvidia: "NVIDIA (CUDA)",
|
||||
dri: "Intel / AMD via /dev/dri",
|
||||
rocm: "AMD ROCm",
|
||||
};
|
||||
|
||||
/** Device nodes an accelerator needs passed through (NVIDIA GPUs are requested from Docker instead). */
|
||||
export const ACCELERATOR_DEVICES: Record<RuntimeAccelerator, string[]> = { cpu: [], nvidia: [], dri: ["/dev/dri"], rocm: ["/dev/kfd", "/dev/dri"] };
|
||||
|
||||
export type RuntimeInput = {
|
||||
name: string;
|
||||
engine: RuntimeEngine;
|
||||
accelerator?: RuntimeAccelerator;
|
||||
image: string;
|
||||
description?: string | null;
|
||||
env?: Record<string, string>;
|
||||
@@ -16,7 +27,7 @@ export type RuntimeInput = {
|
||||
|
||||
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
|
||||
|
||||
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0). */
|
||||
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0; all tags exist). */
|
||||
export const RUNTIME_PRESETS: RuntimePreset[] = [
|
||||
{
|
||||
id: "llama.cpp-cpu",
|
||||
@@ -37,6 +48,77 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
|
||||
extraArgs: ["--dtype=bfloat16"],
|
||||
shmSizeMb: 4096,
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-cuda",
|
||||
name: "llama.cpp (CUDA)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "nvidia",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-cuda",
|
||||
summary: "llama-server for NVIDIA GPUs. Needs the NVIDIA Container Toolkit on the Docker host.",
|
||||
description: "Official llama.cpp server, CUDA build. Layers go to the GPU automatically (-ngl auto); set GPU layers per deployment.",
|
||||
},
|
||||
{
|
||||
id: "vllm-cuda",
|
||||
name: "vLLM (CUDA)",
|
||||
engine: "vllm",
|
||||
accelerator: "nvidia",
|
||||
image: "vllm/vllm-openai:v0.31.0",
|
||||
summary: "Official vLLM image for NVIDIA GPUs (large download). Needs the NVIDIA Container Toolkit.",
|
||||
description: "Official vLLM, CUDA build. vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU up front.",
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-vulkan",
|
||||
name: "llama.cpp (Vulkan)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "dri",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-vulkan",
|
||||
summary: "llama-server over Vulkan: Intel Arc and AMD GPUs via /dev/dri.",
|
||||
description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri.",
|
||||
devices: ["/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-intel",
|
||||
name: "llama.cpp (Intel SYCL)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "dri",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
|
||||
summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs.",
|
||||
description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri).",
|
||||
devices: ["/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-rocm",
|
||||
name: "llama.cpp (ROCm)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "rocm",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-rocm",
|
||||
summary: "llama-server for AMD GPUs with ROCm (/dev/kfd, /dev/dri).",
|
||||
description: "Official llama.cpp server, ROCm build for AMD GPUs.",
|
||||
devices: ["/dev/kfd", "/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "vllm-xpu",
|
||||
name: "vLLM (Intel XPU)",
|
||||
engine: "vllm",
|
||||
accelerator: "dri",
|
||||
image: "vllm/vllm-openai-xpu:v0.31.0",
|
||||
summary: "Official vLLM image for Intel GPUs (Arc, Data Center GPU Max) via /dev/dri.",
|
||||
description: "Official vLLM, XPU build for Intel GPUs.",
|
||||
devices: ["/dev/dri"],
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
{
|
||||
id: "vllm-rocm",
|
||||
name: "vLLM (ROCm)",
|
||||
engine: "vllm",
|
||||
accelerator: "rocm",
|
||||
image: "vllm/vllm-openai-rocm:v0.31.0",
|
||||
summary: "Official vLLM image for AMD GPUs with ROCm.",
|
||||
description: "Official vLLM, ROCm build for AMD GPUs.",
|
||||
devices: ["/dev/kfd", "/dev/dri"],
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
];
|
||||
|
||||
export const RUNTIME_NAME_MAX = 60;
|
||||
@@ -54,6 +136,8 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
|
||||
const name = input.name.trim().replace(/\s+/g, " ");
|
||||
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
|
||||
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
|
||||
const accelerator = input.accelerator ?? "cpu";
|
||||
if (!RUNTIME_ACCELERATORS.includes(accelerator)) throw new RuntimeValidationError("Unknown accelerator.");
|
||||
const image = input.image.trim();
|
||||
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
|
||||
|
||||
@@ -76,6 +160,7 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
|
||||
return {
|
||||
name,
|
||||
engine: input.engine,
|
||||
accelerator,
|
||||
image,
|
||||
description: input.description?.trim() || null,
|
||||
env,
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@ import "server-only";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, runtimes, workerState } from "@/lib/db/schema";
|
||||
import { type DockerHostInfo, RUNTIME_ACCELERATORS, runtimes, workerState } from "@/lib/db/schema";
|
||||
import { deploymentsUsing } from "@/lib/deployments";
|
||||
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
|
||||
|
||||
@@ -12,6 +12,7 @@ export type Runtime = typeof runtimes.$inferSelect;
|
||||
export const RuntimeBody = z.object({
|
||||
name: z.string().max(200),
|
||||
engine: z.enum(["llama.cpp", "vllm"]),
|
||||
accelerator: z.enum(RUNTIME_ACCELERATORS).optional(),
|
||||
image: z.string().max(512),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
env: z.record(z.string(), z.string().max(4000)).optional(),
|
||||
|
||||
Reference in new issue
Block a user