okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
31.1 KiB677 linesraw
1"""serve/telemetry.py - hardware readings for the web app's Monitor tab (idea from PR #22 by code-martin).
2
3A background thread samples once a second and keeps the last 60 readings of each series for the sparklines:
4- GPU: NVIDIA's own NVML library (nvml.dll / libnvidia-ml.so.1, installed with every driver) through ctypes, so no
5  pip package is needed: load, VRAM, temperature, power, PCIe link and throughput.  With the AMD backend (#301): the
6  amdgpu driver's Linux sysfs files - load, VRAM, temperature and power.  On macOS (Metal backend): IOKit's
7  IOAccelerator registry - load and VRAM; the temperature and power sensors need root (`powermetrics`), and an Apple
8  Silicon GPU sits on the die, so there is no PCIe link.
9- CPU, RAM, disk: `psutil` when it is installed (setup installs it); without it the CPU and RAM readings fall back to
10  the OS (Windows GlobalMemoryStatusEx / GetSystemTimes, Linux /proc) and the disk rate is absent.
11Anything that cannot be read is None; nothing here can stop the server.
12"""
13from __future__ import annotations
14
15import collections
16import ctypes
17import os
18from strata_control import sysinfo
19import re
20import subprocess
21import sys
22import threading
23import time
24
25HISTORY = 60
26
27
28# ------------------------------------------------------------------------------------------------ NVML
29class _Nvml:
30    class Util(ctypes.Structure):
31        _fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)]
32
33    class Mem(ctypes.Structure):
34        _fields_ = [("total", ctypes.c_ulonglong), ("free", ctypes.c_ulonglong), ("used", ctypes.c_ulonglong)]
35
36    def __init__(self, index=0):
37        self.lib = self.dev = None
38        names = ["nvml.dll", os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"),
39                                          "NVIDIA Corporation", "NVSMI", "nvml.dll")] if os.name == "nt" \
40            else ["libnvidia-ml.so.1", "libnvidia-ml.so"]
41        for n in names:
42            try:
43                self.lib = ctypes.CDLL(n)
44                break
45            except OSError:
46                continue
47        if self.lib is None:
48            return
49        try:
50            init = getattr(self.lib, "nvmlInit_v2", None) or self.lib.nvmlInit
51            if init() != 0:
52                self.lib = None
53                return
54            h = ctypes.c_void_p()
55            get = getattr(self.lib, "nvmlDeviceGetHandleByIndex_v2", None) or self.lib.nvmlDeviceGetHandleByIndex
56            if get(ctypes.c_uint(index), ctypes.byref(h)) != 0:
57                self.lib = None
58                return
59            self.dev = h
60        except (AttributeError, OSError):
61            self.lib = None
62
63    def ok(self):
64        return self.lib is not None and self.dev is not None
65
66    def _uint(self, fn, *args):
67        v = ctypes.c_uint()
68        try:
69            return v.value if getattr(self.lib, fn)(self.dev, *args, ctypes.byref(v)) == 0 else None
70        except (AttributeError, OSError):
71            return None
72
73    def name(self):
74        buf = ctypes.create_string_buffer(96)
75        try:
76            if self.lib.nvmlDeviceGetName(self.dev, buf, ctypes.c_uint(96)) == 0:
77                return buf.value.decode(errors="replace")
78        except (AttributeError, OSError):
79            pass
80        return None
81
82    def read(self):
83        out = {}
84        u = self.Util()
85        try:
86            if self.lib.nvmlDeviceGetUtilizationRates(self.dev, ctypes.byref(u)) == 0:
87                out["util"] = u.gpu
88        except (AttributeError, OSError):
89            pass
90        m = self.Mem()
91        try:
92            if self.lib.nvmlDeviceGetMemoryInfo(self.dev, ctypes.byref(m)) == 0:
93                out["mem_used"], out["mem_total"] = m.used, m.total
94        except (AttributeError, OSError):
95            pass
96        out["temp"] = self._uint("nvmlDeviceGetTemperature", ctypes.c_uint(0))          # NVML_TEMPERATURE_GPU
97        mw = self._uint("nvmlDeviceGetPowerUsage")
98        out["power"] = mw / 1000.0 if mw is not None else None
99        lim = self._uint("nvmlDeviceGetEnforcedPowerLimit")
100        out["power_limit"] = lim / 1000.0 if lim is not None else None
101        out["pcie_gen"] = self._uint("nvmlDeviceGetCurrPcieLinkGeneration")        # drops at idle (power saving)
102        out["pcie_gen_max"] = self._uint("nvmlDeviceGetMaxPcieLinkGeneration")
103        out["pcie_width"] = self._uint("nvmlDeviceGetCurrPcieLinkWidth")
104        rx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(1))                 # NVML_PCIE_UTIL_RX_BYTES, KB/s
105        tx = self._uint("nvmlDeviceGetPcieThroughput", ctypes.c_uint(0))
106        out["pcie_rx_mb"] = rx / 1024.0 if rx is not None else None
107        out["pcie_tx_mb"] = tx / 1024.0 if tx is not None else None
108        return out
109
110
111# ------------------------------------------------------------------------------------------------ AMD (Linux sysfs)
112SYSFS = "/sys"
113
114
115def amd_device_dir(index, sysfs=None):
116    """The amdgpu sysfs folder (/sys/class/drm/renderD<N>/device) of the AMD GPU that HIP numbers `index`: the KFD
117    topology's GPU nodes in order, the CPU nodes skipped, linked to their render node by drm_render_minor - the
118    numbering setup's amd_gpus() and HIP_VISIBLE_DEVICES use.  None when there is no such card (or no amdgpu)."""
119    base = os.path.join(sysfs or SYSFS, "class", "kfd", "kfd", "topology", "nodes")
120    try:
121        nodes = sorted((n for n in os.listdir(base) if n.isdigit()), key=int)
122    except OSError:
123        return None
124    gpus = []
125    for n in nodes:
126        try:
127            with open(os.path.join(base, n, "properties"), encoding="utf-8") as f:
128                props = dict(line.strip().partition(" ")[::2] for line in f if line.strip())
129            if int(props.get("gfx_target_version") or 0) == 0 or int(props.get("simd_count") or 0) == 0:
130                continue
131            gpus.append(props)
132        except (OSError, ValueError):
133            continue
134    if not 0 <= index < len(gpus) or not gpus[index].get("drm_render_minor"):
135        return None
136    dev = os.path.join(sysfs or SYSFS, "class", "drm", "renderD" + gpus[index]["drm_render_minor"].strip(), "device")
137    return dev if os.path.isdir(dev) else None
138
139
140class _Amd:
141    """#301: an AMD card's readings from the amdgpu driver's sysfs files (Linux; no ROCm library needed), with _Nvml's
142    interface: load (gpu_busy_percent), VRAM (mem_info_vram_used / _total), and from its hwmon folder the temperature
143    (temp1_input, the edge sensor, m°C), power (power1_average or power1_input, µW) and its cap (power1_cap)."""
144
145    def __init__(self, index=0, sysfs=None):
146        self.dev = amd_device_dir(index, sysfs)
147        self.hwmon = None
148        if self.dev:
149            try:
150                hw = sorted(os.listdir(os.path.join(self.dev, "hwmon")))
151                self.hwmon = os.path.join(self.dev, "hwmon", hw[0]) if hw else None
152            except OSError:
153                pass
154
155    def ok(self):
156        return self.dev is not None
157
158    @staticmethod
159    def _int(path):
160        try:
161            with open(path, encoding="utf-8") as f:
162                return int(f.read().strip())
163        except (OSError, ValueError, TypeError):
164            return None
165
166    def name(self):
167        try:
168            with open(os.path.join(self.dev, "product_name"), encoding="utf-8") as f:
169                return f.read().strip() or "AMD Radeon"
170        except (OSError, TypeError):
171            return "AMD Radeon"
172
173    @staticmethod
174    def _gen(text):
175        """The PCIe generation of a link-speed file's contents ("16.0 GT/s PCIe" -> 4), or None."""
176        try:
177            return {2.5: 1, 5.0: 2, 8.0: 3, 16.0: 4, 32.0: 5, 64.0: 6}[float(str(text).split()[0])]
178        except (ValueError, TypeError, IndexError, KeyError):
179            return None
180
181    @staticmethod
182    def _bdf(s):
183        """True for a sysfs pci device name ("0000:03:00.0"); nothing is imported for it."""
184        return (len(s) == 12 and s[4] == ":" and s[7] == ":" and s[10] == "." and s[11] in "01234567"
185                and all(c in "0123456789abcdef" for c in s[0:4] + s[5:7] + s[8:10]))
186
187    @staticmethod
188    def _read(d, name):
189        try:
190            with open(os.path.join(d, name), encoding="utf-8") as f:
191                return f.read().strip()
192        except (OSError, TypeError):
193            return None
194
195    def _hops(self):
196        """The PCIe devices between the root port and this card, the card last: the sysfs path names every
197        hop (a card behind a bridge chain has more than one; a directly attached card has one)."""
198        out, prefix = [], []
199        for part in os.path.realpath(self.dev or "").split("/"):
200            prefix.append(part)
201            if self._bdf(part):
202                out.append("/".join(prefix))
203        return out
204
205    def link(self):
206        """The PCIe link the card actually gets: the **narrowest/slowest hop** between the root port and the card,
207        from each hop's `max_link_speed` / `max_link_width` (the capability, so a power-saving downgrade or a Gen3
208        slot cannot make it read low).  A card that is Gen4 on its own hop but sits behind a Gen3 root port really
209        runs at Gen3, and that is the number a PCIe bandwidth budget needs.
210        `pcie_own_gen` keeps the card's own hop aside: the gap between the two is what a user has to see.
211
212        The bottleneck is only claimed when **every** hop of the path could be read; `pcie_path` reports how many
213        of them were ("4/4").  A kernel or a container that hides part of /sys/devices would otherwise drop the
214        unreadable hops in silence and report the card's own Gen4 hop as the whole path - i.e. be optimistic
215        exactly where it matters.  When the walk is incomplete the reading falls back to the card's own negotiated
216        link and pcie_path says so."""
217        hops = self._hops()
218        gens, widths, read = [], [], 0
219        for d in hops:
220            g = self._gen(_Amd._read(d, "max_link_speed"))
221            w = self._int(os.path.join(d, "max_link_width"))
222            read += 1 if (g is not None or w is not None) else 0
223            if g:
224                gens.append(g)
225            if w:
226                widths.append(w)
227        own = self.dev or ""
228        own_gen = self._gen(_Amd._read(own, "current_link_speed"))
229        whole = bool(hops) and read == len(hops)
230        gen = min(gens) if (whole and gens) else own_gen
231        width = min(widths) if (whole and widths) else self._int(os.path.join(own, "current_link_width"))
232        return {"pcie_gen": gen, "pcie_gen_max": gen, "pcie_own_gen": own_gen, "pcie_width": width,
233                "pcie_path": "%d/%d" % (read, len(hops))}
234
235
236    def read(self):
237        out = {"util": self._int(os.path.join(self.dev, "gpu_busy_percent")),
238               "mem_used": self._int(os.path.join(self.dev, "mem_info_vram_used")),
239               "mem_total": self._int(os.path.join(self.dev, "mem_info_vram_total"))}
240        if self.hwmon:
241            t = self._int(os.path.join(self.hwmon, "temp1_input"))
242            out["temp"] = t / 1000.0 if t is not None else None
243            p = self._int(os.path.join(self.hwmon, "power1_average"))
244            if p is None:
245                p = self._int(os.path.join(self.hwmon, "power1_input"))
246            out["power"] = p / 1e6 if p is not None else None
247            cap = self._int(os.path.join(self.hwmon, "power1_cap"))
248            out["power_limit"] = cap / 1e6 if cap is not None else None
249        out.update(self.link())
250        return out
251
252
253def metal_working_set():
254    """The Apple GPU's memory budget in bytes: MTLCreateSystemDefaultDevice's recommendedMaxWorkingSetSize, through
255    the Metal framework and objc_msgSend (no PyObjC) - the same property metal/src/mtl_rt.mm reads for the engine
256    (its "GPU working set" log line).  None off macOS, or when it cannot be read: a selector the device does not
257    answer would raise an Objective-C exception no ctypes call can catch, so the class is asked first."""
258    if sys.platform != "darwin":
259        return None
260    try:
261        metal = ctypes.CDLL("/System/Library/Frameworks/Metal.framework/Metal")
262        objc = ctypes.CDLL("/usr/lib/libobjc.dylib")
263        metal.MTLCreateSystemDefaultDevice.restype = ctypes.c_void_p
264        objc.sel_registerName.restype = ctypes.c_void_p
265        objc.object_getClass.argtypes = [ctypes.c_void_p]
266        objc.object_getClass.restype = ctypes.c_void_p
267        objc.class_respondsToSelector.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
268        objc.class_respondsToSelector.restype = ctypes.c_ubyte
269        objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
270        objc.objc_msgSend.restype = ctypes.c_ulonglong
271        dev = metal.MTLCreateSystemDefaultDevice()
272        if not dev:
273            return None
274        sel = objc.sel_registerName(b"recommendedMaxWorkingSetSize")
275        if not objc.class_respondsToSelector(objc.object_getClass(dev), sel):
276            return None
277        return int(objc.objc_msgSend(ctypes.c_void_p(dev), ctypes.c_void_p(sel))) or None
278    except (OSError, AttributeError, ValueError):
279        return None
280
281
282class _Metal:
283    """macOS: an Apple GPU's readings from the IOKit registry (`ioreg -l -w0 -r -c IOAccelerator`, 22 ms), with
284    _Nvml's interface: the load and the memory are the driver's PerformanceStatistics of the index'th accelerator
285    node - Device Utilization % and the in-use system memory in bytes.  The total is the device's Metal working set,
286    the budget one app gets of the unified memory.  No temperature or power reading exists without root
287    (`powermetrics`), and an Apple Silicon GPU sits on the die, so the PCIe cards have nothing to show."""
288    note = ("no GPU temperature or power reading without root (powermetrics), and an Apple Silicon GPU sits on the "
289            "die, so there is no PCIe link to show; the engine's own figures are in its log")
290    cmd = ("ioreg", "-l", "-w0", "-r", "-c", "IOAccelerator")
291
292    def __init__(self, index=0, run=None):
293        self.index = index
294        self._run = run or self._ioreg
295        self.nodes = len(self._blocks())
296        self._name = None
297        b = self._block()
298        if b:
299            m = re.search(r'"model" = "([^"]+)"', b)
300            self._name = m.group(1) if m else None
301
302    @staticmethod
303    def _ioreg():
304        try:
305            return subprocess.run(list(_Metal.cmd), capture_output=True, text=True, timeout=10).stdout or ""
306        except (OSError, subprocess.SubprocessError):
307            return ""
308
309    def _blocks(self):
310        """The accelerator nodes, in the registry's order: every node that carries a PerformanceStatistics."""
311        try:
312            out = self._run() or ""
313        except OSError:                     # ioreg missing, or a caller's runner that raises
314            return []
315        return [b for b in re.split(r"^\s*\+-o ", out, flags=re.M) if '"PerformanceStatistics"' in b]
316
317    def _block(self):
318        b = self._blocks()
319        return b[self.index] if 0 <= self.index < len(b) else None
320
321    def ok(self):
322        return self.index < self.nodes
323
324    def name(self):
325        return self._name
326
327    def read(self):
328        b = self._block()
329        if b is None:
330            return {}
331
332        def num(key):
333            m = re.search(r'"%s"=([0-9.]+)' % re.escape(key), b)
334            return float(m.group(1)) if m else None
335
336        out = {}
337        u = num("Device Utilization %")
338        if u is None:                      # older chips report only the renderer and the tiler
339            r, t = num("Renderer Utilization %"), num("Tiler Utilization %")
340            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
341        out["util"] = int(u) if u is not None else None
342        used = num("In use system memory")
343        out["mem_used"] = int(used) if used is not None else None
344        out["mem_total"] = metal_working_set()
345        return out
346
347
348def gpu_reader(index=0, amd=False):
349    """The card's readings: NVML (NVIDIA), the amdgpu sysfs files with the AMD backend (#301), or IOKit's
350    IOAccelerator registry on macOS (Metal backend).  `amd` comes first: no Mac runs the HIP backend, and the
351    tests' AMD trees are read on a Mac too."""
352    if amd:
353        return _Amd(index)
354    return _Metal(index) if sys.platform == "darwin" else _Nvml(index)
355
356
357_DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
358
359
360def windows_display_adapters(vendor=None) -> list:
361    """#1587: the display adapters Windows has drivers for, from the registry's display class (no subprocess, no vendor
362    library): [{"name", "provider", "driver", "vram_bytes"}] in the class's order.  `vendor`: "amd", "nvidia" or
363    "intel" keeps that vendor's cards.  [] off Windows or when nothing can be read."""
364    if os.name != "nt":
365        return []
366    try:
367        import winreg
368        root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS)
369    except OSError:
370        return []
371    out = []
372    i = 0
373    while True:
374        try:
375            sub = winreg.EnumKey(root, i)
376        except OSError:
377            break
378        i += 1
379        if not sub.isdigit():
380            continue
381        try:
382            k = winreg.OpenKey(root, sub)
383        except OSError:
384            continue
385
386        def val(name, k=k):
387            try:
388                return winreg.QueryValueEx(k, name)[0]
389            except OSError:
390                return None
391        name = val("DriverDesc")
392        if not isinstance(name, str) or not name.strip():
393            continue
394        mem = val("HardwareInformation.qwMemorySize")
395        if mem is None:
396            mem = val("HardwareInformation.MemorySize")
397        if isinstance(mem, (bytes, bytearray)):
398            mem = int.from_bytes(bytes(mem[:8]), "little") if mem else None
399        out.append({"name": name.strip(), "provider": str(val("ProviderName") or ""), "driver": val("DriverVersion"),
400                    "vram_bytes": mem if isinstance(mem, int) and mem > 0 else None})
401    if vendor:
402        keys = {"amd": ("advanced micro devices", "amd", "radeon"), "nvidia": ("nvidia",), "intel": ("intel",)}[vendor]
403        out = [a for a in out if any(s in (a["provider"] + " " + a["name"]).lower() for s in keys)]
404    return out
405
406
407def windows_amd_cards(adapters=None) -> list:
408    """The AMD cards HIP runs on, as windows_display_adapters lists them.  A Ryzen's integrated Radeon is listed too
409    (512 MiB on a Ryzen 5 7600): beside a card with 2 GiB or more it is left out (an APU alone keeps it)."""
410    cards = windows_display_adapters("amd") if adapters is None else adapters
411    return [c for c in cards if (c["vram_bytes"] or 0) >= 2 << 30] or cards
412
413
414def free_vram_mib(index=0, amd=False):
415    """Free VRAM of a card in MiB, or None when it cannot be read."""
416    g = gpu_reader(index, amd)
417    if not g.ok():
418        return None
419    r = g.read()
420    if r.get("mem_total") is None or r.get("mem_used") is None:
421        return None
422    return int((r["mem_total"] - r["mem_used"]) >> 20)
423
424
425# ------------------------------------------------------------------------------------------------ CPU / RAM
426def _cpu_topology(root: str = "/sys/devices/system"):
427    """(sockets, NUMA nodes) of this computer: how many CPU packages it has and how many memory nodes (None where it cannot be read).
428    Linux reads /sys, Windows asks GetLogicalProcessorInformationEx / GetNumaHighestNodeNumber, macOS asks sysctl (Apple silicon and every Mac
429    sold so far: one package, no NUMA)."""
430    try:
431        if os.name == "nt":
432            import ctypes
433            kernel32 = ctypes.windll.kernel32
434            needed = ctypes.c_ulong(0)
435            kernel32.GetLogicalProcessorInformationEx(3, None, ctypes.byref(needed))          # RelationProcessorPackage
436            buf = ctypes.create_string_buffer(needed.value)
437            sockets = None
438            if needed.value and kernel32.GetLogicalProcessorInformationEx(3, buf, ctypes.byref(needed)):
439                sockets, offset = 0, 0
440                while offset + 8 <= needed.value:
441                    relationship = int.from_bytes(buf.raw[offset:offset + 4], "little")
442                    size = int.from_bytes(buf.raw[offset + 4:offset + 8], "little")
443                    if size <= 0:
444                        break
445                    sockets += 1 if relationship == 3 else 0
446                    offset += size
447            high = ctypes.c_ulong(0)
448            numa = high.value + 1 if kernel32.GetNumaHighestNodeNumber(ctypes.byref(high)) else None
449            return (sockets or None), numa
450        if sys.platform == "darwin":
451            import subprocess
452            out = subprocess.run(["sysctl", "-n", "hw.packages"], capture_output=True, text=True, timeout=5).stdout.strip()
453            return (int(out) if out.isdigit() else 1), None
454        import glob
455        packages = set()
456        for f in glob.glob(os.path.join(root, "cpu", "cpu[0-9]*", "topology", "physical_package_id")):
457            try:
458                with open(f, encoding="utf-8") as fh:
459                    packages.add(fh.read().strip())
460            except OSError:
461                continue
462        nodes = len(glob.glob(os.path.join(root, "node", "node[0-9]*")))
463        return (len(packages) or None), (nodes or None)
464    except Exception:                                        # noqa: BLE001 - a missing figure is shown as missing, never guessed
465        return None, None
466
467
468def _cpu_name():
469    if os.name == "nt":
470        try:
471            import winreg
472            k = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0")
473            return winreg.QueryValueEx(k, "ProcessorNameString")[0].strip()
474        except OSError:
475            pass
476    elif os.path.exists("/proc/cpuinfo"):
477        with open("/proc/cpuinfo", encoding="utf-8", errors="replace") as fh:
478            for line in fh:
479                if line.startswith("model name"):
480                    return line.split(":", 1)[1].strip()
481    return sysinfo.processor() or None
482
483
484class _CpuRamFallback:
485    """CPU load and RAM without psutil."""
486
487    def __init__(self):
488        self.prev = self._times()
489
490    def _times(self):
491        if os.name == "nt":
492            idle, kern, user = (ctypes.c_ulonglong() for _ in range(3))
493            if ctypes.windll.kernel32.GetSystemTimes(ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user)):
494                return idle.value, kern.value + user.value           # kernel time includes idle
495            return None
496        try:
497            with open("/proc/stat") as fh:
498                f = [int(x) for x in fh.readline().split()[1:]]
499            return f[3] + f[4], sum(f)
500        except (OSError, ValueError):
501            return None
502
503    def cpu(self):
504        cur = self._times()
505        prev, self.prev = self.prev, cur
506        if not cur or not prev or cur[1] == prev[1]:
507            return None
508        return max(0.0, min(100.0, 100.0 * (1 - (cur[0] - prev[0]) / (cur[1] - prev[1]))))
509
510    @staticmethod
511    def ram():
512        if os.name == "nt":
513            class MS(ctypes.Structure):
514                _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
515                            ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
516                            ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
517                            ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
518                            ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
519            m = MS()
520            m.dwLength = ctypes.sizeof(MS)
521            if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)):
522                return m.ullTotalPhys - m.ullAvailPhys, m.ullTotalPhys
523            return None, None
524        try:
525            with open("/proc/meminfo") as fh:
526                info = dict(line.split(":", 1) for line in fh)
527            total = int(info["MemTotal"].split()[0]) * 1024
528            avail = int(info["MemAvailable"].split()[0]) * 1024
529            return total - avail, total
530        except (OSError, KeyError, ValueError):
531            return None, None
532
533
534# ------------------------------------------------------------------------------------------------ the sampler
535class Telemetry:
536    def __init__(self, extra=None, gpu_index=0, gpu_indices=None, amd=False):
537        """`extra()` -> dict of more series to record each second (the server's tok/s).  `gpu_index`: the card the
538        engine runs on, numbered as nvidia-smi and NVML number them (by PCI bus); `gpu_indices`: all of them when
539        the model is split across several (issue #112) - the gpu_* readings are then their total (memory, power,
540        PCIe traffic), mean (load) or hottest (temperature), and "gpus" has each card's own.  `amd`: the AMD backend's
541        cards, numbered as HIP numbers them, read from sysfs (#301)."""
542        self.extra = extra
543        self.lock = threading.Lock()
544        self.now: dict = {}
545        self.hist = collections.defaultdict(lambda: collections.deque(maxlen=HISTORY))
546        idx = list(gpu_indices) if gpu_indices and len(gpu_indices) > 1 else [gpu_index]
547        self.gpus = [(i, gpu_reader(i, amd)) for i in idx]
548        self.gpus = [(i, g) for i, g in self.gpus if g.ok()] or self.gpus[:1]
549        self.gpu = self.gpus[0][1]
550        try:
551            import psutil  # noqa: F401
552            self.ps = sys.modules["psutil"]
553        except ImportError:
554            self.ps = None
555        self.fallback = _CpuRamFallback()
556        gpu_name = " + ".join(g.name() or "?" for _, g in self.gpus) if self.gpu.ok() else None
557        win_amd = None
558        if gpu_name is None and amd and os.name == "nt":
559            # #1587: no readings for an AMD card on Windows yet, but its name (and VRAM size) are in the registry, so the
560            # dashboard and strata_bench do not call the run "CPU only".  The class order is taken as HIP's order.
561            cards = windows_amd_cards()
562            win_amd = [cards[i] for i in idx if 0 <= i < len(cards)] or cards[:1]
563            gpu_name = " + ".join(c["name"] for c in win_amd) if win_amd else None
564        # the macOS reader knows the device's working set (the VRAM budget of the unified memory); None elsewhere
565        vram_total = None
566        if win_amd is None and isinstance(self.gpu, _Metal) and self.gpu.ok():
567            ws = metal_working_set()
568            vram_total = ws >> 20 if ws else None
569        self.static = {
570            "gpu_name": gpu_name,
571            "gpu_vram_total_mib": (sum(c["vram_bytes"] for c in win_amd) >> 20
572                                   if win_amd and all(c["vram_bytes"] for c in win_amd) else vram_total),
573            "gpu_count": len(self.gpus),
574            # #1380: the AMD readings are the amdgpu driver's Linux sysfs files; a Windows AMD card has none yet, and the
575            # dashboard said "not readable (NVML)" or showed empty tiles with no word why
576            "gpu_note": ("no GPU load or VRAM readings for AMD cards on Windows yet (Linux reads them from the amdgpu "
577                         "driver); the engine's own VRAM figures are in its log" if amd and not self.gpu.ok()
578                         else getattr(self.gpu, "note", None)),
579            "cpu_name": _cpu_name(),
580            "cores": (self.ps.cpu_count(logical=False) if self.ps else None) or None,
581            "threads": os.cpu_count(),
582            "sockets": _cpu_topology()[0],
583            "numa_nodes": _cpu_topology()[1],
584            "psutil": self.ps is not None,
585        }
586        self._disk_prev = None
587        self._stop = threading.Event()
588        self._thread = threading.Thread(target=self._loop, daemon=True)
589        self._thread.start()
590
591    def _disk(self):
592        if not self.ps:
593            return None, None
594        try:
595            c = self.ps.disk_io_counters()
596        except (OSError, RuntimeError):
597            return None, None
598        if c is None:   # psutil found no disk (a gVisor container, Windows with its disk counters off)
599            return None, None
600        t = time.time()
601        prev, self._disk_prev = self._disk_prev, (t, c.read_bytes, c.write_bytes)
602        if prev is None or t <= prev[0]:
603            return None, None
604        dt = t - prev[0]
605        return (c.read_bytes - prev[1]) / dt / 2**20, (c.write_bytes - prev[2]) / dt / 2**20
606
607    def sample(self):
608        s = {}
609        if self.gpu.ok():
610            reads = [(i, g.read()) for i, g in self.gpus]
611            g = dict(reads[0][1])
612            if len(reads) > 1:
613                def vals(k):
614                    return [r[k] for _, r in reads if r.get(k) is not None]
615                for k in ("mem_used", "mem_total", "power", "power_limit", "pcie_rx_mb", "pcie_tx_mb"):
616                    v = vals(k)
617                    g[k] = sum(v) if v else None
618                u = vals("util")
619                g["util"] = sum(u) / len(u) if u else None
620                t = vals("temp")
621                g["temp"] = max(t) if t else None
622                s["gpus"] = [{"index": i, "name": reader.name(), "util": r.get("util"), "mem_used": r.get("mem_used"),
623                              "mem_total": r.get("mem_total"), "temp": r.get("temp"), "power": r.get("power")}
624                             for (i, r), (_, reader) in zip(reads, self.gpus)]
625            s.update({f"gpu_{k}": v for k, v in g.items()})
626        if self.ps:
627            try:
628                s["cpu"] = self.ps.cpu_percent(interval=None)
629                vm = self.ps.virtual_memory()
630                s["ram_used"], s["ram_total"] = vm.total - vm.available, vm.total
631            except (OSError, RuntimeError):
632                pass
633        else:
634            s["cpu"] = self.fallback.cpu()
635            s["ram_used"], s["ram_total"] = self.fallback.ram()
636        s["disk_read_mb"], s["disk_write_mb"] = self._disk()
637        if self.extra:
638            try:
639                s.update(self.extra())
640            except Exception:  # noqa: BLE001 - telemetry must never take the server down
641                pass
642        return s
643
644    def close(self):
645        """Ends the sampler thread (a server that stops, a test's service): it used to run for the life of the process."""
646        self._stop.set()
647
648    def _loop(self):
649        """One sample a second, for as long as the server lives.
650
651        A failing sample must not end the thread: on a machine where the GPU/psutil source is not readable
652        (a CI runner, a container without NVML) the first exception used to kill the sampler outright, so
653        `GET /metrics` silently stopped updating and `test_responses.NoLeakedSampler` saw "the server did
654        not start its hardware sampler" - the thread had started and died between two readings.
655        """
656        complained = False
657        while not self._stop.is_set():
658            try:
659                s = self.sample()
660            except Exception as e:                    # noqa: BLE001 - a monitor must outlive its source
661                if not complained:                    # once, not once a second
662                    print(f"[strata] metrics: a sample failed ({e}); the sampler keeps trying", flush=True)
663                    complained = True
664                self._stop.wait(1.0)
665                continue
666            with self.lock:
667                self.now = s
668                for k in ("gpu_util", "gpu_mem_used", "gpu_temp", "gpu_power", "gpu_pcie_rx_mb", "cpu", "ram_used",
669                          "disk_read_mb", "tok_s", "prefill_tok_s_mean"):
670                    v = s.get(k)
671                    self.hist[k].append(round(v, 2) if isinstance(v, float) else v)
672            self._stop.wait(1.0)
673
674    def snapshot(self):
675        with self.lock:
676            return {"now": dict(self.now), "history": {k: list(v) for k, v in self.hist.items()},
677                    "static": dict(self.static)}