okami.mom/strata

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

Niko1221Merge f-0213-secure (fix 0855796e6) into f-0213-int792b62698

main
31.1 KiB632 linesraw
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
33    def add(self, pointer: str, reason: str) -> None:
34        self[pointer] = reason
35
36
37def pointer(*parts) -> str:
38    return "".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)."""
45    if value is None:
46        return None
47    text = str(value).strip()
48    return 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.
53    The 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
54    next 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.
55    The 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>>`)."""
56    subs: list[tuple[re.Pattern, str, bool]] = []     # (pattern, label, is a login or host name)
57
58    def add(value, label, word=False, exact=False, name=False):
59        if value and len(str(value)) >= 4:
60            text = str(value)
61            for form in sorted({text, text.replace("\\", "/"), text.replace("/", "\\")}, key=len, reverse=True):
62                pattern = re.escape(form)
63                if word and exact:
64                    pattern = r"(?<!\w)" + pattern + r"(?!\w)"
65                elif word:
66                    pattern = r"(?<![\w<-])" + pattern + r"(?![\w>-])"
67                subs.append((re.compile(pattern, 0 if exact else re.I), label, name))
68
69    add(ROOT, "<strata>")
70    add(Path.home(), "<home>")
71    add(tempfile.gettempdir(), "<tmp>")
72    try:
73        add(getpass.getuser(), "<user>", True, name=True)
74    except Exception:                                   # noqa: BLE001 - no user name is not an error
75        pass
76    add(socket.gethostname(), "<host>", True, name=True)
77    add(sysinfo.node(), "<host>", True, name=True)
78    add(usable_key(key), "<key>", word=True, exact=True)
79    subs.sort(key=lambda item: -len(item[0].pattern))
80    path_user = re.compile(r"(?i)([A-Za-z]:)?([\\/])(Users|home)([\\/])(?!<)[^\\/\s\"':;,]+")
81    private_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])"
82                            r"|169\.254)\.\d{1,3}\.\d{1,3}\b")
83    bearer = re.compile(r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}")
84
85    def 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
87        schema text, where the word is not the machine's name; paths, addresses and the key are still replaced."""
88        if not isinstance(text, str):
89            return text
90        for pattern, label, is_name in subs:
91            if names or not is_name:
92                text = pattern.sub(label, text)
93        text = path_user.sub(lambda m: f"{m.group(1) or ''}{m.group(2)}{m.group(3)}{m.group(4)}<user>", text)
94        text = bearer.sub(r"\1<key>", text)
95        return private_ip.sub("<ip>", text)
96    clean.structural = lambda text: clean(text, names=False)
97    return clean
98
99
100def redact_values(value, clean):
101    """redact_object for free text: the strings are replaced, the keys stay."""
102    if isinstance(value, dict):
103        return {k: redact_values(v, clean) for k, v in value.items()}
104    if isinstance(value, list):
105        return [redact_values(v, clean) for v in value]
106    return 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
111    descriptions, error messages, engine options, request checks) gets the full redaction; everything else is fixed schema text (field
112    names, enum values, status reasons) and only loses paths, addresses and the key, so a login called "user" or "test" does not turn
113    the report's own words into <user>."""
114    structural = getattr(clean, "structural", clean)
115    out = redact_object(doc, structural)
116    for block in ("hardware", "model", "configuration"):
117        if block in doc:
118            out[block] = redact_values(doc[block], clean)
119    for i, record in enumerate(doc.get("requests") or []):
120        if isinstance(record, dict) and isinstance(record.get("error"), dict):
121            out["requests"][i]["error"] = {**out["requests"][i]["error"],
122                                           "message": redact_values(record["error"].get("message"), clean)}
123    extensions = doc.get("extensions")
124    if isinstance(extensions, dict):
125        for field in ("other_engine_options", "request_checks"):
126            if field in extensions:
127                out["extensions"][field] = redact_values(extensions[field], clean)
128    return out
129
130
131def redact_object(value, clean):
132    if isinstance(value, dict):
133        return {clean(k) if isinstance(k, str) else k: redact_object(v, clean) for k, v in value.items()}
134    if isinstance(value, list):
135        return [redact_object(v, clean) for v in value]
136    return clean(value) if isinstance(value, str) else value
137
138
139# ------------------------------------------------------------------------------------------------------------ commands
140def run_cmd(cmd: list[str], timeout: float = 15) -> str:
141    try:
142        done = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace")
143        return done.stdout if done.returncode == 0 else ""
144    except (OSError, subprocess.SubprocessError):
145        return ""
146
147
148def powershell(script: str, timeout: float = 20) -> str:
149    return run_cmd(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], timeout)
150
151
152def sha256_file(path: Path, chunk: int = 8 << 20) -> str:
153    digest = hashlib.sha256()
154    with open(path, "rb") as stream:
155        while block := stream.read(chunk):
156            digest.update(block)
157    return digest.hexdigest()
158
159
160def sha256_text(text: str) -> str:
161    return hashlib.sha256(text.encode("utf-8")).hexdigest()
162
163
164# ------------------------------------------------------------------------------------------------------------ hardware
165def ram_bytes() -> int | None:
166    try:
167        import psutil
168        return int(psutil.virtual_memory().total)
169    except Exception:                                   # noqa: BLE001
170        pass
171    try:
172        for line in Path("/proc/meminfo").read_text().splitlines():
173            if line.startswith("MemTotal:"):
174                return int(line.split()[1]) * 1024
175    except OSError:
176        pass
177    if sys.platform == "darwin":
178        out = run_cmd(["sysctl", "-n", "hw.memsize"]).strip()
179        return int(out) if out.isdigit() else None
180    return None
181
182
183def cpu_name() -> str | None:
184    try:
185        for line in Path("/proc/cpuinfo").read_text().splitlines():
186            if line.lower().startswith("model name"):
187                return line.split(":", 1)[1].strip()
188    except OSError:
189        pass
190    if sys.platform == "darwin":
191        out = run_cmd(["sysctl", "-n", "machdep.cpu.brand_string"]).strip()
192        if out:
193            return out
194    if os.name == "nt":
195        out = powershell("(Get-CimInstance Win32_Processor | Select-Object -First 1).Name").strip()
196        if out:
197            return out
198    return 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."""
203    out = run_cmd(["nvidia-smi", "--query-gpu=index,name,memory.total,power.limit,driver_version",
204                   "--format=csv,noheader,nounits"])
205    cards = []
206    for line in out.splitlines():
207        part = [x.strip() for x in line.split(",")]
208        if len(part) < 5 or not part[0].isdigit():
209            continue
210
211        def number(text):
212            try:
213                return float(text)
214            except ValueError:
215                return None
216        mib, watts = number(part[2]), number(part[3])
217        cards.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]})
220    cuda = None
221    if cards:
222        # driver 615 prints "CUDA UMD Version: 13.4" where older drivers print "CUDA Version: 13.0"
223        match = re.search(r"CUDA (?:UMD )?Version:\s*([\d.]+)", run_cmd(["nvidia-smi"]))
224        cuda = match.group(1) if match else None
225    return 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)."""
230    cards, driver = [], None
231    rocm = run_cmd(["rocm-smi", "--showproductname"])
232    names = re.findall(r"Card [Ss]eries:\s*(.+)", rocm) or re.findall(r"Card [Mm]odel:\s*(.+)", rocm)
233    if names:
234        match = re.search(r"Driver version:\s*(\S+)", run_cmd(["rocm-smi", "--showdriverversion"]))
235        driver = match.group(1) if match else None
236        cards = [{"device_index": i, "name": n.strip(), "memory_bytes": None, "memory_kind": "dedicated",
237                  "power_limit_w": None} for i, n in enumerate(names)]
238    elif os.name == "nt":
239        try:
240            if str(ROOT) not in sys.path:
241                sys.path.insert(0, str(ROOT))
242            from serve.telemetry import windows_amd_cards
243            found = windows_amd_cards()
244            cards = [{"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)]
246            driver = next((c.get("driver") for c in found if c.get("driver")), None)
247        except Exception:                               # noqa: BLE001 - a report without the card's name is still a report
248            pass
249    elif 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.
253        def amd_json(args):
254            try:
255                return json.loads(run_cmd(["amd-smi", "static"] + args + ["--json"]).strip() or "{}").get("gpu_data") or []
256            except (ValueError, OSError):
257                return []
258        try:
259            bdf = {e.get("gpu"): (e.get("bdf") or "") for e in json.loads(run_cmd(["amd-smi", "list", "--json"]).strip() or "[]")}
260        except (ValueError, OSError):
261            bdf = {}
262        drv = {e.get("gpu"): ((e.get("driver") or {}).get("version") or "") for e in amd_json(["--driver"])}
263        for i, e in enumerate(amd_json(["--asic"])):
264            name = ((e.get("asic") or {}).get("market_name") or "").strip()
265            if not name:
266                continue
267            d = drv.get(e.get("gpu"), "")
268            driver = driver or (d if d.upper() not in ("", "N/A") else None)
269            vram = None
270            for dev in glob.glob("/sys/class/drm/card[0-9]*/device"):
271                try:
272                    if bdf.get(e.get("gpu")) and os.path.basename(os.path.realpath(dev)).lower() == bdf[e["gpu"]].lower():
273                        with open(os.path.join(dev, "mem_info_vram_total"), encoding="utf-8") as f:
274                            total = f.read().strip()
275                        vram = int(total) if total.isdigit() else None
276                except OSError:
277                    pass
278            cards.append({"device_index": i, "name": name, "memory_bytes": vram, "memory_kind": "dedicated",
279                          "power_limit_w": None})
280    elif sys.platform == "darwin":
281        chip = cpu_name()
282        if chip:
283            cards = [{"device_index": 0, "name": chip, "memory_bytes": ram_bytes(), "memory_kind": "shared",
284                      "power_limit_w": None}]
285    return 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."""
292    for base in [os.environ.get("ROCM_PATH", ""), "/opt/rocm"]:
293        if not base:
294            continue
295        for sub in (".info/version", "core/.info/version"):
296            try:
297                with open(os.path.join(base, sub), encoding="utf-8") as f:
298                    found = f.read().strip()
299                if found:
300                    return found
301            except OSError:
302                pass
303    match = re.search(r"ROCm version:\s*([\d.]+)", run_cmd(["amd-smi", "-h"]))
304    return 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
309    is lvm -> partition -> disk, two levels down, so the walk goes all the way down."""
310    def disks(item):
311        if item.get("type") == "disk":
312            yield item
313        for child in item.get("children") or []:
314            yield from disks(child)
315
316    for device in data.get("blockdevices") or []:
317        for item in disks(device):
318            rotational = str(item.get("rota")).lower() in ("1", "true")
319            bus = str(item.get("tran") or "unknown").lower()
320            return [{"kind": "hdd" if rotational else ("nvme" if bus == "nvme" else "ssd"),
321                     "model": str(item.get("model") or "unknown").strip(), "bus": bus}]
322    return 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."""
327    if path is None:
328        return None
329    try:
330        path = path.resolve()
331    except OSError:
332        return None
333    if os.name == "nt":
334        letter = path.drive[:1]
335        if not letter.isalpha():
336            return None
337        out = powershell(f"Get-Partition -DriveLetter {letter} | Get-Disk | Get-PhysicalDisk | "
338                         "Select-Object MediaType,FriendlyName,BusType | ConvertTo-Json -Compress")
339        try:
340            data = json.loads(out)
341        except ValueError:
342            return None
343        rows = data if isinstance(data, list) else [data]
344        return [{"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
346    if sys.platform.startswith("linux"):
347        source = run_cmd(["findmnt", "-n", "-o", "SOURCE", "--target", str(path)]).strip()
348        if not source.startswith("/dev/"):
349            return None
350        try:
351            data = json.loads(run_cmd(["lsblk", "-J", "-s", "-o", "NAME,TYPE,ROTA,MODEL,TRAN", source]))
352        except ValueError:
353            return None
354        return lsblk_disk(data)
355    return 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."""
360    def parse(value):
361        if value is None or value == "":
362            return []
363        items = value if isinstance(value, (list, tuple)) else str(value).split(",")
364        return [int(x) for x in (str(i).strip() for i in items) if x.isdigit()]
365    chosen = parse((config or {}).get("gpu"))
366    if not chosen and argv and "--gpu" in argv and argv.index("--gpu") + 1 < len(argv):
367        chosen = parse(argv[argv.index("--gpu") + 1])
368    return chosen
369
370
371def hardware(why: Why, *, selected: list[int], served_gpu: str | None, model_dir: Path | None,
372             declared_background: list[str]) -> tuple[dict, dict]:
373    """-> (the report's `hardware`, the driver and runtime facts the `software` block uses)."""
374    cards, driver, cuda = nvidia_gpus()
375    if not cards:
376        cards, driver = other_gpus()
377    if selected:
378        cards = [c for c in cards if c["device_index"] in selected] or cards
379    elif len(cards) > 1 and served_gpu:
380        named = [c for c in cards if c["name"] == served_gpu]
381        cards = named[:1] or cards[:1]
382    served = [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
385    stub = re.compile(r"(?i)^(amd radeon|advanced micro devices(,? inc\.?)?|nvidia( corporation)?|intel"
386                      r"( corporation)?)( graphics)?$")
387    if served and cards and not all(stub.match(n) for n in served) \
388            and 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)
390        cards = [{"device_index": i, "name": n, "memory_bytes": None, "memory_kind": "dedicated", "power_limit_w": None}
391                 for i, n in enumerate(served)]
392        driver = cuda = None
393    if not cards and served:
394        cards = [{"device_index": i, "name": n, "memory_bytes": None, "memory_kind": "dedicated", "power_limit_w": None}
395                 for i, n in enumerate(served)]
396    gpus = []
397    for i, card in enumerate(cards):
398        gpus.append({k: card.get(k) for k in ("device_index", "name", "memory_bytes", "memory_kind", "power_limit_w")})
399        if gpus[-1]["memory_bytes"] is None:
400            why.add(pointer("hardware", "gpus", i, "memory_bytes"), "the local tools did not report this card's memory")
401        if gpus[-1]["power_limit_w"] is None:
402            why.add(pointer("hardware", "gpus", i, "power_limit_w"), "no power limit available for this card from the local tools")
403    ram = ram_bytes()
404    cpu = cpu_name()
405    drive = storage_of(model_dir)
406    block = {"gpus": gpus, "cpu": cpu, "ram_bytes": ram, "storage": drive,
407             "background_workloads": declared_background or None}
408    if not gpus:
409        why.add(pointer("hardware", "gpus"), "no GPU was found by the local tools or reported by the server")
410    if cpu is None:
411        why.add(pointer("hardware", "cpu"), "the CPU model could not be read")
412    if ram is None:
413        why.add(pointer("hardware", "ram_bytes"), "installed memory could not be read")
414    if drive is None:
415        why.add(pointer("hardware", "storage"), "the drive holding the model files could not be identified")
416    if not declared_background:
417        why.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
421    rocm = rocm_version() if (sys.platform.startswith("linux") and cards and not cuda) else None
422    return block, {"driver": driver, "cuda": cuda, "rocm": rocm}
423
424
425# ------------------------------------------------------------------------------------------------------------ software
426def os_info() -> dict:
427    if os.name == "nt":
428        return {"name": "Windows", "version": sysinfo.version()}
429    if sys.platform == "darwin":
430        return {"name": "macOS", "version": platform.mac_ver()[0] or sysinfo.release()}
431    name = None
432    try:
433        for line in Path("/etc/os-release").read_text().splitlines():
434            if line.startswith("PRETTY_NAME="):
435                name = line.split("=", 1)[1].strip().strip('"')
436    except OSError:
437        pass
438    return {"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."""
443    if (folder / ".git").exists():
444        out = run_cmd(["git", "-C", str(folder), "rev-parse", "HEAD"]).strip().lower()
445        if HEX40.match(out):
446            return out
447    try:
448        text = (folder / "COMMIT").read_text(encoding="utf-8").strip().lower()
449    except OSError:
450        return None
451    return 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."""
457    if not exe:
458        return None
459    try:
460        record = json.loads((Path(exe).parent / "engine-component.json").read_text(encoding="utf-8"))
461    except (OSError, ValueError):
462        return None
463    match = re.search(r"\+(cuda|rocm|hip|sycl)([\d.]+)\Z", str(record.get("build_id") or "")) if isinstance(record, dict) else None
464    return {"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,
468             engine_build: dict | None = None) -> dict:
469    commit = git_commit()
470    runtime = []
471    if engine_build:
472        # the library the engine runs on; nvidia-smi's "CUDA Version" is only the newest one the driver supports
473        runtime.append(engine_build)
474        if machine.get("cuda") and engine_build["name"] == "cuda":
475            runtime.append({"name": "cuda-driver-supports", "version": machine["cuda"]})
476    elif machine.get("cuda"):
477        runtime.append({"name": "cuda", "version": machine["cuda"]})
478    if machine.get("rocm") and not any(r.get("name") == "rocm" for r in runtime):
479        runtime.append({"name": "rocm", "version": machine["rocm"]})
480    if sys.platform == "darwin":
481        runtime.append({"name": "metal", "version": platform.mac_ver()[0] or sysinfo.release()})
482    drivers = [{"name": "gpu-driver", "version": machine["driver"]}] if machine.get("driver") else []
483    block = {"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}
487    if not drivers:
488        why.add("/software/drivers", "no GPU driver version was reported by the local tools")
489    if not runtime:
490        why.add("/software/runtime", "no CUDA, ROCm or Metal runtime version was reported by the local tools")
491    if commit is None:
492        for field in ("strata_commit", "runner_commit"):
493            why.add(f"/software/{field}", "not a git checkout and no COMMIT file in this install; a release must carry its commit")
494    if engine_version is None:
495        why.add("/software/engine_version", "the server reported no engine version (/props build_info, /v1/status engine)")
496    if build_options is None:
497        why.add("/software/build_options", "the server does not report build options; pass --build-options for a source build")
498    return 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."""
508    found: dict[str, Path] = {}
509    for raw in paths:
510        try:
511            path = Path(raw)
512            if not path.is_file() or path.suffix.lower() not in MODEL_SUFFIXES:
513                continue
514        except (OSError, ValueError):
515            continue
516        found[str(path.resolve())] = path
517        match = SHARD.match(path.name)
518        if match:
519            total = int(match.group(3))
520            for index in range(1, total + 1):
521                sibling = path.with_name(f"{match.group(1)}-{index:05d}-of-{match.group(3)}{match.group(4)}")
522                if sibling.is_file():
523                    found[str(sibling.resolve())] = sibling
524    return sorted(found.values(), key=lambda p: p.name)
525
526
527def detect_quantization(names: list[str]) -> str | None:
528    for name in names:
529        match = QUANT.search(name)
530        if match:
531            return match.group(1).upper()
532    return None
533
534
535def model(why: Why, *, props: dict, status: dict, files: list[Path], declared: dict, log) -> dict:
536    served = props.get("model_alias") or status.get("model")
537    rows = []
538    for index, path in enumerate(files):
539        log(f"hashing model file {index + 1}/{len(files)}: {path.name}")
540        rows.append({"path": path.name, "sha256": sha256_file(path)})
541    quant = declared.get("quantization") or detect_quantization([p.name for p in files] + [str(served or "")])
542    block = {"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")}
546    reasons = {"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)"}
552    for field, reason in reasons.items():
553        if block[field] is None:
554            why.add(f"/model/{field}", reason)
555    return 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):
572    if 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)):
573        return re.split(r"[\\/]", value.rstrip("\\/"))[-1]
574    return 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."""
579    options: dict = {}
580    i = 0
581    while i < len(argv):
582        token = str(argv[i])
583        if token.startswith("--"):
584            name, value = (token.split("=", 1) + [None])[:2] if "=" in token else (token, None)
585            if value is None:
586                nxt = argv[i + 1] if i + 1 < len(argv) else None
587                if nxt is not None and not (str(nxt).startswith("--") and not re.fullmatch(r"-?\d+(\.\d+)?", str(nxt))):
588                    value, i = str(nxt), i + 1
589                else:
590                    value = True
591            value = base_if_path(value)
592            if name in options:
593                options[name] = [*(options[name] if isinstance(options[name], list) else [options[name]]), value]
594            else:
595                options[name] = value
596        i += 1
597    return options
598
599
600def configuration(why: Why, *, options: dict | None, env: dict | None, props: dict, declared: dict,
601                  sampling: dict, template_ref: dict | None) -> tuple[dict, dict]:
602    """-> (the report's `configuration`, the engine options no group takes: they go to extensions)."""
603    grouped = {name: {} for name, _ in GROUPS}
604    other = {}
605    for name, value in (options or {}).items():
606        for group, prefixes in GROUPS:
607            if name.startswith(prefixes):
608                grouped[group][name] = value
609                break
610        else:
611            other[name] = value
612    for name, value in sorted((env or {}).items()):
613        if name.startswith("STRATA_") and not SECRET_KEY.search(name):
614            grouped["experimental_options"][name] = base_if_path(str(value))
615    n_ctx = ((props.get("default_generation_settings") or {}).get("n_ctx"))
616    slots = props.get("total_slots")
617    block = {"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"])}
623    if block["context_tokens"] is None:
624        why.add("/configuration/context_tokens", "the server's /props reported no context size")
625    if block["server_capacity"] is None:
626        why.add("/configuration/server_capacity", "the server's /props reported no slot count")
627    if options is None:
628        for name, _ in GROUPS:
629            why.add(f"/configuration/{name}", "engine options are not exposed by a running server; start it from a profile or pass --config")
630    if template_ref is None:
631        why.add("/configuration/template", "the server's /props returned no chat template")
632    return block, other