okami.mom/strata

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

Niko1221Merge commit 'a0116b27' into f-144-int818845ea1

main
5.4 KiB117 linesraw
1"""Intel Arc (xe driver) readings for the server's Monitor tab, in the shape of serve/telemetry.py's readers.
2
3Kept out of serve/telemetry.py so the SYCL port touches no shared file: sycl/serve/server_intel.py installs it as
4telemetry.gpu_reader when there is no NVIDIA card.  Load and VRAM need root (xe's only VRAM accounting is per-client
5fdinfo), so they come from a root sampler's /run/gpustat.json (sycl/tools/gpustat.py); temperature, power and the
6PCIe link are read from sysfs, so they show without it.
7"""
8from __future__ import annotations
9
10import os
11import sys
12import time
13
14
15# the cards sycl/setup_intel.py names by PCI id (INTEL_ARC)
16ARC_NAMES = {"e223": "Arc Pro B70", "e221": "Arc Pro B60", "e211": "Arc Pro B60", "e20b": "Arc B580", "e20c": "Arc B570",
17             "e212": "Arc B50", "56a0": "Arc A770", "56a1": "Arc A750", "56a2": "Arc A580", "56a5": "Arc A380",
18             "56a6": "Arc A310", "5690": "Arc A770M"}
19
20
21class _XeGpu:
22    """The Intel Arc readings in NVML's shape. Load and VRAM come from /run/gpustat.json (a root sampler: the only
23    VRAM accounting xe exposes is per-client fdinfo, readable by root only); temperature, power and the PCIe link are
24    read from sysfs too, so they show without the sampler."""
25    STAT = "/run/gpustat.json"
26
27    def __init__(self, index=0):
28        import glob
29        self.dev = None
30        cards = []                              # #2001: the Intel cards in sysfs order, as setup numbers them
31        for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")):
32            try:
33                if open(f"{d}/vendor").read().strip() == "0x8086" and os.path.isdir(f"{d}/tile0"):
34                    cards.append(os.path.realpath(d))
35            except OSError:
36                continue
37        if 0 <= index < len(cards):
38            self.dev = cards[index]
39        self.hwmon = None
40        for n in glob.glob(f"{self.dev}/hwmon/hwmon*/name") if self.dev else []:
41            self.hwmon = os.path.dirname(n)
42        self._e = None                          # (t, card energy uJ) for power without the sampler
43
44    def ok(self):
45        return self.dev is not None and sys.platform.startswith("linux")
46
47    def name(self):
48        st = self._stat()
49        if (st or {}).get("name"):
50            return st["name"]
51        try:                                    # the PCI id's name (setup_intel.INTEL_ARC), not a generic one
52            with open(f"{self.dev}/device") as f:
53                return "Intel " + ARC_NAMES.get(f.read().strip().lower().replace("0x", ""), "Arc GPU")
54        except (OSError, TypeError):
55            return "Intel Arc GPU"
56
57    def _stat(self):
58        try:
59            import json
60            with open(self.STAT) as f:
61                st = json.load(f)
62            return st if time.time() - float(st.get("ts", 0)) < 15 else None
63        except (OSError, ValueError):
64            return None
65
66    def _rd(self, p):
67        try:
68            return open(p).read().strip()
69        except OSError:
70            return None
71
72    def _link(self):
73        """The link the card trained at: its own functions sit behind an internal x1 switch, so the first port up
74        the path wider than x1; the max is what card AND slot allow (the root port caps it)."""
75        gen = {"2.5": 1, "5.0": 2, "8.0": 3, "16.0": 4, "32.0": 5, "64.0": 6}
76        d, chain = self.dev, []
77        while d and d.startswith("/sys/devices/pci") and os.path.exists(f"{d}/current_link_speed"):
78            chain.append(d)
79            d = os.path.dirname(d)
80        for p in chain:
81            w = int(self._rd(f"{p}/current_link_width") or 0)
82            if w > 1:
83                g = lambda q, k: gen.get((self._rd(f"{q}/{k}_link_speed") or "").split(" ")[0])
84                card, slot = g(p, "max"), g(chain[-1], "max")
85                return g(p, "current"), min(x for x in (card, slot) if x) if (card or slot) else None, w
86        return None, None, None
87
88    def read(self):
89        out = {}
90        st = self._stat()
91        if st:
92            out["util"] = st.get("busy_pct")
93            if st.get("vram_used_mb") is not None:
94                out["mem_used"] = st["vram_used_mb"] * 2**20
95                out["mem_total"] = st.get("vram_total_mb", 0) * 2**20 or None
96            out["temp"] = st.get("temp_pkg")
97            out["power"] = st.get("power_w")
98            out["power_limit"] = st.get("power_cap_w")
99            out["vram_temp"] = st.get("temp_vram_max") or st.get("temp_vram")
100        if self.hwmon:
101            if out.get("temp") is None:
102                for lab in os.listdir(self.hwmon):
103                    if lab.endswith("_label") and self._rd(f"{self.hwmon}/{lab}") == "pkg":
104                        v = self._rd(f"{self.hwmon}/{lab[:-6]}_input")
105                        out["temp"] = int(v) / 1000 if v else None
106            if out.get("power") is None:
107                e, t = self._rd(f"{self.hwmon}/energy1_input"), time.time()
108                if e and e.isdigit():
109                    if self._e and t > self._e[0] and int(e) >= self._e[1]:
110                        out["power"] = (int(e) - self._e[1]) / 1e6 / (t - self._e[0])
111                    self._e = (t, int(e))
112            if out.get("power_limit") is None:
113                cap = self._rd(f"{self.hwmon}/power1_cap")
114                out["power_limit"] = int(cap) / 1e6 if cap and cap.isdigit() and int(cap) > 0 else None
115        out["pcie_gen"], out["pcie_gen_max"], out["pcie_width"] = self._link()
116        out["pcie_rx_mb"] = out["pcie_tx_mb"] = None    # xe exposes no PCIe traffic counters
117        return out