From e007a35143dab77ba10b72d507c0987be6d14df2 Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Wed, 21 Oct 2026 14:47:00 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 34 +++ package-lock.json | 4 +- package.json | 2 +- .../benchmarks/sweeps/[id]/sweep-detail.tsx | 12 +- src/app/(app)/deployments/deployment-form.tsx | 22 ++ src/app/(app)/deployments/form-data.ts | 39 ++- src/components/benchmark-resources.tsx | 11 +- src/lib/db/schema.ts | 22 +- src/lib/deploy-command.ts | 35 ++- src/lib/runtimes-shared.ts | 13 +- src/worker/benchmarks.ts | 31 ++- src/worker/deployments.ts | 2 + src/worker/gpu-sysfs.test.ts | 169 +++++++++++++ src/worker/gpu-sysfs.ts | 175 +++++++++++++ src/worker/resources.ts | 233 +++++++++++++----- src/worker/runtimes.ts | 75 +++++- 16 files changed, 781 insertions(+), 98 deletions(-) create mode 100644 src/worker/gpu-sysfs.test.ts create mode 100644 src/worker/gpu-sysfs.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ca55e9f..baa7538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,40 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of step 1 (Hugging Face downloader) is released as a minor version. +## [0.12.0] - 2026-10-21 + +Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group +handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page +"Intel GPUs". + +No changes to `compose.yaml` or `.env`. + +### Added + +- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as + NVIDIA (VRAM in use, utilization, power, temperature): + - power and temperature from the GPU's hwmon sensors (energy counter or power reading); + - AMD: VRAM in use and busy percent from sysfs; + - Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the + `xe`/`i915` drivers report them), read by a probe container that runs only during the run: host + PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the + end. Utilization is the busiest engine class, like `intel_gpu_top`. +- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as + sweep table columns. +- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute + buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs' + VRAM, with a hint when it doesn't fit. +- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render, + video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the + GPU. +- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected. + +### Changed + +- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed + by `-ngl auto`). Preset descriptions mention the B-series. +- GPU figures a source doesn't report are now shown as "—" instead of 0. + ## [0.11.0] - 2026-10-20 Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the diff --git a/package-lock.json b/package-lock.json index 4469034..61f4c0a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaname", - "version": "0.11.0", + "version": "0.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaname", - "version": "0.11.0", + "version": "0.12.0", "dependencies": { "@base-ui/react": "^1.8.0", "@libsql/client": "^0.18.0", diff --git a/package.json b/package.json index 9d83a21..a6457dc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kaname", - "version": "0.11.0", + "version": "0.12.0", "private": true, "scripts": { "dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"", diff --git a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx index 3d92e87..7398321 100644 --- a/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx +++ b/src/app/(app)/benchmarks/sweeps/[id]/sweep-detail.tsx @@ -38,6 +38,8 @@ type Row = { cpu: number | null; ram: number | null; vram: number | null; + power: number | null; + temp: number | null; }; function rowsOf(data: SweepData): Row[] { @@ -55,7 +57,9 @@ function rowsOf(data: SweepData): Row[] { peak: h.peak?.tps ?? null, cpu: c?.cpuAvg ?? null, ram: c?.memPeakBytes ?? null, - vram: g.length ? g.reduce((s, x) => s + x.vramPeakMb, 0) : null, + vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null, + power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null, + temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null, }; }); } @@ -121,6 +125,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) { cpu: best(rows, "cpu", false), ram: best(rows, "ram", false), vram: best(rows, "vram", false), + power: best(rows, "power", false), + temp: best(rows, "temp", false), }; const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => ( {v != null ? fmt(v) : "—"} @@ -226,6 +232,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) { CPU cores Peak RAM Peak VRAM + GPU power + Peak temp @@ -257,6 +265,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) { {cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))} {cell(r.ram, bestOf.ram, (x) => formatBytes(x))} {cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)} + {cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)} + {cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)} ))} diff --git a/src/app/(app)/deployments/deployment-form.tsx b/src/app/(app)/deployments/deployment-form.tsx index 00c5aaf..772bf27 100644 --- a/src/app/(app)/deployments/deployment-form.tsx +++ b/src/app/(app)/deployments/deployment-form.tsx @@ -22,6 +22,7 @@ import { Label } from "@/components/ui/label"; import { NativeSelect } from "@/components/ui/native-select"; import type { DeploymentOptions, + HardwareGpu, HostGpu, RuntimeAccelerator, RuntimeEngine, @@ -32,6 +33,7 @@ import { buildCommand, ENGINE_PORT, estimateMemoryMb, + estimateVramMb, renderCommand, } from "@/lib/deploy-command"; import { argsToRows, rowsToArgs } from "@/lib/extra-args"; @@ -62,6 +64,8 @@ export type FormHost = { cpuFeatures: string[]; nvidia: boolean; gpus: HostGpu[]; + /** All GPUs on the host with Settings → Hardware applied (Intel/AMD VRAM for the estimate). */ + hardwareGpus: HardwareGpu[]; } | null; export type FormInitial = { id?: string; @@ -343,6 +347,10 @@ export function DeploymentForm({ ? hostGpus.filter((g) => gpuIds.includes(g.uuid)) : hostGpus; const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0); + // Intel/AMD GPUs come in as /dev/dri: all of them, VRAM as detected (or set in Settings → Hardware). + const driGpus = (host?.hardwareGpus ?? []).filter((g) => (accelerator === "rocm" ? g.vendor === "amd" : g.vendor === "intel" || g.vendor === "amd")); + const gpuVramMb = accelerator === "nvidia" ? vramMb || null : driGpus.some((g) => g.vramMb) ? driGpus.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null; + const vramEstimate = model && gpu ? estimateVramMb(fileBytes, options.contextSize, engine, options, gpuVramMb) : null; const memory = memoryTouched ? intOrNull(memoryMb) : estimate; const preview = runtime && model @@ -840,6 +848,20 @@ export function DeploymentForm({ )} )} + {accelerator !== "nvidia" && driGpus.length > 0 && ( +

+ {driGpus.map((g) => `${g.name ?? "GPU"}${g.vramMb ? ` (${formatBytes(g.vramMb * 2 ** 20)})` : ""}`).join(", ")} via /dev/dri +

+ )} + {model && ( +

gpuVramMb ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground"}`}> + {vramEstimate == null + ? "VRAM need: depends on how many layers/experts go to the GPU." + : `VRAM need, roughly: ${formatBytes(vramEstimate * 2 ** 20)}${gpuVramMb ? ` of ${formatBytes(gpuVramMb * 2 ** 20)}` : ""}${ + engine === "vllm" ? " (vLLM reserves its GPU memory share up front)" : " (weights, KV cache, compute buffers)" + }${gpuVramMb != null && vramEstimate > gpuVramMb ? ". Doesn't fit: lower the context, quantize the KV cache or offload fewer layers." : ""}`} +

+ )} {engine === "llama.cpp" ? ( <> { - const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]); +export async function formData(): Promise<{ + runtimes: FormRuntime[]; + models: FormModel[]; + host: FormHost; + apiKeyCount: number; +}> { + const [runtimes, models, docker, keys, overrides] = await Promise.all([ + listRuntimes(), + listDeployableModels(), + getDockerInfo(), + listApiKeys(), + getHardwareOverrides(), + ]); return { - runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs, accelerator: r.accelerator })), + runtimes: runtimes.map((r) => ({ + id: r.id, + name: r.name, + engine: r.engine, + image: r.image, + imageState: r.imageState, + env: r.env, + extraArgs: r.extraArgs, + accelerator: r.accelerator, + })), models, - host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures, nvidia: !!docker.nvidia, gpus: docker.gpus ?? [] } : null, + host: docker + ? { + cpus: docker.cpus, + memoryBytes: docker.memoryBytes, + cpuFeatures: docker.cpuFeatures, + nvidia: !!docker.nvidia, + gpus: docker.gpus ?? [], + hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [], + } + : null, apiKeyCount: keys.length, }; } diff --git a/src/components/benchmark-resources.tsx b/src/components/benchmark-resources.tsx index 0bef426..71e4297 100644 --- a/src/components/benchmark-resources.tsx +++ b/src/components/benchmark-resources.tsx @@ -2,6 +2,8 @@ import type { ResourceStats } from "@/lib/db/schema"; import { formatBytes } from "@/lib/format"; const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1)); +const mib = (v: number | null | undefined) => (v == null ? "—" : formatBytes(v * 2 ** 20)); +const round = (v: number | null | undefined, unit: string) => (v == null ? "—" : `${Math.round(v)}${unit}`); function Cell({ label, value, note }: { label: string; value: string; note?: string }) { return ( @@ -42,10 +44,11 @@ export function BenchmarkResources({ stats, names }: { stats: ResourceStats; nam GPU {g.index} · {g.name} -
- - - +
+ + + +
))} diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index ba5b8d3..79e95bf 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -377,6 +377,8 @@ export type DockerHostInfo = { gpus?: HostGpu[]; gpuError?: string | null; gpuCheckedAt?: string | null; + /** Group IDs owning /dev/dri on the host (render, video); given to Intel/AMD runtime containers. */ + driGroups?: number[]; /** PCIe, ReBAR, system facts from sysfs/procfs (what the worker's container sees of the host). */ hardware?: HostHardware | null; checkedAt: string; @@ -726,8 +728,24 @@ export type ResourceStats = { }[]; /** Fastest PCIe link seen per GPU (PCI address) during the run. */ links?: Record; - /** Whole-GPU figures (nvidia-smi), not per process. */ - gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[]; + /** + * Whole-GPU figures, not per process: nvidia-smi; hwmon/sysfs for AMD; hwmon plus the DRM fdinfo + * of all processes for Intel. null where a source doesn't report it. + */ + gpus: { + index: number; + name: string; + pciAddress?: string; + vramTotalMb: number | null; + vramPeakMb: number | null; + vramAvgMb: number | null; + utilAvg: number | null; + utilPeak: number | null; + powerAvgW: number | null; + powerPeakW: number | null; + tempAvgC?: number | null; + tempPeakC?: number | null; + }[]; }; /** The deployment as it was when the run started, so results stay comparable after edits. */ diff --git a/src/lib/deploy-command.ts b/src/lib/deploy-command.ts index 4dc49bd..6c2a839 100644 --- a/src/lib/deploy-command.ts +++ b/src/lib/deploy-command.ts @@ -128,6 +128,37 @@ export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192; const KV_TYPE_FACTOR: Record = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 }; +/** llama.cpp KV cache in MiB for a model of `modelMb`: the per-token heuristic below, scaled by the cache type. */ +function kvCacheMb(modelMb: number, contextSize: number, o: Pick): number { + const perTokenKiB = 96 + 24 * Math.sqrt(modelMb / 1024); + const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2; + return (contextSize * perTokenKiB * kvFactor) / 1024; +} + +/** llama.cpp compute buffers and runtime state on the GPU (measured order of magnitude, not exact). */ +const GPU_OVERHEAD_MB = 1024; + +/** + * Rough VRAM need of a GPU deployment in MiB, for NVIDIA and Intel/AMD (/dev/dri) alike; null when it + * can't be told without reading the model (only some layers or the MoE experts offloaded). + * - vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU's VRAM up front. + * - llama.cpp with all layers on the GPU ("auto" fits as many as there is room for): weights + KV + * cache + compute buffers. + */ +export function estimateVramMb( + fileBytes: number, + contextSize: number, + engine: RuntimeEngine, + o: Pick, + vramTotalMb: number | null, +): number | null { + if (engine === "vllm") return vramTotalMb ? Math.ceil(vramTotalMb * (o.gpuMemoryUtilization ?? 0.9)) : null; + const layers = o.gpuLayers ?? "auto"; + if ((layers !== "auto" && layers !== "all") || o.cpuMoe || (o.nCpuMoe ?? 0) > 0) return null; + const model = fileBytes / 2 ** 20; + return Math.ceil(model + kvCacheMb(model, contextSize, o) + GPU_OVERHEAD_MB); +} + /** * Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size * per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA. @@ -144,9 +175,7 @@ export function estimateMemoryMb( // vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0). // On a GPU the weights and KV cache live in VRAM; RAM holds the processes. if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072); - const perTokenKiB = 96 + 24 * Math.sqrt(model / 1024); - const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2; - const kv = (contextSize * perTokenKiB * kvFactor) / 1024; + const kv = kvCacheMb(model, contextSize, o); const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb; // The memory-mapped model counts against the container's limit (page cache), even when offloaded. return Math.ceil(model + (gpu ? 0 : kv) + cache + 768); diff --git a/src/lib/runtimes-shared.ts b/src/lib/runtimes-shared.ts index 21f73f9..7eaaad9 100644 --- a/src/lib/runtimes-shared.ts +++ b/src/lib/runtimes-shared.ts @@ -75,8 +75,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [ engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-vulkan", - summary: "llama-server over Vulkan: Intel Arc and AMD GPUs via /dev/dri.", - description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri.", + summary: "llama-server over Vulkan: Intel Arc (incl. B-series) and AMD GPUs via /dev/dri.", + description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri; compare it with the SYCL build on Intel.", devices: ["/dev/dri"], }, { @@ -85,8 +85,9 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [ engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", - summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs.", - description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri).", + summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs (A- and B-series, Arc Pro).", + description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri). ZES_ENABLE_SYSMAN=1 lets it see free VRAM, which -ngl auto needs.", + env: { ZES_ENABLE_SYSMAN: "1" }, devices: ["/dev/dri"], }, { @@ -105,8 +106,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [ engine: "vllm", accelerator: "dri", image: "vllm/vllm-openai-xpu:v0.31.0", - summary: "Official vLLM image for Intel GPUs (Arc, Data Center GPU Max) via /dev/dri.", - description: "Official vLLM, XPU build for Intel GPUs.", + summary: "Official vLLM image for Intel GPUs (Arc incl. B-series, Data Center GPU Max) via /dev/dri.", + description: "Official vLLM, XPU build for Intel GPUs. vLLM reserves --gpu-memory-utilization (default 0.9) of the VRAM up front.", devices: ["/dev/dri"], shmSizeMb: 8192, }, diff --git a/src/worker/benchmarks.ts b/src/worker/benchmarks.ts index 862d72a..1968cea 100644 --- a/src/worker/benchmarks.ts +++ b/src/worker/benchmarks.ts @@ -19,7 +19,7 @@ import { sanitizeLine } from "./job-log"; import { log } from "./log"; import { normalizePciAddress } from "./hardware"; import { errorCauses } from "./log-causes"; -import { ResourceSampler } from "./resources"; +import { type GpuTargets, ResourceSampler } from "./resources"; import { docker, workerImage } from "./runtimes"; type Current = { @@ -146,16 +146,27 @@ async function target(deploymentId: string | null): Promise { 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)[]) { +/** + * What the sampler watches for the GPUs a run uses: NVIDIA via nvidia-smi, Intel/AMD via sysfs (and + * the fdinfo probe for Intel), and every GPU's link where sysfs shows it. Probes run from our own image. + */ +async function gpuTargets(metas: (RunMeta | null)[]): Promise { 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 = {}; + const { hardware, nvidia } = await effectiveHardware(); + const image = workerImage(); + const used = (hardware?.gpus ?? []).filter((g) => addrs.includes(g.pciAddress)); + const pciByIndex: Record = {}; for (const g of nvidia) { const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`; - if (addrs.includes(addr)) nvidiaIndex[g.index] = addr; + if (addrs.includes(addr)) pciByIndex[g.index] = addr; } - return { sysfs: addrs.filter((a) => !a.startsWith("nvidia-")), nvidiaIndex }; + const others = used.filter((g) => g.vendor !== "nvidia"); + return { + nvidia: image && Object.keys(pciByIndex).length ? { image, pciByIndex } : null, + sysfs: others.map((g, i) => ({ index: i, pciAddress: g.pciAddress, name: g.name ?? `${g.vendor} GPU`, vendor: g.vendor, vramTotalMb: g.vramMb })), + intelProbeImage: image, + linkAddresses: addrs.filter((a) => !a.startsWith("nvidia-")), + }; } /** A/B notes: the shared host facts once, the engine and model per side. */ @@ -249,15 +260,13 @@ async function start(run: typeof benchmarkRuns.$inferSelect) { .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. + // Resource use of the server(s) under test, and of the GPUs they use. const c = docker(); - const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia"; const sampler = c ? new ResourceSampler( c, [{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])], - nvidia ? workerImage() : null, - await linkTargets([meta, metaB]), + await gpuTargets([meta, metaB]), ) : null; await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`)); diff --git a/src/worker/deployments.ts b/src/worker/deployments.ts index 74b80ad..9a6d99e 100644 --- a/src/worker/deployments.ts +++ b/src/worker/deployments.ts @@ -169,6 +169,8 @@ async function start(c: DockerClient, d: Deployment) { ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined, Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })), DeviceRequests: deviceRequests, + // Images that don't run as root need the render/video group to open /dev/dri. + GroupAdd: devices.some((p) => p.startsWith("/dev/dri")) ? (host.driGroups ?? []).map(String) : [], CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [], SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [], PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {}, diff --git a/src/worker/gpu-sysfs.test.ts b/src/worker/gpu-sysfs.test.ts new file mode 100644 index 0000000..86108b4 --- /dev/null +++ b/src/worker/gpu-sysfs.test.ts @@ -0,0 +1,169 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { estimateVramMb } from "@/lib/deploy-command"; +import { aggregateFdinfo, drmUtilization, parseFdinfo, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs"; +import type { SysFs } from "./hardware"; +import { parseGpuLine, summarizeSamples } from "./resources"; +import { parseDriGroups } from "./runtimes"; + +/** An in-memory sysfs: files plus directory links. */ +function memFs(files: Record, links: Record = {}): SysFs { + const resolve = (p: string) => { + const hit = Object.keys(links).find((l) => p === l || p.startsWith(`${l}/`)); + return hit ? links[hit] + p.slice(hit.length) : p; + }; + return { + read: async (p) => files[resolve(p)]?.trim() ?? null, + resolve: async (p) => resolve(p), + list: async (d) => { + const dir = `${resolve(d)}/`; + return [...new Set(Object.keys(files).filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]))]; + }, + }; +} + +const xe = (client: number, vramKiB: number, rcs: number, ccs: number, total: number) => `pos:\t0 +flags:\t02100002 +drm-driver:\txe +drm-client-id:\t${client} +drm-pdev:\t0000:03:00.0 +drm-total-system:\t0 +drm-resident-system:\t0 +drm-total-gtt:\t12 KiB +drm-total-vram0:\t${vramKiB + 1024} KiB +drm-resident-vram0:\t${vramKiB} KiB +drm-cycles-rcs:\t${rcs} +drm-total-cycles-rcs:\t${total} +drm-cycles-ccs:\t${ccs} +drm-total-cycles-ccs:\t${total} +`; + +describe("DRM fdinfo", () => { + it("parses xe: resident VRAM, cycles per engine class", () => { + const c = parseFdinfo(xe(42, 9_437_184, 1000, 30_000, 50_000))!; + assert.equal(c.pdev, "0000:03:00.0"); + assert.equal(c.clientId, "42"); + assert.equal(c.vramBytes, 9_437_184 * 1024); + assert.deepEqual(c.cycles, { rcs: 1000, ccs: 30_000 }); + assert.deepEqual(c.totalCycles, { rcs: 50_000, ccs: 50_000 }); + }); + + it("parses i915 (local memory, nanoseconds) and amdgpu's legacy keys", () => { + const i915 = parseFdinfo("drm-driver: i915\ndrm-pdev: 0000:00:02.0\ndrm-client-id: 7\ndrm-engine-render: 1000000 ns\ndrm-engine-capacity-video: 2\ndrm-total-local0: 1024 KiB\ndrm-resident-local0: 512 KiB\n")!; + assert.equal(i915.vramBytes, 512 * 1024); + assert.deepEqual(i915.ns, { render: 1_000_000 }); + const amd = parseFdinfo("drm-driver:\tamdgpu\ndrm-pdev:\t0000:0a:00.0\ndrm-client-id:\t3\ndrm-memory-vram:\t2048 KiB\ndrm-memory-gtt:\t16 KiB\ndrm-engine-gfx:\t5000 ns\n")!; + assert.equal(amd.vramBytes, 2048 * 1024); + assert.deepEqual(amd.ns, { gfx: 5000 }); + assert.equal(parseFdinfo("pos: 0\nflags: 02\n"), null); + }); + + it("counts each client once and takes the GPU clock as is", () => { + const s = aggregateFdinfo(1000, [xe(1, 1024, 10, 20, 100), xe(1, 1024, 10, 20, 100), xe(2, 2048, 5, 0, 110), "pos: 0\n"]); + const g = s.gpus["0000:03:00.0"]; + assert.equal(g.vramBytes, 3072 * 1024); + assert.deepEqual(g.cycles, { rcs: 15, ccs: 20 }); + assert.deepEqual(g.totalCycles, { rcs: 110, ccs: 110 }); + }); + + it("reports the busiest engine class between two snapshots", () => { + const a = aggregateFdinfo(0, [xe(1, 1024, 0, 0, 1000)]).gpus["0000:03:00.0"]; + const b = aggregateFdinfo(2000, [xe(1, 1024, 100, 800, 2000)]).gpus["0000:03:00.0"]; + assert.equal(drmUtilization(a, b, 2), 80); + assert.equal(drmUtilization(undefined, b, 2), null); + // A client that exited makes the sum drop: idle, not negative. + const c = aggregateFdinfo(4000, [xe(2, 0, 0, 0, 3000)]).gpus["0000:03:00.0"]; + assert.equal(drmUtilization(b, c, 2), 0); + // Nanosecond engines: busy time over wall time. + assert.equal(drmUtilization({ vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 0 } }, { vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 1e9 } }, 2), 50); + }); +}); + +describe("hwmon and amdgpu sysfs", () => { + const dev = "/sys/devices/pci0000:00/0000:00:01.0/0000:03:00.0"; + const fs = memFs( + { + [`${dev}/hwmon/hwmon3/name`]: "xe", + [`${dev}/hwmon/hwmon3/energy1_input`]: "5000000", + [`${dev}/hwmon/hwmon3/power1_max`]: "200000000", + [`${dev}/hwmon/hwmon3/temp2_input`]: "61000", + [`${dev}/hwmon/hwmon3/temp2_label`]: "pkg", + [`${dev}/hwmon/hwmon3/temp3_input`]: "70000", + [`${dev}/hwmon/hwmon3/temp3_label`]: "vram", + "/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/power1_average": "150000000", + "/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/temp1_input": "55000", + "/sys/devices/pci0000:00/0000:0a:00.0/mem_info_vram_used": String(4 * 2 ** 30), + "/sys/devices/pci0000:00/0000:0a:00.0/gpu_busy_percent": "87", + }, + { "/sys/bus/pci/devices/0000:03:00.0": dev, "/sys/bus/pci/devices/0000:0a:00.0": "/sys/devices/pci0000:00/0000:0a:00.0" }, + ); + + it("reads xe's energy counter and package temperature", async () => { + assert.deepEqual(await readHwmon(fs, "0000:03:00.0"), { energyUj: 5_000_000, powerW: null, tempC: 61 }); + }); + + it("reads amdgpu's power, temperature, VRAM in use and busy percent", async () => { + assert.deepEqual(await readHwmon(fs, "0000:0a:00.0"), { energyUj: null, powerW: 150, tempC: 55 }); + assert.deepEqual(await readAmdUsage(fs, "0000:0a:00.0"), { vramUsedMb: 4096, util: 87 }); + }); + + it("turns energy into power between readings", () => { + assert.equal(powerBetween({ energyUj: 1_000_000, powerW: null, tempC: null }, { energyUj: 401_000_000, powerW: null, tempC: null }, 2), 200); + assert.equal(powerBetween(null, { energyUj: 5, powerW: null, tempC: null }, 0), null); + assert.equal(powerBetween(null, { energyUj: null, powerW: 150, tempC: null }, 0), 150); + }); +}); + +describe("GPU summaries", () => { + it("keeps unknown figures unknown and adds temperature", () => { + const s = summarizeSamples( + [], + [ + { index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 120, tempC: 60 }, + { index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 180, tempC: 70 }, + ], + 4, + ); + assert.deepEqual(s.gpus[0], { + index: 0, + name: "Intel Arc Pro B65", + pciAddress: "0000:03:00.0", + vramTotalMb: 32768, + vramPeakMb: null, + vramAvgMb: null, + utilAvg: null, + utilPeak: null, + powerAvgW: 150, + powerPeakW: 180, + tempAvgC: 65, + tempPeakC: 70, + }); + assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16, 47")?.tempC, 47); + }); + + it("reads /dev/dri group IDs", () => { + assert.deepEqual(parseDriGroups(["/dev/dri/card0 44", "/dev/dri/renderD128 993", "/dev/dri/renderD129 993", "/dev/dri/by-path 0", "stat: error"]), [44, 993]); + }); +}); + +describe("VRAM estimate", () => { + const GiB = 2 ** 30; + it("adds weights, KV cache and buffers for llama.cpp with all layers on the GPU", () => { + const f16 = estimateVramMb(5 * GiB, 32768, "llama.cpp", {}, 32768)!; + const q8 = estimateVramMb(5 * GiB, 32768, "llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q8_0" }, 32768)!; + assert.ok(f16 > 5120 + 1024 && f16 < 5120 + 1024 + 8192, String(f16)); + assert.ok(q8 < f16); + assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "all" }, null), estimateVramMb(5 * GiB, 4096, "llama.cpp", {}, null)); + }); + + it("can't tell partial offload", () => { + assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "20" }, 32768), null); + assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { cpuMoe: true }, 32768), null); + }); + + it("uses vLLM's memory share of the VRAM", () => { + assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, 32768), Math.ceil(32768 * 0.9)); + assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", { gpuMemoryUtilization: 0.5 }, 32768), 16384); + assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, null), null); + }); +}); diff --git a/src/worker/gpu-sysfs.ts b/src/worker/gpu-sysfs.ts new file mode 100644 index 0000000..b888bd0 --- /dev/null +++ b/src/worker/gpu-sysfs.ts @@ -0,0 +1,175 @@ +// 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//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 { + 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; + totalCycles: Record; + ns: Record; +}; + +const UNIT: Record = { "": 1, KiB: 1024, MiB: 2 ** 20, GiB: 2 ** 30 }; + +/** One /proc//fdinfo/ of a DRM client; null for other files. */ +export function parseFdinfo(text: string): DrmClient | null { + const kv = new Map(); + 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; totalCycles: Record; ns: Record }> }; + +/** + * 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(); + 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); +`; diff --git a/src/worker/resources.ts b/src/worker/resources.ts index b1a9e69..a409ef2 100644 --- a/src/worker/resources.ts +++ b/src/worker/resources.ts @@ -1,26 +1,42 @@ -// Samples resource use while a benchmark runs: CPU and memory of the deployment containers (Docker -// 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. +// Samples resource use while a benchmark runs (every ~2 s): +// - CPU and memory of the deployment containers (Docker stats); +// - NVIDIA GPUs: whole-GPU VRAM/utilization/power/temperature from one long-lived `nvidia-smi -lms` +// probe container; +// - Intel and AMD GPUs: power and temperature from hwmon, AMD VRAM/busy from sysfs, Intel VRAM and +// utilization from DRM fdinfo via a probe container in the host's PID namespace (gpu-sysfs.ts); +// - 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 { PcieLink, ResourceStats } from "@/lib/db/schema"; -import { currentLinks, nodeFs } from "./hardware"; +import type { GpuVendor, PcieLink, ResourceStats } from "@/lib/db/schema"; import type { DockerClient } from "./docker/client"; +import { aggregateFdinfo, type DrmSnapshot, drmUtilization, type HwmonReading, INTEL_PROBE_SCRIPT, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs"; +import { currentLinks, nodeFs } from "./hardware"; 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; link?: PcieLink | null }; +export type GpuSample = { + index: number; + name: string; + pciAddress?: string; + vramTotalMb: number | null; + vramUsedMb: number | null; + util: number | null; + powerW: number | null; + tempC?: 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); +const known = (xs: (number | null | undefined)[]) => xs.filter((x): x is number => x != null); -const GPU_QUERY = "index,name,memory.total,memory.used,utilization.gpu,power.draw,pcie.link.gen.current,pcie.link.width.current"; +const GPU_QUERY = "index,name,memory.total,memory.used,utilization.gpu,power.draw,pcie.link.gen.current,pcie.link.width.current,temperature.gpu"; -/** One CSV line of `nvidia-smi --query-gpu=${GPU_QUERY}` (the link columns are optional). */ +/** One CSV line of `nvidia-smi --query-gpu=${GPU_QUERY}` (columns after power 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; @@ -30,10 +46,11 @@ export function parseGpuLine(line: string): GpuSample | null { return { index: Number(p[0]), name: p[1], - vramTotalMb: n(p[2]) ?? 0, - vramUsedMb: n(p[3]) ?? 0, - util: n(p[4]) ?? 0, + vramTotalMb: n(p[2]), + vramUsedMb: n(p[3]), + util: n(p[4]), powerW: n(p[5]), + tempC: n(p[8]), link: gen != null || width != null ? { gen, width } : null, }; } @@ -71,47 +88,73 @@ export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[ memLimitBytes: limit, }; }), - gpus: [...new Set(gpus.map((g) => g.index))].sort((a, b) => a - b).map((index) => { - const xs = gpus.filter((g) => g.index === index); - const power = xs.map((x) => x.powerW).filter((x): x is number => x != null); - return { - index, - name: xs[0].name, - vramTotalMb: xs[0].vramTotalMb, - vramPeakMb: peak(xs.map((x) => x.vramUsedMb)) ?? 0, - vramAvgMb: avg(xs.map((x) => x.vramUsedMb)) ?? 0, - utilAvg: avg(xs.map((x) => x.util)) ?? 0, - utilPeak: peak(xs.map((x) => x.util)) ?? 0, - powerAvgW: avg(power), - powerPeakW: peak(power), - }; - }), + gpus: [...new Set(gpus.map((g) => g.index))] + .sort((a, b) => a - b) + .map((index) => { + const xs = gpus.filter((g) => g.index === index); + const vram = known(xs.map((x) => x.vramUsedMb)); + const util = known(xs.map((x) => x.util)); + const power = known(xs.map((x) => x.powerW)); + const temp = known(xs.map((x) => x.tempC)); + return { + index, + name: xs[0].name, + ...(xs[0].pciAddress ? { pciAddress: xs[0].pciAddress } : {}), + vramTotalMb: xs.find((x) => x.vramTotalMb != null)?.vramTotalMb ?? null, + vramPeakMb: peak(vram), + vramAvgMb: avg(vram), + utilAvg: avg(util), + utilPeak: peak(util), + powerAvgW: avg(power), + powerPeakW: peak(power), + tempAvgC: avg(temp), + tempPeakC: peak(temp), + }; + }), }; } +/** A GPU sampled from sysfs (Intel, AMD); `index` is its position among the GPUs of the run. */ +export type SysfsGpu = { index: number; pciAddress: string; name: string; vendor: GpuVendor; vramTotalMb: number | null }; + +export type GpuTargets = { + /** NVIDIA GPUs via nvidia-smi (our own image as the probe); index → PCI address for the link. */ + nvidia: { image: string; pciByIndex: Record } | null; + sysfs: SysfsGpu[]; + /** Image for the Intel fdinfo probe; null: Intel VRAM/utilization aren't sampled. */ + intelProbeImage: string | null; + /** PCI addresses whose link is read from sysfs. */ + linkAddresses: string[]; +}; + +export const NO_GPUS: GpuTargets = { nvidia: null, sysfs: [], intelProbeImage: null, linkAddresses: [] }; + export class ResourceSampler { private containerSamples: ContainerSample[] = []; private gpuSamples: GpuSample[] = []; private linkSamples: LinkSample[] = []; private timer?: NodeJS.Timeout; private busy = false; - private probeId: string | null = null; + private probeIds: string[] = []; private abort = new AbortController(); private started = Date.now(); + private lastHwmon = new Map(); + private lastDrm: DrmSnapshot | null = null; + private intelNow = new Map(); constructor( 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 } = { sysfs: [], nvidiaIndex: {} }, + private gpus: GpuTargets = NO_GPUS, ) {} async start(): Promise { this.started = Date.now(); this.timer = setInterval(() => void this.sample(), INTERVAL_MS); void this.sample(); - if (this.gpuProbeImage) await this.startGpuProbe(this.gpuProbeImage).catch((err) => log.warn(`GPU sampling unavailable: ${err instanceof Error ? err.message : err}`)); + const warn = (what: string) => (err: unknown) => log.warn(`${what} sampling unavailable: ${err instanceof Error ? err.message : err}`); + if (this.gpus.nvidia) await this.startNvidiaProbe(this.gpus.nvidia.image).catch(warn("NVIDIA GPU")); + if (this.gpus.intelProbeImage && this.gpus.sysfs.some((g) => g.vendor === "intel")) await this.startIntelProbe(this.gpus.intelProbeImage).catch(warn("Intel GPU")); } private async sample() { @@ -122,48 +165,118 @@ 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(() => ({})); + if (this.gpus.linkAddresses.length) { + const links = await currentLinks(nodeFs, this.gpus.linkAddresses).catch(() => ({})); for (const [pciAddress, link] of Object.entries(links)) this.linkSamples.push({ pciAddress, link }); } + for (const g of this.gpus.sysfs) await this.sampleSysfs(g).catch(() => {}); } finally { this.busy = false; } } - private async startGpuProbe(image: string) { - const created = await this.c.createContainer(`kaname-gpu-sampler-${Date.now().toString(36)}`, { - Image: image, - Entrypoint: ["nvidia-smi"], - Cmd: [`--query-gpu=${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 }, - }); - this.probeId = created.Id; + private async sampleSysfs(g: SysfsGpu) { + const now = Date.now(); + const r = await readHwmon(nodeFs, g.pciAddress); + const prev = this.lastHwmon.get(g.pciAddress); + this.lastHwmon.set(g.pciAddress, { at: now, r }); + const powerW = powerBetween(prev?.r ?? null, r, prev ? (now - prev.at) / 1000 : 0); + let vramUsedMb: number | null = null; + let util: number | null = null; + if (g.vendor === "amd") ({ vramUsedMb, util } = await readAmdUsage(nodeFs, g.pciAddress)); + if (g.vendor === "intel") { + const x = this.intelNow.get(g.pciAddress); + vramUsedMb = x?.vramMb ?? null; + util = x?.util ?? null; + } + // The first energy reading has nothing to compare with; skip it rather than record no power. + if (prev || r.energyUj == null) { + this.gpuSamples.push({ index: g.index, name: g.name, pciAddress: g.pciAddress, vramTotalMb: g.vramTotalMb, vramUsedMb, util, powerW, tempC: r.tempC }); + } + } + + private async startProbe(name: string, spec: Record, onLine: (line: string) => void) { + const created = await this.c.createContainer(`kaname-${name}-${Date.now().toString(36)}`, spec); + this.probeIds.push(created.Id); await this.c.startContainer(created.Id); - void this.c - .followLogs( - created.Id, - (_s, line) => { - const g = parseGpuLine(line); - 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 }); + void this.c.followLogs(created.Id, (_s, line) => onLine(line), { tail: "all", signal: this.abort.signal }).catch(() => {}); + } + + private startNvidiaProbe(image: string) { + return this.startProbe( + "gpu-sampler", + { + Image: image, + Entrypoint: ["nvidia-smi"], + 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 }, + }, + (line) => { + const g = parseGpuLine(line); + if (!g) return; + const addr = this.gpus.nvidia?.pciByIndex[g.index]; + this.gpuSamples.push(addr ? { ...g, pciAddress: addr } : g); + if (addr && g.link) this.linkSamples.push({ pciAddress: addr, link: g.link }); + }, + ); + } + + /** + * Intel GPUs report VRAM and engine time only per process (DRM fdinfo). The probe runs Node from + * Kaname's image in the host's PID namespace, reads /proc//fdinfo and prints it: no network, + * read-only, all capabilities dropped except reading other processes' fdinfo. + */ + private startIntelProbe(image: string) { + return this.startProbe( + "intel-sampler", + { + Image: image, + User: "0:0", + Entrypoint: ["node", "-e", INTEL_PROBE_SCRIPT], + Cmd: [String(INTERVAL_MS)], + Labels: { "kaname.managed": "true", "kaname.probe": "intel-sampler" }, + HostConfig: { + PidMode: "host", + NetworkMode: "none", + ReadonlyRootfs: true, + CapDrop: ["ALL"], + CapAdd: ["SYS_PTRACE", "DAC_READ_SEARCH"], + SecurityOpt: ["no-new-privileges"], + Memory: 256 * 2 ** 20, + PidsLimit: 32, + Privileged: false, + AutoRemove: false, }, - { tail: "all", signal: this.abort.signal }, - ) - .catch(() => {}); + }, + (line) => { + let msg: { t?: number; f?: string[] }; + try { + msg = JSON.parse(line); + } catch { + return; + } + if (typeof msg.t !== "number" || !Array.isArray(msg.f)) return; + const snap = aggregateFdinfo(msg.t, msg.f); + const prev = this.lastDrm; + this.lastDrm = snap; + for (const g of this.gpus.sysfs.filter((x) => x.vendor === "intel")) { + const cur = snap.gpus[g.pciAddress]; + const util = cur ? drmUtilization(prev?.gpus[g.pciAddress], cur, prev ? (snap.t - prev.t) / 1000 : 0) : prev ? 0 : null; + this.intelNow.set(g.pciAddress, { vramMb: Math.round((cur?.vramBytes ?? 0) / 2 ** 20), util }); + } + }, + ); } /** Stop sampling and return the aggregate (never throws). */ async stop(): Promise { clearInterval(this.timer); this.abort.abort(); - if (this.probeId) { - await this.c.stopContainer(this.probeId, 1).catch(() => {}); - await this.c.removeContainer(this.probeId).catch(() => {}); + for (const id of this.probeIds) { + await this.c.stopContainer(id, 1).catch(() => {}); + await this.c.removeContainer(id).catch(() => {}); } return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000, this.linkSamples); } diff --git a/src/worker/runtimes.ts b/src/worker/runtimes.ts index 32dd6bd..2375656 100644 --- a/src/worker/runtimes.ts +++ b/src/worker/runtimes.ts @@ -106,21 +106,46 @@ async function probeNvidia(c: DockerClient, image: string): Promise<{ gpus: Host } /** Runs `nvidia-smi ` 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 { - const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, { +function nvidiaSmi(c: DockerClient, image: string, args: string[]): Promise { + return runProbe(c, { Image: image, Entrypoint: ["nvidia-smi"], 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 }, }); +} + +/** + * Group IDs of the host's /dev/dri nodes (render, video), as a short-lived container with /dev/dri + * sees them (Docker copies the host's owner and mode). Runtime containers get them as extra groups, + * so images that don't run as root can open the GPU. + */ +async function probeDriGroups(c: DockerClient, image: string): Promise { + const lines = await runProbe(c, { + Image: image, + Entrypoint: ["sh", "-c", "stat -c '%n %g' /dev/dri/*"], + Cmd: [], + HostConfig: { Devices: [{ PathOnHost: "/dev/dri", PathInContainer: "/dev/dri", CgroupPermissions: "r" }], NetworkMode: "none", Privileged: false, ReadonlyRootfs: true }, + }); + return parseDriGroups(lines); +} + +/** "`/dev/dri/renderD128 993`" lines → the distinct non-root group IDs. */ +export function parseDriGroups(lines: string[]): number[] { + const gids = lines.map((l) => l.trim().match(/^\/dev\/dri\/\S+\s+(\d+)$/)?.[1]).filter((g): g is string => !!g).map(Number); + return [...new Set(gids.filter((g) => g > 0))].sort((a, b) => a - b); +} + +/** Runs a short-lived probe container from our own image and returns its output lines. */ +async function runProbe(c: DockerClient, spec: { Image: string; Entrypoint: string[]; Cmd: string[]; Env?: string[]; HostConfig: Record }): Promise { + const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, { ...spec, Labels: { "kaname.managed": "true", "kaname.probe": "gpu" } }); 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(" ")}`); + if (st && st.ExitCode !== 0) throw new Error(`${spec.Entrypoint[0]} exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`); return lines; } finally { await c.removeContainer(created.Id).catch(() => {}); @@ -161,6 +186,45 @@ async function seedGpuPresets() { await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing(); } +const INTEL_SEEDED_KEY = "runtimes.intelPresetSeeded"; + +/** The first time an Intel GPU shows up, add the llama.cpp runtimes for it (SYCL and Vulkan, once). */ +async function seedIntelPresets() { + const d = db(); + if (await d.query.settings.findFirst({ where: eq(settings.key, INTEL_SEEDED_KEY) })) return; + for (const p of RUNTIME_PRESETS.filter((x) => x.id === "llama.cpp-intel" || x.id === "llama.cpp-vulkan")) { + await d.insert(runtimes).values({ + name: p.name, + engine: p.engine, + accelerator: p.accelerator ?? "dri", + image: p.image, + description: p.description ?? null, + env: p.env ?? {}, + devices: p.devices ?? [], + preset: p.id, + }); + log.info(`Intel GPU found: added the "${p.name}" runtime`); + } + await d.insert(settings).values({ key: INTEL_SEEDED_KEY, value: true }).onConflictDoNothing(); +} + +let driCache: { at: number; gids: number[] } | null = null; + +/** Render/video group IDs of /dev/dri, re-checked hourly while there are Intel or AMD GPUs. */ +async function driGroups(c: DockerClient, image: string | null, hardware: HostHardware | null): Promise { + if (!image || !hardware?.gpus.some((g) => g.vendor !== "nvidia")) return undefined; + if (!driCache || Date.now() - driCache.at > GPU_PROBE_MS) { + try { + driCache = { at: Date.now(), gids: await probeDriGroups(c, image) }; + log.info(`/dev/dri groups: ${driCache.gids.join(", ") || "none besides root"}`); + } catch (err) { + driCache = { at: Date.now(), gids: [] }; + log.warn(`/dev/dri group check failed: ${message(err)}`); + } + } + return driCache.gids; +} + /** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */ export async function refreshDockerInfo(instanceId: string): Promise { const c = docker(); @@ -181,6 +245,8 @@ export async function refreshDockerInfo(instanceId: string): Promise { log.warn(`hardware detection failed: ${message(err)}`); return null; }); + if (hardware?.gpus.some((g) => g.vendor === "intel")) await seedIntelPresets(); + const driGids = await driGroups(c, self.image, hardware); info = { connected: true, error: null, @@ -194,6 +260,7 @@ export async function refreshDockerInfo(instanceId: string): Promise { modelsSource: self.modelsSource, ...gpu, hardware, + ...(driGids ? { driGroups: driGids } : {}), }; } catch (err) { info = {