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

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

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

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
// Runs BetterBench against running deployments, one benchmark at a time (two at once would
// measure each other).
import { type ChildProcess, execFile, spawn } from "node:child_process";
import { access, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { db } from "@/lib/db/client";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { errorCauses } from "./log-causes";
type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] };
let current: Current | null = null;
let starting = false;
const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = [];
const partial = new Map<string, string>();
const tails = new Map<string, string[]>();
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
function addLog(runId: string, stream: LogStream, line: string, secrets: string[] = []) {
const clean = sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...secrets]).slice(0, 4000);
pending.push({ runId, stream, line: clean, ts: new Date() });
const tail = tails.get(runId) ?? [];
tail.push(clean);
if (tail.length > 400) tail.shift();
tails.set(runId, tail);
}
/** Split a stream into lines (keeps the unfinished rest per run and stream). */
function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets: string[]) {
const key = `${runId}:${stream}`;
const parts = ((partial.get(key) ?? "") + data.toString("utf8")).split(/\r?\n|\r/);
partial.set(key, parts.pop() ?? "");
for (const p of parts) {
if (!p.trim()) continue;
addLog(runId, stream, p, secrets);
const step = stepOf(p);
if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
}
}
/** BetterBench's progress lines ("[single] chat: …", "[prefill] depth ~2000 tok: …") as a short step label. */
export function stepOf(line: string): string | null {
const m = line.match(/^\[(single|prefill|concurrency)\]\s*([^:]*)/);
if (!m) return null;
const what = m[2].trim();
const name = m[1] === "single" ? "Generation" : m[1] === "prefill" ? "Prompt processing" : "Parallel requests";
return what ? `${name}: ${what}` : name;
}
export async function flushBenchmarkLogs(): Promise<void> {
if (pending.length === 0) return;
const batch = pending.splice(0, pending.length);
for (let i = 0; i < batch.length; i += 500) await db().insert(benchmarkLogs).values(batch.slice(i, i + 500));
}
async function finish(runId: string, set: Partial<typeof benchmarkRuns.$inferInsert>) {
await db()
.update(benchmarkRuns)
.set({ finishedAt: new Date(), ...set })
.where(eq(benchmarkRuns.id, runId));
}
/** Runs left "running" by a previous worker can't be resumed. */
export async function recoverBenchmarks(): Promise<void> {
const res = await db()
.update(benchmarkRuns)
.set({ state: "failed", error: "Interrupted: the worker restarted during the run.", finishedAt: new Date() })
.where(eq(benchmarkRuns.state, "running"))
.returning({ id: benchmarkRuns.id });
if (res.length) log.info(`marked ${res.length} interrupted benchmark(s) as failed`);
}
async function exists(path: string) {
return access(path).then(
() => true,
() => false,
);
}
/** Completed runs whose stored summary predates SUMMARY_VERSION: recompute from results.json. */
export async function refreshSummaries(): Promise<void> {
const rows = await db()
.select({ id: benchmarkRuns.id, summary: benchmarkRuns.summary, settings: benchmarkRuns.settings })
.from(benchmarkRuns)
.where(eq(benchmarkRuns.state, "completed"));
let n = 0;
for (const r of rows) {
if (r.summary?.v === SUMMARY_VERSION) continue;
const results = join(runDir(r.id), RESULTS_FILE);
if (!(await exists(results))) continue;
try {
const summary = { ...(await summarize(results)), quick: !!r.settings.quick };
await db().update(benchmarkRuns).set({ summary }).where(eq(benchmarkRuns.id, r.id));
n++;
} catch (err) {
log.warn(`benchmark ${r.id}: summary refresh failed: ${message(err)}`);
}
}
if (n) log.info(`refreshed ${n} benchmark summar${n === 1 ? "y" : "ies"}`);
}
async function summarize(results: string): Promise<BenchmarkSummary> {
const { stdout } = await promisify(execFile)(betterbenchPython(), ["-c", SUMMARY_SCRIPT, results], { timeout: 120_000, maxBuffer: 16 * 2 ** 20 });
return JSON.parse(stdout) as BenchmarkSummary;
}
async function start(run: typeof benchmarkRuns.$inferSelect) {
const fail = (error: string) => finish(run.id, { state: "failed", error });
const [d] = run.deploymentId
? await db()
.select({ state: deployments.state, containerName: deployments.containerName, engine: runtimes.engine })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(eq(deployments.id, run.deploymentId))
: [];
if (!d || d.state !== "running" || !d.containerName) return fail("The deployment isn't running anymore.");
const dir = runDir(run.id);
await mkdir(dir, { recursive: true });
const keys = run.snapshot.options.requireApiKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const s = run.snapshot;
const args = runArgs({
endpoint: `http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1`,
model: s.repoId,
out: join(dir, RESULTS_FILE),
settings: run.settings,
maxModelLen: s.options.contextSize ?? null,
notes: {
deployment: s.deploymentName,
runtime: s.runtimeName,
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...(run.label ? { label: run.label } : {}),
},
});
// Only what BetterBench needs: no HF_TOKEN or other worker secrets.
const env: Record<string, string | undefined> = {
PATH: process.env.PATH,
HOME: process.env.HOME,
LANG: "C.UTF-8",
PYTHONUNBUFFERED: "1",
NO_COLOR: "1",
BETTERBENCH_HOME: dir,
BETTERBENCH_NO_UPDATE_CHECK: "1",
...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}),
};
addLog(run.id, "system", `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`);
addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const cur: Current = { runId: run.id, deploymentId: run.deploymentId, child, cancelled: false, lost: null, secrets: keys };
current = cur;
child.stdout.on("data", (b: Buffer) => chunk(run.id, "stdout", b, keys));
child.stderr.on("data", (b: Buffer) => chunk(run.id, "stderr", b, keys));
child.on("error", (err: NodeJS.ErrnoException) => {
addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`);
});
child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err)));
log.info(`benchmark ${run.id}: started for ${s.deploymentName}`);
}
async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
const id = cur.runId;
for (const stream of ["stdout", "stderr"] as const) {
const rest = partial.get(`${id}:${stream}`);
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
if (current === cur) current = null;
const dir = runDir(id);
const results = join(dir, RESULTS_FILE);
const hasReport = await exists(join(dir, REPORT_FILE));
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", hasReport });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, hasReport });
} else if (code === 0 && (await exists(results))) {
try {
const summary = { ...(await summarize(results)), quick: false };
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
summary.quick = !!run?.settings.quick;
addLog(id, "system", "Done.");
await finish(id, { state: "completed", summary, hasReport });
} catch (err) {
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
}
} else {
const lines = tails.get(id) ?? [];
const causes = errorCauses(lines);
const why = signal ? `stopped by ${signal}` : `exit code ${code ?? "?"}`;
const last = lines.slice(-12).join("\n");
await finish(id, {
state: "failed",
error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
hasReport,
});
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost ? "failed (deployment gone)" : code === 0 ? "completed" : "failed"}`);
}
function stop(cur: Current) {
if (cur.child.exitCode !== null) return;
cur.child.kill("SIGTERM");
setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref();
}
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
export async function tickBenchmarks(): Promise<void> {
if (starting) return;
if (current) {
const cur = current;
const [run] = await db().select({ cancel: benchmarkRuns.cancelRequestedAt }).from(benchmarkRuns).where(eq(benchmarkRuns.id, cur.runId));
if (!run || run.cancel) {
cur.cancelled = true;
stop(cur);
return;
}
if (cur.deploymentId) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId));
if (!d || d.state !== "running") {
cur.lost = "The deployment stopped during the run.";
stop(cur);
}
}
return;
}
starting = true;
try {
const next = await db().query.benchmarkRuns.findFirst({ where: eq(benchmarkRuns.state, "queued"), orderBy: asc(benchmarkRuns.createdAt) });
if (next) await start(next).catch((err) => finish(next.id, { state: "failed", error: `Could not start: ${message(err)}` }));
} finally {
starting = false;
}
}
/** Worker shutdown: a run can't continue in another process. */
export async function stopBenchmarks(): Promise<void> {
const cur = current;
if (!cur) return;
cur.lost = "Interrupted: the worker stopped during the run.";
stop(cur);
const deadline = Date.now() + 5_000;
while (current === cur && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
}
+54
View File
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { runArgs } from "./betterbench";
import { stepOf } from "./benchmarks";
describe("betterbench runArgs", () => {
const base = { endpoint: "http://kaname-x-abc123:8080/v1", model: "unsloth/Qwen3-0.6B-GGUF", out: "/data/benchmarks/R/results.json", maxModelLen: 4096 };
it("builds a quick run with phases and notes, never checking for updates", () => {
const args = runArgs({ ...base, settings: { quick: true, passes: null, warmup: null, phases: ["decode", "prefill"] }, notes: { ctx: "4096", label: "q8 kv" } });
assert.deepEqual(args, [
"run",
"--endpoint",
"http://kaname-x-abc123:8080/v1",
"--model",
"unsloth/Qwen3-0.6B-GGUF",
"--out",
"/data/benchmarks/R/results.json",
"--max-model-len",
"4096",
"--quick",
"--decode",
"--prefill",
"--note",
"ctx=4096",
"--note",
"label=q8 kv",
"--no-update-check",
]);
});
it("passes explicit passes and warmup, and no phase flags for a full run", () => {
const args = runArgs({ ...base, maxModelLen: null, settings: { quick: false, passes: 10, warmup: 2, phases: [] }, notes: {} });
assert.ok(args.includes("--passes") && args[args.indexOf("--passes") + 1] === "10");
assert.ok(args.includes("--warmup") && args[args.indexOf("--warmup") + 1] === "2");
assert.ok(!args.includes("--quick") && !args.includes("--decode") && !args.includes("--max-model-len"));
});
it("turns progress lines into steps", () => {
assert.equal(stepOf("[single] chat: warmup 1 + 5 runs"), "Generation: chat");
assert.equal(stepOf("[prefill] depth ~2000 tok: warmup 2 + 8"), "Prompt processing: depth ~2000 tok");
assert.equal(stepOf("model max context: 4096 tokens"), null);
});
});
describe("parseNvidiaSmi", () => {
it("reads nvidia-smi CSV", async () => {
const { parseNvidiaSmi } = await import("./runtimes");
assert.deepEqual(parseNvidiaSmi("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14\n"), [
{ vendor: "nvidia", index: 0, uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14" },
]);
assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
});
});
+101
View File
@@ -0,0 +1,101 @@
// BetterBench (https://github.com/GGZ14/BetterBench, Apache-2.0): the benchmark Kaname runs
// against deployments. Flags verified against v0.6.1 (`betterbench run --help`, betterbench/cli.py).
import { dirname, join } from "node:path";
import type { BenchmarkSettings } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
export function betterbenchBin(): string {
return coreEnv().BETTERBENCH_BIN;
}
/** The Python of BetterBench's own venv (it imports `betterbench`). */
export function betterbenchPython(): string {
const bin = betterbenchBin();
return bin.includes("/") ? join(dirname(bin), "python") : "python3";
}
export function runArgs(o: {
endpoint: string;
model: string;
out: string;
settings: BenchmarkSettings;
maxModelLen: number | null;
notes: Record<string, string>;
}): string[] {
const s = o.settings;
return [
"run",
"--endpoint",
o.endpoint,
"--model",
o.model,
"--out",
o.out,
// Kaname knows the context window; llama-server's /v1/models doesn't report it.
...(o.maxModelLen ? ["--max-model-len", String(o.maxModelLen)] : []),
...(s.quick ? ["--quick"] : []),
...(s.passes != null ? ["--passes", String(s.passes)] : []),
...(s.warmup != null ? ["--warmup", String(s.warmup)] : []),
...s.phases.map((p) => `--${p}`),
...Object.entries(o.notes).flatMap(([k, v]) => ["--note", `${k}=${v}`]),
"--no-update-check",
];
}
/**
* Prints Kaname's BenchmarkSummary for a results.json, using BetterBench's own report functions
* so the numbers match its HTML report.
*/
export const SUMMARY_SCRIPT = `
import json, math, sys
from betterbench import report as r
res = json.load(open(sys.argv[1]))
def clean(v):
if isinstance(v, dict):
return {str(k): clean(x) for k, x in v.items()}
if isinstance(v, (list, tuple)):
return [clean(x) for x in v]
if isinstance(v, (bool, str)) or v is None:
return v
try:
f = float(v)
except (TypeError, ValueError):
return None
if math.isnan(f) or math.isinf(f):
return None
return int(f) if float(f).is_integer() and not isinstance(v, float) else f
rows = r.single_rows(res)
cfg = res.get("config", {})
env = res.get("env", {})
reasoning = r.reasoning_rows(res)
gate = res.get("sample_gate") or r.sample_gate(res)
trunc, ok_runs = r.truncation_summary(res)
failed = sum(1 for recs in res.get("single_stream", {}).values() for x in recs if not x.get("ok"))
keep_cfg = ("warmup", "runs_per_category", "temperature", "top_p", "top_k", "greedy", "unique_nonce", "weights",
"concurrency_levels", "concurrency_requests", "prefill_runs", "prefill_warmup", "prefill_max_tokens")
out = {
"v": 2,
"combined": r.combined_score(res, rows),
"single": rows,
"prefill": r.prefill_rows(res),
"concurrency": r.concurrency_rows(res),
"reasoning": reasoning if r.has_reasoning_evidence(reasoning) else [],
"gate": gate.get("under_sampled", []),
"truncated": [trunc, ok_runs],
"failedSingle": failed,
"phases": r.phases_present(res),
"cacheHits": r.cache_hits(res),
"betterbenchVersion": res.get("betterbench_version", ""),
"corpusVersion": res.get("corpus_version", ""),
"corpusHash": env.get("corpus_hash"),
"timestamp": env.get("timestamp"),
"maxModelLen": env.get("max_model_len"),
"config": {k: cfg.get(k) for k in keep_cfg},
"passes": cfg.get("runs_per_category"),
}
print(json.dumps(clean(out)))
`;
/** Version of the summary shape above; older stored summaries are recomputed from results.json. */
export const SUMMARY_VERSION = 2;
+14 -1
View File
@@ -8,6 +8,7 @@ import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
import { ACCELERATOR_DEVICES } from "@/lib/runtimes-shared";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
@@ -136,6 +137,17 @@ async function start(c: DockerClient, d: Deployment) {
}
}
// GPUs: NVIDIA ones are requested from Docker (all, or the selected UUIDs); Intel/AMD come in as /dev nodes.
let deviceRequests: unknown[] = [];
if (runtime.accelerator === "nvidia") {
if (!host.nvidia) return fail(d, "This runtime needs NVIDIA GPUs, but Docker has no NVIDIA runtime (install the NVIDIA Container Toolkit on the Docker host).");
const wanted = d.options.gpus?.length ? d.options.gpus : null;
const missing = wanted?.filter((u) => !(host.gpus ?? []).some((g) => g.uuid === u)) ?? [];
if (missing.length && (host.gpus ?? []).length) return fail(d, `Selected GPU not found: ${missing.join(", ")}. Pick the GPUs again in the deployment.`);
deviceRequests = [{ Driver: "", Count: wanted ? 0 : -1, DeviceIDs: wanted ?? undefined, Capabilities: [["gpu"]] }];
}
const devices = runtime.accelerator === "dri" || runtime.accelerator === "rocm" ? [...new Set([...runtime.devices, ...ACCELERATOR_DEVICES[runtime.accelerator]])] : runtime.devices;
const keys = d.options.requireApiKey ? await loadApiKeys() : [];
if (d.options.requireApiKey && keys.length === 0) return fail(d, "This deployment requires an API key, but there are none. Add one under Settings → API keys.");
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime, apiKeys: keys });
@@ -154,7 +166,8 @@ async function start(c: DockerClient, d: Deployment) {
NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0,
Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0,
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: runtime.devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
DeviceRequests: deviceRequests,
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
+10 -1
View File
@@ -71,7 +71,15 @@ export class DockerClient {
}
info() {
return this.json<{ NCPU: number; MemTotal: number; OperatingSystem: string; Architecture: string; ServerVersion: string }>(
return this.json<{
NCPU: number;
MemTotal: number;
OperatingSystem: string;
Architecture: string;
ServerVersion: string;
Runtimes?: Record<string, unknown>;
DiscoveredDevices?: { Source: string; ID: string }[];
}>(
"GET",
"/info",
);
@@ -83,6 +91,7 @@ export class DockerClient {
return await this.json<{
Id: string;
Name: string;
Image: string;
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
NetworkSettings: { Networks: Record<string, unknown> };
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
+12
View File
@@ -12,6 +12,8 @@ import { coreEnv } from "@/lib/env";
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks";
import { reportL80Status, tickPublications } from "./publish";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
@@ -34,6 +36,7 @@ const DOCKER_INFO_MS = 5 * 60_000;
const IMAGE_SYNC_MS = 60_000;
const PULL_CHECK_MS = 3_000;
const DEPLOYMENT_TICK_MS = 2_000;
const BENCHMARK_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -348,6 +351,8 @@ async function shutdown(reason: string, code = 0) {
// Deployment containers keep running; the next worker re-attaches to them.
stopFollowingLogs();
await flushDeploymentLogs().catch(() => {});
await stopBenchmarks().catch(() => {});
await flushBenchmarkLogs().catch(() => {});
if (runners.size > 0) {
for (const r of runners.values()) r.interrupt();
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
@@ -404,6 +409,13 @@ async function main() {
await adoptContainers();
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
// Benchmarks: one BetterBench run at a time against a running deployment.
await recoverBenchmarks();
void refreshSummaries();
void reportL80Status();
timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), 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();
void tick();
setTimeout(() => void checkHubDue(), 15_000);
+123
View File
@@ -0,0 +1,123 @@
// Publishing benchmark runs to launch80 with the L80 CLI (https://launch80.com/skills), as a double
// opt-in: (1) `L80 betterbench --results … --dry-run --payload-out` builds the exact payload, which the
// user inspects; (2) only after an explicit confirmation is that same file sent with `L80 publish`.
// The token (L80_TOKEN) is only ever in the CLI's environment for step 2.
import { execFile } from "node:child_process";
import { access, mkdir } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq, inArray } from "drizzle-orm";
import { benchmarksDir, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { db } from "@/lib/db/client";
import { benchmarkPublications, settings } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { log } from "./log";
export const L80_STATUS_KEY = "l80.status";
export const RAW_TEMPLATE = "bench.betterbench.v1";
const run = promisify(execFile);
let busy = false;
export const payloadPath = (runId: string, pubId: string) => join(runDir(runId), "publications", `${pubId}.json`);
/** Only what the CLI needs; the token only when publishing. */
function cliEnv(withToken: boolean): NodeJS.ProcessEnv {
const env = coreEnv();
return {
PATH: process.env.PATH,
HOME: process.env.HOME,
// The CLI's local publish history lives next to Kaname's data.
XDG_CONFIG_HOME: join(benchmarksDir(), ".l80"),
NO_COLOR: "1",
...(env.L80_API_BASE ? { L80_API_BASE: env.L80_API_BASE } : {}),
...(withToken && env.L80_TOKEN ? { L80_TOKEN: env.L80_TOKEN } : {}),
} as unknown as NodeJS.ProcessEnv;
}
/** "error: E_X …" plus the remedy line, without anything that could echo a token. */
function cliError(err: unknown): string {
const e = err as { stderr?: string; stdout?: string; message?: string; code?: string | number };
if (e.code === "ENOENT") return `The L80 CLI was not found (${coreEnv().L80_BIN}).`;
const text = `${e.stderr ?? ""}\n${e.stdout ?? ""}`.trim() || e.message || String(err);
const token = coreEnv().L80_TOKEN;
return (token ? text.split(token).join("***") : text).slice(0, 2000);
}
/** CLI version and whether a token is configured, for the UI (never the token itself). */
export async function reportL80Status(): Promise<void> {
const env = coreEnv();
let version: string | null = null;
try {
const { stdout } = await run(env.L80_BIN, ["version"], { env: cliEnv(false), timeout: 15_000 });
version = stdout.trim().split(/\s+/).find((w) => /^v?\d+\.\d+/.test(w)) ?? (stdout.trim() || null);
} catch {
version = null;
}
const value = { version, tokenSet: !!env.L80_TOKEN, apiBase: env.L80_API_BASE ?? "https://launch80.com", checkedAt: new Date().toISOString() };
await db().insert(settings).values({ key: L80_STATUS_KEY, value }).onConflictDoUpdate({ target: settings.key, set: { value } });
log.info(version ? `L80 CLI ${version}, publish token ${value.tokenSet ? "set" : "not set"}` : "L80 CLI not found; publishing to launch80 is unavailable");
}
async function exists(p: string) {
return access(p).then(
() => true,
() => false,
);
}
/** One step at a time: build a preview (dry run) or publish a confirmed one. */
export async function tickPublications(): Promise<void> {
if (busy) return;
busy = true;
try {
const p = await db().query.benchmarkPublications.findFirst({
where: inArray(benchmarkPublications.state, ["preview", "publish"]),
orderBy: asc(benchmarkPublications.createdAt),
});
if (!p) return;
const fail = (error: string) => db().update(benchmarkPublications).set({ state: "failed", error }).where(eq(benchmarkPublications.id, p.id));
const env = coreEnv();
const results = join(runDir(p.runId), RESULTS_FILE);
const payload = payloadPath(p.runId, p.id);
if (p.state === "preview") {
if (!(await exists(results))) return void (await fail("The run has no results.json to publish."));
await mkdir(join(runDir(p.runId), "publications"), { recursive: true });
const args = ["betterbench", "--results", results, "--dry-run", "--payload-out", payload, "--json"];
if (p.title) args.push("--title", p.title);
if (p.summary) args.push("--summary", p.summary);
try {
const { stdout } = await run(env.L80_BIN, args, { env: cliEnv(false), timeout: 60_000, maxBuffer: 8 * 2 ** 20 });
const out = JSON.parse(stdout) as { byte_size?: number; template?: string };
await db()
.update(benchmarkPublications)
.set({ state: "previewed", payloadBytes: out.byte_size ?? null, template: out.template ?? RAW_TEMPLATE, previewedAt: new Date(), error: null })
.where(eq(benchmarkPublications.id, p.id));
log.info(`publication ${p.id}: preview ready (${out.byte_size ?? "?"} bytes)`);
} catch (err) {
await fail(`Preview failed: ${cliError(err)}`);
}
return;
}
// state "publish": confirmed by a user; send exactly the previewed payload.
if (!env.L80_TOKEN) return void (await fail("No launch80 token: set L80_TOKEN for the worker (see .env.example)."));
if (!(await exists(payload))) return void (await fail("The previewed payload is gone; prepare a new preview."));
try {
const { stdout } = await run(env.L80_BIN, ["publish", payload, "--template", p.template, "--json"], { env: cliEnv(true), timeout: 120_000, maxBuffer: 8 * 2 ** 20 });
const a = JSON.parse(stdout) as { url?: string; guid?: string; created_at?: string };
if (!a.url) throw new Error(`no URL in the CLI's answer: ${stdout.slice(0, 300)}`);
await db()
.update(benchmarkPublications)
.set({ state: "published", url: a.url, guid: a.guid ?? null, publishedAt: a.created_at ? new Date(a.created_at) : new Date(), error: null })
.where(eq(benchmarkPublications.id, p.id));
log.info(`publication ${p.id}: published ${a.url}`);
} catch (err) {
await fail(`Publishing failed: ${cliError(err)}`);
}
} finally {
busy = false;
}
}
+86 -7
View File
@@ -6,7 +6,7 @@ import { hostname } from "node:os";
import { resolve } from "node:path";
import { and, eq, isNotNull, ne } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type DockerHostInfo, runtimes, settings, workerState } from "@/lib/db/schema";
import { type DockerHostInfo, type HostGpu, runtimes, settings, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
import { DockerClient, DockerError } from "./docker/client";
@@ -40,14 +40,14 @@ async function cpuFacts(): Promise<{ model: string | null; features: string[] }>
}
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource">> {
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource"> & { image: string | null }> {
const env = coreEnv();
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
: null;
if (network && modelsSource) return { network, modelsSource };
// Always inspected: the worker's own image also serves as the GPU probe image.
const self = await c.inspectContainer(hostname()).catch(() => null);
if (self) {
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
@@ -56,7 +56,80 @@ async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "networ
modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source };
}
}
return { network, modelsSource };
return { network, modelsSource, image: self?.Image ?? null };
}
// --- GPUs ---------------------------------------------------------------------
const GPU_PROBE_MS = 60 * 60_000;
let gpuCache: { at: number; gpus: HostGpu[]; error: string | null } | null = null;
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
export function parseNvidiaSmi(csv: string): HostGpu[] {
return csv
.split(/\r?\n/)
.map((l) => l.split(",").map((p) => p.trim()))
.filter((p) => p.length >= 5 && /^\d+$/.test(p[0]))
.map(([index, uuid, name, mem, driver]) => ({ vendor: "nvidia" as const, index: Number(index), uuid, name, memoryMb: Number(mem) || 0, driver }));
}
/**
* Lists the GPUs containers get from Docker: a short-lived container (our own image) requests all
* GPUs and runs nvidia-smi, which the NVIDIA Container Toolkit injects.
*/
async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, {
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: ["--query-gpu=index,uuid,name,memory.total,driver_version", "--format=csv,noheader,nounits"],
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false },
});
try {
const lines: string[] = [];
await c.startContainer(created.Id);
await c.followLogs(created.Id, (_s, line) => lines.push(line), { tail: "all", signal: AbortSignal.timeout(30_000) });
const st = await c.containerState(created.Id);
if (st && st.ExitCode !== 0) throw new Error(`nvidia-smi exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`);
return parseNvidiaSmi(lines.join("\n"));
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
}
async function gpuFacts(c: DockerClient, info: Awaited<ReturnType<DockerClient["info"]>>, selfImage: string | null) {
const nvidia = !!info.Runtimes?.nvidia || !!info.DiscoveredDevices?.some((d) => d.ID.startsWith("nvidia.com/gpu"));
if (!nvidia) return { nvidia, gpus: [], gpuError: null, gpuCheckedAt: null };
if (!gpuCache || Date.now() - gpuCache.at > GPU_PROBE_MS) {
try {
if (!selfImage) throw new Error("Kaname's own image is unknown (the worker isn't running in a container), so GPUs can't be probed.");
const gpus = await probeNvidia(c, selfImage);
gpuCache = { at: Date.now(), gpus, error: null };
if (gpus.length) {
log.info(`GPUs: ${gpus.map((g) => `${g.index}: ${g.name} (${Math.round(g.memoryMb / 1024)} GiB)`).join(", ")}`);
await seedGpuPresets();
}
} catch (err) {
gpuCache = { at: Date.now(), gpus: [], error: message(err) };
log.warn(`GPU probe failed: ${message(err)}`);
}
}
return { nvidia, gpus: gpuCache.gpus, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
}
const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded";
/** The first time NVIDIA GPUs show up, add the llama.cpp CUDA runtime (once). */
async function seedGpuPresets() {
const d = db();
if (await d.query.settings.findFirst({ where: eq(settings.key, CUDA_SEEDED_KEY) })) return;
const p = RUNTIME_PRESETS.find((x) => x.id === "llama.cpp-cuda");
if (p) {
await d.insert(runtimes).values({ name: p.name, engine: p.engine, accelerator: "nvidia", image: p.image, description: p.description ?? null, preset: p.id });
log.info(`NVIDIA GPU found: added the "${p.name}" runtime`);
}
await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing();
}
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
@@ -72,6 +145,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);
info = {
connected: true,
error: null,
@@ -81,7 +155,9 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
cpus: i.NCPU,
memoryBytes: i.MemTotal,
...base,
...(await selfDetect(c)),
network: self.network,
modelsSource: self.modelsSource,
...(await gpuFacts(c, i, self.image)),
};
} catch (err) {
info = {
@@ -110,10 +186,13 @@ export async function seedRuntimePresets(): Promise<void> {
if (seeded) return;
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
if (existing.length === 0) {
// CPU presets only; GPU ones are added from Settings (or automatically when an NVIDIA GPU shows up).
const presets = RUNTIME_PRESETS.filter((p) => (p.accelerator ?? "cpu") === "cpu");
await d.insert(runtimes).values(
RUNTIME_PRESETS.map((p) => ({
presets.map((p) => ({
name: p.name,
engine: p.engine,
accelerator: p.accelerator ?? "cpu",
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
@@ -124,7 +203,7 @@ export async function seedRuntimePresets(): Promise<void> {
preset: p.id,
})),
);
log.info(`created ${RUNTIME_PRESETS.length} preset runtime(s)`);
log.info(`created ${presets.length} preset runtime(s)`);
}
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
}