Every run records GPUs (PCIe link under load and maximum, ReBAR, P2P), runtime image/tag/digest and the engine version the server reports, model, quant, KV cache, context and concurrency, plus a whitelisted system summary and a description. Shown on the run page, compare and sweep views; passed to BetterBench as notes and to the launch80 preview as sections. Settings -> Hardware for manual values. Also: scripts/intel-probe.sh (read-only diagnostics for Intel hosts), and --quick is no longer passed together with --passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
981c4170fc
commit
ee6c623e2a
45 files changed
+4627
-60
No files matched your search
@@ -6,15 +6,18 @@ import { access, mkdir, readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchmark-meta";
|
||||
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
|
||||
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
|
||||
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema";
|
||||
import { ENGINE_PORT } from "@/lib/deploy-command";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
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 { normalizePciAddress } from "./hardware";
|
||||
import { errorCauses } from "./log-causes";
|
||||
import { ResourceSampler } from "./resources";
|
||||
import { docker, workerImage } from "./runtimes";
|
||||
@@ -25,6 +28,9 @@ type Current = {
|
||||
deploymentIds: string[];
|
||||
child: ChildProcess;
|
||||
sampler: ResourceSampler | null;
|
||||
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
|
||||
meta: RunMeta | null;
|
||||
metaB: RunMeta | null;
|
||||
maxPairs: number | null;
|
||||
cancelled: boolean;
|
||||
lost: string | null;
|
||||
@@ -140,6 +146,32 @@ async function target(deploymentId: string | null): Promise<Target | null> {
|
||||
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
|
||||
}
|
||||
|
||||
/** Which GPU links the sampler reads: sysfs where the GPU is on the visible PCI bus, nvidia-smi otherwise. */
|
||||
async function linkTargets(metas: (RunMeta | null)[]) {
|
||||
const addrs = [...new Set(metas.flatMap((m) => m?.gpus.map((g) => g.pciAddress) ?? []).filter((a): a is string => !!a))];
|
||||
const { nvidia } = await effectiveHardware();
|
||||
const nvidiaIndex: Record<number, string> = {};
|
||||
for (const g of nvidia) {
|
||||
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
|
||||
if (addrs.includes(addr)) nvidiaIndex[g.index] = addr;
|
||||
}
|
||||
return { sysfs: addrs.filter((a) => !a.startsWith("nvidia-")), nvidiaIndex };
|
||||
}
|
||||
|
||||
/** A/B notes: the shared host facts once, the engine and model per side. */
|
||||
function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record<string, string>): Record<string, string> {
|
||||
const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"];
|
||||
const out: Record<string, string> = Object.fromEntries(Object.entries(shared).filter(([k]) => pick.includes(k)));
|
||||
for (const [side, m] of [["a", a], ["b", b]] as const) {
|
||||
if (!m) continue;
|
||||
out[`${side}_engine`] = engineLabel(m) || m.runtime.engine;
|
||||
out[`${side}_model`] = modelLabel(m);
|
||||
if (m.contextSize != null) out[`${side}_ctx`] = String(m.contextSize);
|
||||
if (m.concurrency != null) out[`${side}_concurrency`] = String(m.concurrency);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
|
||||
|
||||
async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
@@ -156,6 +188,10 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
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 maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
|
||||
// What runs on what, recorded now (the deployments are up, so the server's version is known).
|
||||
const setup = await runSetup([a.id, b?.id ?? null]);
|
||||
const [meta, metaB] = setup.metas;
|
||||
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
|
||||
const args =
|
||||
run.kind === "ab" && b
|
||||
? abArgs({
|
||||
@@ -165,7 +201,12 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
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 } : {}) },
|
||||
notes: {
|
||||
a: s.deploymentName,
|
||||
b: run.snapshotB?.deploymentName ?? "B",
|
||||
...(run.label ? { label: run.label } : {}),
|
||||
...abNotes(meta, metaB, metaNotesA),
|
||||
},
|
||||
})
|
||||
: runArgs({
|
||||
endpoint: endpoint(a),
|
||||
@@ -179,6 +220,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
image: s.image,
|
||||
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
|
||||
ctx: String(s.options.contextSize),
|
||||
...metaNotesA,
|
||||
...(run.label ? { label: run.label } : {}),
|
||||
},
|
||||
});
|
||||
@@ -202,7 +244,10 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
: `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));
|
||||
await db()
|
||||
.update(benchmarkRuns)
|
||||
.set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, metaB, system: setup.system })
|
||||
.where(eq(benchmarkRuns.id, run.id));
|
||||
|
||||
// Resource use of the server(s) under test; GPUs when any side runs on NVIDIA.
|
||||
const c = docker();
|
||||
@@ -212,6 +257,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
c,
|
||||
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
|
||||
nvidia ? workerImage() : null,
|
||||
await linkTargets([meta, metaB]),
|
||||
)
|
||||
: null;
|
||||
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
|
||||
@@ -223,6 +269,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
|
||||
deploymentIds: [a.id, ...(b ? [b.id] : [])],
|
||||
child,
|
||||
sampler,
|
||||
meta,
|
||||
metaB,
|
||||
maxPairs: run.kind === "ab" ? maxPairs : null,
|
||||
cancelled: false,
|
||||
lost: null,
|
||||
@@ -247,6 +295,14 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
|
||||
}
|
||||
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
|
||||
if (current === cur) current = null;
|
||||
if (resources?.links) {
|
||||
const loaded = (m: RunMeta | null) => withLoadLinks(m, resources.links, !!m?.overridden.includes("pcie link"));
|
||||
await db()
|
||||
.update(benchmarkRuns)
|
||||
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
|
||||
.where(eq(benchmarkRuns.id, id))
|
||||
.catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`));
|
||||
}
|
||||
const dir = runDir(id);
|
||||
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
|
||||
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
|
||||
|
||||
@@ -29,6 +29,12 @@ describe("betterbench runArgs", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops --quick when passes are given (BetterBench refuses both)", () => {
|
||||
const args = runArgs({ ...base, settings: { quick: true, passes: 2, warmup: null, phases: [] }, notes: {} });
|
||||
assert.ok(!args.includes("--quick"));
|
||||
assert.deepEqual(args.slice(args.indexOf("--passes"), args.indexOf("--passes") + 2), ["--passes", "2"]);
|
||||
});
|
||||
|
||||
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");
|
||||
@@ -46,8 +52,18 @@ describe("betterbench runArgs", () => {
|
||||
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("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14, 00000000:2B:00.0, 1, 4, 16, 16\n"), [
|
||||
{
|
||||
vendor: "nvidia",
|
||||
index: 0,
|
||||
uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84",
|
||||
name: "NVIDIA GeForce RTX 3080",
|
||||
memoryMb: 10240,
|
||||
driver: "617.14",
|
||||
pciAddress: "0000:2b:00.0",
|
||||
linkCurrent: { gen: 1, width: 16 },
|
||||
linkMax: { gen: 4, width: 16 },
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
|
||||
});
|
||||
|
||||
@@ -34,7 +34,8 @@ export function runArgs(o: {
|
||||
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"] : []),
|
||||
// BetterBench refuses --quick together with --passes; explicit passes win.
|
||||
...(s.quick && s.passes == null ? ["--quick"] : []),
|
||||
...(s.passes != null ? ["--passes", String(s.passes)] : []),
|
||||
...(s.warmup != null ? ["--warmup", String(s.warmup)] : []),
|
||||
...s.phases.map((p) => `--${p}`),
|
||||
|
||||
@@ -6,13 +6,14 @@ import { stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
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 { apiKeys, deploymentLogs, deployments, type EngineInfo, type LogStream, models, type RuntimeEngine, 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";
|
||||
import { log } from "./log";
|
||||
import { fetchEngineInfo, versionFromLog } from "./engine-info";
|
||||
import { errorCauses } from "./log-causes";
|
||||
import { docker } from "./runtimes";
|
||||
import type { DockerClient } from "./docker/client";
|
||||
@@ -196,6 +197,7 @@ async function start(c: DockerClient, d: Deployment) {
|
||||
error: null,
|
||||
exitCode: null,
|
||||
stats: null,
|
||||
engineInfo: null,
|
||||
});
|
||||
await c.startContainer(created.Id);
|
||||
// A fresh container: everything it printed belongs to this run. (Following before the start
|
||||
@@ -241,6 +243,19 @@ async function healthy(name: string, port: number): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Version, slots and context from the server; the version from its startup log if it doesn't say. */
|
||||
async function engineInfo(d: Deployment, engine: RuntimeEngine, base: string): Promise<EngineInfo> {
|
||||
const key = d.options.requireApiKey ? ((await loadApiKeys())[0] ?? null) : null;
|
||||
const info = await fetchEngineInfo(engine, base, key);
|
||||
if (!info.version) {
|
||||
await flushDeploymentLogs();
|
||||
const lines = await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)).orderBy(asc(deploymentLogs.id)).limit(500);
|
||||
info.version = versionFromLog(engine, lines.map((l) => l.line));
|
||||
}
|
||||
if (info.version) addLog(d.id, "system", `Engine: ${engine} ${info.version}${info.slots ? `, ${info.slots} slots` : ""}${info.contextSize ? `, context ${info.contextSize}` : ""}`);
|
||||
return { ...info, at: new Date().toISOString() };
|
||||
}
|
||||
|
||||
// --- reconcile -----------------------------------------------------------------------------------
|
||||
|
||||
const lastStats = new Map<string, number>();
|
||||
@@ -284,7 +299,7 @@ async function reconcileOne(c: DockerClient, d: Deployment) {
|
||||
const now = new Date();
|
||||
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
|
||||
addLog(d.id, "system", `Ready after ${secs} s.`);
|
||||
await update(d.id, { state: "running", readyAt: now });
|
||||
await update(d.id, { state: "running", readyAt: now, engineInfo: await engineInfo(d, runtime?.engine ?? "llama.cpp", `http://${d.containerName}:${port}`) });
|
||||
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
|
||||
await c.stopContainer(d.containerId).catch(() => {});
|
||||
await c.removeContainer(d.containerId).catch(() => {});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// What a ready inference server says about itself: version, slots and context. llama.cpp: GET /props
|
||||
// (build_info "b11429-d81235049", total_slots, default_generation_settings.n_ctx; checked with build
|
||||
// 11429). vLLM: GET /version and GET /v1/models (max_model_len). Startup log lines as a fallback.
|
||||
|
||||
import type { EngineInfo, RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const int = (v: unknown) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null);
|
||||
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim().slice(0, 100) : null);
|
||||
|
||||
export function parseLlamaProps(props: Json | null): Omit<EngineInfo, "at"> {
|
||||
const gen = (props?.default_generation_settings ?? {}) as Json;
|
||||
return { version: str(props?.build_info), slots: int(props?.total_slots), contextSize: int(gen.n_ctx) };
|
||||
}
|
||||
|
||||
export function parseVllm(version: Json | null, models: Json | null): Omit<EngineInfo, "at"> {
|
||||
const data = Array.isArray(models?.data) ? (models.data as Json[]) : [];
|
||||
return { version: str(version?.version), slots: null, contextSize: int(data[0]?.max_model_len) };
|
||||
}
|
||||
|
||||
/** "build: 11429 (d8123504)" (llama.cpp), "vLLM API server version 0.31.0" (vLLM and most forks). */
|
||||
export function versionFromLog(engine: RuntimeEngine, lines: string[]): string | null {
|
||||
const re = engine === "llama.cpp" ? /\bbuild[:=]\s*(\d+)\s*\(([0-9a-f]+)\)/ : /\bversion\s+v?(\d+\.\d+[\w.+-]*)/i;
|
||||
for (const l of lines) {
|
||||
const m = l.match(re);
|
||||
if (m) return engine === "llama.cpp" ? `b${m[1]}-${m[2]}` : m[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getJson(url: string, key: string | null): Promise<Json | null> {
|
||||
try {
|
||||
const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(3_000) });
|
||||
return res.ok ? ((await res.json()) as Json) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ask the server at http://name:port; `key` when the deployment requires an API key. */
|
||||
export async function fetchEngineInfo(engine: RuntimeEngine, base: string, key: string | null): Promise<Omit<EngineInfo, "at">> {
|
||||
if (engine === "llama.cpp") return parseLlamaProps(await getJson(`${base}/props`, key));
|
||||
const [version, models] = await Promise.all([getJson(`${base}/version`, key), getJson(`${base}/v1/models`, key)]);
|
||||
return parseVllm(version, models);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { before, describe, it } from "node:test";
|
||||
import { fetchEngineInfo, parseLlamaProps, parseVllm, versionFromLog } from "./engine-info";
|
||||
import { currentLinks, detectHardware, gpuDisplayName, type SysFs, largestBarMb, mountDevice, normalizePciAddress, parseCpu, parseP2p, pciName } from "./hardware";
|
||||
import { fastestLinks, parseGpuLine, summarizeSamples } from "./resources";
|
||||
import { parseNvidiaSmi, repoDigest } from "./runtimes";
|
||||
|
||||
const GiB = 2 ** 30;
|
||||
const hex = (n: number) => `0x${n.toString(16).padStart(16, "0")}`;
|
||||
/** A `resource` line: start, end, flags (0x0014220c = 64-bit prefetchable memory). */
|
||||
const bar = (start: number, size: number) => `${hex(start)} ${hex(start + size - 1)} 0x000000000014220c`;
|
||||
const EMPTY = `${hex(0)} ${hex(0)} 0x0000000000000000`;
|
||||
|
||||
const PCI_IDS = `# test pci.ids
|
||||
10de NVIDIA Corporation
|
||||
\t2684 AD102 [GeForce RTX 4090]
|
||||
8086 Intel Corporation
|
||||
\te211 Battlemage G31 [Arc Pro B65]
|
||||
\t\t8086 1234 Arc Pro B65 32GB
|
||||
\te20b Battlemage G21 [Arc B580]
|
||||
1af4 Red Hat, Inc.
|
||||
`;
|
||||
|
||||
const CPUINFO = [0, 1, 2, 3]
|
||||
.map((p) => `processor\t: ${p}\nmodel name\t: AMD EPYC 9124 16-Core Processor\nphysical id\t: 0\ncore id\t\t: ${p % 2}\nflags\t\t: fpu avx2 hypervisor\n`)
|
||||
.join("\n");
|
||||
|
||||
const files = new Map<string, string>();
|
||||
const links = new Map<string, string>();
|
||||
|
||||
/** An in-memory sysfs: files plus directory symlinks (sysfs names contain ":", which Windows can't store). */
|
||||
function memFs(): SysFs {
|
||||
const resolve = (p: string): string => {
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const hit = [...links.keys()].find((l) => p === l || p.startsWith(`${l}/`));
|
||||
if (!hit) return p;
|
||||
p = links.get(hit)! + p.slice(hit.length);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
read: async (p) => files.get(resolve(p))?.trim() ?? null,
|
||||
resolve: async (p) => resolve(p),
|
||||
list: async (d) => {
|
||||
const dir = `${resolve(d)}/`;
|
||||
const names = [...files.keys(), ...links.keys()].filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]);
|
||||
return [...new Set(names)];
|
||||
},
|
||||
};
|
||||
}
|
||||
const file = (path: string, content: string) => files.set(`/${path}`, content);
|
||||
const link = (path: string, target: string) => links.set(`/${path}`, `/${target}`);
|
||||
|
||||
before(() => {
|
||||
// Intel Arc Pro B65: root port 00:01.0 → on-card switch (01:00.0 up, 02:01.0 down) → GPU 03:00.0.
|
||||
const rp = "sys/devices/pci0000:00/0000:00:01.0";
|
||||
const up = `${rp}/0000:01:00.0`;
|
||||
const down = `${up}/0000:02:01.0`;
|
||||
const gpu = `${down}/0000:03:00.0`;
|
||||
file(`${rp}/vendor`, "0x1022");
|
||||
file(`${up}/vendor`, "0x8086");
|
||||
file(`${up}/current_link_speed`, "16.0 GT/s PCIe");
|
||||
file(`${up}/current_link_width`, "8");
|
||||
file(`${up}/max_link_speed`, "32.0 GT/s PCIe");
|
||||
file(`${up}/max_link_width`, "16");
|
||||
file(`${down}/vendor`, "0x8086");
|
||||
file(`${gpu}/vendor`, "0x8086");
|
||||
file(`${gpu}/device`, "0xe211");
|
||||
file(`${gpu}/subsystem_vendor`, "0x8086");
|
||||
file(`${gpu}/subsystem_device`, "0x1234");
|
||||
file(`${gpu}/class`, "0x030000");
|
||||
file(`${gpu}/uevent`, "DRIVER=xe\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:03:00.0");
|
||||
// What the GPU function itself reports: the switch-internal link.
|
||||
file(`${gpu}/current_link_speed`, "2.5 GT/s PCIe");
|
||||
file(`${gpu}/current_link_width`, "1");
|
||||
file(`${gpu}/resource`, [bar(0xa0000000, 16 * 2 ** 20), EMPTY, bar(0x4000000000, 32 * GiB)].join("\n"));
|
||||
file(`${gpu}/tile0/physical_vram_size_bytes`, String(32 * GiB));
|
||||
link("sys/bus/pci/devices/0000:03:00.0", gpu);
|
||||
|
||||
// NVIDIA card directly on a root port, 256 MiB BAR (no ReBAR).
|
||||
const nv = "sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0";
|
||||
file("sys/devices/pci0000:00/0000:00:03.0/vendor", "0x1022");
|
||||
file(`${nv}/vendor`, "0x10de");
|
||||
file(`${nv}/device`, "0x2684");
|
||||
file(`${nv}/class`, "0x030000");
|
||||
file(`${nv}/uevent`, "DRIVER=nvidia");
|
||||
file(`${nv}/current_link_speed`, "16.0 GT/s PCIe");
|
||||
file(`${nv}/current_link_width`, "16");
|
||||
file(`${nv}/max_link_speed`, "16.0 GT/s PCIe");
|
||||
file(`${nv}/max_link_width`, "16");
|
||||
file(`${nv}/resource`, [bar(0xb0000000, 16 * 2 ** 20), bar(0x6000000000, 256 * 2 ** 20)].join("\n"));
|
||||
link("sys/bus/pci/devices/0000:05:00.0", nv);
|
||||
file("sys/module/nvidia/version", "580.82.07");
|
||||
|
||||
// A virtio NIC: not a GPU.
|
||||
file("sys/devices/pci0000:00/0000:00:12.0/vendor", "0x1af4");
|
||||
file("sys/devices/pci0000:00/0000:00:12.0/class", "0x020000");
|
||||
link("sys/bus/pci/devices/0000:00:12.0", "sys/devices/pci0000:00/0000:00:12.0");
|
||||
|
||||
file("usr/share/misc/pci.ids", PCI_IDS);
|
||||
file("proc/cpuinfo", CPUINFO);
|
||||
file("proc/meminfo", "MemTotal: 65536000 kB\nMemFree: 1 kB\n");
|
||||
file("sys/class/dmi/id/sys_vendor", "QEMU");
|
||||
file("sys/class/dmi/id/product_name", "Standard PC (Q35 + ICH9, 2009)");
|
||||
|
||||
// Models on /dev/nvme0n1p2 (259:2).
|
||||
file("proc/self/mountinfo", ["22 1 259:1 / / rw - ext4 /dev/nvme0n1p1 rw", "1521 1471 259:2 /srv/models /models rw,relatime - ext4 /dev/nvme0n1p2 rw"].join("\n"));
|
||||
const disk = "sys/devices/pci0000:00/0000:00:06.0/nvme/nvme0/nvme0n1";
|
||||
file(`${disk}/device/model`, "Samsung SSD 990 PRO 2TB ");
|
||||
file(`${disk}/queue/rotational`, "0");
|
||||
file(`${disk}/size`, String(3_907_029_168));
|
||||
file(`${disk}/nvme0n1p2/partition`, "2");
|
||||
link("sys/dev/block/259:2", `${disk}/nvme0n1p2`);
|
||||
});
|
||||
|
||||
describe("hardware detection (sysfs fixture)", () => {
|
||||
it("finds GPUs, the card's upstream link behind an on-card switch, ReBAR and names", async () => {
|
||||
const hw = await detectHardware({
|
||||
fs: memFs(),
|
||||
modelsDir: "/models",
|
||||
kernel: "6.17.1-pve",
|
||||
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 4090", memoryMb: 24564, driver: "580.82.07", pciAddress: "00000000:05:00.0" }],
|
||||
});
|
||||
assert.equal(hw.gpus.length, 2);
|
||||
const [intel, nv] = hw.gpus;
|
||||
assert.deepEqual(
|
||||
{ ...intel },
|
||||
{
|
||||
vendor: "intel",
|
||||
pciAddress: "0000:03:00.0",
|
||||
name: "Intel Arc Pro B65 32GB",
|
||||
vramMb: 32768,
|
||||
driver: "xe",
|
||||
driverVersion: "kernel 6.17.1-pve",
|
||||
linkCurrent: { gen: 4, width: 8 },
|
||||
linkMax: { gen: 5, width: 16 },
|
||||
barMb: 32768,
|
||||
rebar: true,
|
||||
},
|
||||
);
|
||||
assert.equal(nv.name, "NVIDIA GeForce RTX 4090");
|
||||
assert.equal(nv.vramMb, 24564);
|
||||
assert.equal(nv.driverVersion, "580.82.07");
|
||||
assert.deepEqual(nv.linkCurrent, { gen: 4, width: 16 });
|
||||
assert.equal(nv.barMb, 256);
|
||||
assert.equal(nv.rebar, false);
|
||||
assert.equal(hw.p2p, null);
|
||||
});
|
||||
|
||||
it("reads CPU, RAM, VM and the models disk", async () => {
|
||||
const hw = await detectHardware({ fs: memFs(), modelsDir: "/models/", kernel: "6.17.1-pve" });
|
||||
assert.deepEqual(hw.cpu, { model: "AMD EPYC 9124 16-Core Processor", cores: 2, threads: 4 });
|
||||
assert.equal(hw.memoryBytes, 65536000 * 1024);
|
||||
assert.deepEqual(hw.virtualization, { vm: true, hypervisor: "KVM/QEMU" });
|
||||
assert.deepEqual(hw.storage, { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 3_907_029_168 * 512 });
|
||||
});
|
||||
|
||||
it("doesn't fail on a host without any of it", async () => {
|
||||
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
|
||||
const hw = await detectHardware({ fs: empty, modelsDir: "/models", kernel: null });
|
||||
assert.deepEqual(hw.gpus, []);
|
||||
assert.equal(hw.storage, null);
|
||||
assert.deepEqual(hw.cpu, { model: null, cores: null, threads: null });
|
||||
assert.deepEqual(hw.virtualization, { vm: null, hypervisor: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("hardware parsers", () => {
|
||||
it("normalizes nvidia-smi bus IDs and reads them from the probe CSV", () => {
|
||||
assert.equal(normalizePciAddress("00000000:0A:00.0"), "0000:0a:00.0");
|
||||
assert.deepEqual(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07, 00000000:01:00.0")[0].pciAddress, "0000:01:00.0");
|
||||
assert.equal(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07")[0].pciAddress, null);
|
||||
});
|
||||
|
||||
it("takes the largest memory BAR", () => {
|
||||
assert.equal(largestBarMb([bar(0x1000, 2 ** 20), bar(0x100000000, 8 * GiB), "0x0000000000001000 0x000000000000107f 0x0000000000040101"].join("\n")), 8192);
|
||||
assert.equal(largestBarMb(EMPTY), null);
|
||||
assert.equal(largestBarMb(null), null);
|
||||
});
|
||||
|
||||
it("names GPUs from pci.ids, board name first", () => {
|
||||
assert.equal(pciName(PCI_IDS, "0x8086", "0xe20b"), "Battlemage G21 [Arc B580]");
|
||||
assert.equal(pciName(PCI_IDS, "0x8086", "0xe211", "0x8086", "0x1234"), "Arc Pro B65 32GB");
|
||||
assert.equal(pciName(PCI_IDS, "0x8086", "0xffff"), null);
|
||||
assert.equal(gpuDisplayName("intel", "Battlemage G21 [Arc B580]"), "Intel Arc B580");
|
||||
assert.equal(gpuDisplayName("nvidia", "AD102 [GeForce RTX 4090]"), "NVIDIA GeForce RTX 4090");
|
||||
});
|
||||
|
||||
it("reads nvidia-smi's P2P matrix", () => {
|
||||
const m = (cells: string) => `\tGPU0\tGPU1\n GPU0\tX\t${cells}\n GPU1\t${cells}\tX\n\nLegend:\n X = Self\n OK = Status Ok`;
|
||||
assert.equal(parseP2p(m("OK")), "on");
|
||||
assert.equal(parseP2p(m("CNS")), "off");
|
||||
assert.equal(parseP2p("\tGPU0\tGPU1\tGPU2\n GPU0\tX\tOK\tNS\n GPU1\tOK\tX\tNS\n GPU2\tNS\tNS\tX"), "partial");
|
||||
assert.equal(parseP2p("garbage"), null);
|
||||
});
|
||||
|
||||
it("counts cores per socket and sees the hypervisor flag", () => {
|
||||
const c = parseCpu(CPUINFO);
|
||||
assert.equal(c.cores, 2);
|
||||
assert.equal(c.threads, 4);
|
||||
assert.ok(c.hypervisor);
|
||||
assert.equal(parseCpu(null).model, null);
|
||||
});
|
||||
|
||||
it("finds the mount holding a folder", () => {
|
||||
const mi = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n2 1 8:16 / /models rw - ext4 /dev/sdb rw\n3 1 8:32 / /models-old rw - ext4 /dev/sdc rw";
|
||||
assert.equal(mountDevice(mi, "/models"), "8:16");
|
||||
assert.equal(mountDevice(mi, "/models/unsloth"), "8:16");
|
||||
assert.equal(mountDevice(mi, "/models-old"), "8:32");
|
||||
assert.equal(mountDevice(mi, "/data"), "8:1");
|
||||
});
|
||||
|
||||
it("picks the digest of the image's own repository", () => {
|
||||
assert.equal(repoDigest("ghcr.io/ggml-org/llama.cpp:server", ["ghcr.io/ggml-org/llama.cpp@sha256:aaa", "mirror.local/llama.cpp@sha256:bbb"]), "sha256:aaa");
|
||||
assert.equal(repoDigest("vllm/vllm-openai:v0.31.0", ["vllm/vllm-openai@sha256:ccc"]), "sha256:ccc");
|
||||
assert.equal(repoDigest("local:dev", []), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("engine info", () => {
|
||||
it("reads llama-server /props (build 11429)", () => {
|
||||
assert.deepEqual(parseLlamaProps({ build_info: "b11429-d81235049", total_slots: 4, default_generation_settings: { n_ctx: 4096 } }), {
|
||||
version: "b11429-d81235049",
|
||||
slots: 4,
|
||||
contextSize: 4096,
|
||||
});
|
||||
assert.deepEqual(parseLlamaProps(null), { version: null, slots: null, contextSize: null });
|
||||
});
|
||||
|
||||
it("reads vLLM /version and /v1/models", () => {
|
||||
assert.deepEqual(parseVllm({ version: "0.5.7" }, { data: [{ id: "x", max_model_len: 32768 }] }), { version: "0.5.7", slots: null, contextSize: 32768 });
|
||||
});
|
||||
|
||||
it("falls back to startup log lines", () => {
|
||||
assert.equal(versionFromLog("llama.cpp", ["main: build: 11429 (d8123504) with gcc"]), "b11429-d8123504");
|
||||
assert.equal(versionFromLog("vllm", ["INFO 10-20 api_server.py:1 vLLM API server version 0.31.0"]), "0.31.0");
|
||||
assert.equal(versionFromLog("vllm", ["nothing here"]), null);
|
||||
});
|
||||
|
||||
it("returns nulls when the server can't be reached", async () => {
|
||||
const info = await fetchEngineInfo("llama.cpp", "http://127.0.0.1:9", null);
|
||||
assert.deepEqual(info, { version: null, slots: null, contextSize: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("PCIe link under load", () => {
|
||||
it("reads each card's current link from sysfs", async () => {
|
||||
assert.deepEqual(await currentLinks(memFs(), ["0000:03:00.0", "0000:05:00.0", "0000:09:00.0"]), {
|
||||
"0000:03:00.0": { gen: 4, width: 8 },
|
||||
"0000:05:00.0": { gen: 4, width: 16 },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the fastest link seen and reads nvidia-smi's link columns", () => {
|
||||
const l = (gen: number, width: number) => ({ gen, width });
|
||||
assert.deepEqual(
|
||||
fastestLinks([
|
||||
{ pciAddress: "a", link: l(1, 16) },
|
||||
{ pciAddress: "a", link: l(4, 16) },
|
||||
{ pciAddress: "a", link: l(4, 8) },
|
||||
{ pciAddress: "b", link: l(3, 4) },
|
||||
]),
|
||||
{ a: l(4, 16), b: l(3, 4) },
|
||||
);
|
||||
assert.deepEqual(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16")?.link, l(4, 16));
|
||||
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5")?.link, null);
|
||||
const stats = summarizeSamples([], [], 10, [{ pciAddress: "a", link: l(1, 16) }, { pciAddress: "a", link: l(4, 16) }]);
|
||||
assert.deepEqual(stats.links, { a: l(4, 16) });
|
||||
});
|
||||
|
||||
it("lists NVIDIA GPUs that aren't on the visible PCI bus (WSL2), with nvidia-smi's link", async () => {
|
||||
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
|
||||
const hw = await detectHardware({
|
||||
fs: empty,
|
||||
modelsDir: "/models",
|
||||
kernel: null,
|
||||
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14", pciAddress: "00000000:01:00.0", linkMax: { gen: 4, width: 16 } }],
|
||||
});
|
||||
assert.equal(hw.gpus.length, 1);
|
||||
assert.equal(hw.gpus[0].pciAddress, "0000:01:00.0");
|
||||
assert.deepEqual(hw.gpus[0].linkMax, { gen: 4, width: 16 });
|
||||
assert.equal(hw.gpus[0].rebar, null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,316 @@
|
||||
// Host hardware from sysfs and procfs, which a container sees unprivileged: GPUs on the PCI bus with
|
||||
// their PCIe link and BAR size (for Resizable BAR), CPU, RAM, kernel, virtualization and the disk
|
||||
// holding the models folder. Root-only sources (lspci's extended capabilities, DMI serials) and host
|
||||
// tools (systemd-detect-virt) aren't available in the worker, so this reads the same facts from files.
|
||||
// Everything reads through a SysFs, so tests run against an in-memory tree.
|
||||
|
||||
import { readdir, readFile, realpath } from "node:fs/promises";
|
||||
import { release } from "node:os";
|
||||
import { posix } from "node:path";
|
||||
import type { GpuVendor, HardwareGpu, HostGpu, HostHardware, PcieLink } from "@/lib/db/schema";
|
||||
import { linkGen, rebarFrom } from "@/lib/hardware";
|
||||
|
||||
const VENDORS: Record<string, GpuVendor> = { "0x10de": "nvidia", "0x8086": "intel", "0x1002": "amd" };
|
||||
const VENDOR_LABEL: Record<GpuVendor, string> = { nvidia: "NVIDIA", intel: "Intel", amd: "AMD" };
|
||||
const PCI_ADDR = /^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i;
|
||||
const PCI_IDS = ["/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids"];
|
||||
/** Where drivers report total VRAM, if they do (amdgpu; xe/i915 vary by kernel). */
|
||||
const VRAM_FILES = ["mem_info_vram_total", "tile0/physical_vram_size_bytes", "lmem_total_bytes"];
|
||||
const IORESOURCE_MEM = BigInt(0x200);
|
||||
const ZERO = BigInt(0);
|
||||
const MIB = BigInt(2 ** 20);
|
||||
|
||||
const { basename, dirname, join } = posix;
|
||||
|
||||
/** The few file operations detection needs (absolute POSIX paths). */
|
||||
export type SysFs = {
|
||||
/** Trimmed file content, or null when it can't be read. */
|
||||
read(path: string): Promise<string | null>;
|
||||
list(dir: string): Promise<string[]>;
|
||||
/** Symlinks resolved (sysfs device links); the path itself when it isn't one. */
|
||||
resolve(path: string): Promise<string>;
|
||||
};
|
||||
|
||||
export const nodeFs: SysFs = {
|
||||
read: (p) => readFile(p, "utf8").then((t) => t.trim(), () => null),
|
||||
list: (d) => readdir(d).catch(() => []),
|
||||
resolve: (p) => realpath(p).catch(() => p),
|
||||
};
|
||||
|
||||
const num = (s: string | null) => (s != null && /^\d+$/.test(s) ? Number(s) : null);
|
||||
|
||||
/** nvidia-smi's "00000000:01:00.0" → sysfs "0000:01:00.0". */
|
||||
export function normalizePciAddress(id: string): string {
|
||||
const [domain, ...rest] = id.trim().toLowerCase().split(":");
|
||||
return [domain.slice(-4).padStart(4, "0"), ...rest].join(":");
|
||||
}
|
||||
|
||||
/** Largest memory BAR in MiB, from a device's `resource` file ("start end flags" per line). */
|
||||
export function largestBarMb(resource: string | null): number | null {
|
||||
if (!resource) return null;
|
||||
let max = ZERO;
|
||||
for (const line of resource.split("\n")) {
|
||||
const [start, end, flags] = line.trim().split(/\s+/).map((x) => {
|
||||
try {
|
||||
return BigInt(x);
|
||||
} catch {
|
||||
return ZERO;
|
||||
}
|
||||
});
|
||||
if (!end || !(flags & IORESOURCE_MEM)) continue;
|
||||
const size = end - start + BigInt(1);
|
||||
if (size > max) max = size;
|
||||
}
|
||||
return max > ZERO ? Number(max / MIB) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The card's own upstream link: cards like Intel's Arc B-series sit behind an on-card PCIe switch,
|
||||
* whose internal link is what the GPU function reports. Walk up while the parent belongs to the same
|
||||
* vendor and isn't the root port.
|
||||
*/
|
||||
async function cardUpstream(fs: SysFs, dev: string, vendor: string): Promise<string> {
|
||||
let cur = dev;
|
||||
for (;;) {
|
||||
const parent = dirname(cur);
|
||||
if (!PCI_ADDR.test(basename(parent)) || !PCI_ADDR.test(basename(dirname(parent)))) return cur;
|
||||
if ((await fs.read(join(parent, "vendor"))) !== vendor) return cur;
|
||||
cur = parent;
|
||||
}
|
||||
}
|
||||
|
||||
async function link(fs: SysFs, dir: string, kind: "current" | "max") {
|
||||
const gen = linkGen(await fs.read(join(dir, `${kind}_link_speed`)));
|
||||
const width = num(await fs.read(join(dir, `${kind}_link_width`)));
|
||||
return gen == null && width == null ? null : { gen, width };
|
||||
}
|
||||
|
||||
const pciIds = new WeakMap<SysFs, Promise<string | null>>();
|
||||
async function pciIdsText(fs: SysFs): Promise<string | null> {
|
||||
if (!pciIds.has(fs)) {
|
||||
pciIds.set(
|
||||
fs,
|
||||
(async () => {
|
||||
for (const p of PCI_IDS) {
|
||||
const text = await fs.read(p);
|
||||
if (text) return text;
|
||||
}
|
||||
return null;
|
||||
})(),
|
||||
);
|
||||
}
|
||||
return pciIds.get(fs)!;
|
||||
}
|
||||
|
||||
/** Name from pci.ids: the subsystem's (board) name if listed, else the chip's; "[Arc B580]" preferred. */
|
||||
export function pciName(ids: string, vendor: string, device: string, subVendor?: string | null, subDevice?: string | null): string | null {
|
||||
const v = vendor.replace(/^0x/, "").toLowerCase();
|
||||
const d = device.replace(/^0x/, "").toLowerCase();
|
||||
const sub = subVendor && subDevice ? `${subVendor.replace(/^0x/, "")} ${subDevice.replace(/^0x/, "")}`.toLowerCase() : null;
|
||||
const lines = ids.split("\n");
|
||||
let i = lines.findIndex((l) => l.startsWith(`${v} `));
|
||||
if (i < 0) return null;
|
||||
let chip: string | null = null;
|
||||
for (i++; i < lines.length && (lines[i].startsWith("\t") || lines[i].startsWith("#") || !lines[i].trim()); i++) {
|
||||
const l = lines[i];
|
||||
if (!l.startsWith("\t\t") && l.startsWith("\t")) {
|
||||
if (chip) break;
|
||||
if (l.slice(1, 5).toLowerCase() === d) chip = l.slice(7).trim();
|
||||
} else if (chip && sub && l.startsWith("\t\t") && l.slice(2, 11).toLowerCase() === sub) {
|
||||
return l.slice(13).trim();
|
||||
}
|
||||
}
|
||||
return chip;
|
||||
}
|
||||
|
||||
/** "AD102 [GeForce RTX 4090]" → "NVIDIA GeForce RTX 4090". */
|
||||
export function gpuDisplayName(vendor: GpuVendor, pciIdsName: string | null): string | null {
|
||||
if (!pciIdsName) return null;
|
||||
const bracket = pciIdsName.match(/\[([^\]]+)\]/)?.[1];
|
||||
const name = bracket ?? pciIdsName;
|
||||
const label = VENDOR_LABEL[vendor];
|
||||
return name.toLowerCase().startsWith(label.toLowerCase()) ? name : `${label} ${name}`;
|
||||
}
|
||||
|
||||
function uevent(text: string | null): Record<string, string> {
|
||||
return Object.fromEntries((text ?? "").split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
|
||||
}
|
||||
|
||||
/** Display controllers (class 0x03…) from NVIDIA, Intel and AMD. NVIDIA names/VRAM come from nvidia-smi. */
|
||||
export async function detectGpus(fs: SysFs, nvidia: HostGpu[], kernel: string | null): Promise<HardwareGpu[]> {
|
||||
const base = "/sys/bus/pci/devices";
|
||||
const addrs = (await fs.list(base)).filter((a) => PCI_ADDR.test(a)).sort();
|
||||
const out: HardwareGpu[] = [];
|
||||
for (const addr of addrs) {
|
||||
const dev = await fs.resolve(join(base, addr));
|
||||
const [cls, vendorId] = await Promise.all([fs.read(join(dev, "class")), fs.read(join(dev, "vendor"))]);
|
||||
const vendor = vendorId ? VENDORS[vendorId.toLowerCase()] : undefined;
|
||||
if (!cls?.startsWith("0x03") || !vendor) continue;
|
||||
const ev = uevent(await fs.read(join(dev, "uevent")));
|
||||
const driver = ev.DRIVER || null;
|
||||
const up = await cardUpstream(fs, dev, vendorId!.toLowerCase());
|
||||
const nv = nvidia.find((g) => g.pciAddress && normalizePciAddress(g.pciAddress) === addr.toLowerCase());
|
||||
let vramMb: number | null = nv?.memoryMb ?? null;
|
||||
for (const f of VRAM_FILES) {
|
||||
if (vramMb) break;
|
||||
const bytes = num(await fs.read(join(dev, f)));
|
||||
if (bytes) vramMb = Math.round(bytes / 2 ** 20);
|
||||
}
|
||||
const ids = await pciIdsText(fs);
|
||||
const [device, subVendor, subDevice] = await Promise.all(["device", "subsystem_vendor", "subsystem_device"].map((f) => fs.read(join(dev, f))));
|
||||
const barMb = largestBarMb(await fs.read(join(dev, "resource")));
|
||||
const moduleVersion = driver ? await fs.read(join("/sys/module", driver, "version")) : null;
|
||||
out.push({
|
||||
vendor,
|
||||
pciAddress: addr.toLowerCase(),
|
||||
name: nv?.name ?? (ids && device ? gpuDisplayName(vendor, pciName(ids, vendorId!, device, subVendor, subDevice)) : null),
|
||||
vramMb,
|
||||
driver,
|
||||
driverVersion: nv?.driver ?? moduleVersion ?? (driver && kernel ? `kernel ${kernel}` : null),
|
||||
linkCurrent: (await link(fs, up, "current")) ?? nv?.linkCurrent ?? null,
|
||||
linkMax: (await link(fs, up, "max")) ?? nv?.linkMax ?? null,
|
||||
barMb,
|
||||
rebar: rebarFrom(barMb, vramMb),
|
||||
});
|
||||
}
|
||||
// NVIDIA GPUs that aren't on the visible PCI bus (WSL2 passes them through its own driver).
|
||||
for (const g of nvidia) {
|
||||
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
|
||||
if (out.some((o) => o.pciAddress === addr)) continue;
|
||||
out.push({
|
||||
vendor: "nvidia",
|
||||
pciAddress: addr,
|
||||
name: g.name,
|
||||
vramMb: g.memoryMb || null,
|
||||
driver: "nvidia",
|
||||
driverVersion: g.driver || null,
|
||||
linkCurrent: g.linkCurrent ?? null,
|
||||
linkMax: g.linkMax ?? null,
|
||||
barMb: null,
|
||||
rebar: null,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The current link of each GPU's card (upstream port), for sampling during a run; skips unknown ones. */
|
||||
export async function currentLinks(fs: SysFs, pciAddresses: string[]): Promise<Record<string, PcieLink>> {
|
||||
const out: Record<string, PcieLink> = {};
|
||||
for (const addr of pciAddresses) {
|
||||
const dev = await fs.resolve(join("/sys/bus/pci/devices", addr));
|
||||
const vendor = await fs.read(join(dev, "vendor"));
|
||||
if (!vendor) continue;
|
||||
const l = await link(fs, await cardUpstream(fs, dev, vendor.toLowerCase()), "current");
|
||||
if (l) out[addr] = l;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `nvidia-smi topo -p2p r`: "OK" between every pair → on, none → off. */
|
||||
export function parseP2p(text: string): "on" | "off" | "partial" | null {
|
||||
const cells = text
|
||||
.split("\n")
|
||||
.filter((l) => /^\s*GPU\d+\s/.test(l))
|
||||
.flatMap((l) => l.trim().split(/\s+/).slice(1))
|
||||
.filter((c) => c !== "X" && !/^GPU\d+$/.test(c));
|
||||
if (cells.length === 0) return null;
|
||||
const ok = cells.filter((c) => c === "OK").length;
|
||||
return ok === cells.length ? "on" : ok === 0 ? "off" : "partial";
|
||||
}
|
||||
|
||||
export function parseCpu(cpuinfo: string | null): HostHardware["cpu"] & { hypervisor: boolean } {
|
||||
if (!cpuinfo) return { model: null, cores: null, threads: null, hypervisor: false };
|
||||
const blocks = cpuinfo.split(/\n\s*\n/).filter((b) => /^processor\s*:/m.test(b));
|
||||
const field = (b: string, k: string) => b.match(new RegExp(`^${k}\\s*:\\s*(.*)$`, "m"))?.[1]?.trim() ?? null;
|
||||
const cores = new Set(blocks.map((b) => `${field(b, "physical id") ?? 0}:${field(b, "core id") ?? field(b, "processor")}`));
|
||||
return {
|
||||
model: blocks[0] ? field(blocks[0], "model name") : null,
|
||||
cores: blocks.length ? cores.size : null,
|
||||
threads: blocks.length || null,
|
||||
hypervisor: blocks[0] ? /\bhypervisor\b/.test(field(blocks[0], "flags") ?? "") : false,
|
||||
};
|
||||
}
|
||||
|
||||
const HYPERVISORS: [RegExp, string][] = [
|
||||
[/^QEMU|KVM/i, "KVM/QEMU"],
|
||||
[/Microsoft/i, "Hyper-V"],
|
||||
[/VMware/i, "VMware"],
|
||||
[/Xen/i, "Xen"],
|
||||
[/innotek|VirtualBox/i, "VirtualBox"],
|
||||
[/Amazon/i, "AWS"],
|
||||
[/Google/i, "Google Cloud"],
|
||||
];
|
||||
|
||||
/** VM or bare metal, from the CPU's hypervisor flag and the DMI vendor (both readable unprivileged). */
|
||||
export async function detectVirtualization(fs: SysFs, hypervisorFlag: boolean, kernel: string | null): Promise<HostHardware["virtualization"]> {
|
||||
const dmi = [await fs.read("/sys/class/dmi/id/sys_vendor"), await fs.read("/sys/class/dmi/id/product_name")].filter(Boolean).join(" ");
|
||||
if (kernel && /microsoft.*wsl/i.test(kernel)) return { vm: true, hypervisor: "WSL2 (Hyper-V)" };
|
||||
const known = HYPERVISORS.find(([re]) => re.test(dmi))?.[1] ?? null;
|
||||
if (hypervisorFlag || known) return { vm: true, hypervisor: known };
|
||||
return { vm: dmi ? false : null, hypervisor: null };
|
||||
}
|
||||
|
||||
/** The mount holding `dir` (longest mount point that is a prefix), as "major:minor". */
|
||||
export function mountDevice(mountinfo: string, dir: string): string | null {
|
||||
const target = posix.normalize(dir.replace(/\\/g, "/")).replace(/(.)\/$/, "$1");
|
||||
let best: { point: string; dev: string } | null = null;
|
||||
for (const line of mountinfo.split("\n")) {
|
||||
const f = line.split(" ");
|
||||
if (f.length < 5) continue;
|
||||
const point = f[4].replace(/\\040/g, " ");
|
||||
const inside = target === point || target.startsWith(point.endsWith("/") ? point : `${point}/`);
|
||||
if (inside && (!best || point.length > best.point.length)) best = { point, dev: f[2] };
|
||||
}
|
||||
return best?.dev ?? null;
|
||||
}
|
||||
|
||||
/** The disk behind a block device: partitions → their disk, device-mapper (LVM, LUKS) → first slave. */
|
||||
async function diskOf(fs: SysFs, devDir: string, depth = 0): Promise<string | null> {
|
||||
if (depth > 4) return null;
|
||||
if (await fs.read(join(devDir, "partition"))) return dirname(devDir);
|
||||
if (basename(devDir).startsWith("dm-") || basename(devDir).startsWith("md")) {
|
||||
const slaves = await fs.list(join(devDir, "slaves"));
|
||||
if (!slaves[0]) return devDir;
|
||||
return diskOf(fs, await fs.resolve(join("/sys/class/block", slaves[0])), depth + 1);
|
||||
}
|
||||
return devDir;
|
||||
}
|
||||
|
||||
export async function detectStorage(fs: SysFs, modelsDir: string): Promise<HostHardware["storage"]> {
|
||||
const mountinfo = await fs.read("/proc/self/mountinfo");
|
||||
const dev = mountinfo ? mountDevice(mountinfo, modelsDir) : null;
|
||||
if (!dev || dev.startsWith("0:")) return null; // ZFS, overlay, network filesystems: no block device
|
||||
const blockDir = join("/sys/dev/block", dev);
|
||||
if ((await fs.list(blockDir)).length === 0) return null;
|
||||
const disk = await diskOf(fs, await fs.resolve(blockDir));
|
||||
if (!disk) return null;
|
||||
const name = basename(disk);
|
||||
const model = (await fs.read(join(disk, "device/model")))?.replace(/\s+/g, " ") || null;
|
||||
const vendor = (await fs.read(join(disk, "device/vendor")))?.trim() ?? "";
|
||||
const rotational = await fs.read(join(disk, "queue/rotational"));
|
||||
const sectors = num(await fs.read(join(disk, "size")));
|
||||
const virtual = /^vd|^xvd/.test(name) || vendor === "0x1af4" || /QEMU|Virtual Disk|VBOX|VMware/i.test(`${vendor} ${model ?? ""}`);
|
||||
return {
|
||||
model: model ?? (virtual ? "virtio disk" : null),
|
||||
kind: virtual ? "virtual" : name.startsWith("nvme") ? "nvme" : rotational === "1" ? "hdd" : rotational === "0" ? "ssd" : null,
|
||||
sizeBytes: sectors != null ? sectors * 512 : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function detectHardware(o: { fs?: SysFs; modelsDir: string; nvidia?: HostGpu[]; p2p?: HostHardware["p2p"]; kernel?: string | null }): Promise<HostHardware> {
|
||||
const fs = o.fs ?? nodeFs;
|
||||
const kernel = o.kernel !== undefined ? o.kernel : release();
|
||||
const cpu = parseCpu(await fs.read("/proc/cpuinfo"));
|
||||
const memKb = Number((await fs.read("/proc/meminfo"))?.match(/^MemTotal:\s+(\d+)\s*kB/m)?.[1]);
|
||||
const gpus = await detectGpus(fs, o.nvidia ?? [], kernel);
|
||||
return {
|
||||
gpus,
|
||||
p2p: gpus.length >= 2 ? (o.p2p ?? null) : null,
|
||||
cpu: { model: cpu.model, cores: cpu.cores, threads: cpu.threads },
|
||||
memoryBytes: Number.isFinite(memKb) && memKb > 0 ? memKb * 1024 : null,
|
||||
kernel,
|
||||
virtualization: await detectVirtualization(fs, cpu.hypervisor, kernel),
|
||||
storage: await detectStorage(fs, o.modelsDir).catch(() => null),
|
||||
checkedAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
+14
-1
@@ -10,7 +10,9 @@ 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 { benchmarkPublications, benchmarkRuns, settings } from "@/lib/db/schema";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { systemSummaryLines } from "@/lib/hardware";
|
||||
import { coreEnv } from "@/lib/env";
|
||||
import { log } from "./log";
|
||||
|
||||
@@ -60,6 +62,16 @@ export async function reportL80Status(): Promise<void> {
|
||||
log.info(version ? `L80 CLI ${version}, publish token ${value.tokenSet ? "set" : "not set"}` : "L80 CLI not found; publishing to launch80 is unavailable");
|
||||
}
|
||||
|
||||
/** The run's description, hardware/runtime facts and system summary, as page sections (only whitelisted host facts). */
|
||||
export async function runSections(runId: string): Promise<[string, string][]> {
|
||||
const run = await db().query.benchmarkRuns.findFirst({ columns: { description: true, system: true, meta: true }, where: eq(benchmarkRuns.id, runId) });
|
||||
const out: [string, string][] = [];
|
||||
if (run?.description?.trim()) out.push(["Description", run.description.trim()]);
|
||||
if (run?.meta) out.push(["Hardware and runtime", metaRows(run.meta).map((r) => `${r.label}: ${r.value}`).join("\n")]);
|
||||
if (run?.system) out.push(["System", systemSummaryLines(run.system).join("\n")]);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function exists(p: string) {
|
||||
return access(p).then(
|
||||
() => true,
|
||||
@@ -88,6 +100,7 @@ export async function tickPublications(): Promise<void> {
|
||||
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);
|
||||
for (const [heading, body] of await runSections(p.runId)) args.push("--section", `${heading}=${body}`);
|
||||
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 };
|
||||
|
||||
+49
-11
@@ -1,32 +1,60 @@
|
||||
// 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.
|
||||
// stats, every ~2 s), on NVIDIA hosts whole-GPU VRAM/utilization/power from one long-lived
|
||||
// `nvidia-smi -lms` probe container, and the GPUs' PCIe link (it drops to a slower speed when idle,
|
||||
// so the fastest one seen under load is the one worth recording). Aggregation is pure
|
||||
// (summarizeSamples) for tests.
|
||||
|
||||
import type { ResourceStats } from "@/lib/db/schema";
|
||||
import type { PcieLink, ResourceStats } from "@/lib/db/schema";
|
||||
import { currentLinks, nodeFs } from "./hardware";
|
||||
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 };
|
||||
export type GpuSample = { index: number; name: string; vramTotalMb: number; vramUsedMb: number; util: number; powerW: number | null; link?: PcieLink | null };
|
||||
export type LinkSample = { pciAddress: string; link: PcieLink };
|
||||
|
||||
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`. */
|
||||
const GPU_QUERY = "index,name,memory.total,memory.used,utilization.gpu,power.draw,pcie.link.gen.current,pcie.link.width.current";
|
||||
|
||||
/** One CSV line of `nvidia-smi --query-gpu=${GPU_QUERY}` (the link columns are optional). */
|
||||
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]) };
|
||||
const n = (s: string | undefined) => (s != null && s !== "" && Number.isFinite(Number(s)) ? Number(s) : null);
|
||||
const gen = n(p[6]);
|
||||
const width = n(p[7]);
|
||||
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]),
|
||||
link: gen != null || width != null ? { gen, width } : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number): ResourceStats {
|
||||
/** Faster link: higher generation first, then more lanes. */
|
||||
const faster = (a: PcieLink | undefined, b: PcieLink) => !a || (b.gen ?? 0) > (a.gen ?? 0) || ((b.gen ?? 0) === (a.gen ?? 0) && (b.width ?? 0) > (a.width ?? 0));
|
||||
|
||||
/** Fastest link per GPU over the run. */
|
||||
export function fastestLinks(samples: LinkSample[]): Record<string, PcieLink> {
|
||||
const out: Record<string, PcieLink> = {};
|
||||
for (const s of samples) if (faster(out[s.pciAddress], s.link)) out[s.pciAddress] = s.link;
|
||||
return out;
|
||||
}
|
||||
|
||||
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number, links: LinkSample[] = []): ResourceStats {
|
||||
const sides = [...new Set(containers.map((c) => c.side))].sort();
|
||||
const fastest = fastestLinks(links);
|
||||
return {
|
||||
samples: containers.length,
|
||||
seconds: Math.round(seconds),
|
||||
...(Object.keys(fastest).length ? { links: fastest } : {}),
|
||||
containers: sides.map((side) => {
|
||||
const xs = containers.filter((c) => c.side === side);
|
||||
// Docker reports CPU in percent of one core; keep cores.
|
||||
@@ -64,6 +92,7 @@ export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[
|
||||
export class ResourceSampler {
|
||||
private containerSamples: ContainerSample[] = [];
|
||||
private gpuSamples: GpuSample[] = [];
|
||||
private linkSamples: LinkSample[] = [];
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private probeId: string | null = null;
|
||||
@@ -74,6 +103,8 @@ export class ResourceSampler {
|
||||
private c: DockerClient,
|
||||
private targets: { side: "a" | "b"; containerId: string }[],
|
||||
private gpuProbeImage: string | null,
|
||||
/** GPUs whose link to sample: PCI addresses read from sysfs, NVIDIA indexes mapped to addresses. */
|
||||
private gpuLinks: { sysfs: string[]; nvidiaIndex: Record<number, string> } = { sysfs: [], nvidiaIndex: {} },
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
@@ -91,6 +122,10 @@ export class ResourceSampler {
|
||||
const s = await this.c.containerStats(t.containerId).catch(() => null);
|
||||
if (s) this.containerSamples.push({ side: t.side, ...s });
|
||||
}
|
||||
if (this.gpuLinks.sysfs.length) {
|
||||
const links = await currentLinks(nodeFs, this.gpuLinks.sysfs).catch(() => ({}));
|
||||
for (const [pciAddress, link] of Object.entries(links)) this.linkSamples.push({ pciAddress, link });
|
||||
}
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
@@ -100,7 +135,7 @@ export class ResourceSampler {
|
||||
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)],
|
||||
Cmd: [`--query-gpu=${GPU_QUERY}`, "--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 },
|
||||
@@ -112,7 +147,10 @@ export class ResourceSampler {
|
||||
created.Id,
|
||||
(_s, line) => {
|
||||
const g = parseGpuLine(line);
|
||||
if (g) this.gpuSamples.push(g);
|
||||
if (!g) return;
|
||||
this.gpuSamples.push(g);
|
||||
const addr = this.gpuLinks.nvidiaIndex[g.index];
|
||||
if (addr && g.link) this.linkSamples.push({ pciAddress: addr, link: g.link });
|
||||
},
|
||||
{ tail: "all", signal: this.abort.signal },
|
||||
)
|
||||
@@ -127,6 +165,6 @@ export class ResourceSampler {
|
||||
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);
|
||||
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000, this.linkSamples);
|
||||
}
|
||||
}
|
||||
+56
-16
@@ -6,10 +6,11 @@ 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, type HostGpu, runtimes, settings, workerState } from "@/lib/db/schema";
|
||||
import { type DockerHostInfo, type HostGpu, type HostHardware, type PcieLink, 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";
|
||||
import { detectHardware, normalizePciAddress, parseP2p } from "./hardware";
|
||||
import { log } from "./log";
|
||||
|
||||
const PROGRESS_MS = 1_000;
|
||||
@@ -66,7 +67,7 @@ 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;
|
||||
let gpuCache: { at: number; gpus: HostGpu[]; p2p: HostHardware["p2p"]; error: string | null } | null = null;
|
||||
|
||||
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
|
||||
export function parseNvidiaSmi(csv: string): HostGpu[] {
|
||||
@@ -74,18 +75,42 @@ export function parseNvidiaSmi(csv: string): HostGpu[] {
|
||||
.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 }));
|
||||
.map(([index, uuid, name, mem, driver, bus, genCur, genMax, widthCur, widthMax]) => ({
|
||||
vendor: "nvidia" as const,
|
||||
index: Number(index),
|
||||
uuid,
|
||||
name,
|
||||
memoryMb: Number(mem) || 0,
|
||||
driver,
|
||||
pciAddress: bus ? normalizePciAddress(bus) : null,
|
||||
linkCurrent: nvLink(genCur, widthCur),
|
||||
linkMax: nvLink(genMax, widthMax),
|
||||
}));
|
||||
}
|
||||
|
||||
const nvNum = (s: string | undefined) => (s && /^\d+$/.test(s) ? Number(s) : null);
|
||||
function nvLink(gen: string | undefined, width: string | undefined): PcieLink | null {
|
||||
const l = { gen: nvNum(gen), width: nvNum(width) };
|
||||
return l.gen == null && l.width == null ? null : l;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Lists the GPUs containers get from Docker (nvidia-smi, which the NVIDIA Container Toolkit injects)
|
||||
* and, with two or more, whether they can talk peer-to-peer.
|
||||
*/
|
||||
async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
|
||||
async function probeNvidia(c: DockerClient, image: string): Promise<{ gpus: HostGpu[]; p2p: HostHardware["p2p"] }> {
|
||||
const gpus = parseNvidiaSmi((await nvidiaSmi(c, image, ["--query-gpu=index,uuid,name,memory.total,driver_version,pci.bus_id,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,pcie.link.width.max", "--format=csv,noheader,nounits"])).join("\n"));
|
||||
let p2p: HostHardware["p2p"] = null;
|
||||
if (gpus.length >= 2) p2p = parseP2p((await nvidiaSmi(c, image, ["topo", "-p2p", "r"]).catch(() => [])).join("\n"));
|
||||
return { gpus, p2p };
|
||||
}
|
||||
|
||||
/** Runs `nvidia-smi <args>` in a short-lived container (our own image) that gets every GPU; its output lines. */
|
||||
async function nvidiaSmi(c: DockerClient, image: string, args: string[]): Promise<string[]> {
|
||||
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"],
|
||||
Cmd: args,
|
||||
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
|
||||
Labels: { "kaname.managed": "true", "kaname.probe": "gpu" },
|
||||
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false },
|
||||
@@ -96,7 +121,7 @@ async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
|
||||
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"));
|
||||
return lines;
|
||||
} finally {
|
||||
await c.removeContainer(created.Id).catch(() => {});
|
||||
}
|
||||
@@ -104,22 +129,22 @@ async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
|
||||
|
||||
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 (!nvidia) return { nvidia, gpus: [], p2p: null, 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 };
|
||||
const { gpus, p2p } = await probeNvidia(c, selfImage);
|
||||
gpuCache = { at: Date.now(), gpus, p2p, 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) };
|
||||
gpuCache = { at: Date.now(), gpus: [], p2p: null, error: message(err) };
|
||||
log.warn(`GPU probe failed: ${message(err)}`);
|
||||
}
|
||||
}
|
||||
return { nvidia, gpus: gpuCache.gpus, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
|
||||
return { nvidia, gpus: gpuCache.gpus, p2p: gpuCache.p2p, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
|
||||
}
|
||||
|
||||
const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded";
|
||||
@@ -151,6 +176,11 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
const [v, i] = await Promise.all([c.version(), c.info()]);
|
||||
const self = await selfDetect(c);
|
||||
ownImage = self.image;
|
||||
const { p2p, ...gpu } = await gpuFacts(c, i, self.image);
|
||||
const hardware = await detectHardware({ modelsDir: coreEnv().MODELS_DIR, nvidia: gpu.gpus, p2p }).catch((err) => {
|
||||
log.warn(`hardware detection failed: ${message(err)}`);
|
||||
return null;
|
||||
});
|
||||
info = {
|
||||
connected: true,
|
||||
error: null,
|
||||
@@ -162,7 +192,8 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
...base,
|
||||
network: self.network,
|
||||
modelsSource: self.modelsSource,
|
||||
...(await gpuFacts(c, i, self.image)),
|
||||
...gpu,
|
||||
hardware,
|
||||
};
|
||||
} catch (err) {
|
||||
info = {
|
||||
@@ -182,6 +213,14 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
|
||||
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
|
||||
}
|
||||
|
||||
/** The registry digest ("sha256:…") of an image reference, from Docker's RepoDigests ("repo@sha256:…"). */
|
||||
export function repoDigest(ref: string, repoDigests: string[] | null | undefined): string | null {
|
||||
const repo = ref.split("@")[0].replace(/:[^/:]+$/, "");
|
||||
const all = repoDigests ?? [];
|
||||
const hit = all.find((d) => d.split("@")[0] === repo) ?? all[0];
|
||||
return hit?.split("@")[1] ?? null;
|
||||
}
|
||||
|
||||
const SEEDED_KEY = "runtimes.presetsSeeded";
|
||||
|
||||
/** Create the preset runtimes once (deleted presets don't come back). */
|
||||
@@ -225,8 +264,8 @@ export async function syncImageStates(): Promise<void> {
|
||||
.update(runtimes)
|
||||
.set(
|
||||
img
|
||||
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageCheckedAt: new Date() }
|
||||
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageCheckedAt: new Date() },
|
||||
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageDigest: repoDigest(r.image, img.RepoDigests), imageCheckedAt: new Date() }
|
||||
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, imageCheckedAt: new Date() },
|
||||
)
|
||||
.where(eq(runtimes.id, r.id));
|
||||
} catch (err) {
|
||||
@@ -278,6 +317,7 @@ export async function handlePullRequests(): Promise<void> {
|
||||
imageId: img?.Id ?? null,
|
||||
imageSize: img?.Size ?? null,
|
||||
imageCreated: img?.Created ?? null,
|
||||
imageDigest: img ? repoDigest(next.image, img.RepoDigests) : null,
|
||||
pullProgress: null,
|
||||
pullError: img ? null : "Pull finished but the image isn't there.",
|
||||
imageCheckedAt: new Date(),
|
||||
|
||||
Reference in new issue
Block a user