okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
792b62698
main
1"""What a standard benchmark report says about the machine, the build, the model and the settings (docs/BENCHMARK_PROTOCOL.md). 2 3Every probe is best effort and local: it reads the inference host's own tools (nvidia-smi, rocm-smi, amd-smi, PowerShell, /proc, sysctl) and the 4server's answers. A fact that cannot be read becomes `None` with a reason in `Why`, never a guess. Nothing here changes the machine. 5""" 6 7from __future__import annotations 8 9import getpass 10import glob 11import hashlib 12import json 13import os 14import platform 15from strata_control import sysinfo 16import re 17import socket 18import subprocess 19import sys 20import tempfile 21from pathlib import Path 22 23ROOT = Path (__file__ ).resolve ().parents [1 ] 24LOOPBACK = frozenset ({"localhost" ,"127.0.0.1" ,"::1" }) 25HEX40 = re .compile (r"^[0-9a-f]{40}$" ) 26MODEL_SUFFIXES = (".gguf" ,".safetensors" ,".pack" ,".bin" ) 27SECRET_KEY = re .compile (r"(?i)key|token|secret|password|auth" ) 28 29 30class Why (dict ): 31"""JSON Pointer -> the reason a value is null. Built while the report is assembled and written as `missing`.""" 32 33def add (self ,pointer :str ,reason :str )-> None : 34self [pointer ]= reason 35 36 37def pointer (* parts )-> str : 38return "" .join ("/" + str (p ).replace ("~" ,"~0" ).replace ("/" ,"~1" )for p in parts ) 39 40 41# ------------------------------------------------------------------------------------------------------------ redaction 42def usable_key (value )-> str | None : 43"""A credential as a client may send it: None for nothing, blanks, or "none" in any case (#4483: the server's spelling of 44"no key", serve.server.explicit_no_key; it is not a key, so it is neither sent as a Bearer token nor redacted as a word).""" 45if value is None : 46return None 47text = str (value ).strip () 48return None if not text or text .lower ()== "none" else text 49 50 51def redactor (key :str = "" ): 52"""text -> text with this machine's home folders, user and host names, the Strata folder, private IP addresses and the API key replaced. 53The key is replaced only where it stands as a whole token and in its own case (#4483): a short key is also a common word or a part of a hash. A hyphen 54next to it does not make it part of a longer word (`pack-<key>`, `<key>-1`: the key was a leak there); letters, digits and the underscore do. 55The names (user, host) are not touched inside a label this function wrote: redacting a text twice gives the same text (a user called "user" gave `<<user>>`).""" 56subs :list [tuple [re .Pattern ,str ,bool ]]= []# (pattern, label, is a login or host name) 57 58def add (value ,label ,word = False ,exact = False ,name = False ): 59if value and len (str (value ))>= 4 : 60text = str (value ) 61for form in sorted ({text ,text .replace ("\\" ,"/" ),text .replace ("/" ,"\\" )},key = len ,reverse = True ): 62pattern = re .escape (form ) 63if word and exact : 64pattern = r"(?<!\w)" + pattern + r"(?!\w)" 65elif word : 66pattern = r"(?<![\w<-])" + pattern + r"(?![\w>-])" 67subs .append ((re .compile (pattern ,0 if exact else re .I ),label ,name )) 68 69add (ROOT ,"<strata>" ) 70add (Path .home (),"<home>" ) 71add (tempfile .gettempdir (),"<tmp>" ) 72try : 73add (getpass .getuser (),"<user>" ,True ,name = True ) 74except Exception :# noqa: BLE001 - no user name is not an error 75pass 76add (socket .gethostname (),"<host>" ,True ,name = True ) 77add (sysinfo .node (),"<host>" ,True ,name = True ) 78add (usable_key (key ),"<key>" ,word = True ,exact = True ) 79subs .sort (key = lambda item :- len (item [0 ].pattern )) 80path_user = re .compile (r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+" ) 81private_ip = re .compile (r"\b(?:192\.168|10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])" 82r"|169\.254)\.\d{1,3}\.\d{1,3}\b" ) 83bearer = re .compile (r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}" ) 84 85def clean (text ,names = True ): 86"""names=False leaves a login or host name that is also an ordinary word ("user", "test", "admin") alone: for fixed 87schema text, where the word is not the machine's name; paths, addresses and the key are still replaced.""" 88if not isinstance (text ,str ): 89return text 90for pattern ,label ,is_name in subs : 91if names or not is_name : 92text = pattern .sub (label ,text ) 93text = path_user .sub (lambda m :f" { m . group ( 1 ) or '' } { m . group ( 2 ) } { m . group ( 3 ) } { m . group ( 4 ) } <user>" ,text ) 94text = bearer .sub (r"\1<key>" ,text ) 95return private_ip .sub ("<ip>" ,text ) 96clean .structural = lambda text :clean (text ,names = False ) 97return clean 98 99 100def redact_values (value ,clean ): 101"""redact_object for free text: the strings are replaced, the keys stay.""" 102if isinstance (value ,dict ): 103return {k :redact_values (v ,clean )for k ,v in value .items ()} 104if isinstance (value ,list ): 105return [redact_values (v ,clean )for v in value ] 106return clean (value )if isinstance (value ,str )else value 107 108 109def redact_document (doc :dict ,clean )-> dict : 110"""The benchmark report as results.json carries it (#4484): the text an operator or a server wrote (hardware, model and configuration 111descriptions, error messages, engine options, request checks) gets the full redaction; everything else is fixed schema text (field 112names, enum values, status reasons) and only loses paths, addresses and the key, so a login called "user" or "test" does not turn 113the report's own words into <user>.""" 114structural = getattr (clean ,"structural" ,clean ) 115out = redact_object (doc ,structural ) 116for block in ("hardware" ,"model" ,"configuration" ): 117if block in doc : 118out [block ]= redact_values (doc [block ],clean ) 119for i ,record in enumerate (doc .get ("requests" )or []): 120if isinstance (record ,dict )and isinstance (record .get ("error" ),dict ): 121out ["requests" ][i ]["error" ]= {** out ["requests" ][i ]["error" ], 122"message" :redact_values (record ["error" ].get ("message" ),clean )} 123extensions = doc .get ("extensions" ) 124if isinstance (extensions ,dict ): 125for field in ("other_engine_options" ,"request_checks" ): 126if field in extensions : 127out ["extensions" ][field ]= redact_values (extensions [field ],clean ) 128return out 129 130 131def redact_object (value ,clean ): 132if isinstance (value ,dict ): 133return {clean (k )if isinstance (k ,str )else k :redact_object (v ,clean )for k ,v in value .items ()} 134if isinstance (value ,list ): 135return [redact_object (v ,clean )for v in value ] 136return clean (value )if isinstance (value ,str )else value 137 138 139# ------------------------------------------------------------------------------------------------------------ commands 140def run_cmd (cmd :list [str ],timeout :float = 15 )-> str : 141try : 142done = subprocess .run (cmd ,capture_output = True ,text = True ,timeout = timeout ,encoding = "utf-8" ,errors = "replace" ) 143return done .stdout if done .returncode == 0 else "" 144except (OSError ,subprocess .SubprocessError ): 145return "" 146 147 148def powershell (script :str ,timeout :float = 20 )-> str : 149return run_cmd (["powershell" ,"-NoProfile" ,"-NonInteractive" ,"-Command" ,script ],timeout ) 150 151 152def sha256_file (path :Path ,chunk :int = 8 << 20 )-> str : 153digest = hashlib .sha256 () 154with open (path ,"rb" )as stream : 155while block := stream .read (chunk ): 156digest .update (block ) 157return digest .hexdigest () 158 159 160def sha256_text (text :str )-> str : 161return hashlib .sha256 (text .encode ("utf-8" )).hexdigest () 162 163 164# ------------------------------------------------------------------------------------------------------------ hardware 165def ram_bytes ()-> int | None : 166try : 167import psutil 168return int (psutil .virtual_memory ().total ) 169except Exception :# noqa: BLE001 170pass 171try : 172for line in Path ("/proc/meminfo" ).read_text ().splitlines (): 173if line .startswith ("MemTotal:" ): 174return int (line .split ()[1 ])* 1024 175except OSError : 176pass 177if sys .platform == "darwin" : 178out = run_cmd (["sysctl" ,"-n" ,"hw.memsize" ]).strip () 179return int (out )if out .isdigit ()else None 180return None 181 182 183def cpu_name ()-> str | None : 184try : 185for line in Path ("/proc/cpuinfo" ).read_text ().splitlines (): 186if line .lower ().startswith ("model name" ): 187return line .split (":" ,1 )[1 ].strip () 188except OSError : 189pass 190if sys .platform == "darwin" : 191out = run_cmd (["sysctl" ,"-n" ,"machdep.cpu.brand_string" ]).strip () 192if out : 193return out 194if os .name == "nt" : 195out = powershell ("(Get-CimInstance Win32_Processor | Select-Object -First 1).Name" ).strip () 196if out : 197return out 198return sysinfo .processor ()or None 199 200 201def nvidia_gpus ()-> tuple [list [dict ],str | None ,str | None ]: 202"""-> (cards, driver version, CUDA version) from nvidia-smi.""" 203out = run_cmd (["nvidia-smi" ,"--query-gpu=index,name,memory.total,power.limit,driver_version" , 204"--format=csv,noheader,nounits" ]) 205cards = [] 206for line in out .splitlines (): 207part = [x .strip ()for x in line .split ("," )] 208if len (part )< 5 or not part [0 ].isdigit (): 209continue 210 211def number (text ): 212try : 213return float (text ) 214except ValueError : 215return None 216mib ,watts = number (part [2 ]),number (part [3 ]) 217cards .append ({"device_index" :int (part [0 ]),"name" :part [1 ], 218"memory_bytes" :int (mib * 1024 * 1024 )if mib else None , 219"memory_kind" :"dedicated" ,"power_limit_w" :watts ,"driver" :part [4 ]}) 220cuda = None 221if cards : 222# driver 615 prints "CUDA UMD Version: 13.4" where older drivers print "CUDA Version: 13.0" 223match = re .search (r"CUDA (?:UMD )?Version:\s*([\d.]+)" ,run_cmd (["nvidia-smi" ])) 224cuda = match .group (1 )if match else None 225return cards , (cards [0 ]["driver" ]if cards else None ),cuda 226 227 228def other_gpus ()-> tuple [list [dict ],str | None ]: 229"""AMD (rocm-smi, or the Windows registry), Apple silicon: -> (cards, driver version).""" 230cards ,driver = [],None 231rocm = run_cmd (["rocm-smi" ,"--showproductname" ]) 232names = re .findall (r"Card [Ss]eries:\s*(.+)" ,rocm )or re .findall (r"Card [Mm]odel:\s*(.+)" ,rocm ) 233if names : 234match = re .search (r"Driver version:\s*(\S+)" ,run_cmd (["rocm-smi" ,"--showdriverversion" ])) 235driver = match .group (1 )if match else None 236cards = [{"device_index" :i ,"name" :n .strip (),"memory_bytes" :None ,"memory_kind" :"dedicated" , 237"power_limit_w" :None }for i ,n in enumerate (names )] 238elif os .name == "nt" : 239try : 240if str (ROOT )not in sys .path : 241sys .path .insert (0 ,str (ROOT )) 242from serve .telemetry import windows_amd_cards 243found = windows_amd_cards () 244cards = [{"device_index" :i ,"name" :c ["name" ],"memory_bytes" :c .get ("vram_bytes" )or None , 245"memory_kind" :"dedicated" ,"power_limit_w" :None }for i ,c in enumerate (found )] 246driver = next ((c .get ("driver" )for c in found if c .get ("driver" )),None ) 247except Exception :# noqa: BLE001 - a report without the card's name is still a report 248pass 249elif os .name != "nt" and sys .platform != "darwin" :# (a Mac has no AMD card to ask for; its chip is read below) 250# ROCm 7 and newer ship amd-smi and no rocm-smi (verified on ROCm 10.1). Different grammar: `static --asic` 251# gives the marketing name, `static --driver` the kernel driver's version, and the PCI address only comes 252# from `amd-smi list`; the VRAM size is the amdgpu driver's sysfs file for that address. 253def amd_json (args ): 254try : 255return json .loads (run_cmd (["amd-smi" ,"static" ]+ args + ["--json" ]).strip ()or "{}" ).get ("gpu_data" )or [] 256except (ValueError ,OSError ): 257return [] 258try : 259bdf = {e .get ("gpu" ): (e .get ("bdf" )or "" )for e in json .loads (run_cmd (["amd-smi" ,"list" ,"--json" ]).strip ()or "[]" )} 260except (ValueError ,OSError ): 261bdf = {} 262drv = {e .get ("gpu" ): ((e .get ("driver" )or {}).get ("version" )or "" )for e in amd_json (["--driver" ])} 263for i ,e in enumerate (amd_json (["--asic" ])): 264name = ((e .get ("asic" )or {}).get ("market_name" )or "" ).strip () 265if not name : 266continue 267d = drv .get (e .get ("gpu" ),"" ) 268driver = driver or (d if d .upper ()not in ("" ,"N/A" )else None ) 269vram = None 270for dev in glob .glob ("/sys/class/drm/card[0-9]*/device" ): 271try : 272if bdf .get (e .get ("gpu" ))and os .path .basename (os .path .realpath (dev )).lower ()== bdf [e ["gpu" ]].lower (): 273with open (os .path .join (dev ,"mem_info_vram_total" ),encoding = "utf-8" )as f : 274total = f .read ().strip () 275vram = int (total )if total .isdigit ()else None 276except OSError : 277pass 278cards .append ({"device_index" :i ,"name" :name ,"memory_bytes" :vram ,"memory_kind" :"dedicated" , 279"power_limit_w" :None }) 280elif sys .platform == "darwin" : 281chip = cpu_name () 282if chip : 283cards = [{"device_index" :0 ,"name" :chip ,"memory_bytes" :ram_bytes (),"memory_kind" :"shared" , 284"power_limit_w" :None }] 285return cards ,driver 286 287 288def rocm_version ()-> str | None : 289"""ROCm's own version, which `rocm-smi --showdriverversion` used to report with the driver. ROCm 10 has no 290`rocm-smi` and no `/opt/rocm/.info/`: its version file sits under `<install>/core/.info/version`, and 291`amd-smi -h` prints the same version.""" 292for base in [os .environ .get ("ROCM_PATH" ,"" ),"/opt/rocm" ]: 293if not base : 294continue 295for sub in (".info/version" ,"core/.info/version" ): 296try : 297with open (os .path .join (base ,sub ),encoding = "utf-8" )as f : 298found = f .read ().strip () 299if found : 300return found 301except OSError : 302pass 303match = re .search (r"ROCm version:\s*([\d.]+)" ,run_cmd (["amd-smi" ,"-h" ])) 304return match .group (1 )if match else None 305 306 307def lsblk_disk (data :dict )-> list [dict ]| None : 308"""The first physical disk in `lsblk -J -s` output. `-s` lists the parents of a device as nested children: an LVM volume 309is lvm -> partition -> disk, two levels down, so the walk goes all the way down.""" 310def disks (item ): 311if item .get ("type" )== "disk" : 312yield item 313for child in item .get ("children" )or []: 314yield from disks (child ) 315 316for device in data .get ("blockdevices" )or []: 317for item in disks (device ): 318rotational = str (item .get ("rota" )).lower ()in ("1" ,"true" ) 319bus = str (item .get ("tran" )or "unknown" ).lower () 320return [{"kind" :"hdd" if rotational else ("nvme" if bus == "nvme" else "ssd" ), 321"model" :str (item .get ("model" )or "unknown" ).strip (),"bus" :bus }] 322return None 323 324 325def storage_of (path :Path | None )-> list [dict ]| None : 326"""The drive that holds `path`: [{kind, model, bus}], or None when it cannot be told.""" 327if path is None : 328return None 329try : 330path = path .resolve () 331except OSError : 332return None 333if os .name == "nt" : 334letter = path .drive [:1 ] 335if not letter .isalpha (): 336return None 337out = powershell (f"Get-Partition -DriveLetter { letter } | Get-Disk | Get-PhysicalDisk | " 338"Select-Object MediaType,FriendlyName,BusType | ConvertTo-Json -Compress" ) 339try : 340data = json .loads (out ) 341except ValueError : 342return None 343rows = data if isinstance (data ,list )else [data ] 344return [{"kind" :str (r .get ("MediaType" )or "unknown" ).lower (),"model" :str (r .get ("FriendlyName" )or "unknown" ), 345"bus" :str (r .get ("BusType" )or "unknown" ).lower ()}for r in rows if isinstance (r ,dict )]or None 346if sys .platform .startswith ("linux" ): 347source = run_cmd (["findmnt" ,"-n" ,"-o" ,"SOURCE" ,"--target" ,str (path )]).strip () 348if not source .startswith ("/dev/" ): 349return None 350try : 351data = json .loads (run_cmd (["lsblk" ,"-J" ,"-s" ,"-o" ,"NAME,TYPE,ROTA,MODEL,TRAN" ,source ])) 352except ValueError : 353return None 354return lsblk_disk (data ) 355return None 356 357 358def gpu_selection (config :dict | None ,argv :list [str ]| None )-> list [int ]: 359"""The card numbers the engine is told to use, from the run config's "gpu" or a `--gpu` in its arguments.""" 360def parse (value ): 361if value is None or value == "" : 362return [] 363items = value if isinstance (value , (list ,tuple ))else str (value ).split ("," ) 364return [int (x )for x in (str (i ).strip ()for i in items )if x .isdigit ()] 365chosen = parse ((config or {}).get ("gpu" )) 366if not chosen and argv and "--gpu" in argv and argv .index ("--gpu" )+ 1 < len (argv ): 367chosen = parse (argv [argv .index ("--gpu" )+ 1 ]) 368return chosen 369 370 371def hardware (why :Why ,* ,selected :list [int ],served_gpu :str | None ,model_dir :Path | None , 372declared_background :list [str ])-> tuple [dict ,dict ]: 373"""-> (the report's `hardware`, the driver and runtime facts the `software` block uses).""" 374cards ,driver ,cuda = nvidia_gpus () 375if not cards : 376cards ,driver = other_gpus () 377if selected : 378cards = [c for c in cards if c ["device_index" ]in selected ]or cards 379elif len (cards )> 1 and served_gpu : 380named = [c for c in cards if c ["name" ]== served_gpu ] 381cards = named [:1 ]or cards [:1 ] 382served = [n for n in (served_gpu or "" ).split (" + " )if n and n != "?" ] 383# the amdgpu driver's product_name is empty on some cards (gfx1201 among them), so the server falls back to a bare 384# "AMD Radeon": that names the vendor, not the card, and the local probe's marketing name is the one to keep 385stub = re .compile (r"(?i)^(amd radeon|advanced micro devices(,? inc\.?)?|nvidia( corporation)?|intel" 386r"( corporation)?)( graphics)?$" ) 387if served and cards and not all (stub .match (n )for n in served ) \ 388and not all (n in {c ["name" ]for c in cards }for n in served ): 389# the server reads cards the local tools do not list (another vendor's, or a different numbering) 390cards = [{"device_index" :i ,"name" :n ,"memory_bytes" :None ,"memory_kind" :"dedicated" ,"power_limit_w" :None } 391for i ,n in enumerate (served )] 392driver = cuda = None 393if not cards and served : 394cards = [{"device_index" :i ,"name" :n ,"memory_bytes" :None ,"memory_kind" :"dedicated" ,"power_limit_w" :None } 395for i ,n in enumerate (served )] 396gpus = [] 397for i ,card in enumerate (cards ): 398gpus .append ({k :card .get (k )for k in ("device_index" ,"name" ,"memory_bytes" ,"memory_kind" ,"power_limit_w" )}) 399if gpus [- 1 ]["memory_bytes" ]is None : 400why .add (pointer ("hardware" ,"gpus" ,i ,"memory_bytes" ),"the local tools did not report this card's memory" ) 401if gpus [- 1 ]["power_limit_w" ]is None : 402why .add (pointer ("hardware" ,"gpus" ,i ,"power_limit_w" ),"no power limit available for this card from the local tools" ) 403ram = ram_bytes () 404cpu = cpu_name () 405drive = storage_of (model_dir ) 406block = {"gpus" :gpus ,"cpu" :cpu ,"ram_bytes" :ram ,"storage" :drive , 407"background_workloads" :declared_background or None } 408if not gpus : 409why .add (pointer ("hardware" ,"gpus" ),"no GPU was found by the local tools or reported by the server" ) 410if cpu is None : 411why .add (pointer ("hardware" ,"cpu" ),"the CPU model could not be read" ) 412if ram is None : 413why .add (pointer ("hardware" ,"ram_bytes" ),"installed memory could not be read" ) 414if drive is None : 415why .add (pointer ("hardware" ,"storage" ),"the drive holding the model files could not be identified" ) 416if not declared_background : 417why .add (pointer ("hardware" ,"background_workloads" ), 418"the runner does not inspect other programs; none were declared with --background" ) 419# an AMD card on Linux runs on ROCm, which the report names as the runtime; on ROCm 7 and newer that version no 420# longer comes from rocm-smi, but from the install itself 421rocm = rocm_version ()if (sys .platform .startswith ("linux" )and cards and not cuda )else None 422return block , {"driver" :driver ,"cuda" :cuda ,"rocm" :rocm } 423 424 425# ------------------------------------------------------------------------------------------------------------ software 426def os_info ()-> dict : 427if os .name == "nt" : 428return {"name" :"Windows" ,"version" :sysinfo .version ()} 429if sys .platform == "darwin" : 430return {"name" :"macOS" ,"version" :platform .mac_ver ()[0 ]or sysinfo .release ()} 431name = None 432try : 433for line in Path ("/etc/os-release" ).read_text ().splitlines (): 434if line .startswith ("PRETTY_NAME=" ): 435name = line .split ("=" ,1 )[1 ].strip ().strip ('"' ) 436except OSError : 437pass 438return {"name" :name or sysinfo .system (),"version" :sysinfo .release ()} 439 440 441def git_commit (folder :Path = ROOT )-> str | None : 442"""The full commit of this checkout, or the COMMIT file a release archive carries; None for neither.""" 443if (folder / ".git" ).exists (): 444out = run_cmd (["git" ,"-C" ,str (folder ),"rev-parse" ,"HEAD" ]).strip ().lower () 445if HEX40 .match (out ): 446return out 447try : 448text = (folder / "COMMIT" ).read_text (encoding = "utf-8" ).strip ().lower () 449except OSError : 450return None 451return text if HEX40 .match (text )else None 452 453 454def engine_build_runtime (exe :str | None )-> dict | None : 455"""The GPU runtime a release engine was built with, from its engine-component.json (build_id "a7bdbfdabc9a+cuda12.9"): 456{"name": "cuda", "version": "12.9"}. None for a source build or an engine without that file.""" 457if not exe : 458return None 459try : 460record = json .loads ((Path (exe ).parent / "engine-component.json" ).read_text (encoding = "utf-8" )) 461except (OSError ,ValueError ): 462return None 463match = re .search (r"\+(cuda|rocm|hip|sycl)([\d.]+)\Z" ,str (record .get ("build_id" )or "" ))if isinstance (record ,dict )else None 464return {"name" :"rocm" if match .group (1 )== "hip" else match .group (1 ),"version" :match .group (2 )}if match else None 465 466 467def software (why :Why ,machine :dict ,* ,engine_version :str | None ,build_options :list [str ]| None , 468engine_build :dict | None = None )-> dict : 469commit = git_commit () 470runtime = [] 471if engine_build : 472# the library the engine runs on; nvidia-smi's "CUDA Version" is only the newest one the driver supports 473runtime .append (engine_build ) 474if machine .get ("cuda" )and engine_build ["name" ]== "cuda" : 475runtime .append ({"name" :"cuda-driver-supports" ,"version" :machine ["cuda" ]}) 476elif machine .get ("cuda" ): 477runtime .append ({"name" :"cuda" ,"version" :machine ["cuda" ]}) 478if machine .get ("rocm" )and not any (r .get ("name" )== "rocm" for r in runtime ): 479runtime .append ({"name" :"rocm" ,"version" :machine ["rocm" ]}) 480if sys .platform == "darwin" : 481runtime .append ({"name" :"metal" ,"version" :platform .mac_ver ()[0 ]or sysinfo .release ()}) 482drivers = [{"name" :"gpu-driver" ,"version" :machine ["driver" ]}]if machine .get ("driver" )else [] 483block = {"os" :os_info (),"drivers" :drivers or None ,"runtime" :runtime or None , 484"strata_commit" :commit ,"engine_version" :engine_version , 485"build_kind" :"source" if (ROOT / ".git" ).exists ()else "release" , 486"runner_commit" :commit ,"build_options" :build_options } 487if not drivers : 488why .add ("/software/drivers" ,"no GPU driver version was reported by the local tools" ) 489if not runtime : 490why .add ("/software/runtime" ,"no CUDA, ROCm or Metal runtime version was reported by the local tools" ) 491if commit is None : 492for field in ("strata_commit" ,"runner_commit" ): 493why .add (f"/software/ { field } " ,"not a git checkout and no COMMIT file in this install; a release must carry its commit" ) 494if engine_version is None : 495why .add ("/software/engine_version" ,"the server reported no engine version (/props build_info, /v1/status engine)" ) 496if build_options is None : 497why .add ("/software/build_options" ,"the server does not report build options; pass --build-options for a source build" ) 498return block 499 500 501# ------------------------------------------------------------------------------------------------------------ model 502QUANT = re .compile (r"(?i)(?:^|[-_.])((?:UD-)?(?:IQ\d_[A-Z]+|Q\d_[A-Z0-9_]+|Q\d_K(?:_[A-Z]+)?|IQ\d_?[A-Z]*|BF16|F16|NVFP4|Q\d))(?=[-_.]|$)" ) 503SHARD = re .compile (r"^(.*)-(\d{5})-of-(\d{5})(\.gguf)$" ) 504 505 506def model_files_from (paths :list [str ])-> list [Path ]: 507"""The model files behind these paths: each existing file, and the other shards of a split GGUF.""" 508found :dict [str ,Path ]= {} 509for raw in paths : 510try : 511path = Path (raw ) 512if not path .is_file ()or path .suffix .lower ()not in MODEL_SUFFIXES : 513continue 514except (OSError ,ValueError ): 515continue 516found [str (path .resolve ())]= path 517match = SHARD .match (path .name ) 518if match : 519total = int (match .group (3 )) 520for index in range (1 ,total + 1 ): 521sibling = path .with_name (f" { match . group ( 1 ) } - { index :05d } -of- { match . group ( 3 ) } { match . group ( 4 ) } " ) 522if sibling .is_file (): 523found [str (sibling .resolve ())]= sibling 524return sorted (found .values (),key = lambda p :p .name ) 525 526 527def detect_quantization (names :list [str ])-> str | None : 528for name in names : 529match = QUANT .search (name ) 530if match : 531return match .group (1 ).upper () 532return None 533 534 535def model (why :Why ,* ,props :dict ,status :dict ,files :list [Path ],declared :dict ,log )-> dict : 536served = props .get ("model_alias" )or status .get ("model" ) 537rows = [] 538for index ,path in enumerate (files ): 539log (f"hashing model file { index + 1 } / { len ( files ) } : { path . name } " ) 540rows .append ({"path" :path .name ,"sha256" :sha256_file (path )}) 541quant = declared .get ("quantization" )or detect_quantization ([p .name for p in files ]+ [str (served or "" )]) 542block = {"id" :str (served )if served else None , 543"revision" :declared .get ("model_revision" ),"source_revision" :declared .get ("source_revision" ), 544"quantization" :quant ,"files" :rows or None ,"tokenizer_revision" :declared .get ("tokenizer_revision" ), 545"custom_pack" :declared .get ("custom_pack" )} 546reasons = {"id" :"the server reported no model name" ,"quantization" :"no quantization name found in the model file names; pass --quantization" , 547"files" :"no local model file could be found to hash (the server reports no model_path or it is not on this host)" , 548"revision" :"not given: the quantization repository's immutable revision cannot be read from the engine; pass --model-revision" , 549"source_revision" :"not given: pass --source-revision" , 550"tokenizer_revision" :"not given: pass --tokenizer-revision" , 551"custom_pack" :"no custom pack or expert profile was declared by the operator (--custom-pack)" } 552for field ,reason in reasons .items (): 553if block [field ]is None : 554why .add (f"/model/ { field } " ,reason ) 555return block 556 557 558# ------------------------------------------------------------------------------------------------------------ configuration 559GROUPS = ( 560 ("kv_cache" , ("--kv" ,)), 561 ("expert_cache" , ("--expert" ,)), 562 ("offloading" , ("--gpu" ,"--layer-split" ,"--low-ram" ,"--offload" ,"--split" ,"--vram" ,"--pcie" ,"--host-core" , 563"--pool" ,"--numa" ,"--unmap" ,"--cpu-expert" ,"--tail-skip" )), 564 ("prefill" , ("--prefill" ,)), 565 ("mtp" , ("--mtp" ,"--spec" ,"--draft" ,"--batch-mtp" )), 566 ("calibration" , ("--calib" ,)), 567 ("experimental_options" , ("--experimental" ,"--exp-" )), 568) 569 570 571def base_if_path (value ): 572if isinstance (value ,str )and (("/" in value or "\\" in value )or re .search (r"\.(gguf|bin|json|pack|txt|jinja|so|dll|exe)$" ,value ,re .I )): 573return re .split (r"[\\/]" ,value .rstrip ("\\/" ))[- 1 ] 574return value 575 576 577def parse_options (argv :list [str ])-> dict : 578"""['--kv', 'int8', '--low-ram'] -> {'--kv': 'int8', '--low-ram': True}; a repeated option becomes a list.""" 579options :dict = {} 580i = 0 581while i < len (argv ): 582token = str (argv [i ]) 583if token .startswith ("--" ): 584name ,value = (token .split ("=" ,1 )+ [None ])[:2 ]if "=" in token else (token ,None ) 585if value is None : 586nxt = argv [i + 1 ]if i + 1 < len (argv )else None 587if nxt is not None and not (str (nxt ).startswith ("--" )and not re .fullmatch (r"-?\d+(\.\d+)?" ,str (nxt ))): 588value ,i = str (nxt ),i + 1 589else : 590value = True 591value = base_if_path (value ) 592if name in options : 593options [name ]= [* (options [name ]if isinstance (options [name ],list )else [options [name ]]),value ] 594else : 595options [name ]= value 596i += 1 597return options 598 599 600def configuration (why :Why ,* ,options :dict | None ,env :dict | None ,props :dict ,declared :dict , 601sampling :dict ,template_ref :dict | None )-> tuple [dict ,dict ]: 602"""-> (the report's `configuration`, the engine options no group takes: they go to extensions).""" 603grouped = {name : {}for name ,_ in GROUPS } 604other = {} 605for name ,value in (options or {}).items (): 606for group ,prefixes in GROUPS : 607if name .startswith (prefixes ): 608grouped [group ][name ]= value 609break 610else : 611other [name ]= value 612for name ,value in sorted ((env or {}).items ()): 613if name .startswith ("STRATA_" )and not SECRET_KEY .search (name ): 614grouped ["experimental_options" ][name ]= base_if_path (str (value )) 615n_ctx = ((props .get ("default_generation_settings" )or {}).get ("n_ctx" )) 616slots = props .get ("total_slots" ) 617block = {"track" :declared ["track" ],"track_notes" :declared ["track_notes" ], 618"context_tokens" :n_ctx if isinstance (n_ctx ,int )and not isinstance (n_ctx ,bool )else None , 619"server_capacity" :slots if isinstance (slots ,int )and not isinstance (slots ,bool )else None , 620** ({name :grouped [name ]for name ,_ in GROUPS }if options is not None else {name :None for name ,_ in GROUPS }), 621"template" :template_ref ,"sampling" :dict (sampling ["sampling" ]), 622"chat_template_kwargs" :dict (sampling ["chat_template_kwargs" ])} 623if block ["context_tokens" ]is None : 624why .add ("/configuration/context_tokens" ,"the server's /props reported no context size" ) 625if block ["server_capacity" ]is None : 626why .add ("/configuration/server_capacity" ,"the server's /props reported no slot count" ) 627if options is None : 628for name ,_ in GROUPS : 629why .add (f"/configuration/ { name } " ,"engine options are not exposed by a running server; start it from a profile or pass --config" ) 630if template_ref is None : 631why .add ("/configuration/template" ,"the server's /props returned no chat template" ) 632return block ,other