okami.mom/strata

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

Niko1221Merge f-draft-vocab 925d6fb05 into f-p4-int (the draft vocabulary is picked by the computer's languages; a renamed Flash-Next file starts the drafter)bc6f248ff

main
43.7 KiB821 linesraw
1"""Bounded, read-only discovery of setup-written local model run configs.
2
3The setup installer writes strata-*.json beside setup.py. A configured model is
4not automatically a compatible or loadable model: component presence and native
5engine compatibility are reported separately.
6
7Finding an existing install: a terminal archive is a new folder with no run configs in it. The places where Strata
8installs keep run configs (the Terminal's own folder, the folders earlier installs remembered in the user's settings file,
9and the desktop app's install folder, which the Terminal shares) are searched read-only by strata_control/discovery.py,
10the same function the launch screens use; the first place that has any is the main one. Nothing is copied or moved:
11the configs name their engine and model files by absolute path, so the old install and its data folder keep
12serving the models.
13"""
14
15from __future__ import annotations
16
17import hashlib
18import json
19import os
20import re
21import stat
22import sys
23from pathlib import Path
24
25from strata_control import discovery
26from strata_control.doctor import inspect as inspect_components
27from strata_control.gguf_preflight import inspect_metadata, real_model_file
28from strata_control.profiles import ProfileError
29
30
31ROOT = Path(__file__).resolve().parents[1]
32# a dot is allowed inside the name (DeepSeek-V4.1-Flash: "deepseek-v4.1-flash-ist-das-2.00bpw"), never two in a row and never first
33MODEL_ID = re.compile(r"[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,127}\Z")
34MAX_CONFIG_BYTES = 1024 * 1024
35MAX_CONFIGS = 128
36MAX_IMPORT_SHARDS = 128
37SHARD = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z", re.I)
38SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "qwen/IQ3_S",
39                                   "swift/IQ2_XS", "swift/IQ3_XXS", "swift/IQ3_S", "coder/IQ1_M",
40                                   "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "unsloth/UD-Q5_K_XL", "unsloth/UD-Q6_K_XL",
41                                   # round 0214: Unsloth's v3.1 sets (revision d9620119); the v3.1 UD-IQ4_XS has its own name, its Hub file names are UD-IQ4_XS's with four shards
42                                   "unsloth/UD-IQ1_M", "unsloth/UD-Q2_0", "unsloth/UD-IQ2_XS", "unsloth/UD-Q2_K_XL", "unsloth/UD-IQ3_XXS",
43                                   "unsloth/UD-Q3_K_XL", "unsloth/UD-IQ4_XS-v31",
44                                   "unsloth/Q8_0", "gyro/Gyro-S", "gyro/Gyro-M"})
45
46
47def settings_path() -> Path:
48    """The user's Strata settings file: the same place setup.py writes it (%APPDATA%/Strata/settings.json, or
49    $XDG_CONFIG_HOME/strata/settings.json). The desktop app sets STRATA_SETTINGS_FILE to a file of its own (in its data folder), so it
50    never reads an older command-line install's list of Strata folders."""
51    return discovery.own_settings_file()
52
53
54def remembered_installs() -> list[Path]:
55    """Earlier Strata folders recorded in the settings file, newest first. Read-only; a missing or unreadable file
56    is an empty list."""
57    return discovery._installs_in(discovery._read_json(settings_path()))        # noqa: SLF001
58
59
60def _has_configs(directory: Path) -> bool:
61    try:
62        return directory.is_dir() and bool(_paths(directory))
63    except (ProfileError, OSError):
64        return False
65
66
67def resolve_install(override: str | None = None) -> tuple[Path, str]:
68    """(the main install folder, how it was found): explicit (an argument or STRATA_INSTALL_DIR), here (this folder has run
69    configs), remembered (an earlier install from the settings file), app (the desktop app's install folder, shared with the
70    Terminal) or default (the app's folder, with no model in it yet)."""
71    raw = override or os.environ.get("STRATA_INSTALL_DIR")
72    if raw is not None:
73        path = Path(raw).expanduser()
74        if not path.is_absolute() or not path.is_dir():
75            raise ProfileError("install directory must be an existing absolute directory", 5)
76        return path.resolve(), "explicit"
77    return discovery.find_install(here=ROOT)
78
79
80def all_installs(override: str | None = None) -> list[tuple[Path, str]]:
81    """Every folder with run configs, main one first: what `strata models list` shows and what the launch screens read."""
82    directory, source = resolve_install(override)
83    if source == "explicit":
84        return [(directory, source)]
85    found = [(p.path, p.source) for p in discovery.places(here=ROOT)]
86    return found or [(directory, source)]
87
88
89def install_dir(override: str | None = None) -> Path:
90    return resolve_install(override)[0]
91
92
93def _model_id(path: Path) -> str | None:
94    if not path.name.startswith("strata-") or not path.name.endswith(".json") or \
95            path.name.endswith(".shared-settings.json"):
96        return None
97    value = path.name[len("strata-"):-len(".json")]
98    return value if MODEL_ID.fullmatch(value) else None
99
100
101def _paths(directory: Path) -> list[tuple[str, Path]]:
102    try:
103        entries = [(name, path) for path in directory.iterdir() if (name := _model_id(path)) is not None]
104    except OSError:
105        raise ProfileError("cannot read installed model directory", 5) from None
106    if len(entries) > MAX_CONFIGS:
107        raise ProfileError("more than 128 model configs need inspection", 5)
108    return sorted(entries, key=lambda item: item[0])
109
110
111def _read(path: Path) -> tuple[bytes, dict]:
112    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
113    try:
114        if stat.S_ISLNK(path.lstat().st_mode):
115            raise ProfileError("run config must not be a symlink", 5)
116        descriptor = os.open(path, flags)
117        with os.fdopen(descriptor, "rb") as stream:
118            details = os.fstat(stream.fileno())
119            if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_CONFIG_BYTES:
120                raise ProfileError("run config must be a regular file under 1 MiB", 5)
121            raw = stream.read(MAX_CONFIG_BYTES + 1)
122        if len(raw) > MAX_CONFIG_BYTES:
123            raise ProfileError("run config exceeds 1 MiB", 5)
124        value = json.loads(raw.decode("utf-8-sig"))
125    except (OSError, UnicodeError, ValueError) as exc:
126        if isinstance(exc, ProfileError):
127            raise
128        raise ProfileError("run config is unreadable or invalid JSON", 5) from None
129    if not isinstance(value, dict) or not isinstance(value.get("exe"), str) or not value["exe"] or \
130            not isinstance(value.get("tokenizer"), str) or not value["tokenizer"] or \
131            not isinstance(value.get("args"), list) or \
132            not all(isinstance(arg, str) for arg in value["args"]):
133        raise ProfileError("run config lacks engine, tokenizer or string arguments", 5)
134    return raw, value
135
136
137def _short(value: object) -> str | None:
138    if not isinstance(value, str):
139        return None
140    return "".join(char if char.isprintable() and char not in "\x1b\x7f" else " " for char in value)[:120]
141
142
143def _arg(args: list[str], flag: str) -> str | None:
144    try:
145        index = args.index(flag)
146        return args[index + 1] if index + 1 < len(args) else None
147    except ValueError:
148        return None
149
150
151def _missing_parts(report: dict) -> list[dict]:
152    """The required parts a model's run config names that are not there: {"part": the component, "file": its file or folder name,
153    "status": "missing" | "invalid"}. The app names them so a person is not told only that "some files are missing" (#3478)."""
154    found = []
155    for item in report.get("components", []):
156        if item.get("required") and item.get("status") in ("missing", "invalid"):
157            where = item.get("path")
158            found.append({"part": _short(item.get("name")), "file": _short(os.path.basename(str(where).rstrip("/\\"))) if where else None,
159                          "status": item["status"]})
160    return found[:12]
161
162
163def _summary(model_id: str, path: Path, raw: bytes, cfg: dict, report: dict) -> dict:
164    context = _arg(cfg["args"], "--max-context")
165    context_tokens = int(context) if isinstance(context, str) and 1 <= len(context) <= 8 and \
166        context.isascii() and context.isdecimal() and 1 <= int(context) <= 16_777_216 else None
167    backend = cfg.get("backend")
168    return {"id": model_id, "name": _short(cfg.get("model_name")) or model_id,
169            "source_config": str(path), "source_sha256": hashlib.sha256(raw).hexdigest(),
170            "backend": _short(backend) if backend is not None else None,
171            "context_tokens": context_tokens,
172            "component_status": "present" if report["ok"] else "missing_or_invalid",
173            "issue_codes": [item.get("code") for item in report["issues"]][:32],
174            "missing": _missing_parts(report),
175            "execution_compatibility": "unverified"}
176
177
178def _inspect_one(model_id: str, path: Path) -> tuple[dict, dict]:
179    raw, cfg = _read(path)
180    from strata_control import retired
181    if retired.config_reason(cfg) or retired.config_file_reason(path):
182        # DeepSeek: listed so the person sees it and where its files are, never inspected, started or written (strata_control/retired.py)
183        report = {"ok": False, "issues": []}
184        summary = _summary(model_id, path, raw, cfg, report)
185        summary.update(component_status="retired", retired="deepseek", name=retired.title(cfg, path), retired_line=retired.row_line(cfg),
186                       refusal=retired.refusal(cfg, retired.title(cfg, path)), execution_compatibility="retired")
187        return summary, report
188    try:
189        report = inspect_components(path)
190        after, _ = _read(path)
191    except (OSError, ValueError):
192        raise ProfileError("run config changed or became invalid during inspection", 6) from None
193    if after != raw:
194        raise ProfileError("run config changed during inspection; retry", 6)
195    return _summary(model_id, path, raw, cfg, report), report
196
197
198def list_installed(override: str | None = None) -> dict:
199    directory, source = resolve_install(override)
200    places = all_installs(override)
201    models = []
202    for place, place_source in places:
203        try:
204            entries = _paths(place) if place.is_dir() else []
205        except ProfileError as exc:
206            models.append({"id": place.name, "install_dir": str(place), "component_status": "invalid", "error": str(exc),
207                           "execution_compatibility": "unverified"})
208            continue
209        for model_id, path in entries:
210            if any(m.get("id") == model_id for m in models):
211                continue                                   # the same model in a later place: the main one wins
212            try:
213                summary, _ = _inspect_one(model_id, path)
214            except ProfileError as exc:
215                summary = {"id": model_id, "source_config": str(path), "component_status": "invalid",
216                           "error": str(exc), "execution_compatibility": "unverified"}
217            summary["install_dir"] = str(place)
218            summary["install_dir_source"] = place_source
219            models.append(summary)
220    return {"scope": "local_run_configs", "install_dir": str(directory), "install_dir_source": source,
221            "install_dirs": [str(p) for p, _ in places],
222            "models": models,
223            "model_count": len(models), "discovery_limit": MAX_CONFIGS}
224
225
226def inspect(model_id: str, override: str | None = None) -> dict:
227    if not isinstance(model_id, str) or not MODEL_ID.fullmatch(model_id):
228        raise ProfileError("model ID must be a setup config name without a path")
229    directory, path = None, None
230    for place, _src in all_installs(override):
231        try:
232            choices = dict(_paths(place)) if place.is_dir() else {}
233        except ProfileError:
234            continue
235        if model_id in choices:
236            directory, path = place, choices[model_id]
237            break
238    if path is None:
239        raise ProfileError(f"model {model_id!r} is not configured in this installation", 5)
240    summary, report = _inspect_one(model_id, path)
241    return {"scope": "local_run_config", "install_dir": str(directory), "model": summary,
242            "components": report}
243
244
245def _gguf_header(path: Path) -> dict:
246    """The first bytes of one model file (a link to it is followed: Hugging Face cache snapshots and Ollama blobs are links)."""
247    real = real_model_file(path)
248    try:
249        descriptor = os.open(real, os.O_RDONLY)
250        with os.fdopen(descriptor, "rb") as stream:
251            details = os.fstat(stream.fileno())
252            if not stat.S_ISREG(details.st_mode) or details.st_size < 8:
253                raise ProfileError("GGUF shard is not a nonempty regular file", 5)
254            header = stream.read(8)
255    except OSError:
256        raise ProfileError("GGUF shard is unreadable", 5) from None
257    if header[:4] != b"GGUF":
258        raise ProfileError("file does not begin with a GGUF header", 5)
259    version = int.from_bytes(header[4:8], "little")
260    if version not in (2, 3):
261        raise ProfileError("GGUF header version is not recognized", 5)
262    return {"name": path.name, "path": str(path), "bytes": details.st_size,
263            "gguf_version": version}
264
265
266def _candidate_selection(shards: list[Path]) -> dict | None:
267    fingerprint_file = ROOT / "data" / "gguf_fingerprints.json"
268    try:
269        if fingerprint_file.stat().st_size > 128 * 1024:
270            raise ProfileError("model fingerprint catalog exceeds 128 KiB", 5)
271        catalog = json.loads(fingerprint_file.read_text(encoding="utf-8"))
272    except (OSError, UnicodeError, ValueError):
273        raise ProfileError("model fingerprint catalog is unavailable", 5) from None
274    names = {item.name for item in shards}
275    for selection in sorted(SUPPORTED_SELECTIONS):
276        row = catalog.get(selection) if isinstance(catalog, dict) else None
277        expected = row.get("files") if isinstance(row, dict) else None
278        if isinstance(expected, list) and expected and names == {Path(name).name for name in expected}:
279            family, model = selection.split("/", 1)
280            expected_experts = row.get("expert_bytes")
281            return {"family": family, "model": model, "basis": "known_shard_names_only",
282                    "expected_expert_types": sorted(expected_experts) if isinstance(expected_experts, dict) else [],
283                    "expected_tensor_count": row.get("tensors") if type(row.get("tensors")) is int else None,
284                    "setup_args_hint": ["--family", family, "--model", model,
285                                        "--gguf-dir", str(shards[0].parent)]}
286    return None
287
288
289def _candidate_by_header(shards: list[Path], tensors: int, payload: int, experts: set[str]) -> dict | None:
290    """A file set whose NAME setup does not know (renamed, or downloaded elsewhere) but whose header is exactly a known one: the same tensor
291    count, the same payload size and the same expert formats as a row of the fingerprint table."""
292    try:
293        catalog = json.loads((ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))
294    except (OSError, UnicodeError, ValueError):
295        return None
296    for selection in sorted(SUPPORTED_SELECTIONS):
297        row = catalog.get(selection) if isinstance(catalog, dict) else None
298        if not isinstance(row, dict) or row.get("tensors") != tensors or row.get("bytes") != payload:
299            continue
300        expected = row.get("expert_bytes")
301        if not isinstance(expected, dict) or set(expected) != experts:
302            continue
303        family, model = selection.split("/", 1)
304        return {"family": family, "model": model, "basis": "header_size_and_tensors",
305                "expected_expert_types": sorted(expected), "expected_tensor_count": tensors,
306                "setup_args_hint": ["--family", family, "--model", model, "--gguf-dir", str(shards[0].parent)]}
307    return None
308
309
310def known_set_by_header(first_shard: Any) -> str | None:
311    """``family/model`` (``qwen/IQ3_S``, ``unsloth/UD-Q4_K_XL``) of the file set that starts at ``first_shard`` when its header is EXACTLY one row of data/gguf_fingerprints.json: the same tensor count,
312    the same payload size and the same expert formats over every shard (the other shards are found beside the first by their ``-00001-of-0000N`` names). Never the layout guess of
313    ``_candidate_by_layout``. None: no exact match, a shard missing, or a file that cannot be read."""
314    try:
315        path = Path(first_shard)
316        match = SHARD.match(path.name)
317        if match:
318            total = int(match.group(3))
319            if not 1 <= total <= MAX_IMPORT_SHARDS:
320                return None
321            shards = [path.with_name(f"{match.group(1)}-{i:05d}-of-{total:05d}.gguf") for i in range(1, total + 1)]
322            if not all(p.is_file() for p in shards):
323                return None
324        else:
325            shards = [path]
326        tensors = payload = 0
327        experts: set[str] = set()
328        for number, item in enumerate(shards):
329            inspected = inspect_metadata(item)
330            # the first shard names the architecture; a later shard of a split set (llama.cpp's gguf-split, Strata's own IQ3_S) carries tensors only: no architecture is no objection, another one is
331            if inspected["architecture"] != "qwen4exp" and (number == 0 or inspected["architecture"] is not None):
332                return None
333            experts.update(inspected["expert_tensor_types"])
334            tensors += inspected["tensor_count_scanned"]
335            payload += int(inspected.get("payload_bytes_required") or 0)
336        found = _candidate_by_header(shards, tensors, payload, experts)
337        return f"{found['family']}/{found['model']}" if found else None
338    except Exception:                         # noqa: BLE001 - a file that cannot be judged is not matched
339        return None
340
341
342def _candidate_by_layout(shards: list[Path], tensors: int, payload: int, experts: set[str]) -> dict | None:
343    """A qwen4exp file set that is no build Strata has tested (a fine-tune, a K-quant mix from another maker) but has the layout of one
344    (#3651 #3777): the closest row by expert formats, then by size. Strata uses the files as that model and says so; it never refuses a
345    working file for not being on the list (recommend, never force)."""
346    try:
347        catalog = json.loads((ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))
348    except (OSError, UnicodeError, ValueError):
349        return None
350    best = None
351    for selection in sorted(SUPPORTED_SELECTIONS):
352        row = catalog.get(selection) if isinstance(catalog, dict) else None
353        if not isinstance(row, dict) or row.get("tensors") != tensors or not isinstance(row.get("expert_bytes"), dict):
354            continue
355        have = set(row["expert_bytes"])
356        union = have | experts
357        score = (len(have & experts) / len(union)) if union else 0.0
358        key = (-score, abs(int(row.get("bytes") or 0) - payload), selection)
359        if score > 0 and (best is None or key < best[0]):
360            best = (key, selection, have)
361    if best is None:
362        return None
363    family, model = best[1].split("/", 1)
364    return {"family": family, "model": model, "basis": "same_layout_other_build",
365            "expected_expert_types": sorted(best[2] | experts), "expected_tensor_count": tensors,
366            "setup_args_hint": ["--family", family, "--model", model, "--gguf-dir", str(shards[0].parent)]}
367
368
369def _already_set_up(shards: list[Path], candidate: dict | None) -> dict | None:
370    """Is this model already installed (a run config of any known install names the file) and what was prepared beside it (pack, draft
371    layer, picture reader)? Read-only; None when the file set is not one Strata knows."""
372    if not shards or candidate is None:
373        return None
374    first = shards[0]
375    cfg = discovery.run_config_for(first, discovery.places(here=ROOT))
376    beside = discovery.prepared_beside(first, discovery.remembered_data_dirs())     # the data folder in use too: a model folder outside it must not hide the draft layer setup wrote there
377    if cfg is None and not any(beside.get(k) for k in ("pack", "mtp", "mmproj")):
378        return {"config": None, "data_dir": str(beside["data_dir"]) if beside.get("data_dir") else None, "pack": None, "mtp": None, "mmproj": None}
379    return {"config": str(cfg) if cfg else None, **{k: (str(v) if v else None) for k, v in beside.items()}}
380
381
382ISSUE_WORDS = {
383    "multiple_model_groups": "the folder holds more than one model",
384    "incomplete_or_invalid_shard_set": "some parts of the model are missing",
385    "unrecognized_or_unsupported_model_variant": "this is not a model size Strata knows",
386    "unsupported_or_missing_architecture": "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)",
387    "unsupported_or_incomplete_tokenizer_metadata": "the file has no usable tokenizer",
388    "missing_or_unexpected_expert_quantization": "its quantization is not one Strata knows",
389}
390# the checker's own sentences about one file, in words
391_REASON_WORDS = (
392    ("not a nonempty regular file", "the file is empty or is not a file"),
393    ("unreadable", "the file cannot be read (is it open in another program, or on a drive that is gone?)"),
394    ("could not be read", "the file cannot be read (is it open in another program, or on a drive that is gone?)"),
395    ("is missing", "the file is not there"),
396    ("link to a file that is not there", "this is a shortcut to a file that is not there any more"),
397    ("does not begin with a gguf header", "this is not a GGUF model file"),
398    ("header version", "this GGUF is from a format Strata does not read"),
399    ("requires gguf v3", "this GGUF is in an old format (version 2); Strata reads version 3"),
400    ("metadata is truncated", "the file is cut short (a download or copy that did not finish)"),
401    ("payload is shorter", "the file is shorter than its own header says (a download or copy that did not finish)"),
402    ("exceeds the bounded inspection limit", "its header is larger than Strata reads"),
403    ("too large to inspect", "its header is larger than Strata reads"),
404    ("unsupported encoding or shape", "it stores weights in a format Strata does not read"),
405    ("unsupported array type", "its header uses a type Strata does not read"),
406    ("unsupported value type", "its header uses a type Strata does not read"),
407    ("byte ranges overlap", "its header is damaged"),
408    ("unsupported_architecture", "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)"),
409    ("symlink", "this is a shortcut (symbolic link) that cannot be followed"),
410)
411
412
413def plain_issue(code: str) -> str:
414    """One problem from the GGUF preview, in words, with the file's name when it is about one file
415    (`file.gguf: GGUF shard is not a nonempty regular file`)."""
416    code = str(code)
417    if code in ISSUE_WORDS:
418        return ISSUE_WORDS[code]
419    name, sep, reason = code.partition(": ")
420    if not (sep and name.lower().endswith(".gguf")):
421        name, reason = "", code
422    low = reason.lower()
423    words = next((w for key, w in _REASON_WORDS if key in low), reason.replace("_", " "))
424    return f"{name}: {words}" if name else words
425
426
427def missing_words(missing: list | None) -> str:
428    """"x-00002-of-00002.gguf is missing" for the shards of a split model that are not in the folder (#3478); "" when none are known."""
429    names = [str(n) for n in missing or []]
430    if not names:
431        return ""
432    if len(names) == 1:
433        return f"{names[0]} is missing"
434    if len(names) == 2:
435        return f"{names[0]} and {names[1]} are missing"
436    return f"{names[0]}, {names[1]} and {len(names) - 2} more files are missing"
437
438
439def problem_words(issues: list, limit: int = 3, missing: list | None = None) -> str:
440    """The problems of a file set as ONE sentence part, each said once: the same reason for several files names the files together
441    ("a.gguf and b.gguf: the file is cut short"), a reason that was already given is not given again, and a long list is cut with a count.
442    A folder that holds several models does not also say "not a size Strata knows"."""
443    codes = [str(x) for x in issues or []]
444    named = missing_words(missing)
445    if named:                                                # the generic "some parts are missing" is replaced by the files
446        codes = [x for x in codes if x != "incomplete_or_invalid_shard_set"]
447    if "multiple_model_groups" in codes:
448        codes = [x for x in codes if x != "unrecognized_or_unsupported_model_variant"]
449    by_reason: dict[str, list[str]] = {}
450    for code in codes:
451        words = plain_issue(code)
452        name, sep, reason = words.partition(": ")
453        if sep and name.lower().endswith(".gguf"):
454            by_reason.setdefault(reason, []).append(name)
455        else:
456            by_reason.setdefault(words, [])
457    parts = [named] if named else []
458    for reason, names in by_reason.items():
459        if not names:
460            parts.append(reason)
461        elif len(names) <= 2:
462            parts.append(f"{' and '.join(names)}: {reason}")
463        else:
464            parts.append(f"{names[0]}, {names[1]} and {len(names) - 2} more files: {reason}")
465    if len(parts) > limit:
466        parts = parts[:limit] + [f"and {len(parts) - limit} more problem" + ("s" if len(parts) - limit > 1 else "")]
467    return "; ".join(parts)
468
469
470UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. "
471                          "Add it as a Custom model API (llama-server) instead.")
472# The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model).
473# (name, size in bytes) as setup.py pins them: setup would delete a file of that name with another size, so only an exact
474# match is called "the official one".
475PINNED_PROJECTORS = {"mmproj-qwen3.8-flash-next-bf16.gguf": 907543008, "mmproj-f16.gguf": 899283584}
476OUR_PROJECTOR_TYPES = {"qwen3vl_merger"}
477
478
479def _assess_projector(path: Path) -> dict:
480    """What a picture-reader file (mmproj*.gguf) next to a model is, in words; never blocks the import."""
481    try:
482        size = path.stat().st_size
483    except OSError:
484        size = -1
485    row = {"name": path.name, "status": "unreadable", "pinned": PINNED_PROJECTORS.get(path.name.lower()) == size}
486    try:
487        info = inspect_metadata(path)
488    except ProfileError:
489        row["plain"] = f"{path.name} could not be read as a picture reader, so it is not used."
490        return row
491    row["architecture"], row["projector_type"] = info["architecture"], info.get("projector_type")
492    if info["architecture"] != "clip":
493        row["status"] = "not_a_projector"
494        row["plain"] = f"{path.name} is not a picture reader (mmproj) file, so it is not used."
495    elif info.get("projector_type") not in OUR_PROJECTOR_TYPES:
496        row["status"] = "unsupported"
497        row["plain"] = (f"{path.name} reads pictures for a different kind of model. "
498                        "Strata cannot use it; add that model as a Custom model API (llama-server) instead.")
499    elif row["pinned"]:
500        row["status"] = "ok"
501        row["plain"] = f"{path.name} is the picture reader Strata uses for this model family; pictures will work."
502    else:
503        row["status"] = "other_name"
504        row["plain"] = (f"{path.name} is a picture reader of the right kind but not the file Strata checks; "
505                        "Strata uses the official one (mmproj-Qwen3.8-Flash-Next-BF16.gguf) and "
506                        "downloads it when it is not in the folder.")
507    return row
508
509
510MAX_LISTED = 5000            # .gguf files looked at in one folder (the checker reads headers of the chosen set only)
511MAX_TREE_DIRS = 300          # folders looked into when the picked folder holds no GGUF itself
512TREE_DEPTH = 3
513SKIP_DIRS = frozenset({"packs", "mtp", "engine", "node_modules", "windows", "program files", "program files (x86)",
514                       "$recycle.bin", "system volume information", "appdata"})
515
516
517DRAFT_LAYER = re.compile(r"mtp[-_][a-z0-9_.-]*\.gguf")
518
519
520def _list_gguf(folder: Path) -> tuple[list[Path], list[str], bool]:
521    """(model files, picture-reader file names, cut) of one folder. A link to a file counts (it is followed when read); a name that
522    only ends in .gguf but is a folder does not."""
523    shards: list[Path] = []
524    readers: list[str] = []
525    cut = False
526    try:
527        with os.scandir(folder) as entries:
528            for entry in entries:
529                low = entry.name.lower()
530                if not low.endswith(".gguf"):
531                    continue
532                try:
533                    is_file = entry.is_file() or entry.is_symlink()
534                except OSError:
535                    is_file = False
536                if not is_file:
537                    continue
538                if low.startswith("mmproj"):
539                    readers.append(entry.name)
540                    continue
541                if DRAFT_LAYER.fullmatch(low):
542                    continue                          # Strata's own draft layer (mtp-q2_0.gguf) is not a second model (#4693)
543                if len(shards) >= MAX_LISTED:
544                    cut = True
545                    break
546                shards.append(Path(entry.path))
547    except OSError:
548        raise ProfileError("cannot inspect GGUF directory", 5) from None
549    return shards, readers, cut
550
551
552def _folders_with_models(root: Path) -> list[Path]:
553    """The folders under `root` (a Strata data folder, a whole Hugging Face repository, a drive's model folder) that hold model files,
554    breadth first, `TREE_DEPTH` levels deep. A folder with models is not searched further."""
555    found: list[Path] = []
556    seen: set[str] = set()
557    queue = [(root, 0)]
558    while queue and len(seen) < MAX_TREE_DIRS:
559        folder, depth = queue.pop(0)
560        try:
561            key = os.path.normcase(os.path.realpath(folder))
562        except OSError:
563            continue
564        if key in seen:
565            continue
566        seen.add(key)
567        try:
568            with os.scandir(folder) as scan:
569                entries = sorted(scan, key=lambda e: e.name.lower())
570        except OSError:
571            continue
572        if any(e.name.lower().endswith(".gguf") and not e.name.lower().startswith("mmproj") for e in entries):
573            found.append(folder)
574            continue
575        if depth >= TREE_DEPTH:
576            continue
577        for e in entries:
578            try:
579                if e.is_dir() and not e.name.startswith(".") and e.name.lower() not in SKIP_DIRS:
580                    queue.append((Path(e.path), depth + 1))
581            except OSError:
582                continue
583    return found
584
585
586def _split_groups(shards: list[Path]) -> dict:
587    """Model files by set: (name before -0000i-of-0000N, N) -> files. A file with no shard number is a set of its own."""
588    groups: dict = {}
589    for item in shards:
590        match = SHARD.fullmatch(item.name)
591        key = (match.group(1), int(match.group(3))) if match else (item.name, 1)
592        groups.setdefault(key, []).append(item)
593    return groups
594
595
596def _known(members: list[Path]) -> dict | None:
597    try:
598        return _candidate_selection(sorted(members, key=lambda item: item.name))
599    except ProfileError:
600        return None
601
602
603def _holds(groups_by_place: list) -> list[dict]:
604    """What a folder (or several) holds, set by set, for the message that asks the person to point at one."""
605    rows = []
606    for place, members_by_key in groups_by_place:
607        for key in sorted(members_by_key):
608            members = sorted(members_by_key[key], key=lambda item: item.name)
609            sel = _known(members)
610            rows.append({"file": members[0].name, "files": len(members), "folder": str(place),
611                         "family": sel["family"] if sel else None, "model": sel["model"] if sel else None})
612    return rows
613
614
615def absolute(picked: str) -> str:
616    """The picked path as an absolute path, links left alone (a snapshot file in the Hugging Face cache keeps its model name)."""
617    return os.path.abspath(os.path.expanduser(str(picked)))
618
619
620def import_target(picked: str, plan: dict) -> str:
621    """What to hand on as the person's model files: the file when they picked a file (a folder of several sizes needs the name), else the
622    folder the model files are really in (they may have picked the folder above it)."""
623    picked = absolute(picked)
624    try:
625        if Path(picked).is_file():
626            return picked
627    except OSError:
628        pass
629    return plan.get("model_dir") or picked
630
631
632def own_path_problem(picked: str) -> tuple[str, str] | None:
633    """(what is wrong, what to do) when the path a person gave for their own model files is not there or holds no model file, in plain
634    words; None when there is something to look at. Said before anything is installed or downloaded, with the path the person typed."""
635    path = Path(absolute(picked))
636    kind = "file" if path.name.lower().endswith(".gguf") else "folder"
637    try:
638        if not path.exists():
639            if path.is_symlink():
640                return (f"This {kind} is a shortcut to something that is not there any more: {path}.",
641                        "Point it at the real folder, or at the .gguf file itself. Nothing was downloaded or changed.")
642            return (f"This {kind} does not exist: {path}.",
643                    "Check the spelling, and that the drive or folder is connected (in Docker or a virtual machine it has to be shared with it). "
644                    "Nothing was downloaded or changed.")
645        if path.is_dir():
646            has_files = any(entry.name.lower().endswith(".gguf") for entry in os.scandir(path))
647            if not has_files and not _folders_with_models(path):
648                return (f"There are no .gguf model files in {path}, nor in the folders inside it.",
649                        "Point it at the folder that holds the model's .gguf files (names like ...-00001-of-00002.gguf), or at one of the files. "
650                        "Nothing was downloaded or changed.")
651    except OSError:
652        return None
653    return None
654
655
656def plan_import(raw_path: str) -> dict:
657    """Inspect a local candidate without copying, parsing tensors or adopting it.
658
659    The picked path can be a .gguf file (any shard of a split set), the folder with the files, or a folder above it (a Strata data
660    folder, a whole Hugging Face repository): the folder with the model is looked for, and when a folder holds several models
661    the one Strata knows is used if it is the only one; with two it says which and asks for the file. The result's `model_dir`
662    is the folder to hand to setup (--gguf-dir). Links to files and folders are followed."""
663    path = Path(raw_path).expanduser()
664    if not path.is_absolute():
665        raise ProfileError("model import path must be absolute")
666    try:
667        details = path.stat()
668    except OSError:
669        raise ProfileError("model import path does not exist (or is a link to something that is gone)", 5) from None
670    from strata_control import retired
671    if retired.folder_reason(path):                    # DeepSeek files: named, never set up (strata_control/retired.py)
672        raise ProfileError(retired.own_files(path), 5)
673    notes: list[str] = []
674    folder_holds: list[dict] = []
675    issues: list[str] = []
676    missing_shards: list[str] = []
677    if stat.S_ISDIR(details.st_mode):
678        shards, ignored_auxiliary, cut = _list_gguf(path)
679        if cut:
680            notes.append(f"This folder holds more than {MAX_LISTED} GGUF files; only the first {MAX_LISTED} were looked at.")
681        if not shards:
682            places = _folders_with_models(path)
683            if not places:
684                raise ProfileError("no GGUF files found at the model import path (or in the folders inside it)", 5)
685            scanned = [(place, *_list_gguf(place)[:2]) for place in places]
686            usable = [(place, files, readers, members) for place, files, readers in scanned
687                      for _key, members in sorted(_split_groups(files).items(), key=lambda kv: kv[0]) if _known(members)]
688            if len(usable) == 1:
689                place, shards, ignored_auxiliary, members = usable[0]
690                notes.append(f"The model files are in {place}.")
691            else:
692                place, shards, ignored_auxiliary = scanned[0]
693                if len(usable) > 1 or len(scanned) > 1:
694                    issues.append("multiple_model_groups")
695                    folder_holds = _holds([(p, _split_groups(f)) for p, f, _r in scanned])
696                else:
697                    notes.append(f"The model files are in {place}.")
698    elif stat.S_ISREG(details.st_mode) and path.name.lower().endswith(".gguf"):
699        ignored_auxiliary = []
700        try:                       # the picture reader that sits next to a chosen model file
701            ignored_auxiliary = [c.name for c in path.parent.iterdir()
702                                 if c.name.lower().startswith("mmproj") and c.name.lower().endswith(".gguf")][:8]
703        except OSError:
704            pass
705        if path.name.lower().startswith("mmproj"):
706            raise ProfileError("this is a picture reader (mmproj), not a model. Choose the model's own "
707                               ".gguf file; Strata finds the reader next to it", 5)
708        match = SHARD.fullmatch(path.name)
709        if match:
710            total = int(match.group(3))
711            if not 1 <= total <= MAX_IMPORT_SHARDS:
712                raise ProfileError("GGUF shard count must be in 1..128", 5)
713            shards = [path.with_name(f"{match.group(1)}-{i:05d}-of-{total:05d}.gguf")
714                      for i in range(1, total + 1)]
715        else:
716            shards = [path]
717    else:
718        raise ProfileError("model import needs a GGUF file or directory", 5)
719    if not shards:
720        raise ProfileError("no GGUF files found at the model import path", 5)
721    shards.sort(key=lambda item: item.name)
722    groups = _split_groups(shards)
723    if len(groups) != 1 and "multiple_model_groups" not in issues:
724        known_sets = [key for key, members in groups.items() if _known(members)]
725        if len(known_sets) == 1:
726            # one set in the folder is a model Strata knows: use it and say what else is there
727            keep = known_sets[0]
728            others = sorted(sorted(m, key=lambda x: x.name)[0].name for k, m in groups.items() if k != keep)
729            shards = sorted(groups[keep], key=lambda item: item.name)
730            notes.append("The folder also holds " + ", ".join(others[:6]) + (" and more" if len(others) > 6 else "") +
731                         f"; Strata uses {shards[0].name} and leaves the others alone.")
732            groups = {keep: shards}
733        else:
734            issues.append("multiple_model_groups")
735            folder_holds = _holds([(shards[0].parent, groups)])
736    if len(groups) == 1 and "multiple_model_groups" not in issues:
737        (_, total), members = next(iter(groups.items()))
738        found = {int(m.group(2)) for m in (SHARD.fullmatch(item.name) for item in members) if m} or {1}
739        if total > MAX_IMPORT_SHARDS or found != set(range(1, total + 1)):
740            issues.append("incomplete_or_invalid_shard_set")
741            sample = next((SHARD.fullmatch(item.name) for item in members if SHARD.fullmatch(item.name)), None)
742            if sample and total <= MAX_IMPORT_SHARDS:        # #3478: name the files that are not there
743                missing_shards = [f"{sample.group(1)}-{i:05d}-of-{total:05d}.gguf" for i in range(1, total + 1) if i not in found]
744    files = []
745    for item in shards:
746        if missing_shards and not item.exists():
747            continue                                         # a shard that is named only to be reported missing has no header to read
748        try:
749            files.append(_gguf_header(item))
750        except ProfileError as exc:
751            issues.append(f"{item.name}: {exc}")
752    metadata = None
753    observed_experts: set[str] = set()
754    observed_tensor_count = 0
755    observed_payload = 0
756    if files and not issues:
757        for item in shards:
758            try:
759                inspected = inspect_metadata(item)
760            except ProfileError as exc:
761                issues.append(f"{item.name}: {exc}")
762                continue
763            if metadata is None:
764                metadata = inspected
765            observed_experts.update(inspected["expert_tensor_types"])
766            observed_tensor_count += inspected["tensor_count_scanned"]
767            observed_payload += int(inspected.get("payload_bytes_required") or 0)
768            if inspected["architecture"] is not None and inspected["architecture"] != "qwen4exp":
769                issues.append(f"{item.name}: unsupported_architecture")
770    if metadata is not None:
771        if metadata["architecture"] != "qwen4exp":
772            issues.append("unsupported_or_missing_architecture")
773        if metadata["tokenizer_model"] != "gpt2" or not metadata["tokenizer_tokens_present"] or \
774                not metadata["tokenizer_merges_present"]:
775            issues.append("unsupported_or_incomplete_tokenizer_metadata")
776    model_dir = shards[0].parent
777    projectors = [_assess_projector(model_dir / n) for n in sorted(ignored_auxiliary)[:8]]
778    messages = list(notes)
779    if folder_holds:
780        several = len({h.get("folder") for h in folder_holds}) > 1
781        names = [(f"{h['family']} {h['model']}" if h.get("model") else h["file"]) + (f" in {h['folder']}" if several else f" ({h['file']})")
782                 for h in folder_holds[:8]]
783        messages.append(f"The folder holds {len(folder_holds)} models: " + "; ".join(names) + (" and more" if len(folder_holds) > 8 else "") +
784                        ". Choose the folder of the one you want, or type the path of its .gguf file.")
785    if any(i.endswith("unsupported_architecture") or i == "unsupported_or_missing_architecture" for i in issues):
786        messages.append(UNSUPPORTED_MODEL_TYPE)
787    elif projectors:
788        messages.extend(p["plain"] for p in projectors)
789    candidate = _candidate_selection(shards)
790    if candidate is None and metadata is not None and not issues:
791        candidate = _candidate_by_header(shards, observed_tensor_count, observed_payload, observed_experts)
792        if candidate is None:
793            candidate = _candidate_by_layout(shards, observed_tensor_count, observed_payload, observed_experts)
794            if candidate is not None:
795                messages.append(f"These files are not exactly a build Strata has tested; they have the layout of {candidate['family']} "
796                                f"{candidate['model']}, so Strata uses them as that model. Check a few answers before you rely on them.")
797    if "multiple_model_groups" in issues:
798        candidate = None                                  # nothing is chosen for the person
799    if candidate is None and not {"multiple_model_groups", "incomplete_or_invalid_shard_set"} & set(issues):
800        issues.append("unrecognized_or_unsupported_model_variant")
801    elif candidate is not None and metadata is not None:
802        expected = set(candidate["expected_expert_types"])
803        if not observed_experts or observed_experts - expected:
804            issues.append("missing_or_unexpected_expert_quantization")
805    return {"source": str(path), "model_dir": str(model_dir), "scope": "local_gguf_candidate", "files": files,
806            "file_count": len(files), "total_bytes": sum(item["bytes"] for item in files),
807            "metadata": metadata, "candidate_selection": candidate,
808            "plain_issues": list(dict.fromkeys((missing_words(missing_shards) if (i == "incomplete_or_invalid_shard_set" and missing_shards) else plain_issue(i)) for i in issues)),
809            "observed_expert_types": sorted(observed_experts),
810            "observed_tensor_count": observed_tensor_count,
811            "ignored_auxiliary_files": sorted(ignored_auxiliary),
812            "projectors": projectors, "messages": messages, "already_set_up": _already_set_up(shards, candidate),
813            "reads_pictures": any(p["status"] in ("ok", "other_name") for p in projectors) and
814            not any(i.endswith("unsupported_architecture") for i in issues),
815            "folder_holds": folder_holds, "missing_shards": missing_shards,
816            "file_set_status": "plausible" if not issues else "invalid_or_incomplete",
817            "issues": issues, "adoption_status": "requires_architecture_quantization_tokenizer_and_engine_checks",
818            "execution_compatibility": "unverified", "would_write": False,
819            "notes": ["A known shard name is only a selection hint; it does not prove provenance or file integrity",
820                      "Tensor directory, model-pack, engine version and hardware checks remain before adoption",
821                      "No model is adopted or copied by this preview"]}