okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ad33b8074
main
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: 4name, vram_used_mb / vram_total_mb (sum of drm-resident-vram0 over unique drm 5clients from /proc/*/fdinfo - the only VRAM accounting xe exposes; root-only), 6busy_pct (compute/render cycle deltas), temp_pkg/temp_vram (hwmon 'xe'), 7power_w / pkg_power_w (energy counter deltas over a POWER_WINDOW s window: the counters update in 8bursts, so a 3 s delta swings 0.6 <-> 48 W), power_cap_w, fan_rpm, freq_mhz, the PCIe link the card 9trained at (the first upstream port wider than x1 - the card's own functions sit behind an internal 10x1 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/ 14sudo 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.""" 28for d in sorted (glob .glob ("/sys/class/drm/card[0-9]*/device" )): 29try : 30if open (f" { d } /vendor" ).read ().strip ()== "0x8086" and glob .glob (f" { d } /tile*/gt*" ): 31return os .path .basename (os .path .realpath (d )) 32except OSError : 33continue 34return None 35 36 37PCI = os .environ .get ("GPUSTAT_PCI" )or find_card ()or "0000:00:00.0" 38 39 40def vram_total_mb (): 41if os .environ .get ("GPUSTAT_VRAM_MB" ): 42return int (os .environ ["GPUSTAT_VRAM_MB" ]) 43try :# with resizable BAR the largest BAR maps all of VRAM 44sizes = [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 ())] 46return max (sizes )// 2 ** 20 47except (OSError ,ValueError ): 48return 0 49 50 51def card_name (dev_id ): 52if dev_id in NAMES : 53return NAMES [dev_id ] 54try : 55out = subprocess .run (["lspci" ,"-mm" ,"-s" ,PCI ],capture_output = True ,text = True ,timeout = 5 ).stdout 56parts = [p .strip ('"' )for p in out .split ('" "' )] 57if len (parts )>= 3 and parts [2 ]: 58return parts [2 ] 59except (OSError ,subprocess .SubprocessError ): 60pass 61return 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.""" 70d = os .path .realpath (f"/sys/bus/pci/devices/ { PCI } " ) 71chain = [] 72while d .startswith ("/sys/devices/pci" )and os .path .exists (f" { d } /current_link_speed" ): 73chain .append (d );d = os .path .dirname (d ) 74def link (p ,kind ): 75sp = (rd (f" { p } / { kind } _link_speed" ,"" )or "" ).split (" " )[0 ] 76return {"gen" :GEN .get (sp ),"gts" :sp ,"width" :int (rd (f" { p } / { kind } _link_width" ,"0" )or 0 )} 77for i ,p in enumerate (chain ): 78cur = link (p ,"current" ) 79if cur ["width" ]> 1 : 80root = chain [- 1 ]# the CPU's root port: what the slot can do 81return {"cur" :cur ,"card_max" :link (p ,"max" ),"slot_max" :link (root ,"max" )} 82return None 83 84def hwmon_dir (): 85for n in glob .glob ("/sys/class/hwmon/hwmon*/name" ): 86if open (n ).read ().strip ()== "xe" : 87return os .path .dirname (n ) 88return None 89 90def rd (p ,default = None ): 91try : 92return open (p ).read ().strip () 93except Exception : 94return default 95 96def hw_temps (h ): 97t = {} 98for lab in glob .glob (f" { h } /temp*_label" ): 99name = rd (lab );v = rd (lab .replace ("_label" ,"_input" )) 100if name and v :t [name ]= int (v )/ 1000 101return t 102 103def clients (): 104"""{client_id: {pid, comm, vram_kb, cycles, total_cycles}} across all processes.""" 105res = {} 106for pdir in glob .glob ("/proc/[0-9]*" ): 107try : 108fds = os .listdir (f" { pdir } /fd" ) 109except Exception : 110continue 111for fd in fds : 112try : 113if not os .readlink (f" { pdir } /fd/ { fd } " ).startswith ("/dev/dri/" ): 114continue 115info = dict (l .split (":\t" ,1 )for l in open (f" { pdir } /fdinfo/ { fd } " ).read ().splitlines ()if l .startswith ("drm-" )) 116except Exception : 117continue 118cid = info .get ("drm-client-id" ) 119if not cid or cid in res : 120continue 121kb = lambda k :int (info .get (k ,"0" ).split ()[0 ]or 0 ) 122cyc = max (kb ("drm-cycles-rcs" ),kb ("drm-cycles-ccs" )) 123tot = max (kb ("drm-total-cycles-rcs" ),kb ("drm-total-cycles-ccs" )) 124res [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 } 126return res 127 128def main (): 129h = hwmon_dir () 130dev_id = (rd (f"/sys/bus/pci/devices/ { PCI } /device" ,"0x0" )or "0x0" )[2 :] 131name = card_name (dev_id ) 132prev = {};t_prev = time .time () 133ring = collections .deque ()# (t, card uJ, pkg uJ) over the last POWER_WINDOW s 134link = pcie_link ();link_t = time .time () 135while True : 136now = time .time ();dt = max (now - t_prev ,1e-3 ) 137cl = clients () 138busy = 0.0 139for cid ,c in cl .items (): 140p = prev .get (cid ) 141if p and c ["total" ]> p ["total" ]: 142busy += (c ["cycles" ]- p ["cycles" ])/ (c ["total" ]- p ["total" ])* 100 143e = int (rd (f" { h } /energy1_input" ,"0" )or 0 )if h else 0 144e2 = int (rd (f" { h } /energy2_input" ,"0" )or 0 )if h else 0 145ring .append ((now ,e ,e2 )) 146while len (ring )> 2 and now - ring [1 ][0 ]>= POWER_WINDOW : 147ring .popleft () 148t0 ,ea ,eb = ring [0 ] 149span = now - t0 150power = (e - ea )/ 1e6 / span if span >= 2.5 and e >= ea else None 151pkg_power = (e2 - eb )/ 1e6 / span if span >= 2.5 and e2 >= eb else None 152if now - link_t > 30 :# the link can retrain (power saving, errors): re-read it 153link = pcie_link ();link_t = now 154temps = hw_temps (h )if h else {} 155vram_ch = [v for k ,v in temps .items ()if k .startswith ("vram_ch_" )] 156cap = rd (f" { h } /power1_cap" )if h else None 157used_mb = sum (c ["vram_kb" ]for c in cl .values ())// 1024 158out = { 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 ) 173if glob .glob (f"/sys/bus/pci/devices/ { PCI } /tile0/gt0/freq0/act_freq" )else None , 174 } 175tmp = OUT + ".tmp" 176with open (tmp ,"w" )as f :json .dump (out ,f ) 177os .chmod (tmp ,0o644 );os .replace (tmp ,OUT ) 178prev ,t_prev = cl ,now 179time .sleep (INTERVAL ) 180 181if __name__ == "__main__" : 182main ()