Files
Kaname/src/worker/gpu-sysfs.ts
T
Pascal LinxweilerandClaude Opus 5.5 e007a35143
Release / release (push) Successful in 3m40s
Release 0.12.0: Intel GPU support
Intel/AMD GPU telemetry in benchmark runs (hwmon power/temperature,
amdgpu sysfs, Intel VRAM/utilization from DRM fdinfo via a minimal
host-PID probe container), temperature for all GPUs, VRAM estimate for
NVIDIA and Intel/AMD in the deployment form, /dev/dri group IDs added to
Intel/AMD runtime containers, Intel llama.cpp presets seeded on first
detection, ZES_ENABLE_SYSMAN=1 for the SYCL preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:47:00 +02:00

176 lines
8.2 KiB
TypeScript

// GPU telemetry without nvidia-smi, for Intel and AMD GPUs.
// - hwmon (sysfs, readable unprivileged): power (energy counter or power reading) and temperature.
// - AMD (amdgpu): VRAM in use and busy percent are plain sysfs files.
// - Intel (xe, i915): the driver has no whole-GPU VRAM/utilization file; both are only reported per
// process in DRM fdinfo (/proc/<pid>/fdinfo, kernel "drm-usage-stats"). A probe container in the
// host's PID namespace dumps those (INTEL_PROBE_SCRIPT); parsing and aggregation happen here.
// Pure parsers for tests; the readers take a SysFs.
import { posix } from "node:path";
import type { SysFs } from "./hardware";
const { join } = posix;
export type HwmonReading = { energyUj: number | null; powerW: number | null; tempC: number | null };
const num = (s: string | null) => (s != null && /^-?\d+$/.test(s.trim()) ? Number(s.trim()) : null);
/**
* Power and temperature from the device's hwmon: an energy counter (µJ, xe: energy1_input) when there
* is one, else a power reading (µW, amdgpu: power1_average); the "pkg"/"edge" temperature, else the
* highest one.
*/
export async function readHwmon(fs: SysFs, pciAddress: string): Promise<HwmonReading> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const dirs = (await fs.list(join(dev, "hwmon"))).filter((d) => d.startsWith("hwmon"));
const out: HwmonReading = { energyUj: null, powerW: null, tempC: null };
for (const d of dirs) {
const h = join(dev, "hwmon", d);
const files = await fs.list(h);
const energy = files.filter((f) => /^energy\d+_input$/.test(f)).sort()[0];
if (energy && out.energyUj == null) out.energyUj = num(await fs.read(join(h, energy)));
for (const f of ["power1_average", "power1_input"]) {
if (out.powerW != null || !files.includes(f)) continue;
const uw = num(await fs.read(join(h, f)));
if (uw != null) out.powerW = uw / 1e6;
}
const temps: { label: string; c: number }[] = [];
for (const f of files.filter((x) => /^temp\d+_input$/.test(x))) {
const v = num(await fs.read(join(h, f)));
if (v == null || v <= 0) continue;
const label = (await fs.read(join(h, f.replace("_input", "_label")))) ?? "";
temps.push({ label: label.toLowerCase(), c: v / 1000 });
}
const main = temps.find((t) => t.label === "pkg" || t.label === "edge") ?? temps.sort((a, b) => b.c - a.c)[0];
if (main && out.tempC == null) out.tempC = main.c;
}
return out;
}
/** amdgpu's own whole-GPU figures. */
export async function readAmdUsage(fs: SysFs, pciAddress: string): Promise<{ vramUsedMb: number | null; util: number | null }> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const used = num(await fs.read(join(dev, "mem_info_vram_used")));
const busy = num(await fs.read(join(dev, "gpu_busy_percent")));
return { vramUsedMb: used != null ? Math.round(used / 2 ** 20) : null, util: busy };
}
/** Power between two readings: from the energy counter if both have one, else the instant reading. */
export function powerBetween(prev: HwmonReading | null, cur: HwmonReading, seconds: number): number | null {
if (prev?.energyUj != null && cur.energyUj != null && cur.energyUj >= prev.energyUj && seconds > 0) return (cur.energyUj - prev.energyUj) / 1e6 / seconds;
return cur.powerW;
}
// --- DRM fdinfo ---------------------------------------------------------------------------------
export type DrmClient = {
pdev: string;
clientId: string;
/** Bytes resident in device memory (regions named vram* / local*). */
vramBytes: number;
/** Per engine class: busy cycles and the GPU's total cycles (xe), or busy nanoseconds (i915, amdgpu). */
cycles: Record<string, number>;
totalCycles: Record<string, number>;
ns: Record<string, number>;
};
const UNIT: Record<string, number> = { "": 1, KiB: 1024, MiB: 2 ** 20, GiB: 2 ** 30 };
/** One /proc/<pid>/fdinfo/<fd> of a DRM client; null for other files. */
export function parseFdinfo(text: string): DrmClient | null {
const kv = new Map<string, string>();
for (const line of text.split("\n")) {
const i = line.indexOf(":");
if (i > 0) kv.set(line.slice(0, i).trim(), line.slice(i + 1).trim());
}
const pdev = kv.get("drm-pdev");
const clientId = kv.get("drm-client-id");
if (!pdev || !clientId) return null;
const c: DrmClient = { pdev: pdev.toLowerCase(), clientId, vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} };
// Resident is what occupies VRAM now; older drivers only report total or the legacy drm-memory-*.
const mem: Record<"resident" | "total" | "memory", number> = { resident: 0, total: 0, memory: 0 };
const seen = { resident: false, total: false, memory: false };
for (const [k, v] of kv) {
let m = k.match(/^drm-(resident|total|memory)-(.+)$/);
if (m && /vram|local/i.test(m[2])) {
const [, n, unit = ""] = v.match(/^(\d+)\s*(KiB|MiB|GiB)?$/) ?? [];
if (n == null) continue;
const kind = m[1] as keyof typeof mem;
mem[kind] += Number(n) * (UNIT[unit] ?? 1);
seen[kind] = true;
continue;
}
if ((m = k.match(/^drm-total-cycles-(.+)$/))) c.totalCycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-cycles-(.+)$/))) c.cycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-engine-(.+)$/)) && !k.startsWith("drm-engine-capacity-")) c.ns[m[1]] = Number(v.replace(/\s*ns$/, "")) || 0;
}
c.vramBytes = seen.resident ? mem.resident : seen.total ? mem.total : mem.memory;
return c;
}
export type DrmSnapshot = { t: number; gpus: Record<string, { vramBytes: number; cycles: Record<string, number>; totalCycles: Record<string, number>; ns: Record<string, number> }> };
/**
* Sum the clients per GPU. One client shows up once per open file descriptor (and process), so
* duplicates by client id are counted once. The GPU's total cycles are a clock, not a sum: max.
*/
export function aggregateFdinfo(t: number, texts: string[]): DrmSnapshot {
const seen = new Set<string>();
const gpus: DrmSnapshot["gpus"] = {};
for (const text of texts) {
const c = parseFdinfo(text);
if (!c || seen.has(`${c.pdev}#${c.clientId}`)) continue;
seen.add(`${c.pdev}#${c.clientId}`);
const g = (gpus[c.pdev] ??= { vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} });
g.vramBytes += c.vramBytes;
for (const [k, v] of Object.entries(c.cycles)) g.cycles[k] = (g.cycles[k] ?? 0) + v;
for (const [k, v] of Object.entries(c.totalCycles)) g.totalCycles[k] = Math.max(g.totalCycles[k] ?? 0, v);
for (const [k, v] of Object.entries(c.ns)) g.ns[k] = (g.ns[k] ?? 0) + v;
}
return { t, gpus };
}
/**
* Busy percent of the busiest engine class between two snapshots (like intel_gpu_top's headline).
* Clients that exit in between make a sum drop; those classes count as idle rather than negative.
*/
export function drmUtilization(prev: DrmSnapshot["gpus"][string] | undefined, cur: DrmSnapshot["gpus"][string], seconds: number): number | null {
if (!prev || seconds <= 0) return null;
const busy: number[] = [];
for (const cls of Object.keys(cur.cycles)) {
const dc = cur.cycles[cls] - (prev.cycles[cls] ?? 0);
const dt = (cur.totalCycles[cls] ?? 0) - (prev.totalCycles[cls] ?? 0);
if (dt > 0) busy.push(Math.max(0, dc) / dt);
}
for (const cls of Object.keys(cur.ns)) busy.push(Math.max(0, cur.ns[cls] - (prev.ns[cls] ?? 0)) / (seconds * 1e9));
if (busy.length === 0) return null;
return Math.min(100, Math.max(...busy) * 100);
}
/**
* Runs inside the probe container (Node from Kaname's own image): every interval, the fdinfo of every
* open DRM file on the host, one JSON line. Reads only; prints nothing else.
*/
export const INTEL_PROBE_SCRIPT = `
const fs = require("fs");
const every = Number(process.argv[1]) || 2000;
function tick() {
const f = [];
let pids = [];
try { pids = fs.readdirSync("/proc").filter((p) => /^\\d+$/.test(p)); } catch {}
for (const p of pids) {
let fds = [];
try { fds = fs.readdirSync("/proc/" + p + "/fdinfo"); } catch { continue; }
for (const d of fds) {
try {
const t = fs.readFileSync("/proc/" + p + "/fdinfo/" + d, "utf8");
if (t.includes("drm-client-id:")) f.push(t);
} catch {}
}
}
process.stdout.write(JSON.stringify({ t: Date.now(), f }) + "\\n");
}
tick();
setInterval(tick, every);
`;