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:
1 parent
9e167a44f6
commit
b623b16a6d
37 files changed
+4314
-214
No files matched your search
@@ -0,0 +1,50 @@
|
||||
// `betterbench ab` output (ab.json) → Kaname's AbSummary. Keeps BetterBench's own paired_compare
|
||||
// results as reported; drops the endpoints (they never leave the machine). Pure, for tests.
|
||||
|
||||
import type { AbSummary, PairedResult } from "@/lib/db/schema";
|
||||
|
||||
type AbJson = {
|
||||
betterbench_version?: string;
|
||||
corpus_version?: string;
|
||||
config?: Record<string, unknown>;
|
||||
env?: { timestamp?: string };
|
||||
pairs: number;
|
||||
decode_tps: PairedResult;
|
||||
gap_median?: PairedResult & { batched?: boolean };
|
||||
itl_median?: PairedResult;
|
||||
paired_cv: number;
|
||||
pairs_needed_for_mde: number;
|
||||
target_mde_pct: number;
|
||||
conf: number;
|
||||
raw?: { a_tps?: number[]; b_tps?: number[] };
|
||||
};
|
||||
|
||||
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
||||
|
||||
export function abSummary(raw: string, maxPairs: number | null): AbSummary {
|
||||
const j = JSON.parse(raw) as AbJson;
|
||||
if (!j.decode_tps || typeof j.pairs !== "number") throw new Error("not a BetterBench ab.json");
|
||||
const gap = j.gap_median ?? (j.itl_median ? { ...j.itl_median, batched: false } : null);
|
||||
const cfg = j.config ?? {};
|
||||
return {
|
||||
pairs: j.pairs,
|
||||
decode_tps: j.decode_tps,
|
||||
gap_median: { ...(gap as PairedResult), batched: !!(gap as { batched?: boolean } | null)?.batched },
|
||||
paired_cv: j.paired_cv,
|
||||
pairs_needed_for_mde: j.pairs_needed_for_mde,
|
||||
target_mde_pct: j.target_mde_pct,
|
||||
conf: j.conf,
|
||||
maxPairs,
|
||||
raw: { a_tps: j.raw?.a_tps ?? [], b_tps: j.raw?.b_tps ?? [] },
|
||||
betterbenchVersion: j.betterbench_version ?? "",
|
||||
corpusVersion: j.corpus_version ?? "",
|
||||
timestamp: j.env?.timestamp ?? null,
|
||||
config: {
|
||||
greedy: typeof cfg.greedy === "boolean" ? cfg.greedy : null,
|
||||
temperature: num(cfg.temperature),
|
||||
warmup: num(cfg.warmup),
|
||||
unique_nonce: typeof cfg.unique_nonce === "boolean" ? cfg.unique_nonce : null,
|
||||
ab_min_pairs: num(cfg.ab_min_pairs),
|
||||
},
|
||||
};
|
||||
}
|
||||
+120
-45
@@ -2,7 +2,7 @@
|
||||
// measure each other).
|
||||
|
||||
import { type ChildProcess, execFile, spawn } from "node:child_process";
|
||||
import { access, mkdir } from "node:fs/promises";
|
||||
import { access, mkdir, readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
@@ -11,12 +11,25 @@ import { db } from "@/lib/db/client";
|
||||
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
|
||||
import { ENGINE_PORT } from "@/lib/deploy-command";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
|
||||
import { abSummary } from "./ab-summary";
|
||||
import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
|
||||
import { sanitizeLine } from "./job-log";
|
||||
import { log } from "./log";
|
||||
import { errorCauses } from "./log-causes";
|
||||
import { ResourceSampler } from "./resources";
|
||||
import { docker, workerImage } from "./runtimes";
|
||||
|
||||
type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] };
|
||||
type Current = {
|
||||
runId: string;
|
||||
kind: "run" | "ab";
|
||||
deploymentIds: string[];
|
||||
child: ChildProcess;
|
||||
sampler: ResourceSampler | null;
|
||||
maxPairs: number | null;
|
||||
cancelled: boolean;
|
||||
lost: string | null;
|
||||
secrets: string[];
|
||||
};
|
||||
|
||||
let current: Current | null = null;
|
||||
let starting = false;
|
||||
@@ -114,36 +127,61 @@ async function summarize(results: string): Promise<BenchmarkSummary> {
|
||||
return JSON.parse(stdout) as BenchmarkSummary;
|
||||
}
|
||||
|
||||
type Target = { id: string; containerId: string; containerName: string; engine: "llama.cpp" | "vllm"; accelerator: string };
|
||||
|
||||
async function target(deploymentId: string | null): Promise<Target | null> {
|
||||
if (!deploymentId) return null;
|
||||
const [d] = await db()
|
||||
.select({ state: deployments.state, containerId: deployments.containerId, containerName: deployments.containerName, engine: runtimes.engine, accelerator: runtimes.accelerator })
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(eq(deployments.id, deploymentId));
|
||||
if (!d || d.state !== "running" || !d.containerName || !d.containerId) return null;
|
||||
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
|
||||
}
|
||||
|
||||
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
|
||||
|
||||
async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
const fail = (error: string) => finish(run.id, { state: "failed", error });
|
||||
const [d] = run.deploymentId
|
||||
? await db()
|
||||
.select({ state: deployments.state, containerName: deployments.containerName, engine: runtimes.engine })
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(eq(deployments.id, run.deploymentId))
|
||||
: [];
|
||||
if (!d || d.state !== "running" || !d.containerName) return fail("The deployment isn't running anymore.");
|
||||
const a = await target(run.deploymentId);
|
||||
if (!a) return fail(run.kind === "ab" ? "Deployment A isn't running anymore." : "The deployment isn't running anymore.");
|
||||
const b = run.kind === "ab" ? await target(run.deploymentBId) : null;
|
||||
if (run.kind === "ab" && !b) return fail("Deployment B isn't running anymore.");
|
||||
|
||||
const dir = runDir(run.id);
|
||||
await mkdir(dir, { recursive: true });
|
||||
const keys = run.snapshot.options.requireApiKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
|
||||
const needsKey = run.snapshot.options.requireApiKey || run.snapshotB?.options.requireApiKey;
|
||||
// One key works for both: BETTERBENCH_API_KEY fills in every missing key flag.
|
||||
const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
|
||||
const s = run.snapshot;
|
||||
const args = runArgs({
|
||||
endpoint: `http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1`,
|
||||
model: s.repoId,
|
||||
out: join(dir, RESULTS_FILE),
|
||||
settings: run.settings,
|
||||
maxModelLen: s.options.contextSize ?? null,
|
||||
notes: {
|
||||
deployment: s.deploymentName,
|
||||
runtime: s.runtimeName,
|
||||
image: s.image,
|
||||
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
|
||||
ctx: String(s.options.contextSize),
|
||||
...(run.label ? { label: run.label } : {}),
|
||||
},
|
||||
});
|
||||
const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
|
||||
const args =
|
||||
run.kind === "ab" && b
|
||||
? abArgs({
|
||||
endpointA: endpoint(a),
|
||||
endpointB: endpoint(b),
|
||||
model: s.repoId,
|
||||
out: join(dir, AB_FILE),
|
||||
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
|
||||
maxPairs,
|
||||
notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}) },
|
||||
})
|
||||
: runArgs({
|
||||
endpoint: endpoint(a),
|
||||
model: s.repoId,
|
||||
out: join(dir, RESULTS_FILE),
|
||||
settings: run.settings,
|
||||
maxModelLen: s.options.contextSize ?? null,
|
||||
notes: {
|
||||
deployment: s.deploymentName,
|
||||
runtime: s.runtimeName,
|
||||
image: s.image,
|
||||
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
|
||||
ctx: String(s.options.contextSize),
|
||||
...(run.label ? { label: run.label } : {}),
|
||||
},
|
||||
});
|
||||
// Only what BetterBench needs: no HF_TOKEN or other worker secrets.
|
||||
const env: Record<string, string | undefined> = {
|
||||
PATH: process.env.PATH,
|
||||
@@ -156,20 +194,48 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}),
|
||||
};
|
||||
|
||||
addLog(run.id, "system", `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`);
|
||||
addLog(
|
||||
run.id,
|
||||
"system",
|
||||
run.kind === "ab"
|
||||
? `Paired A/B: ${s.deploymentName} (A) vs ${run.snapshotB?.deploymentName} (B), ${s.repoId}, with BetterBench`
|
||||
: `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`,
|
||||
);
|
||||
addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
|
||||
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
|
||||
|
||||
// Resource use of the server(s) under test; GPUs when any side runs on NVIDIA.
|
||||
const c = docker();
|
||||
const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia";
|
||||
const sampler = c
|
||||
? new ResourceSampler(
|
||||
c,
|
||||
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
|
||||
nvidia ? workerImage() : null,
|
||||
)
|
||||
: null;
|
||||
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
|
||||
|
||||
const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
||||
const cur: Current = { runId: run.id, deploymentId: run.deploymentId, child, cancelled: false, lost: null, secrets: keys };
|
||||
const cur: Current = {
|
||||
runId: run.id,
|
||||
kind: run.kind,
|
||||
deploymentIds: [a.id, ...(b ? [b.id] : [])],
|
||||
child,
|
||||
sampler,
|
||||
maxPairs: run.kind === "ab" ? maxPairs : null,
|
||||
cancelled: false,
|
||||
lost: null,
|
||||
secrets: keys,
|
||||
};
|
||||
current = cur;
|
||||
child.stdout.on("data", (b: Buffer) => chunk(run.id, "stdout", b, keys));
|
||||
child.stderr.on("data", (b: Buffer) => chunk(run.id, "stderr", b, keys));
|
||||
child.stdout.on("data", (buf: Buffer) => chunk(run.id, "stdout", buf, keys));
|
||||
child.stderr.on("data", (buf: Buffer) => chunk(run.id, "stderr", buf, keys));
|
||||
child.on("error", (err: NodeJS.ErrnoException) => {
|
||||
addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`);
|
||||
});
|
||||
child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err)));
|
||||
log.info(`benchmark ${run.id}: started for ${s.deploymentName}`);
|
||||
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
|
||||
}
|
||||
|
||||
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
|
||||
@@ -179,26 +245,33 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
|
||||
partial.delete(`${id}:${stream}`);
|
||||
}
|
||||
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
|
||||
if (current === cur) current = null;
|
||||
const dir = runDir(id);
|
||||
const results = join(dir, RESULTS_FILE);
|
||||
const hasReport = await exists(join(dir, REPORT_FILE));
|
||||
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
|
||||
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
|
||||
|
||||
if (cur.cancelled) {
|
||||
addLog(id, "system", "Cancelled.");
|
||||
await finish(id, { state: "cancelled", hasReport });
|
||||
await finish(id, { state: "cancelled", hasReport, resources });
|
||||
} else if (cur.lost) {
|
||||
addLog(id, "system", cur.lost);
|
||||
await finish(id, { state: "failed", error: cur.lost, hasReport });
|
||||
await finish(id, { state: "failed", error: cur.lost, hasReport, resources });
|
||||
} else if (code === 0 && (await exists(results))) {
|
||||
try {
|
||||
const summary = { ...(await summarize(results)), quick: false };
|
||||
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
|
||||
summary.quick = !!run?.settings.quick;
|
||||
addLog(id, "system", "Done.");
|
||||
await finish(id, { state: "completed", summary, hasReport });
|
||||
if (cur.kind === "ab") {
|
||||
const ab = abSummary(await readFile(results, "utf8"), cur.maxPairs);
|
||||
addLog(id, "system", `Done: ${ab.decode_tps.verdict} (${ab.pairs} pairs).`);
|
||||
await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, resources, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." });
|
||||
} else {
|
||||
const summary = { ...(await summarize(results)), quick: false };
|
||||
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
|
||||
summary.quick = !!run?.settings.quick;
|
||||
addLog(id, "system", "Done.");
|
||||
await finish(id, { state: "completed", summary, hasReport, resources });
|
||||
}
|
||||
} catch (err) {
|
||||
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
|
||||
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport, resources });
|
||||
}
|
||||
} else {
|
||||
const lines = tails.get(id) ?? [];
|
||||
@@ -209,6 +282,7 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
state: "failed",
|
||||
error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
|
||||
hasReport,
|
||||
resources,
|
||||
});
|
||||
}
|
||||
tails.delete(id);
|
||||
@@ -233,11 +307,12 @@ export async function tickBenchmarks(): Promise<void> {
|
||||
stop(cur);
|
||||
return;
|
||||
}
|
||||
if (cur.deploymentId) {
|
||||
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId));
|
||||
for (const depId of cur.deploymentIds) {
|
||||
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId));
|
||||
if (!d || d.state !== "running") {
|
||||
cur.lost = "The deployment stopped during the run.";
|
||||
cur.lost = cur.deploymentIds.length > 1 ? "A deployment of the A/B stopped during the run." : "The deployment stopped during the run.";
|
||||
stop(cur);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -43,6 +43,39 @@ export function runArgs(o: {
|
||||
];
|
||||
}
|
||||
|
||||
/** `betterbench ab`: interleaved paired A/B until the CI is tighter than --mde (or --max-pairs). */
|
||||
export function abArgs(o: {
|
||||
endpointA: string;
|
||||
endpointB: string;
|
||||
model: string;
|
||||
out: string;
|
||||
mdePct: number;
|
||||
maxPairs: number;
|
||||
notes: Record<string, string>;
|
||||
}): string[] {
|
||||
return [
|
||||
"ab",
|
||||
"--endpoint-a",
|
||||
o.endpointA,
|
||||
"--endpoint-b",
|
||||
o.endpointB,
|
||||
"--model",
|
||||
o.model,
|
||||
"--out",
|
||||
o.out,
|
||||
"--mde",
|
||||
String(o.mdePct),
|
||||
"--max-pairs",
|
||||
String(o.maxPairs),
|
||||
...Object.entries(o.notes).flatMap(([k, v]) => ["--note", `${k}=${v}`]),
|
||||
"--no-update-check",
|
||||
];
|
||||
}
|
||||
|
||||
export { AB_FILE } from "@/lib/benchmark-paths";
|
||||
export const AB_DEFAULT_MDE_PCT = 1;
|
||||
export const AB_DEFAULT_MAX_PAIRS = 200;
|
||||
|
||||
/**
|
||||
* Prints Kaname's BenchmarkSummary for a results.json, using BetterBench's own report functions
|
||||
* so the numbers match its HTML report.
|
||||
|
||||
@@ -14,6 +14,7 @@ import { backfillMetadata } from "@/lib/hub/refresh";
|
||||
import { DeleteRunner } from "./delete";
|
||||
import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks";
|
||||
import { reportL80Status, tickPublications } from "./publish";
|
||||
import { tickSweeps } from "./sweeps";
|
||||
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
|
||||
import { DownloadRunner } from "./download";
|
||||
import { log } from "./log";
|
||||
@@ -414,6 +415,7 @@ async function main() {
|
||||
void refreshSummaries();
|
||||
void reportL80Status();
|
||||
timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS));
|
||||
timers.push(setInterval(() => void tickSweeps(), BENCHMARK_TICK_MS));
|
||||
timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS));
|
||||
timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS));
|
||||
void scanFolders();
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// Samples resource use while a benchmark runs: CPU and memory of the deployment containers (Docker
|
||||
// stats, every ~2 s) and, on NVIDIA hosts, whole-GPU VRAM/utilization/power from one long-lived
|
||||
// `nvidia-smi -lms` probe container. Aggregation is pure (summarizeSamples) for tests.
|
||||
|
||||
import type { ResourceStats } from "@/lib/db/schema";
|
||||
import type { DockerClient } from "./docker/client";
|
||||
import { log } from "./log";
|
||||
|
||||
const INTERVAL_MS = 2_000;
|
||||
|
||||
export type ContainerSample = { side: "a" | "b"; cpuPercent: number; memoryBytes: number; memoryLimitBytes: number };
|
||||
export type GpuSample = { index: number; name: string; vramTotalMb: number; vramUsedMb: number; util: number; powerW: number | null };
|
||||
|
||||
const avg = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null);
|
||||
const peak = (xs: number[]) => (xs.length ? Math.max(...xs) : null);
|
||||
|
||||
/** One CSV line of `nvidia-smi --query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw`. */
|
||||
export function parseGpuLine(line: string): GpuSample | null {
|
||||
const p = line.split(",").map((x) => x.trim());
|
||||
if (p.length < 6 || !/^\d+$/.test(p[0])) return null;
|
||||
const n = (s: string) => (Number.isFinite(Number(s)) ? Number(s) : null);
|
||||
return { index: Number(p[0]), name: p[1], vramTotalMb: n(p[2]) ?? 0, vramUsedMb: n(p[3]) ?? 0, util: n(p[4]) ?? 0, powerW: n(p[5]) };
|
||||
}
|
||||
|
||||
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number): ResourceStats {
|
||||
const sides = [...new Set(containers.map((c) => c.side))].sort();
|
||||
return {
|
||||
samples: containers.length,
|
||||
seconds: Math.round(seconds),
|
||||
containers: sides.map((side) => {
|
||||
const xs = containers.filter((c) => c.side === side);
|
||||
// Docker reports CPU in percent of one core; keep cores.
|
||||
const cpu = xs.map((x) => x.cpuPercent / 100);
|
||||
const mem = xs.map((x) => x.memoryBytes);
|
||||
const limit = xs.find((x) => x.memoryLimitBytes > 0)?.memoryLimitBytes ?? null;
|
||||
return {
|
||||
side,
|
||||
cpuAvg: avg(cpu),
|
||||
cpuPeak: peak(cpu),
|
||||
memAvgBytes: avg(mem),
|
||||
memPeakBytes: peak(mem),
|
||||
// Without a limit Docker reports the host's memory; that isn't a limit.
|
||||
memLimitBytes: limit,
|
||||
};
|
||||
}),
|
||||
gpus: [...new Set(gpus.map((g) => g.index))].sort((a, b) => a - b).map((index) => {
|
||||
const xs = gpus.filter((g) => g.index === index);
|
||||
const power = xs.map((x) => x.powerW).filter((x): x is number => x != null);
|
||||
return {
|
||||
index,
|
||||
name: xs[0].name,
|
||||
vramTotalMb: xs[0].vramTotalMb,
|
||||
vramPeakMb: peak(xs.map((x) => x.vramUsedMb)) ?? 0,
|
||||
vramAvgMb: avg(xs.map((x) => x.vramUsedMb)) ?? 0,
|
||||
utilAvg: avg(xs.map((x) => x.util)) ?? 0,
|
||||
utilPeak: peak(xs.map((x) => x.util)) ?? 0,
|
||||
powerAvgW: avg(power),
|
||||
powerPeakW: peak(power),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export class ResourceSampler {
|
||||
private containerSamples: ContainerSample[] = [];
|
||||
private gpuSamples: GpuSample[] = [];
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private probeId: string | null = null;
|
||||
private abort = new AbortController();
|
||||
private started = Date.now();
|
||||
|
||||
constructor(
|
||||
private c: DockerClient,
|
||||
private targets: { side: "a" | "b"; containerId: string }[],
|
||||
private gpuProbeImage: string | null,
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.started = Date.now();
|
||||
this.timer = setInterval(() => void this.sample(), INTERVAL_MS);
|
||||
void this.sample();
|
||||
if (this.gpuProbeImage) await this.startGpuProbe(this.gpuProbeImage).catch((err) => log.warn(`GPU sampling unavailable: ${err instanceof Error ? err.message : err}`));
|
||||
}
|
||||
|
||||
private async sample() {
|
||||
if (this.busy) return;
|
||||
this.busy = true;
|
||||
try {
|
||||
for (const t of this.targets) {
|
||||
const s = await this.c.containerStats(t.containerId).catch(() => null);
|
||||
if (s) this.containerSamples.push({ side: t.side, ...s });
|
||||
}
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async startGpuProbe(image: string) {
|
||||
const created = await this.c.createContainer(`kaname-gpu-sampler-${Date.now().toString(36)}`, {
|
||||
Image: image,
|
||||
Entrypoint: ["nvidia-smi"],
|
||||
Cmd: ["--query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw", "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)],
|
||||
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
|
||||
Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" },
|
||||
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false },
|
||||
});
|
||||
this.probeId = created.Id;
|
||||
await this.c.startContainer(created.Id);
|
||||
void this.c
|
||||
.followLogs(
|
||||
created.Id,
|
||||
(_s, line) => {
|
||||
const g = parseGpuLine(line);
|
||||
if (g) this.gpuSamples.push(g);
|
||||
},
|
||||
{ tail: "all", signal: this.abort.signal },
|
||||
)
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
/** Stop sampling and return the aggregate (never throws). */
|
||||
async stop(): Promise<ResourceStats> {
|
||||
clearInterval(this.timer);
|
||||
this.abort.abort();
|
||||
if (this.probeId) {
|
||||
await this.c.stopContainer(this.probeId, 1).catch(() => {});
|
||||
await this.c.removeContainer(this.probeId).catch(() => {});
|
||||
}
|
||||
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000);
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,10 @@ async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "networ
|
||||
// --- GPUs ---------------------------------------------------------------------
|
||||
|
||||
const GPU_PROBE_MS = 60 * 60_000;
|
||||
let ownImage: string | null = null;
|
||||
|
||||
/** The worker's own image (from the last host check); probe containers run from it. */
|
||||
export const workerImage = () => ownImage;
|
||||
let gpuCache: { at: number; gpus: HostGpu[]; error: string | null } | null = null;
|
||||
|
||||
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
|
||||
@@ -146,6 +150,7 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
try {
|
||||
const [v, i] = await Promise.all([c.version(), c.info()]);
|
||||
const self = await selfDetect(c);
|
||||
ownImage = self.image;
|
||||
info = {
|
||||
connected: true,
|
||||
error: null,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// Runs benchmark sweeps one variant at a time: a temporary deployment with the variant's settings,
|
||||
// a benchmark run against it once it is healthy, then the deployment is removed again. State lives in
|
||||
// the sweep row, so a worker restart picks up where it was (an interrupted run fails its variant).
|
||||
|
||||
import { and, asc, eq, inArray } from "drizzle-orm";
|
||||
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
|
||||
import { estimateMemoryMb } from "@/lib/deploy-command";
|
||||
import { applyOverrides } from "@/lib/sweep";
|
||||
import { log } from "./log";
|
||||
|
||||
let busy = false;
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
type Sweep = typeof benchmarkSweeps.$inferSelect;
|
||||
|
||||
async function save(id: string, set: Partial<typeof benchmarkSweeps.$inferInsert>) {
|
||||
await db().update(benchmarkSweeps).set(set).where(eq(benchmarkSweeps.id, id));
|
||||
}
|
||||
|
||||
/** Stop and remove a sweep's temporary deployment (the deployments reconciler does the work). */
|
||||
async function removeDeployment(id: string | null | undefined) {
|
||||
if (!id) return;
|
||||
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
/** The variant's memory limit: the base limit, raised to the estimate when the variant needs more. */
|
||||
async function memoryFor(sweep: Sweep, options: Sweep["base"]["options"], accelerator: string, engine: "llama.cpp" | "vllm"): Promise<number | null> {
|
||||
if (!sweep.base.memoryMb) return null;
|
||||
const files = await db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, sweep.base.modelId), eq(modelFiles.selected, true)));
|
||||
const bytes =
|
||||
engine === "llama.cpp"
|
||||
? files.filter((f) => [options.modelFile, options.mmproj, options.draftFile].includes(f.path)).reduce((s, f) => s + f.size, 0)
|
||||
: files.reduce((s, f) => s + f.size, 0);
|
||||
const est = estimateMemoryMb(bytes, options.contextSize, engine, { ...options, accelerator: accelerator as never });
|
||||
return Math.max(sweep.base.memoryMb, est);
|
||||
}
|
||||
|
||||
async function advance(sweep: Sweep): Promise<void> {
|
||||
const variants = [...sweep.variants];
|
||||
const put = async (i: number, patch: Partial<SweepVariant>) => {
|
||||
variants[i] = { ...variants[i], ...patch };
|
||||
await save(sweep.id, { variants });
|
||||
};
|
||||
|
||||
if (sweep.cancelRequestedAt) {
|
||||
for (const v of variants) {
|
||||
if (v.state === "benchmarking" && v.runId) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, v.runId));
|
||||
if (v.state === "deploying" || v.state === "benchmarking") await removeDeployment(v.deploymentId);
|
||||
}
|
||||
await save(sweep.id, {
|
||||
state: "cancelled",
|
||||
finishedAt: new Date(),
|
||||
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" ? { ...v, state: "skipped" as const } : v)),
|
||||
});
|
||||
log.info(`sweep ${sweep.id}: cancelled`);
|
||||
return;
|
||||
}
|
||||
|
||||
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking");
|
||||
if (i < 0) {
|
||||
const ok = variants.filter((v) => v.state === "done").length;
|
||||
await save(sweep.id, { state: ok > 0 ? "completed" : "failed", finishedAt: new Date(), error: ok > 0 ? null : "No variant could be benchmarked." });
|
||||
log.info(`sweep ${sweep.id}: ${ok}/${variants.length} variants done`);
|
||||
return;
|
||||
}
|
||||
const v = variants[i];
|
||||
|
||||
if (v.state === "pending") {
|
||||
const rt = await db().query.runtimes.findFirst({ columns: { engine: true, accelerator: true }, where: eq(runtimes.id, sweep.base.runtimeId) });
|
||||
if (!rt) return void (await put(i, { state: "failed", error: "The runtime was deleted." }));
|
||||
const { options, cpus } = applyOverrides(sweep.base, v.overrides);
|
||||
const memoryMb = await memoryFor(sweep, options, rt.accelerator, rt.engine);
|
||||
const [row] = await db()
|
||||
.insert(deployments)
|
||||
.values({
|
||||
name: `${sweep.base.name} · ${v.label}`.slice(0, 80),
|
||||
runtimeId: sweep.base.runtimeId,
|
||||
modelId: sweep.base.modelId,
|
||||
options,
|
||||
cpus,
|
||||
memoryMb,
|
||||
hostPort: null,
|
||||
desiredState: "running",
|
||||
sweepId: sweep.id,
|
||||
})
|
||||
.returning({ id: deployments.id });
|
||||
await put(i, { state: "deploying", deploymentId: row.id });
|
||||
log.info(`sweep ${sweep.id}: variant ${i + 1}/${variants.length} (${v.label}) deploying`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (v.state === "deploying") {
|
||||
const d = v.deploymentId ? await db().query.deployments.findFirst({ columns: { state: true, error: true }, where: eq(deployments.id, v.deploymentId) }) : null;
|
||||
if (!d) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
|
||||
if (d.state === "failed") {
|
||||
await put(i, { state: "failed", error: d.error ?? "The deployment failed to start." });
|
||||
return removeDeployment(v.deploymentId);
|
||||
}
|
||||
if (d.state !== "running") return; // still starting
|
||||
const snap = await deploymentSnapshot(v.deploymentId!);
|
||||
if (!snap) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
|
||||
const [run] = await db()
|
||||
.insert(benchmarkRuns)
|
||||
.values({
|
||||
kind: "run",
|
||||
deploymentId: snap.id,
|
||||
modelId: snap.modelId,
|
||||
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label}`.slice(0, 120),
|
||||
settings: sweep.settings,
|
||||
snapshot: snap.snapshot,
|
||||
sweepId: sweep.id,
|
||||
})
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
await put(i, { state: "benchmarking", runId: run.id });
|
||||
return;
|
||||
}
|
||||
|
||||
// benchmarking
|
||||
const run = v.runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, v.runId) }) : null;
|
||||
if (!run) {
|
||||
await put(i, { state: "failed", error: "The variant's run disappeared." });
|
||||
return removeDeployment(v.deploymentId);
|
||||
}
|
||||
if (run.state === "queued" || run.state === "running") return;
|
||||
await put(i, run.state === "completed" ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
|
||||
await removeDeployment(v.deploymentId);
|
||||
}
|
||||
|
||||
/** Drive the running sweep (or start the oldest queued one). */
|
||||
export async function tickSweeps(): Promise<void> {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
let sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.state, "running"), orderBy: asc(benchmarkSweeps.createdAt) });
|
||||
if (!sweep) {
|
||||
const next = await db().query.benchmarkSweeps.findFirst({ where: inArray(benchmarkSweeps.state, ["queued"]), orderBy: asc(benchmarkSweeps.createdAt) });
|
||||
if (!next) return;
|
||||
await save(next.id, { state: "running", startedAt: new Date() });
|
||||
sweep = { ...next, state: "running" };
|
||||
log.info(`sweep ${next.id}: started (${next.variants.length} variants)`);
|
||||
}
|
||||
await advance(sweep).catch((err) => log.error(`sweep ${sweep!.id}`, err));
|
||||
} catch (err) {
|
||||
log.error("sweeps", message(err));
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user