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