okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6b63729a9
main
1"""What the tuner needs to know about this PC, read without ever raising. 2 3Every probe here is optional: a missing tool or an unreadable file gives ``None`` (or an empty list), never an 4exception, because the tuner must still run on a machine whose sensors it cannot read, only with fewer guards. 5A guard that cannot read its input says so in the report ("the free graphics memory could not be read"); it does not 6pretend the memory was free. 7 8Stdlib only, like the rest of Strata Control. 9""" 10 11from __future__import annotations 12 13import hashlib 14import json 15import os 16from strata_control import sysinfo 17import re 18import shutil 19import subprocess 20import sys 21import time 22from pathlib import Path 23from typing import Any 24 25MIB = 1024 * 1024 26 27 28# --------------------------------------------------------------------------- memory 29 30def memory ()-> dict [str ,int | None ]: 31"""System RAM in MiB: ``total`` and ``available`` (what a new process could use without swapping).""" 32try : 33if os .name == "nt" : 34import ctypes 35 36class _Status (ctypes .Structure ): 37_fields_ = [("dwLength" ,ctypes .c_ulong ), ("dwMemoryLoad" ,ctypes .c_ulong ), 38 ("ullTotalPhys" ,ctypes .c_ulonglong ), ("ullAvailPhys" ,ctypes .c_ulonglong ), 39 ("ullTotalPageFile" ,ctypes .c_ulonglong ), ("ullAvailPageFile" ,ctypes .c_ulonglong ), 40 ("ullTotalVirtual" ,ctypes .c_ulonglong ), ("ullAvailVirtual" ,ctypes .c_ulonglong ), 41 ("ullAvailExtendedVirtual" ,ctypes .c_ulonglong )] 42 43status = _Status () 44status .dwLength = ctypes .sizeof (_Status ) 45if ctypes .windll .kernel32 .GlobalMemoryStatusEx (ctypes .byref (status )): 46return {"total_mib" :int (status .ullTotalPhys // MIB ),"available_mib" :int (status .ullAvailPhys // MIB )} 47elif sys .platform == "darwin" : 48total = int (subprocess .run (["sysctl" ,"-n" ,"hw.memsize" ],capture_output = True ,text = True , 49timeout = 5 ).stdout .strip ())// MIB 50vm = subprocess .run (["vm_stat" ],capture_output = True ,text = True ,timeout = 5 ).stdout 51page = int (re .search (r"page size of (\d+)" ,vm ).group (1 ))if re .search (r"page size of (\d+)" ,vm )else 16384 52pages = 0 53for key in ("Pages free" ,"Pages inactive" ,"Pages speculative" ): 54m = re .search (rf" { key } :\s+(\d+)" ,vm ) 55pages += int (m .group (1 ))if m else 0 56return {"total_mib" :total ,"available_mib" :pages * page // MIB } 57else : 58# /proc/meminfo; inside a container its memory limit (strata_control/cgroup_memory.py) 59from strata_control import cgroup_memory 60total ,available = cgroup_memory .ram_bytes () 61if total is not None and available is not None : 62return {"total_mib" :total // MIB ,"available_mib" :available // MIB } 63except Exception :# noqa: BLE001 - a probe must not raise 64pass 65return {"total_mib" :None ,"available_mib" :None } 66 67 68# --------------------------------------------------------------------------- graphics cards 69 70def _run (argv :list [str ],timeout :float = 10.0 )-> str | None : 71try : 72return subprocess .run (argv ,capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ).stdout 73except Exception :# noqa: BLE001 74return None 75 76 77def gpus ()-> list [dict [str ,Any ]]: 78"""Graphics cards with their memory: ``name``, ``vram_total_mib``, ``vram_used_mib`` (None when unreadable), 79``driver``, ``vendor``. NVIDIA through nvidia-smi, AMD through the kernel's sysfs files; Intel and Apple report 80their name only where it is known, and leave the memory unreadable.""" 81out :list [dict [str ,Any ]]= [] 82smi = shutil .which ("nvidia-smi" ) 83if smi : 84text = _run ([smi ,"--query-gpu=index,name,memory.total,memory.used,driver_version" , 85"--format=csv,noheader,nounits" ]) 86for line in (text or "" ).splitlines (): 87parts = [p .strip ()for p in line .split ("," )] 88if len (parts )>= 5 : 89try : 90out .append ({"vendor" :"nvidia" ,"index" :int (parts [0 ]),"name" :parts [1 ], 91"vram_total_mib" :int (float (parts [2 ])),"vram_used_mib" :int (float (parts [3 ])), 92"driver" :parts [4 ]}) 93except ValueError : 94continue 95if not out and sys .platform .startswith ("linux" ): 96base = Path ("/sys/class/drm" ) 97if base .is_dir (): 98index = 0 99for card in sorted (base .glob ("card[0-9]*" )): 100dev = card / "device" 101try : 102vendor = (dev / "vendor" ).read_text ().strip () 103total = int ((dev / "mem_info_vram_total" ).read_text ())// MIB 104used = int ((dev / "mem_info_vram_used" ).read_text ())// MIB 105except (OSError ,ValueError ): 106continue 107if vendor != "0x1002" : 108continue 109name = None 110try : 111name = (dev / "product_name" ).read_text ().strip () 112except OSError : 113pass 114out .append ({"vendor" :"amd" ,"index" :index ,"name" :name or f"AMD GPU { index } " , 115"vram_total_mib" :total ,"vram_used_mib" :used ,"driver" :None }) 116index += 1 117return out 118 119 120def gpu_used_mib (indexes :list [int ]| None = None )-> int | None : 121"""Graphics memory in use now, summed over the cards the model runs on (all when ``indexes`` is None).""" 122cards = gpus () 123if not cards : 124return None 125vals = [c ["vram_used_mib" ]for c in cards if c .get ("vram_used_mib" )is not None 126and (not indexes or c ["index" ]in indexes )] 127return sum (vals )if vals else None 128 129 130# --------------------------------------------------------------------------- processor 131 132def cpu ()-> dict [str ,Any ]: 133"""``model``, ``logical`` and ``physical`` thread counts, and ``hybrid`` (performance plus efficiency cores).""" 134logical = os .cpu_count ()or 1 135model = sysinfo .processor ()or sysinfo .machine () 136physical :int | None = None 137hybrid = False 138try : 139if sys .platform .startswith ("linux" ): 140text = Path ("/proc/cpuinfo" ).read_text () 141m = re .search (r"model name\s*:\s*(.+)" ,text ) 142if m : 143model = m .group (1 ).strip () 144cores = set () 145for block in text .split ("\n\n" ): 146pid = re .search (r"physical id\s*:\s*(\d+)" ,block ) 147cid = re .search (r"core id\s*:\s*(\d+)" ,block ) 148if pid and cid : 149cores .add ((pid .group (1 ),cid .group (1 ))) 150physical = len (cores )or None 151hybrid = Path ("/sys/devices/cpu_core" ).exists ()and Path ("/sys/devices/cpu_atom" ).exists () 152elif os .name == "nt" : 153try : 154import winreg 155with winreg .OpenKey (winreg .HKEY_LOCAL_MACHINE ,r"HARDWARE\DESCRIPTION\System\CentralProcessor\0" )as k : 156model = str (winreg .QueryValueEx (k ,"ProcessorNameString" )[0 ]).strip ()or model 157except OSError : 158pass 159physical ,hybrid = _windows_cores () 160elif sys .platform == "darwin" : 161model = (_run (["sysctl" ,"-n" ,"machdep.cpu.brand_string" ])or model ).strip () 162phys = _run (["sysctl" ,"-n" ,"hw.physicalcpu" ]) 163physical = int (phys )if phys and phys .strip ().isdigit ()else None 164hybrid = False 165except Exception :# noqa: BLE001 166pass 167return {"model" :model ,"logical" :logical ,"physical" :physical ,"hybrid" :hybrid } 168 169 170def _windows_cores ()-> tuple [int | None ,bool ]: 171"""(physical cores, hybrid) from GetLogicalProcessorInformationEx: hybrid when the cores have more than one 172efficiency class (performance and efficiency cores).""" 173try : 174import ctypes 175from ctypes import wintypes 176 177k = ctypes .windll .kernel32 178k .GetLogicalProcessorInformationEx .argtypes = [wintypes .DWORD ,ctypes .c_void_p ,ctypes .POINTER (wintypes .DWORD )] 179size = wintypes .DWORD (0 ) 180k .GetLogicalProcessorInformationEx (0 ,None ,ctypes .byref (size ))# 0 = RelationProcessorCore 181buf = ctypes .create_string_buffer (size .value ) 182if not k .GetLogicalProcessorInformationEx (0 ,buf ,ctypes .byref (size )): 183return None ,False 184raw = bytes (buf .raw [:size .value ]) 185classes ,cores ,offset = set (),0 ,0 186while offset + 10 <= len (raw ): 187rel_size = int .from_bytes (raw [offset + 4 :offset + 8 ],"little" ) 188if rel_size <= 0 : 189break 190classes .add (raw [offset + 9 ])# PROCESSOR_RELATIONSHIP.EfficiencyClass 191cores += 1 192offset += rel_size 193return (cores or None ),len (classes )> 1 194except Exception :# noqa: BLE001 195return None ,False 196 197 198_last_cpu :tuple [float ,int ,int ]| None = None 199 200 201def cpu_busy_percent (sample_s :float = 1.0 )-> float | None : 202"""How busy the whole CPU was over the last ``sample_s`` seconds (0-100), or None when unreadable.""" 203def read ()-> tuple [int ,int ]| None : 204try : 205if sys .platform .startswith ("linux" ): 206f = Path ("/proc/stat" ).read_text ().splitlines ()[0 ].split ()[1 :] 207v = [int (x )for x in f ] 208idle = v [3 ]+ (v [4 ]if len (v )> 4 else 0 ) 209return sum (v ),idle 210if os .name == "nt" : 211import ctypes 212from ctypes import wintypes 213idle ,kern ,user = wintypes .FILETIME (),wintypes .FILETIME (),wintypes .FILETIME () 214if not ctypes .windll .kernel32 .GetSystemTimes (ctypes .byref (idle ),ctypes .byref (kern ),ctypes .byref (user )): 215return None 216q = lambda t : (t .dwHighDateTime << 32 )| t .dwLowDateTime # noqa: E731 217return q (kern )+ q (user ),q (idle ) 218except Exception :# noqa: BLE001 219return None 220return None 221 222a = read () 223if a is None : 224return None 225time .sleep (sample_s ) 226b = read () 227if b is None or b [0 ]== a [0 ]: 228return None 229return round (100.0 * (1.0 - (b [1 ]- a [1 ])/ (b [0 ]- a [0 ])),1 ) 230 231 232def other_engines (own_pids :set [int ]| None = None )-> list [str ]: 233"""Command lines of Strata engines that this tune did not start (a second engine changes every number).""" 234own = own_pids or set () 235found :list [str ]= [] 236try : 237if os .name == "nt" : 238text = _run (["powershell" ,"-NoProfile" ,"-Command" , 239"Get-CimInstance Win32_Process -Filter \"Name='strata.exe'\" | " 240"Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress" ],timeout = 20 ) 241if text and text .strip (): 242data = json .loads (text ) 243for row in data if isinstance (data ,list )else [data ]: 244if int (row .get ("ProcessId" ,0 ))not in own and "--serve" in (row .get ("CommandLine" )or "" ): 245found .append ((row .get ("CommandLine" )or "" )[:160 ]) 246else : 247text = _run (["ps" ,"-eo" ,"pid=,args=" ])or "" 248for line in text .splitlines (): 249pid_s ,_ ,args = line .strip ().partition (" " ) 250if pid_s .isdigit ()and int (pid_s )not in own and re .search (r"(^|/)strata(\s|$)" ,args .split (" --serve" )[0 ]) \ 251and " --serve" in args : 252found .append (args [:160 ]) 253except Exception :# noqa: BLE001 254pass 255return found 256 257 258# --------------------------------------------------------------------------- the key a preset is valid for 259 260def _round_down (value :int | None ,step :int )-> int | None : 261return None if value is None else value - value % step 262 263 264def hardware_identity (* ,pcie :str | None = None )-> dict [str ,Any ]: 265"""Hardware in two parts. ``hard``: a change means the stored settings may not even start (graphics card, 266memory sizes, processor). ``soft``: a change deserves a short re-check (graphics driver).""" 267cards = gpus () 268mem = memory () 269c = cpu () 270return { 271"hard" : { 272"gpus" : [{"name" :g ["name" ],"vram_mib" :g ["vram_total_mib" ]}for g in cards ], 273"cpu" :c ["model" ],"logical" :c ["logical" ],"physical" :c ["physical" ],"hybrid" :c ["hybrid" ], 274"ram_gib" :_round_down ((mem ["total_mib" ]or 0 )// 1024 or None ,2 ), 275"pcie" :pcie ,"os" :sysinfo .system (), 276 }, 277"soft" : {"driver" :sorted ({g ["driver" ]for g in cards if g .get ("driver" )}),"os_release" :sysinfo .release ()}, 278 } 279 280 281def engine_identity (exe :str | os .PathLike [str ])-> dict [str ,Any ]: 282"""The engine build: version, backend, build id and executable SHA-256 from its manifest, plus the manifest's 283``tuning_epoch`` (bumped when a kernel or default change can move a tuning result).""" 284folder = Path (exe ).resolve ().parent 285manifest :dict [str ,Any ]= {} 286try : 287manifest = json .loads ((folder / "engine-component.json" ).read_text (encoding = "utf-8" )) 288except (OSError ,ValueError ): 289pass 290sha = None 291for entry in manifest .get ("files" )or []: 292if entry .get ("path" )== manifest .get ("entrypoint" ,Path (exe ).name ): 293sha = entry .get ("sha256" ) 294return {"version" :manifest .get ("version" ),"backend" :manifest .get ("backend" ), 295"build_id" :manifest .get ("build_id" ),"sha256" :sha , 296"tuning_epoch" :int (manifest .get ("tuning_epoch" )or 0 ),"path" :str (exe )} 297 298 299def model_identity (files :list [str | os .PathLike [str ]])-> dict [str ,Any ]: 300"""The model file(s): size and a digest of the head, middle and tail of the first shard (the whole file would 301mean reading tens of gigabytes before every tune).""" 302from strata_control import tune_history 303out :list [dict [str ,Any ]]= [] 304for f in files [:2 ]: 305ident = tune_history .file_identity (Path (f )) 306out .append ({"name" :Path (f ).name ,"bytes" :ident .get ("bytes" ),"digest" :ident .get ("digest" ), 307"method" :ident .get ("method" )}) 308first = out [0 ]if out else {} 309return {"files" :out ,"sha256_shard1" :first .get ("digest" ),"bytes" :first .get ("bytes" )} 310 311 312def stable_hash (obj :Any )-> str : 313return hashlib .sha256 (json .dumps (obj ,sort_keys = True ,default = str ).encode ()).hexdigest ()[:16 ]