okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
8.4 KiB182 linesraw
1#!/usr/bin/env python3
2"""GPU telemetry sampler for an Intel Arc on the xe driver (runs as root: sycl/tools/gpustat.service).
3Writes /run/gpustat.json every INTERVAL s; Strata's web app (serve/telemetry.py) shows it in the Monitor tab:
4  name, vram_used_mb / vram_total_mb (sum of drm-resident-vram0 over unique drm
5  clients from /proc/*/fdinfo - the only VRAM accounting xe exposes; root-only),
6  busy_pct (compute/render cycle deltas), temp_pkg/temp_vram (hwmon 'xe'),
7  power_w / pkg_power_w (energy counter deltas over a POWER_WINDOW s window: the counters update in
8  bursts, so a 3 s delta swings 0.6 <-> 48 W), power_cap_w, fan_rpm, freq_mhz, the PCIe link the card
9  trained at (the first upstream port wider than x1 - the card's own functions sit behind an internal
10  x1 switch), the hottest VRAM channel, and the host's 1-minute load. Device totals only.
11Without it the Monitor tab still shows temperature, power and the PCIe link (sysfs), but not load or VRAM: xe
12reports those per client in /proc/*/fdinfo, which only root can read.
13Install:  sudo install -m 755 sycl/tools/gpustat.py /usr/local/sbin/
14          sudo install -m 644 sycl/tools/gpustat.service /etc/systemd/system/ && sudo systemctl enable --now gpustat
15Env: GPUSTAT_INTERVAL (s), GPUSTAT_POWER_WINDOW (s), GPUSTAT_PCI (the card, e.g. 0000:03:00.0; default the first
16Intel GPU on xe), GPUSTAT_VRAM_MB (the total; default the card's largest PCI BAR, which maps all of VRAM with
17resizable BAR - a little above what the runtime reports as usable).
18"""
19import collections, glob, json, os, subprocess, time
20
21OUT = "/run/gpustat.json"
22INTERVAL = float(os.environ.get("GPUSTAT_INTERVAL", "3"))   # each sample scans /proc/*/fd; keep it modest
23NAMES = {"e223": "Intel(R) Arc(TM) Pro B70 Graphics"}
24
25
26def find_card():
27    """The first Intel GPU on the xe driver (it has tile*/gt*), as a PCI address."""
28    for d in sorted(glob.glob("/sys/class/drm/card[0-9]*/device")):
29        try:
30            if open(f"{d}/vendor").read().strip() == "0x8086" and glob.glob(f"{d}/tile*/gt*"):
31                return os.path.basename(os.path.realpath(d))
32        except OSError:
33            continue
34    return None
35
36
37PCI = os.environ.get("GPUSTAT_PCI") or find_card() or "0000:00:00.0"
38
39
40def vram_total_mb():
41    if os.environ.get("GPUSTAT_VRAM_MB"):
42        return int(os.environ["GPUSTAT_VRAM_MB"])
43    try:                                   # with resizable BAR the largest BAR maps all of VRAM
44        sizes = [int(e, 16) - int(s, 16) + 1 for s, e, _ in
45                 (l.split() for l in open(f"/sys/bus/pci/devices/{PCI}/resource") if l.strip())]
46        return max(sizes) // 2**20
47    except (OSError, ValueError):
48        return 0
49
50
51def card_name(dev_id):
52    if dev_id in NAMES:
53        return NAMES[dev_id]
54    try:
55        out = subprocess.run(["lspci", "-mm", "-s", PCI], capture_output=True, text=True, timeout=5).stdout
56        parts = [p.strip('"') for p in out.split('" "')]
57        if len(parts) >= 3 and parts[2]:
58            return parts[2]
59    except (OSError, subprocess.SubprocessError):
60        pass
61    return f"Intel GPU 8086:{dev_id}"
62
63
64TOTAL_MB = vram_total_mb()
65POWER_WINDOW = float(os.environ.get("GPUSTAT_POWER_WINDOW", "15"))
66GEN = {"2.5": 1, "5.0": 2, "8.0": 3, "16.0": 4, "32.0": 5, "64.0": 6}
67
68def pcie_link():
69    """The link the card trained at: walk up from the GPU function to the first port wider than x1."""
70    d = os.path.realpath(f"/sys/bus/pci/devices/{PCI}")
71    chain = []
72    while d.startswith("/sys/devices/pci") and os.path.exists(f"{d}/current_link_speed"):
73        chain.append(d); d = os.path.dirname(d)
74    def link(p, kind):
75        sp = (rd(f"{p}/{kind}_link_speed", "") or "").split(" ")[0]
76        return {"gen": GEN.get(sp), "gts": sp, "width": int(rd(f"{p}/{kind}_link_width", "0") or 0)}
77    for i, p in enumerate(chain):
78        cur = link(p, "current")
79        if cur["width"] > 1:
80            root = chain[-1]                                  # the CPU's root port: what the slot can do
81            return {"cur": cur, "card_max": link(p, "max"), "slot_max": link(root, "max")}
82    return None
83
84def hwmon_dir():
85    for n in glob.glob("/sys/class/hwmon/hwmon*/name"):
86        if open(n).read().strip() == "xe":
87            return os.path.dirname(n)
88    return None
89
90def rd(p, default=None):
91    try:
92        return open(p).read().strip()
93    except Exception:
94        return default
95
96def hw_temps(h):
97    t = {}
98    for lab in glob.glob(f"{h}/temp*_label"):
99        name = rd(lab); v = rd(lab.replace("_label", "_input"))
100        if name and v: t[name] = int(v) / 1000
101    return t
102
103def clients():
104    """{client_id: {pid, comm, vram_kb, cycles, total_cycles}} across all processes."""
105    res = {}
106    for pdir in glob.glob("/proc/[0-9]*"):
107        try:
108            fds = os.listdir(f"{pdir}/fd")
109        except Exception:
110            continue
111        for fd in fds:
112            try:
113                if not os.readlink(f"{pdir}/fd/{fd}").startswith("/dev/dri/"):
114                    continue
115                info = dict(l.split(":\t", 1) for l in open(f"{pdir}/fdinfo/{fd}").read().splitlines() if l.startswith("drm-"))
116            except Exception:
117                continue
118            cid = info.get("drm-client-id")
119            if not cid or cid in res:
120                continue
121            kb = lambda k: int(info.get(k, "0").split()[0] or 0)
122            cyc = max(kb("drm-cycles-rcs"), kb("drm-cycles-ccs"))
123            tot = max(kb("drm-total-cycles-rcs"), kb("drm-total-cycles-ccs"))
124            res[cid] = {"pid": int(pdir[6:]), "comm": rd(f"{pdir}/comm", "?"),
125                        "cg": rd(f"{pdir}/cgroup", ""), "vram_kb": kb("drm-resident-vram0"), "cycles": cyc, "total": tot}
126    return res
127
128def main():
129    h = hwmon_dir()
130    dev_id = (rd(f"/sys/bus/pci/devices/{PCI}/device", "0x0") or "0x0")[2:]
131    name = card_name(dev_id)
132    prev = {}; t_prev = time.time()
133    ring = collections.deque()                  # (t, card uJ, pkg uJ) over the last POWER_WINDOW s
134    link = pcie_link(); link_t = time.time()
135    while True:
136        now = time.time(); dt = max(now - t_prev, 1e-3)
137        cl = clients()
138        busy = 0.0
139        for cid, c in cl.items():
140            p = prev.get(cid)
141            if p and c["total"] > p["total"]:
142                busy += (c["cycles"] - p["cycles"]) / (c["total"] - p["total"]) * 100
143        e = int(rd(f"{h}/energy1_input", "0") or 0) if h else 0
144        e2 = int(rd(f"{h}/energy2_input", "0") or 0) if h else 0
145        ring.append((now, e, e2))
146        while len(ring) > 2 and now - ring[1][0] >= POWER_WINDOW:
147            ring.popleft()
148        t0, ea, eb = ring[0]
149        span = now - t0
150        power = (e - ea) / 1e6 / span if span >= 2.5 and e >= ea else None
151        pkg_power = (e2 - eb) / 1e6 / span if span >= 2.5 and e2 >= eb else None
152        if now - link_t > 30:                   # the link can retrain (power saving, errors): re-read it
153            link = pcie_link(); link_t = now
154        temps = hw_temps(h) if h else {}
155        vram_ch = [v for k, v in temps.items() if k.startswith("vram_ch_")]
156        cap = rd(f"{h}/power1_cap") if h else None
157        used_mb = sum(c["vram_kb"] for c in cl.values()) // 1024
158        out = {
159            "name": name, "pci": PCI, "ts": now,
160            "vram_used_mb": used_mb, "vram_total_mb": TOTAL_MB,
161            "busy_pct": round(min(busy, 100), 1),
162            "temp_pkg": temps.get("pkg"), "temp_vram": temps.get("vram"),
163            "power_w": None if power is None else round(power, 1),
164            "pkg_power_w": None if pkg_power is None else round(pkg_power, 1),
165            "power_cap_w": round(int(cap) / 1e6) if cap and cap.isdigit() and int(cap) > 0 else None,
166            "temp_vram_max": max(vram_ch) if vram_ch else None,
167            "temp_pcie": temps.get("pcie"), "temp_mctrl": temps.get("mctrl"),
168            "pcie": link,
169            "host_load1": round(os.getloadavg()[0], 2), "host_cpus": os.cpu_count(),
170            "energy_j": round(e / 1e6, 1),           # cumulative card energy (hwmon energy1 = "card", uJ)
171            "fan_rpm": int(rd(f"{h}/fan1_input", "0") or 0) if h else None,
172            "freq_mhz": int(rd(glob.glob(f"/sys/bus/pci/devices/{PCI}/tile0/gt0/freq0/act_freq")[0], "0") or 0)
173                        if glob.glob(f"/sys/bus/pci/devices/{PCI}/tile0/gt0/freq0/act_freq") else None,
174        }
175        tmp = OUT + ".tmp"
176        with open(tmp, "w") as f: json.dump(out, f)
177        os.chmod(tmp, 0o644); os.replace(tmp, OUT)
178        prev, t_prev = cl, now
179        time.sleep(INTERVAL)
180
181if __name__ == "__main__":
182    main()