okami.mom/strata

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

Niko1221launch: Auto tells setup the drafter the start runs (12 GB card, IQ3_S)68a2916b7

main
15.6 KiB287 linesraw
1"""What a model still needs on this computer, in plain words: the one place the Folder step, the download question and the final summary ask.
2
3A model that is already installed is "already downloaded". What can still be missing are helper files, each with its own size: the
4draft layer (MTP, makes answers faster) and the picture reader. Only when the weights themselves are gone does it say the model
5is downloaded again. Nothing here reads more than a run config and file existence.
6"""
7
8from __future__ import annotations
9
10import os
11from dataclasses import dataclass, field
12from pathlib import Path
13
14from strata_control import discovery
15from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB
16
17
18@dataclass
19class Part:
20    kind: str                        # weights | mtp | mmproj
21    label: str                       # "the draft layer"
22    gb: float
23
24
25@dataclass
26class ModelState:
27    installed: bool = False          # a run config for this model exists and names files that are there
28    own_files: bool = False          # the person's own model files
29    total_gb: float = 0.0            # the whole model (the catalog's figure)
30    parts: list[Part] = field(default_factory=list)       # what is missing and would be downloaded
31    folder: Path | None = None       # where the model lives now (its data folder), None when not installed
32    on_disk_gb: float = 0.0          # weights already in the model's folder (a partial download)
33    notes: list[str] = field(default_factory=list)
34
35    @property
36    def remaining_gb(self) -> float:
37        return sum(p.gb for p in self.parts)
38
39    @property
40    def only_helpers(self) -> bool:
41        return bool(self.parts) and all(p.kind != "weights" for p in self.parts)
42
43    def _names(self) -> str:
44        names = [f"{p.label} ({p.gb:.1f} GB)" for p in self.parts]
45        return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1]
46
47    def headline(self) -> str:
48        """One plain sentence for the size line of the Folder step."""
49        if self.own_files:
50            if not self.parts:
51                return "Your model files are used where they are. Nothing needs to be downloaded."
52            return f"Your model files are used where they are. Strata still needs to fetch {self._names()}."
53        if self.installed and not self.parts:
54            return f"Already downloaded ({self.total_gb:.0f} GB on this computer). Nothing more to download."
55        if self.installed and self.only_helpers:
56            first = self.parts[0]
57            if len(self.parts) == 1:
58                return f"The model is already downloaded ({self.total_gb:.0f} GB). Only {first.label} is missing ({first.gb:.1f} GB)."
59            return f"The model is already downloaded ({self.total_gb:.0f} GB). Only {self._names()} are missing."
60        if self.installed:
61            return (f"The model's files are no longer all on this computer. About {self.remaining_gb:.0f} GB would be downloaded "
62                    f"({self._names()}).")
63        if self.on_disk_gb >= 1:
64            return (f"{self.on_disk_gb:.0f} GB of the model is already in the folder. About {self.remaining_gb:.0f} GB left to download "
65                    f"(the whole model is {self.total_gb:.0f} GB).")
66        return f"Not downloaded yet: about {self.remaining_gb:.0f} GB to download."
67
68    def question(self) -> tuple[str, str]:
69        """(title, text) for the "Download?" pop-up before a start that needs a download."""
70        gb = self.remaining_gb
71        if self.only_helpers:
72            return (f"Download {self._names()}?",
73                    "The model itself is already on this computer and is not downloaded again. Strata needs this extra file to start "
74                    "with the choices you made; an interrupted download continues where it stopped.")
75        return (f"Download about {gb:.0f} GB?",
76                f"This model is not on this computer yet. Strata will download about {gb:.0f} GB now; "
77                "an interrupted download continues where it stopped.")
78
79
80#: The families whose setup also fetches the draft layer and the picture reader after the model (setup.py steps 5 and 6). NVFP4 packs bring
81#: theirs inside the download, Qwen3.6 has its own engine path.
82HELPER_FAMILIES = ("qwen", "swift", "coder", "unsloth", "gyro")
83
84
85def resolved_drafting(drafting: str | None, family: str | None, *, model_name: str | None = None, args: list | None = None,
86                      vram_mib: float | None = None) -> str:
87    """The drafter a choice means for this family on this computer: ``dflash2`` | ``mtp`` | ``off`` (strata_control/drafting.py: Auto is DFlash2 where the engine
88    has it). ``model_name`` / ``args`` / ``vram_mib``: the model's set and the card signals the start's decision reads (runner.auto_signals; the 12 GB card with
89    IQ3_S is the MTP). Never raises; an unknown computer is the MTP."""
90    try:
91        from strata_control import drafting as _d
92        backend, archs = _d.detect_hardware()
93        return _d.choice_of(drafting, family=family, backend=backend, archs=archs, model_name=model_name, args=args, vram_mib=vram_mib)
94    except Exception:                                        # noqa: BLE001
95        return "mtp"
96
97
98def drafting_for_family(choice: str | None, family: str | None) -> str | None:
99    """The Drafting choice to keep when the model changes to `family`: DFlash2/MTP/Off belong to Qwen3.8-Flash-Next (qwen, gyro, unsloth); any other model (Coder;
100    Swift; NVFP4) goes back to Auto (None), so a choice made for one model never rides along to another. An unknown family keeps it."""
101    from strata_control import drafting as _d
102    return choice if (not family or family in _d.SUPPORTED_FAMILIES) else None
103
104
105def drafting_to_save(key: str, saved: object) -> str | None:
106    """What the Drafting step writes into the launch settings for the row the person chose. Auto stays "nobody chose" (None: a saved preset writes nothing), except when the
107    model's own settings file already holds another choice (the app's Models screen writes its Drafting choice there and a launch starts from that file): then Auto is
108    written as "auto", so it overrides the older choice instead of silently running it."""
109    if key != "auto":
110        return key
111    from strata_control import drafting as _d
112    return "auto" if saved is not None and _d.normalize(saved) != "auto" else None
113
114
115def layer_off_without_choice(base: dict | None) -> bool:
116    """The model's installed config has its draft layer off ("mtp": false: setup's --mtp off from a Drafting Off launch, or the app's Draft layer switch) and holds
117    no Drafting choice: the engine starts without a drafter, so the Drafting step shows Off; a drafter picked there is saved (runner.layer_back)."""
118    return isinstance(base, dict) and base.get("drafting") is None and base.get("mtp") is False
119
120
121def mtp_choice(mtp: str | None, drafting: str | None = None) -> str | None:
122    """The draft-layer choice for what to fetch: off when the person said --mtp off, or the drafter is off or DFlash2 (``drafting`` is the resolved drafter,
123    resolved_drafting(); nothing then uses the layer, so a new install does not download it), else as chosen."""
124    if str(drafting or "").strip().lower() in ("off", "dflash2"):
125        return "off"
126    return mtp
127
128
129def mmproj_name(catalog, family: str | None) -> str:
130    try:
131        _m, families, _c, _s = catalog.tables()
132        name = (families.get(family or "") or {}).get("mmproj")
133        if name:
134            return str(name)
135        mod = catalog.strata.setup_module()
136        if mod is not None and getattr(mod, "MMPROJ", None):
137            return str(mod.MMPROJ)
138    except Exception:                                        # noqa: BLE001
139        pass
140    return "mmproj-Qwen3.8-Flash-Next-BF16.gguf"
141
142
143def assess(catalog, family: str | None, model: str | None, *, vision: str = "off", model_path: str | None = None,
144           data_dir: str | Path | None = None, config: Path | None = None, desc: dict | None = None, rows: list | None = None,
145           mtp: str | None = None, drafting: str | None = None, use_installed: bool = True) -> ModelState:
146    """The state of `family model` for these choices. `config` / `desc` are the installed run config and its description (looked up when
147    not given)."""
148    st = ModelState()
149    mtp = mtp_choice(mtp, drafting)
150    row = next((r for r in (rows if rows is not None else catalog.rows()) if r.family == family and r.model == model), None) if (family and model) else None
151    st.total_gb = float(row.download_gb) if row else 0.0
152    wants_pictures = vision != "off" and (row is None or row.images)
153    data = Path(data_dir) if data_dir else None
154    if model_path:
155        st.own_files = True
156        first = _first_gguf(Path(model_path))
157        beside = discovery.prepared_beside(first, data_places(catalog, data)) if first else {}     # the model folder's own layout, then --data-dir and the remembered folder (where setup writes the draft layer)
158        st.folder = beside.get("data_dir")
159        if beside.get("pack") is not None and beside.get("mtp") is None and mtp != "off":
160            st.parts.append(Part("mtp", "the draft layer", MTP_FETCH_GB))
161        if wants_pictures and beside.get("pack") is not None and \
162                not reader_present(catalog, family, [st.folder, *data_places(catalog, data)], own=first.parent if first else None):
163            st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB))
164        return st
165    if config is None and family and model and use_installed:          # (False: the installed copy is in another data folder than the one this launch uses)
166        config = catalog.installed_config(catalog.tag_of(family, model))
167    cfg = None
168    if config is not None:
169        try:
170            import json
171            cfg = json.loads(Path(config).read_text(encoding="utf-8-sig"))
172        except (OSError, ValueError):
173            cfg = None
174    if cfg is not None:
175        fp = discovery.footprint(cfg, Path(config))
176        st.installed = True
177        st.folder = fp.data_dir
178        gone = [m for m in fp.missing() if m.kind == "weights"]
179        if gone:
180            st.installed = False
181            st.parts.append(Part("weights", "the model", max(st.total_gb, 0.0)))
182            return st
183        for m in fp.missing():
184            if m.kind == "mtp" and mtp != "off":
185                st.parts.append(Part("mtp", "the draft layer", MTP_FETCH_GB))
186            elif m.kind == "mmproj" and wants_pictures:
187                st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB))
188        images = (desc or {}).get("images") if desc is not None else ("cpu" if fp.mmproj else "off")
189        if wants_pictures and (images in (None, "off")) and not any(p.kind == "mmproj" for p in st.parts):
190            base = st.folder / "models" if st.folder else data
191            have = (base / mmproj_name(catalog, family)) if base else None
192            if have is None or not have.exists():
193                st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB))
194        return st
195    # not installed: whatever of the weights is in the model's folder counts
196    if family and model:
197        base = data or Path(catalog.data_dir())
198        folder = catalog.model_folder(base, family, model)
199        got = 0
200        try:
201            got = sum(f.stat().st_size for f in folder.glob("*.gguf") if not f.name.lower().startswith("mmproj"))
202        except OSError:
203            pass
204        st.on_disk_gb = got / 1e9
205        st.parts.append(Part("weights", "the model", max(st.total_gb - st.on_disk_gb, 0.0)))
206        if family in HELPER_FAMILIES:
207            # setup fetches the draft layer and the picture reader after the model, so the question and the disk check count them too
208            if mtp != "off" and not (base / "mtp" / "rt" / "experts.bin").is_file():
209                st.parts.append(Part("mtp", "the draft layer", MTP_FETCH_GB))
210            if wants_pictures and not reader_present(catalog, family, [base, *data_places(catalog, None)]):     # setup's rule: the pinned name, here or in a folder it reuses
211                st.parts.append(Part("mmproj", "the picture reader", MMPROJ_GB))
212    return st
213
214
215def data_places(catalog, data: Path | None) -> list[Path]:
216    """The data folders besides the model folder's own layout that may already hold the draft layer: the one the launch names (--data-dir), then the one every command agrees on."""
217    out: list[Path] = [data] if data else []
218    try:
219        default = catalog.data_dir()
220        if default and not any(os.path.normcase(str(default)) == os.path.normcase(str(d)) for d in out):
221            out.append(Path(default))
222    except Exception:                                        # noqa: BLE001 - a question asked early is never a reason to stop
223        pass
224    return out
225
226
227def mmproj_size(catalog, family: str | None, name: str) -> int | None:
228    """The pinned size of the family's picture reader (setup's fam["mmproj_sha256"] or ISTA_FILES), None when setup does not pin one."""
229    try:
230        _m, families, _c, _s = catalog.tables()
231        pin = (families.get(family or "") or {}).get("mmproj_sha256")
232        if not pin:
233            mod = catalog.strata.setup_module()
234            pin = (getattr(mod, "ISTA_FILES", None) or {}).get(name) if mod is not None else None
235        return int(pin[0]) if pin else None
236    except Exception:                                        # noqa: BLE001
237        return None
238
239
240def reader_present(catalog, family: str | None, data_folders, own: Path | None = None) -> bool:
241    """Whether setup will find the picture reader without a download - setup's own rule (setup.py step 5 and mmproj_beside), not any
242    mmproj*.gguf: the family's pinned file name in a data folder's models/ (the one in use, or a folder setup reuses), or with the person's own
243    files in their folder (by name), or in the folder above it or that folder's models/ (by name, at the pinned size). Or, when there is no pinned
244    file, a verified Unsloth mmproj-F16.gguf (setup.accepted_alt_reader: the same function the start uses)."""
245    name = mmproj_name(catalog, family)
246    for base in data_folders:
247        if not base:
248            continue
249        for sub in ("models", "Models"):
250            try:
251                if (Path(base) / sub / name).is_file():
252                    return True
253            except OSError:
254                pass
255    if own is not None:
256        own = Path(own)
257        try:
258            if (own / name).is_file():
259                return True
260            size = mmproj_size(catalog, family, name)
261            for r in (own.parent, own.parent / "models"):
262                f = r / name
263                if f.is_file() and (size is None or f.stat().st_size == size):
264                    return True
265        except OSError:
266            pass
267    try:                                                     # no pinned file: a verified Unsloth mmproj-F16.gguf the person already has counts, as in setup
268        mod = catalog.strata.setup_module()
269        alt = (getattr(mod, "ALT_READERS", None) or {}).get(name) if mod is not None else None
270        if alt is None:
271            return False
272        places = [Path(b) / sub / alt[0] for b in data_folders if b for sub in ("models", "Models")]
273        if own is not None:
274            places += [Path(own) / alt[0], Path(own).parent / alt[0], Path(own).parent / "models" / alt[0]]
275        return mod.accepted_alt_reader(name, places, start=False) is not None      # (the plan hashes without writing a mark and says nothing)
276    except Exception:                                        # noqa: BLE001 - the plan must not fail on this
277        return False
278
279
280def _first_gguf(path: Path) -> Path | None:
281    try:
282        if path.is_file():
283            return path
284        found = sorted(p for p in path.glob("*.gguf") if not p.name.lower().startswith("mmproj"))
285        return found[0] if found else None
286    except OSError:
287        return None