okami.mom/strata

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

Niko1221Drafting Off in the app: a model saved with Off loads after a restart, and the Models screen shows the saved choice (0.2.15 release test)c77572806

main
16.9 KiB340 linesraw
1"""Read-only inventory of the components a saved run config needs."""
2
3from __future__ import annotations
4
5import csv
6import io
7import json
8import os
9import platform
10from strata_control import sysinfo
11import re
12import shutil
13import subprocess
14import sys
15from importlib import metadata, util
16from pathlib import Path
17
18from strata_control.profiles import read_run_config
19
20
21PATH_FLAGS = {
22    "--pack": "directory",
23    "--native": "file",
24    "--ple-gguf": "file",
25    "--expert-profile": "file",
26    "--mtp": "directory",
27    "--control-vector-scaled": "file_with_scale",
28}
29MONITOR_TEXTUAL_VERSION = "8.2.8"
30
31
32def _location(raw: str, cfg: dict, config_path: Path) -> Path:
33    from strata_control import engine_component
34    if engine_component.is_reference(raw):
35        try:
36            return Path(engine_component.expand(raw, cfg, full=False))
37        except engine_component.EngineMissing:
38            return engine_component.engine_dir() / "(no engine for this PC)"     # reported as missing
39    value = Path(raw).expanduser()
40    if value.is_absolute():
41        return value
42    cwd = cfg.get("cwd")
43    return (Path(cwd) if isinstance(cwd, str) and cwd else config_path.parent) / value
44
45
46def _drafter_is_dflash2(cfg: dict) -> bool:
47    """Does this run config's drafting choice mean DFlash2 on this computer (Auto included)? Never raises."""
48    try:
49        from strata_control import drafting
50        backend, archs = drafting.detect_hardware()
51        return cfg.get("mtp") is not False and drafting.choice_of(cfg.get("drafting"), model_name=cfg.get("model_name"), backend=backend, archs=archs) == "dflash2"
52    except Exception:                                    # noqa: BLE001 - unknown means the MTP, which stays required
53        return False
54
55
56def _drafter_needs_mtp(cfg: dict) -> bool:
57    """Will a start of this run config load the MTP layer? Not when the saved Drafting choice is Off, and not when the choice means DFlash2 (Auto
58    included). Only then is the --mtp folder a required file (0.2.15 release test: an app model saved with Off and no MTP folder was reported as missing
59    "rt" after a restart and could not load). A config that switched the layer off by hand ("mtp": false) is unchanged. Never raises; unknown keeps it
60    required."""
61    try:
62        from strata_control import drafting
63        if drafting.normalize(cfg.get("drafting")) == "off":
64            return False
65    except Exception:                                    # noqa: BLE001 - unknown: decided below
66        pass
67    return not _drafter_is_dflash2(cfg)
68
69
70def _item(name: str, path: Path, kind: str, *, required: bool = True) -> dict:
71    try:
72        if kind == "file":
73            valid = path.is_file() and path.stat().st_size > 0
74        else:
75            valid = path.is_dir()
76    except OSError:
77        valid = False
78    return {"name": name, "status": "ok" if valid else ("missing" if required else "optional_missing"),
79            "path": str(path), "kind": kind, "required": required}
80
81
82def _selected_indices(value: object) -> list[int] | None:
83    if value is None:
84        return None
85    if isinstance(value, str):
86        parts: object = value.split(",")
87    elif isinstance(value, list):
88        parts = value
89    else:
90        parts = [value]
91    if not isinstance(parts, list) or not 1 <= len(parts) <= 64:
92        raise ValueError("GPU selection must contain 1..64 numeric device indices")
93    result = []
94    for part in parts:
95        if type(part) is int and 0 <= part <= 1023:
96            result.append(part)
97        elif isinstance(part, str) and re.fullmatch(r"[0-9]{1,4}", part.strip()) and int(part) <= 1023:
98            result.append(int(part))
99        else:
100            raise ValueError("GPU selection must contain numeric device indices")
101    if len(set(result)) != len(result):
102        raise ValueError("GPU selection repeats a device index")
103    return result
104
105
106def _nvidia_cards() -> tuple[list[dict] | None, str | None]:
107    """One bounded, read-only host query. It does not establish engine compatibility."""
108    tool = shutil.which("nvidia-smi")
109    if tool is None:
110        return None, "nvidia-smi is not installed or is not on PATH"
111    try:
112        result = subprocess.run(
113            [tool, "--query-gpu=index,name,uuid,memory.total,driver_version",
114             "--format=csv,noheader,nounits"], capture_output=True, text=True, errors="replace", timeout=5, check=False,
115        )
116    except (OSError, UnicodeError, subprocess.TimeoutExpired):
117        return None, "nvidia-smi could not complete within five seconds"
118    if result.returncode != 0:
119        return None, "nvidia-smi returned an error"
120    if len(result.stdout) > 65536:
121        return None, "nvidia-smi output exceeded the size limit"
122    cards = []
123    try:
124        for row in csv.reader(io.StringIO(result.stdout)):
125            if len(row) != 5 or len(cards) >= 64:
126                raise ValueError("invalid field count")
127            index_raw, name, uuid, memory_raw, driver = [part.strip() for part in row]
128            unified = memory_raw == "[N/A]" and sysinfo.machine().lower() in ("aarch64", "arm64")   # a DGX Spark's GB10: no separate graphics memory
129            if not (re.fullmatch(r"[0-9]{1,4}", index_raw)
130                    and (unified or re.fullmatch(r"[0-9]{1,9}", memory_raw))
131                    and 0 <= int(index_raw) <= 1023 and (unified or int(memory_raw) > 0)
132                    and 1 <= len(name) <= 128 and 1 <= len(uuid) <= 128
133                    and 1 <= len(driver) <= 64
134                    and all(part.isprintable() for part in (name, uuid, driver))):
135                raise ValueError("invalid card fields")
136            cards.append({"index": int(index_raw), "name": name, "uuid": uuid,
137                          "memory_mib": None if unified else int(memory_raw), "driver_version": driver})
138    except (csv.Error, ValueError):
139        return None, "nvidia-smi returned an unrecognized card list"
140    if not cards or len({card["index"] for card in cards}) != len(cards):
141        return None, "nvidia-smi returned no cards or duplicate device indices"
142    return cards, None
143
144
145def _live_probe(cfg: dict, backend: str) -> tuple[dict, list[dict]]:
146    try:
147        selected = _selected_indices(cfg.get("gpu"))
148    except ValueError as exc:
149        return ({"status": "invalid_selection", "selected_indices": None, "cards": []},
150                [{"code": "GPU_SELECTION_INVALID", "severity": "error", "message": str(exc)}])
151    if backend == "cpu" and selected is None:
152        return {"status": "not_applicable", "selected_indices": None, "cards": []}, []
153    if backend not in ("cuda", "cuda_or_cpu_unverified", "cpu"):
154        return ({"status": "unverified", "selected_indices": selected, "cards": [],
155                 "reason": f"{backend} device numbering needs a qualified live probe"},
156                [{"code": "LIVE_GPU_PROBE_UNAVAILABLE", "severity": "error", "message":
157                  f"{backend} device/driver verification is not implemented for this command"}])
158    cards, reason = _nvidia_cards()
159    if cards is None:
160        severity = "error" if selected is not None or backend == "cuda" else "warning"
161        return ({"status": "unavailable", "selected_indices": selected, "cards": [], "reason": reason},
162                [{"code": "LIVE_GPU_PROBE_UNAVAILABLE", "severity": severity, "message": reason}])
163    available = {card["index"] for card in cards}
164    missing = [index for index in selected or [] if index not in available]
165    issues = ([{"code": "GPU_NOT_VISIBLE", "severity": "error", "message":
166                "selected NVIDIA device indices are not visible: " + ", ".join(map(str, missing))}]
167              if missing else [])
168    return ({"status": "missing_selected" if missing else ("ok" if selected is not None else "selection_unverified"),
169             "selected_indices": selected, "cards": cards,
170             "scope": "host card inventory only; engine execution, CUDA compatibility and topology unverified"}, issues)
171
172
173def inspect(config_path: Path | None, *, profile_id: str | None = None, live: bool = False) -> dict:
174    report = {"schema_version": 1, "profile": profile_id, "source_config": str(config_path) if config_path else None,
175              "components": [], "issues": [], "backend": None, "devices_selected": None,
176              "live_gpu_probe": None}
177    components: list[dict] = report["components"]
178    if config_path is None:
179        report["issues"].append({"code": "PROFILE_NOT_SELECTED", "severity": "info",
180                                 "message": "select a run config or saved profile for model-specific checks"})
181        components.append({"name": "terminal_cli", "status": "ok", "kind": "python_module", "required": True})
182        components.append(_monitor_component())
183        if live:
184            report["issues"].append({"code": "PROFILE_NOT_SELECTED_FOR_LIVE_PROBE", "severity": "error",
185                                     "message": "select a profile to compare its chosen devices with the host"})
186        report["ok"] = not live
187        return report
188
189    cfg = read_run_config(config_path)
190    report["backend"] = cfg.get("backend") or "cuda_or_cpu_unverified"
191    report["devices_selected"] = cfg.get("gpu")
192    exe = _location(cfg["exe"], cfg, config_path)
193    components.append(_item("engine", exe, "file"))
194    if components[-1]["status"] == "ok" and os.name != "nt" and not os.access(exe, os.X_OK):
195        components[-1]["status"] = "invalid"
196        components[-1]["reason"] = "engine file is not executable"
197    build = exe.parent / "BUILD.json"
198    if build.is_file():
199        try:
200            value = json.loads(build.read_text(encoding="utf-8"))
201            if isinstance(value, dict):
202                components[-1]["version"] = value.get("version")
203        except (OSError, ValueError):
204            components[-1]["build_metadata"] = "invalid"
205    else:
206        components[-1]["build_metadata"] = "unavailable"
207
208    tokenizer = _location(cfg["tokenizer"], cfg, config_path)
209    for child in ("vocab.json", "merges.txt", "token_type.json"):
210        components.append(_item(f"tokenizer/{child}", tokenizer / child, "file"))
211
212    args = cfg["args"]
213    for index, arg in enumerate(args):
214        kind = PATH_FLAGS.get(arg)
215        if kind is None:
216            continue
217        if index + 1 >= len(args):
218            components.append({"name": arg, "status": "invalid", "kind": kind,
219                               "required": True, "reason": "missing argument value"})
220            continue
221        raw = args[index + 1]
222        if arg == "--mtp" and str(raw).isdigit():
223            continue                                    # Qwen3.6: --mtp 2 is the draft depth, not a folder (#3298)
224        if kind == "file_with_scale":
225            candidate, separator, scale = raw.rpartition(":")
226            if separator:
227                try:
228                    float(scale)
229                    raw = candidate
230                except ValueError:
231                    pass
232            kind = "file"
233        # The MTP layer is one of two drafters, never both: a model whose drafter is DFlash2, or Off, has no layer on disk, and the run config keeps `--mtp <folder>`
234        # for a later switch to the MTP. Its absence then does not make the model unusable (strata_control/drafting.py loads the drafter that is there).
235        components.append(_item(arg.lstrip("-"), _location(raw, cfg, config_path), kind, required=not (arg == "--mtp" and not _drafter_needs_mtp(cfg))))
236
237    vision = cfg.get("vision")
238    if isinstance(vision, dict):
239        for key in ("exe", "mmproj", "model"):
240            raw = vision.get(key)
241            if isinstance(raw, str) and raw:
242                components.append(_item(f"vision/{key}", _location(raw, cfg, config_path), "file"))
243            else:
244                components.append({"name": f"vision/{key}", "status": "invalid", "kind": "file",
245                                   "required": True, "reason": "missing path"})
246
247    components.append(_monitor_component())
248    driver_name = "rocminfo" if cfg.get("backend") == "hip" else "nvidia-smi"
249    components.append({"name": "gpu_driver_probe", "status": "unverified", "kind": "external_tool",
250                       "required": False, "tool": shutil.which(driver_name),
251                       "reason": "device/driver compatibility needs a live probe on the target host"})
252    for item in components:
253        if item["status"] in ("missing", "invalid") and item["required"]:
254            report["issues"].append({"code": "COMPONENT_" + item["status"].upper(), "severity": "error",
255                                     "component": item["name"], "message": item.get("reason") or "required component unavailable"})
256    access = _device_access_issue(cfg.get("backend"))
257    if access:
258        report["issues"].append(access)
259    cpu_pack = _cpu_pack_issue(cfg, config_path)
260    if cpu_pack:
261        report["issues"].append(cpu_pack)
262    if live:
263        report["live_gpu_probe"], live_issues = _live_probe(cfg, report["backend"])
264        report["issues"].extend(live_issues)
265    report["ok"] = not any(issue["severity"] == "error" for issue in report["issues"])
266    report["integrity"] = "unverified_no_manifest_hashes"
267    return report
268
269
270def _device_access_issue(backend: str | None, dev_root: str = "/dev") -> dict | None:
271    """Linux Intel (SYCL) and AMD (HIP) open the card through /dev/dri/renderD* (and /dev/kfd): a user outside the `render`
272    group gets "No device of requested type available" from the engine, which names nothing to fix. None when it is fine,
273    cannot apply (other OS, other backend) or there is no such device node at all."""
274    if backend not in ("sycl", "hip") or not sys.platform.startswith("linux"):
275        return None
276    nodes = sorted(Path(dev_root, "dri").glob("renderD*"))
277    if backend == "hip" and Path(dev_root, "kfd").exists():
278        nodes.append(Path(dev_root, "kfd"))
279    if not nodes or any(os.access(node, os.R_OK | os.W_OK) for node in nodes):
280        return None
281    return {"code": "GPU_DEVICE_ACCESS", "severity": "warning",
282            "message": f"this user cannot open {', '.join(str(n) for n in nodes)}; the {backend} engine will not see the card. "
283                       "Add the user to the `render` group (and `video` for some distributions), then log in again"}
284
285
286AVX512_FULL = {"avx512f", "avx512bw", "avx512vl", "avx512_vnni", "avx512vbmi"}   # what the Q2_0 pack's CPU kernel uses
287
288
289def _cpu_flags(cpuinfo: str = "/proc/cpuinfo") -> set[str] | None:
290    """The CPU feature flags on Linux; None where they cannot be read (other OS, no /proc)."""
291    if not sys.platform.startswith("linux"):
292        return None
293    try:
294        for line in Path(cpuinfo).read_text(encoding="utf-8", errors="replace").splitlines():
295            if line.startswith("flags"):
296                return set(line.partition(":")[2].split())
297    except OSError:
298        return None
299    return None
300
301
302def _cpu_pack_issue(cfg: dict, config_path: Path, cpuinfo: str = "/proc/cpuinfo") -> dict | None:
303    """The canonical Q2_0 pack (a --pack folder with index.txt and no native_experts.txt) has an AVX-512 CPU kernel; the engine stops at
304    start on any other CPU with "this CPU cannot run the expert kernel". An i-quant, NVFP4 or Unsloth pack (native_experts.txt) runs on AVX2
305    CPUs. None when it is fine, cannot apply (a pack of another engine, a CPU whose flags cannot be read) or there is no such pack."""
306    args = cfg.get("args") or []
307    if "--pack" not in args or args.index("--pack") + 1 >= len(args):
308        return None
309    pack = _location(args[args.index("--pack") + 1], cfg, config_path)
310    if not (pack / "index.txt").is_file() or (pack / "native_experts.txt").exists() or (pack / "ds4.txt").exists():
311        return None
312    flags = _cpu_flags(cpuinfo)
313    if flags is None or AVX512_FULL <= flags:
314        return None
315    return {"code": "CPU_PACK_NEEDS_AVX512", "severity": "warning",
316            "message": f"{pack} is the pack for CPUs with AVX-512 (it has no native_experts.txt), and this CPU has no AVX-512 (Ryzen 3000-5000 and "
317                       "Intel Core 12th-14th generation do not): the engine will stop at start. Run `strata setup` again; on this CPU it builds "
318                       "the pack that runs on AVX2"}
319
320
321def _monitor_component() -> dict:
322    component = {"name": "monitor_tui", "kind": "python_module", "required": False,
323                 "expected_version": MONITOR_TEXTUAL_VERSION}
324    try:
325        found = util.find_spec("textual")
326    except (ImportError, ValueError):
327        found = None
328    if found is None:
329        return {**component, "status": "optional_missing",
330                "reason": "install the optional monitor dependency from requirements-monitor.txt"}
331    try:
332        version = metadata.version("textual")
333    except metadata.PackageNotFoundError:
334        return {**component, "status": "unverified",
335                "reason": "Textual module is present but its installed version is unavailable"}
336    if version != MONITOR_TEXTUAL_VERSION:
337        return {**component, "status": "unverified", "version": version,
338                "reason": f"interactive monitor was qualified with Textual {MONITOR_TEXTUAL_VERSION}"}
339    return {**component, "status": "ok", "version": version,
340            "check": "package_version_only"}