diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 1d651bbd..d50e707b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -465,6 +465,11 @@ app. It has three tabs: images are on, and sampling and thinking-level settings. Chats stay in your browser. - **Monitor:** what the model is doing (reading the prompt, with progress, or writing, at how many tokens/s); GPU load, VRAM, temperature, power and PCIe traffic; CPU, RAM and disk; the context in use; the last requests. + +On a Mac (Metal backend) the Monitor's GPU load and VRAM come from IOKit's IOAccelerator nodes - the driver's Device +Utilization % and its in-use system memory, against the device's Metal working set - and the card says the rest: there +is no temperature or power reading without root (`powermetrics`), and an Apple Silicon GPU sits on the die, so there is +no PCIe link. The engine's own VRAM figures are in its log. - **About:** the model and engine settings, and the addresses to connect other apps. `http://127.0.0.1:8080/?q=your question` opens it with a new chat already asking. The API is at diff --git a/serve/server.py b/serve/server.py index 78cf3e46..771cc93f 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3299,20 +3299,17 @@ class Service: threading.Thread(target=loop, daemon=True).start() def free_vram_mib(self) -> int | None: - """Free VRAM on the engine's (first) GPU, from NVML (AMD backend: amdgpu's sysfs files, #301); None when it can't - be read (then nothing is refused).""" + """Free VRAM on the engine's (first) GPU, from the backend's reader - NVML, the amdgpu sysfs files (#301) or + IOKit on macOS (Metal backend); None when it can't be read (then nothing is refused).""" try: - if getattr(self, "backend", None) == "hip": - from serve.telemetry import free_vram_mib - return free_vram_mib(int(getattr(self, "gpu_index", 0) or 0), amd=True) - from serve.telemetry import _Nvml - nv = _Nvml(int(getattr(self, "gpu_index", 0) or 0)) - if not nv.ok(): + from serve.telemetry import gpu_reader + g = gpu_reader(int(getattr(self, "gpu_index", 0) or 0), amd=getattr(self, "backend", None) == "hip") + if not g.ok(): return None - m = nv.Mem() - if nv.lib.nvmlDeviceGetMemoryInfo(nv.dev, ctypes.byref(m)) != 0: + r = g.read() + if r.get("mem_total") is None or r.get("mem_used") is None: return None - return int(m.free >> 20) + return int((r["mem_total"] - r["mem_used"]) >> 20) except Exception: return None diff --git a/serve/telemetry.py b/serve/telemetry.py index 3232c63c..2e2a28ad 100644 --- a/serve/telemetry.py +++ b/serve/telemetry.py @@ -3,7 +3,9 @@ A background thread samples once a second and keeps the last 60 readings of each series for the sparklines: - GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no pip package is needed: load, VRAM, temperature, power, PCIe link and throughput. With the AMD backend (#301): the - amdgpu driver's Linux sysfs files - load, VRAM, temperature and power. + amdgpu driver's Linux sysfs files - load, VRAM, temperature and power. On macOS (Metal backend): IOKit's + IOAccelerator registry - load and VRAM; the temperature and power sensors need root (`powermetrics`), and an Apple + Silicon GPU sits on the die, so there is no PCIe link. - CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent. Anything that cannot be read is None; nothing here can stop the server. @@ -14,6 +16,8 @@ import collections import ctypes import os import platform +import re +import subprocess import sys import threading import time @@ -246,9 +250,108 @@ class _Amd: return out +def metal_working_set(): + """The Apple GPU's memory budget in bytes: MTLCreateSystemDefaultDevice's recommendedMaxWorkingSetSize, through + the Metal framework and objc_msgSend (no PyObjC) - the same property metal/src/mtl_rt.mm reads for the engine + (its "GPU working set" log line). None off macOS, or when it cannot be read: a selector the device does not + answer would raise an Objective-C exception no ctypes call can catch, so the class is asked first.""" + if sys.platform != "darwin": + return None + try: + metal = ctypes.CDLL("/System/Library/Frameworks/Metal.framework/Metal") + objc = ctypes.CDLL("/usr/lib/libobjc.dylib") + metal.MTLCreateSystemDefaultDevice.restype = ctypes.c_void_p + objc.sel_registerName.restype = ctypes.c_void_p + objc.object_getClass.argtypes = [ctypes.c_void_p] + objc.object_getClass.restype = ctypes.c_void_p + objc.class_respondsToSelector.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + objc.class_respondsToSelector.restype = ctypes.c_ubyte + objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + objc.objc_msgSend.restype = ctypes.c_ulonglong + dev = metal.MTLCreateSystemDefaultDevice() + if not dev: + return None + sel = objc.sel_registerName(b"recommendedMaxWorkingSetSize") + if not objc.class_respondsToSelector(objc.object_getClass(dev), sel): + return None + return int(objc.objc_msgSend(ctypes.c_void_p(dev), ctypes.c_void_p(sel))) or None + except (OSError, AttributeError, ValueError): + return None + + +class _Metal: + """macOS: an Apple GPU's readings from the IOKit registry (`ioreg -l -w0 -r -c IOAccelerator`, 22 ms), with + _Nvml's interface: the load and the memory are the driver's PerformanceStatistics of the index'th accelerator + node - Device Utilization % and the in-use system memory in bytes. The total is the device's Metal working set, + the budget one app gets of the unified memory. No temperature or power reading exists without root + (`powermetrics`), and an Apple Silicon GPU sits on the die, so the PCIe cards have nothing to show.""" + note = ("no GPU temperature or power reading without root (powermetrics), and an Apple Silicon GPU sits on the " + "die, so there is no PCIe link to show; the engine's own figures are in its log") + cmd = ("ioreg", "-l", "-w0", "-r", "-c", "IOAccelerator") + + def __init__(self, index=0, run=None): + self.index = index + self._run = run or self._ioreg + self.nodes = len(self._blocks()) + self._name = None + b = self._block() + if b: + m = re.search(r'"model" = "([^"]+)"', b) + self._name = m.group(1) if m else None + + @staticmethod + def _ioreg(): + try: + return subprocess.run(list(_Metal.cmd), capture_output=True, text=True, timeout=10).stdout or "" + except (OSError, subprocess.SubprocessError): + return "" + + def _blocks(self): + """The accelerator nodes, in the registry's order: every node that carries a PerformanceStatistics.""" + try: + out = self._run() or "" + except OSError: # ioreg missing, or a caller's runner that raises + return [] + return [b for b in re.split(r"^\s*\+-o ", out, flags=re.M) if '"PerformanceStatistics"' in b] + + def _block(self): + b = self._blocks() + return b[self.index] if 0 <= self.index < len(b) else None + + def ok(self): + return self.index < self.nodes + + def name(self): + return self._name + + def read(self): + b = self._block() + if b is None: + return {} + + def num(key): + m = re.search(r'"%s"=([0-9.]+)' % re.escape(key), b) + return float(m.group(1)) if m else None + + out = {} + u = num("Device Utilization %") + if u is None: # older chips report only the renderer and the tiler + r, t = num("Renderer Utilization %"), num("Tiler Utilization %") + u = max(v for v in (r, t) if v is not None) if (r is not None or t is not None) else None + out["util"] = int(u) if u is not None else None + used = num("In use system memory") + out["mem_used"] = int(used) if used is not None else None + out["mem_total"] = metal_working_set() + return out + + def gpu_reader(index=0, amd=False): - """The card's readings: NVML (NVIDIA), or the amdgpu sysfs files with the AMD backend (#301).""" - return _Amd(index) if amd else _Nvml(index) + """The card's readings: NVML (NVIDIA), the amdgpu sysfs files with the AMD backend (#301), or IOKit's + IOAccelerator registry on macOS (Metal backend). `amd` comes first: no Mac runs the HIP backend, and the + tests' AMD trees are read on a Mac too.""" + if amd: + return _Amd(index) + return _Metal(index) if sys.platform == "darwin" else _Nvml(index) _DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}" @@ -413,15 +516,21 @@ class Telemetry: cards = windows_amd_cards() win_amd = [cards[i] for i in idx if 0 <= i < len(cards)] or cards[:1] gpu_name = " + ".join(c["name"] for c in win_amd) if win_amd else None + # the macOS reader knows the device's working set (the VRAM budget of the unified memory); None elsewhere + vram_total = None + if win_amd is None and isinstance(self.gpu, _Metal) and self.gpu.ok(): + ws = metal_working_set() + vram_total = ws >> 20 if ws else None self.static = { "gpu_name": gpu_name, "gpu_vram_total_mib": (sum(c["vram_bytes"] for c in win_amd) >> 20 - if win_amd and all(c["vram_bytes"] for c in win_amd) else None), + if win_amd and all(c["vram_bytes"] for c in win_amd) else vram_total), "gpu_count": len(self.gpus), # #1380: the AMD readings are the amdgpu driver's Linux sysfs files; a Windows AMD card has none yet, and the # dashboard said "not readable (NVML)" or showed empty tiles with no word why "gpu_note": ("no GPU load or VRAM readings for AMD cards on Windows yet (Linux reads them from the amdgpu " - "driver); the engine's own VRAM figures are in its log" if amd and not self.gpu.ok() else None), + "driver); the engine's own VRAM figures are in its log" if amd and not self.gpu.ok() + else getattr(self.gpu, "note", None)), "cpu_name": _cpu_name(), "cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None, "threads": os.cpu_count(), diff --git a/serve/test_server.py b/serve/test_server.py index d1205031..0e566ef5 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -4514,6 +4514,84 @@ class AmdTelemetry(unittest.TestCase): self.assertEqual(svc.free_vram_mib(), 26 << 10) +IOREG_FIXTURE = ''' + +-o AGXAcceleratorG13X + { + "IOClass" = "AGXAcceleratorG13X" + "model" = "Apple M1 Max" + "PerformanceStatistics" = {"In use system memory (driver)"=0,"Alloc system memory"=22991831040,"Tiler Utilization %"=36,"recoveryCount"=44,"lastRecoveryTime"=216970984728,"Renderer Utilization %"=35,"TiledSceneBytes"=1671168,"Device Utilization %"=76,"SplitSceneCount"=0,"Allocated PB Size"=76152832,"In use system memory"=13384105984} + +-o IOUserClientCreator + { + "IOUserClientCreator" = "pid 402, WindowServer" + } + } + + +-o AGXAccelerator + { + "IOClass" = "AGXAccelerator" + "model" = "Apple M2 Ultra" + "PerformanceStatistics" = {"Renderer Utilization %"=3,"Tiler Utilization %"=2,"In use system memory"=1234567890} + } +''' + +WORKING_SET = 26800603136 # bytes; the M1 Max's device in the fixture above + + +class MacTelemetry(unittest.TestCase): + """The macOS (Metal backend) reader: IOKit's IOAccelerator nodes and the device's Metal working set.""" + + def _reader(self, index=0, text=IOREG_FIXTURE): + from serve import telemetry + return telemetry._Metal(index, run=lambda: text) + + def test_readings(self): + g = self._reader() + self.assertTrue(g.ok()) + self.assertEqual(g.name(), "Apple M1 Max") + with mock.patch("serve.telemetry.metal_working_set", lambda: WORKING_SET): + self.assertEqual(g.read(), {"util": 76, "mem_used": 13384105984, "mem_total": WORKING_SET}) + # the second accelerator is index 1: the older chips' renderer/tiler-only utilization is the fallback + g1 = self._reader(1) + self.assertTrue(g1.ok()) + with mock.patch("serve.telemetry.metal_working_set", lambda: WORKING_SET): + self.assertEqual(g1.read()["util"], 3) # the renderer, the higher of the two + self.assertEqual(g1.name(), "Apple M2 Ultra") + self.assertFalse(self._reader(5).ok()) + + def test_no_registry(self): + g = self._reader(text="") + self.assertFalse(g.ok()) + self.assertEqual(g.read(), {}) + self.assertIsNone(g.name()) + + def test_bad_process(self): + from serve import telemetry + g = telemetry._Metal(0, run=lambda: (_ for _ in ()).throw(OSError("no ioreg"))) + self.assertFalse(g.ok()) + self.assertEqual(g.read(), {}) + + def test_note_reaches_the_monitor(self): + from serve import telemetry + t = telemetry.Telemetry(extra=lambda: {"tok_s": 1.0}) + try: + with mock.patch.object(telemetry, "gpu_reader", lambda index=0, amd=False: self._reader()): + t2 = telemetry.Telemetry(extra=lambda: {"tok_s": 1.0}) + try: + self.assertEqual(t2.static["gpu_name"], "Apple M1 Max") + self.assertIn("powermetrics", t2.static["gpu_note"]) + with mock.patch("serve.telemetry.metal_working_set", lambda: WORKING_SET): + s = t2.sample() + self.assertEqual(s["gpu_util"], 76) + self.assertEqual(s["gpu_mem_used"], 13384105984) + self.assertEqual(s["gpu_mem_total"], WORKING_SET) + self.assertIsNone(s.get("gpu_temp")) # no reading without root; the cards show a dash + self.assertIsNone(s.get("gpu_pcie_gen")) + finally: + t2.close() + finally: + t.close() + + class TelemetryNoDisks(unittest.TestCase): """psutil.disk_io_counters() returns None where it finds no disk (a gVisor container; Windows with its disk counters off): the sampler goes on without a disk reading instead of its thread ending at the first sample, which left